+/*
+ * We try to find an optimal triangle grid
+ */
+
+#include "common.h"
+#include "bgl.h"
+#include "mgraph.h"
+
+#define BEST_F "best"
+#define INITIAL_F "initial"
+
+static double edgewise_vertex_displacement_cost(const Vertices vertices);
+
+static void compute_vertex_areas(const Vertices vertices, double areas[N]);
+static double best_energy= DOUBLE_MAX;
+static void flushoutput(void);
+
+static void cost(double *energy, double tweight, double tcost);
+#define COST(weight, compute) cost(&energy, (weight), (compute))
+
+/*---------- main energy computation and subroutines ----------*/
+
+static double compute_energy(Vertices vertices) {
+ double vertex_areas[N], energy;
+
+ compute_vertex_areas(vertices,vertex_areas);
+ energy= 0;
+ printf("cost > energy |");
+
+ COST(1000.0, edgewise_vertex_displacement_cost(vertices));
+ COST(1.0, graph_layout_cost(vertices,vertex_areas));
+ COST(1e6, noncircular_edge_cost(vertices));
+
+ printf("| total %# e |", energy);
+ if (energy < best_energy) {
+ FILE *best;
+ printf(" BEST");
+
+ best_f= fopen(BEST_F ".new","wb"); if (!best_f) diee("fopen new best");
+ r= fwrite(vertices,sizeof(vertices),1,best_f); if (r!=1) diee("fwrite");
+ if (fclose(best_f)) diee("fclose new best");
+ if (rename(BEST_F ".new", BEST_F)) diee("rename install new best");
+ }
+ putchar('\n');
+ flushoutput();
+
+ return energy;
+}
+
+static void cost(double *energy, double tweight, double tcost) {
+ double tenergy= tweight * tcost;
+ printf(" %# e > %# e |", tcost, tenergy);
+ *energy += tenergy;
+}
+
+static void flushoutput(void) {
+ if (fflush(stdout) || ferror(stdout)) { perror("stdout"); exit(-1); }
+}
+
+static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
+ FOR_VERTEX(v0) {
+ double total= 0.0;
+ int count= 0;
+
+ FOR_VEDGE(v0,e1,v1) {
+ e2= (e1+1) % V6;
+ v2= EDGE_END2(v0,e2);
+ if (v2<0) continue;
+
+ double e1v[D3], e2v[D3], av[D3];
+ K {
+ e1v[k]= vertices[v1][k] - vertices[v0][k];
+ e2v[k]= vertices[v2][k] - vertices[v0][k];
+ }
+ xprod(av, e1v, e2v);
+ total += hypotD1(av);
+ count++;
+ }
+ areas[v0]= total / count;
+ }
+}
+
+/*---------- use of GSL ----------*/
+
+ /* We want to do multidimensional minimisation.
+ *
+ * We don't think there are any local minima. Or at least, if there
+ * are, the local minimum which will be found from the starting
+ * state is the one we want.
+ *
+ * We don't want to try to provide a derivative of the cost
+ * function. That's too tedious (and anyway the polynomial
+ * approximation to our our cost function sometimes has high degree
+ * in the inputs which means the quadratic model implied by most of
+ * the gradient descent minimisers is not ideal).
+ *
+ * This eliminates most of the algorithms. Nelder and Mead's
+ * simplex algorithm is still available and we will try that.
+ *
+ * In our application we are searching for the optimal locations of
+ * N actualvertices in D3 (3) dimensions - ie, we are searching for
+ * the optimal metapoint in an N*D3-dimensional space.
+ *
+ * So eg with X=Y=100, the simplex will contain 300 metavertices
+ * each of which is an array of 300 doubles for the actualvertex
+ * coordinates. Hopefully this won't be too slow ...
+ */
+
+static void gsldie(const char *what, int status) {
+ fprintf(stderr,"gsl function failed: %s: %s\n", what, gsl_strerror(status));
+ exit(-1);
+}
+
+static gsl_multimin_fminimizer *minimiser;
+
+static const stop_epsilon= 1e-4;
+
+#define DIM (N*D3)
+
+static double minfunc_f(const gsl_vector *x, void *params) {
+ assert(x->size == DIM);
+ assert(x->stride == 1);
+ return compute_energy((Vertices)x->data);
+}
+
+int main(int argc, const char *const *argv) {
+ struct gsl_multimin_function multimin_function;
+ double size;
+ Vertices initial;
+ FILE *initial;
+ gsl_vector initial_gsl, *step_size;
+ int r;
+
+ if (argc>1) { fputs("takes no arguments\n",stderr); exit(8); }
+
+ minimiser= gsl_multimin_fminimizer_alloc
+ (gsl_multimin_fminimizer_nmsimplex, DIM);
+ if (!minimiser) { perror("alloc minimiser"); exit(-1); }
+
+ multimin_function.f= minfunc_f;
+ multimin_function.n= DIM;
+ multimin_function.params= 0;
+
+ initial_f= fopen(INITIAL_F,"rb"); if (!initial_f) diee("fopen initial");
+ errno= 0; r= fread(initial,sizeof(initial),1,initial_f);
+ if (r!=1) diee("fread");
+ fclose(initial_f);
+
+ initial_gsl.size= DIM;
+ initial_gsl.stride= 1;
+ initial_gsl.data= initial;
+ initial_gsl.block= 0;
+ initial_gsl.owner= 0;
+
+ step_size= gsl_vector_alloc(DIM); if (!step_size) gsldie("alloc step");
+ gsl_vector_set_all(step_size, 1e-3);
+
+ r= gsl_multimin_fminimizer_set(minimiser, &multimin_function,
+ &initial_gsl, &step_size);
+ if (r) { gsldie("fminimizer_set",r); }
+
+ for (;;) {
+ r= gsl_multimin_fminimizer_iterate(minimiser);
+ if (r) { gsldie("fminimizer_iterate",r); }
+
+ size= gsl_multimin_fminimizer_size(minimiser);
+ r= gsl_multimin_test_size(size, stop_epsilon);
+
+ printf("size %# e, r=%d\n", size, r);
+ flushoutput();
+
+ if (r==GSL_SUCCESS) break;
+ assert(r==GSL_CONTINUE);
+ }
+}
+
+/*---------- Edgewise vertex displacement ----------*/
+
+ /*
+ *
+ *
+ *
+ * Q `-_
+ * / | `-_
+ * R' - _ _ _/_ | `-.
+ * . / M - - - - - S
+ * . / | _,-'
+ * . / | _,-'
+ * . / , P '
+ * . / ,-'
+ * . /,-'
+ * . /'
+ * R
+ *
+ *
+ *
+ * Find R', the `expected' location of R, by
+ * reflecting S in M (the midpoint of QP).
+ *
+ * Let 2d = |RR'|
+ * b = |PQ|
+ * l = |RS|
+ *
+ * Giving energy contribution:
+ *
+ * 2
+ * b d
+ * E = F . ----
+ * vd, edge PQ vd 3
+ * l
+ *
+ * (The dimensions of this are those of F_vd.)
+ *
+ * By symmetry, this calculation gives the same answer with R and S
+ * exchanged. Looking at the projection in the RMS plane:
+ *
+ *
+ * S'
+ * ,'
+ * ,'
+ * R' ,' 2d" = |SS'| = |RR'| = 2d
+ * `-._ ,'
+ * `-._ ,' By congruent triangles,
+ * ` M with M' = midpoint of RS,
+ * ,' `-._ |MM'| = |RR'|/2 = d
+ * ,' `-._
+ * ,' ` S So use
+ * ,' M' _ , - ' d = |MM'|
+ * ,' _ , - '
+ * R - '
+ *
+ * We choose this value for l (rather than |RM|+|MS|, say, or |RM|)
+ * because we want this symmetry and because we're happy to punish
+ * bending more than uneveness in the metric.
+ *
+ * In practice to avoid division by zero we'll add epsilon to l^3
+ * and the huge energy ought then to be sufficient for the model to
+ * avoid being close to R=S.
+ */
+
+static double edgewise_vertex_displacement_cost(const Vertices vertices) {
+ static const l3_epsison= 1e-6;
+
+ int pi,e,qi,ri,si, k;
+ double m[D3], mprime[D3], b, d2, l, sigma_bd2_l3;
+
+ FOR_EDGE(pi,e,qi) {
+ ri= EDGE_END2(pi,(e+1)%V6); if (r<0) continue;
+ si= EDGE_END2(pi,(e+5)%V6); if (s<0) continue;
+ assert(ri == EDGE_END2(qi,(e+2)%V6));
+ assert(si == EDGE_END2(qi,(e+4)%V6));
+
+ K m[k]= (vertices[pi][k] + vertices[qi][k]) * 0.5;
+ K mprime[k]= (vertices[ri][k] + vertices[si][k]) * 0.5;
+ b= hypotD(vertices[pi], vertices[qi]);
+ d2= hypotD2(m, mprime);
+ l= hypotD(vertices[ri][k] - vertices[si][k]);
+ l3 = l*l*l + l3_epsilon;
+
+ sigma_bd2_l3 += b * d2 / l3;
+ }
+ return sigma_bd2_l3;
+}