chiark / gitweb /
improvements?
[moebius2.git] / energy.c
index c3b8754aff63dfa661cfd5dcbbbc41e67ae36885..867330cbf2da74a6293cdf55c58ba58edffc77af 100644 (file)
--- a/energy.c
+++ b/energy.c
@@ -3,77 +3,93 @@
  */
 
 #include "common.h"
-#include "bgl.h"
+#include "minimise.h"
 #include "mgraph.h"
 
-#define BEST_F "best"
-#define INITIAL_F "initial"
+#include <gsl/gsl_errno.h>
+#include <gsl/gsl_multimin.h>
 
-static double edgewise_vertex_displacement_cost(const Vertices vertices);
+#include <signal.h>
+#include <sys/time.h>
+
+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= DOUBLE_MAX;
-static void flushoutput(void);
+static double best_energy= DBL_MAX;
+
+enum printing_instance { pr_cost, pr_size, pr__max };
 
-static void cost(double *energy, double tweight, double tcost);
-#define COST(weight, compute) cost(&energy, (weight), (compute))
+static void addcost(double *energy, double tweight, double tcost, int pr);
+#define COST(weight, compute) addcost(&energy, (weight), (compute), printing)
+static int printing_check(enum printing_instance);
+static void printing_init(void);
 
 /*---------- main energy computation and subroutines ----------*/
 
-static double compute_energy(Vertices vertices) {
+static double compute_energy(const Vertices vertices) {
   double vertex_areas[N], energy;
+  int printing;
 
   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);
+  printing= printing_check(pr_cost);
+
+  if (printing) printf("cost > energy |");
+
+  COST(1e2, edgewise_vertex_displacement_cost(vertices));
+//  COST(1e0, graph_layout_cost(vertices,vertex_areas));
+  COST(1e4, noncircular_rim_cost(vertices));
+
+  if (printing) 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");
+    FILE *best_f;
+    int r;
+
+    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");
     if (fclose(best_f)) diee("fclose new best");
-    if (rename(BEST_F ".new", BEST_F)) diee("rename install new best");
+    if (rename(output_file_tmp,output_file)) diee("rename install new best");
+
+    best_energy= energy;
+  }
+  if (printing) {
+    putchar('\n');
+    flushoutput();
   }
-  putchar('\n');
-  flushoutput();
 
   return energy;
-}    
+}
 
-static void cost(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 flushoutput(void) {
-  if (fflush(stdout) || ferror(stdout)) { perror("stdout"); exit(-1); }
-}
-
 static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
+  int v0,v1,v2, e1,e2, k;
+
   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);
+      total += magnD(av);
       count++;
     }
     areas[v0]= total / count;
@@ -100,39 +116,40 @@ static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
    * 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 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((Vertices)x->data);
+  return compute_energy((const double(*)[D3])x->data);
 }
 
 int main(int argc, const char *const *argv) {
-  struct gsl_multimin_function multimin_function;
+  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); }
+  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();
+  printing_init();
+  
   minimiser= gsl_multimin_fminimizer_alloc
     (gsl_multimin_fminimizer_nmsimplex, DIM);
   if (!minimiser) { perror("alloc minimiser"); exit(-1); }
@@ -141,123 +158,181 @@ int main(int argc, const char *const *argv) {
   multimin_function.n= DIM;
   multimin_function.params= 0;
 
-  initial_f= fopen(INITIAL_F,"rb");  if (!initial_f) diee("fopen initial");
+  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.data= initial;
   initial_gsl.block= 0;
   initial_gsl.owner= 0;
+  step_size_gsl= initial_gsl;
 
-  step_size= gsl_vector_alloc(DIM);  if (!step_size) gsldie("alloc step");
-  gsl_vector_set_all(step_size, 1e-3);
+  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) );
 
-  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); }
+    GA( gsl_multimin_fminimizer_iterate(minimiser) );
 
     size= gsl_multimin_fminimizer_size(minimiser);
     r= gsl_multimin_test_size(size, stop_epsilon);
 
-    printf("size %# e, r=%d\n", size, r);
+    if (printing_check(pr_size))
+      printf("%*s size %# e, r=%d\n", 135,"", size, r);
     flushoutput();
 
     if (r==GSL_SUCCESS) break;
     assert(r==GSL_CONTINUE);
   }
+  return 0;
 }
 
 /*---------- Edgewise vertex displacement ----------*/
 
   /*
-   *  
+   *
    *
    *
    *                       Q `-_
    *              / |    `-_
-   *   R' - _ _ _/_ |       `-.
-   *    .       /   M - - - - - S
-   *    .      /    |      _,-'
-   *    .     /     |  _,-'
-   *    .    /    , P '
-   *    .   /  ,-'
-   *    .  /,-'
-   *    . /'
+   *             /  |       `-.
+   *            /   M - - - - - S
+   *           /  ' |      _,-'
+   *          /  '  |  _,-'
+   *         / '  , P '
+   *        / ',-'
+   *       /,-'
+   *      /'
    *            R
    *
+   *  Let delta =  180deg - angle RMS
    *
-   *
-   *  Find R', the `expected' location of R, by
-   *  reflecting S in M (the midpoint of QP).
-   *
-   *  Let 2d = |RR'|
-   *       b = |PQ|
-   *       l = |RS|
+   *  Let  l = |PQ|
+   *       d = |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:
+   *                                   2
+   *                            l delta
+   *    E             =  F   .  --------
+   *     vd, edge PQ      vd       d
    *
    *
-   *                          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 - '
+   *  (The dimensions of this are those of F_vd.)
    *
-   *  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.
+   *  We calculate delta as  atan2(|AxB|, A.B)
+   *  where A = RM, B = MS
    *
-   *  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.
+   *  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
+   *  model to avoid being close to R=S.
    */
 
-static double edgewise_vertex_displacement_cost(const Vertices vertices) {
-  static const l3_epsison= 1e-6;
+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], mprime[D3], b, d2, l, sigma_bd2_l3;
+  double m[D3], a[D3], b[D3], axb[D3];
+  double total_cost= 0;
 
   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));
-    
+    ri= EDGE_END2(pi,(e+1)%V6); if (ri<0) continue;
+    si= EDGE_END2(pi,(e+5)%V6); if (si<0) continue;
+
     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;
+    K a[k]= -vertices[ri][k] + m[k];
+    K b[k]= -m[k] + vertices[si][k];
 
-    sigma_bd2_l3 += b * d2 / l3;
+    xprod(axb,a,b);
+    
+    double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
+    double cost= delta * delta;
+    total_cost += cost;
+  }
+  return total_cost;
+}
+
+/*---------- noncircular rim cost ----------*/
+
+double noncircular_rim_cost(const Vertices vertices) {
+  int vy,vx,v;
+  double cost= 0.0;
+
+  FOR_RIM_VERTEX(vy,vx,v) {
+    double oncircle[3];
+    /* By symmetry, nearest point on circle is the one with
+     * the same angle subtended at the z axis. */
+    oncircle[0]= vertices[v][0];
+    oncircle[1]= vertices[v][1];
+    oncircle[2]= 0;
+    double mult= 1.0/ magnD(oncircle);
+    oncircle[0] *= mult;
+    oncircle[1] *= mult;
+    double d2= hypotD2(vertices[v], oncircle);
+    cost += d2*d2;
   }
-  return sigma_bd2_l3;
+  return cost;
+}
+
+/*---------- printing rate limit ----------*/
+
+static volatile unsigned print_todo;
+static sigset_t print_alarmset;
+
+static int printing_check(enum printing_instance which) {
+  static int skipped[pr__max];
+  
+  unsigned bits= 1u << which;
+  int sk;
+
+  if (!(print_todo & bits)) {
+    skipped[which]++;
+    return 0;;
+  }
+
+  sigprocmask(SIG_BLOCK,&print_alarmset,0);
+  print_todo &= ~bits;
+  sigprocmask(SIG_UNBLOCK,&print_alarmset,0);
+
+  sk= skipped[which];
+  if (sk) printf("[%4d] ",sk);
+  else printf("       ");
+  skipped[which]= 0;
+
+  return 1;
+}
+
+static void alarmhandler(int ignored) {
+  print_todo= ~0u;
+}
+
+static void printing_init(void) {
+  struct sigaction sa;
+  struct itimerval itv;
+
+  sigemptyset(&print_alarmset);
+  sigaddset(&print_alarmset,SIGALRM);
+
+  sa.sa_handler= alarmhandler;
+  sa.sa_mask= print_alarmset;
+  sa.sa_flags= SA_RESTART;
+  if (sigaction(SIGALRM,&sa,0)) diee("sigaction ALRM");
+  
+  itv.it_interval.tv_sec= 0;
+  itv.it_interval.tv_usec= 200000;
+  itv.it_value= itv.it_interval;
+
+  if (setitimer(ITIMER_REAL,&itv,0)) diee("setitimer REAL");
+
+  raise(SIGALRM);
 }