chiark / gitweb /
minor improvements
[moebius2.git] / energy.c
index 07a410009467ac646811427d0beb875f2c98dc54..2bbf0492a5a41312d6819907995857bce9d1e180 100644 (file)
--- a/energy.c
+++ b/energy.c
@@ -3,65 +3,78 @@
  */
 
 #include "common.h"
-#include "bgl.h"
+#include "minimise.h"
 #include "mgraph.h"
 
-#include <gsl/gsl_errno.h>
-#include <gsl/gsl_multimin.h>
+double vertex_areas[N], vertex_mean_edge_lengths[N], edge_lengths[N][V6];
 
-static const char *input_file, *output_file;
-static char *output_file_tmp;
-
-static void compute_vertex_areas(const Vertices vertices, double areas[N]);
 static double best_energy= DBL_MAX;
 
-static void addcost(double *energy, double tweight, double tcost);
-#define COST(weight, compute) addcost(&energy, (weight), (compute))
+static void addcost(double *energy, double tweight, double tcost, int pr);
+#define COST(weight, compute) addcost(&energy, (weight), (compute), printing)
 
 /*---------- main energy computation and subroutines ----------*/
 
-static double compute_energy(const Vertices vertices) {
-  double vertex_areas[N], energy;
+double compute_energy(const struct Vertices *vs) {
+  double energy;
+  int printing;
 
-  compute_vertex_areas(vertices,vertex_areas);
+  compute_edge_lengths(vs->a);
+  compute_vertex_areas(vs->a);
   energy= 0;
-  printf("cost > energy |");
 
-  COST(1e4, edgewise_vertex_displacement_cost(vertices));
-  COST(1e2, graph_layout_cost(vertices,vertex_areas));
-//  COST(1e4, noncircular_rim_cost(vertices));
+  printing= printing_check(pr_cost);
+
+  if (printing) printf("cost > energy |");
+
+  COST(1e2, edgewise_vertex_displacement_cost(vs->a));
+  COST(1e2, graph_layout_cost(vs->a));
+  COST(1e3, edge_length_variation_cost(vs->a));
+//  COST(1e6, noncircular_rim_cost(vs->a));
+
+  if (printing) printf("| total %# e |", energy);
 
-  printf("| total %# e |", energy);
   if (energy < best_energy) {
     FILE *best_f;
     int r;
 
-    printf(" BEST");
+    if (printing) printf(" BEST");
 
     best_f= fopen(output_file_tmp,"wb");  if (!best_f) diee("fopen new out");
-    r= fwrite(vertices,sizeof(Vertices),1,best_f); if (r!=1) diee("fwrite");
+    r= fwrite(vs->a,sizeof(vs->a),1,best_f); if (r!=1) diee("fwrite");
     if (fclose(best_f)) diee("fclose new best");
     if (rename(output_file_tmp,output_file)) diee("rename install new best");
 
     best_energy= energy;
   }
-  putchar('\n');
-  flushoutput();
+  if (printing) {
+    putchar('\n');
+    flushoutput();
+  }
 
   return energy;
 }
 
-static void addcost(double *energy, double tweight, double tcost) {
+static void addcost(double *energy, double tweight, double tcost, int pr) {
   double tenergy= tweight * tcost;
-  printf(" %# e > %# e |", tcost, tenergy);
+  if (pr) printf(" %# e > %# e |", tcost, tenergy);
   *energy += tenergy;
 }
 
-static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
+/*---------- Precomputations ----------*/
+
+void compute_edge_lengths(const Vertices vertices) {
+  int v1,e,v2;
+  
+  FOR_EDGE(v1,e,v2)
+    edge_lengths[v1][e]= hypotD(vertices[v1],vertices[v2]);
+}
+
+void compute_vertex_areas(const Vertices vertices) {
   int v0,v1,v2, e1,e2, k;
 
   FOR_VERTEX(v0) {
-    double total= 0.0;
+    double total= 0.0, edges_total=0;
     int count= 0;
 
     FOR_VEDGE(v0,e1,v1) {
@@ -69,6 +82,8 @@ static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
       v2= EDGE_END2(v0,e2);
       if (v2<0) continue;
 
+      edges_total += edge_lengths[v0][e1];
+
       double e1v[D3], e2v[D3], av[D3];
       K {
        e1v[k]= vertices[v1][k] - vertices[v0][k];
@@ -76,109 +91,12 @@ static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
       }
       xprod(av, e1v, e2v);
       total += magnD(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 gsl_multimin_fminimizer *minimiser;
-
-static const double stop_epsilon= 1e-4;
-
-static double minfunc_f(const gsl_vector *x, void *params) {
-  assert(x->size == DIM);
-  assert(x->stride == 1);
-  return compute_energy((const double(*)[D3])x->data);
-}
-
-int main(int argc, const char *const *argv) {
-  gsl_multimin_function multimin_function;
-  double size;
-  Vertices initial, step_size;
-  FILE *initial_f;
-  gsl_vector initial_gsl, step_size_gsl;
-  int r, v, k;
-
-  if (argc!=3 || argv[1][0]=='-' || strncmp(argv[2],"-o",2))
-    { fputs("usage: minimise <input> -o<output\n",stderr); exit(8); }
-
-  input_file= argv[1];
-  output_file= argv[2]+2;
-  if (asprintf(&output_file_tmp,"%s.new",output_file) <= 0) diee("asprintf");
-
-  graph_layout_prepare();
-  
-  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(input_file,"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.block= 0;
-  initial_gsl.owner= 0;
-  step_size_gsl= initial_gsl;
-
-  initial_gsl.data= &initial[0][0];
-  step_size_gsl.data= &step_size[0][0];
-
-  FOR_VERTEX(v)
-    K step_size[v][k]= 0.03;
-//int vx,vy;
-//  FOR_RIM_VERTEX(vx,vy,v)
-//    step_size[v][3] *= 0.1;
-
-  GA( gsl_multimin_fminimizer_set(minimiser, &multimin_function,
-                                 &initial_gsl, &step_size_gsl) );
-
-  for (;;) {
-    GA( gsl_multimin_fminimizer_iterate(minimiser) );
-
-    size= gsl_multimin_fminimizer_size(minimiser);
-    r= gsl_multimin_test_size(size, stop_epsilon);
-
-    printf("%*s size %# e, r=%d\n", 135,"", size, r);
-    flushoutput();
-
-    if (r==GSL_SUCCESS) break;
-    assert(r==GSL_CONTINUE);
+    vertex_areas[v0]= total / count;
+    vertex_mean_edge_lengths[v0]= edges_total / count;
   }
-  return 0;
 }
 
 /*---------- Edgewise vertex displacement ----------*/
@@ -206,7 +124,7 @@ int main(int argc, const char *const *argv) {
    *
    *  Giving energy contribution:
    *
-   *                                   2
+   *                                   3
    *                            l delta
    *    E             =  F   .  --------
    *     vd, edge PQ      vd       d
@@ -215,7 +133,7 @@ int main(int argc, const char *const *argv) {
    *  (The dimensions of this are those of F_vd.)
    *
    *  We calculate delta as  atan2(|AxB|, A.B)
-   *  where A = RM, B = MS
+   *  where A = PQ, B = QR
    *
    *  In practice to avoid division by zero we'll add epsilon to d and
    *  |AxB| and the huge energy ought then to be sufficient for the
@@ -225,27 +143,44 @@ int main(int argc, const char *const *argv) {
 double edgewise_vertex_displacement_cost(const Vertices vertices) {
   static const double axb_epsilon= 1e-6;
 
-  int pi,e,qi,ri,si, k;
-  double m[D3], a[D3], b[D3], axb[D3];
+  int pi,e,qi,ri, k; //,si
+  double  a[D3], b[D3], axb[D3]; //m[D3],
   double total_cost= 0;
 
-  FOR_EDGE(pi,e,qi) {
-    ri= EDGE_END2(pi,(e+1)%V6); if (ri<0) continue;
-    si= EDGE_END2(pi,(e+5)%V6); if (si<0) continue;
+  FOR_EDGE(qi,e,ri) {
+    pi= EDGE_END2(qi,(e+3)%V6); if (pi<0) continue;
 
-    K m[k]= (vertices[pi][k] + vertices[qi][k]) * 0.5;
-    K a[k]= -vertices[ri][k] + m[k];
-    K b[k]= -m[k] + vertices[si][k];
+//    K m[k]= (vertices[pi][k] + vertices[qi][k]) * 0.5;
+    K a[k]= -vertices[pi][k] + vertices[qi][k];
+    K b[k]= -vertices[qi][k] + vertices[ri][k];
 
     xprod(axb,a,b);
     
     double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
-    double cost= delta * delta;
+    double cost= pow(delta,3);
+
+    if (!e && !(qi & YMASK))
+      cost *= 10;
+
     total_cost += cost;
   }
   return total_cost;
 }
 
+/*---------- edge length variation ----------*/
+
+double edge_length_variation_cost(const Vertices vertices) {
+  double diff, cost= 0;
+  int v0, efwd,vfwd, eback;
+
+  FOR_EDGE(v0,efwd,vfwd) {
+    eback= edge_reverse(v0,efwd);
+    diff= edge_lengths[v0][efwd] - edge_lengths[v0][eback];
+    cost += diff*diff;
+  }
+  return cost;
+}    
+
 /*---------- noncircular rim cost ----------*/
 
 double noncircular_rim_cost(const Vertices vertices) {