chiark / gitweb /
stopping point for 64
[moebius2.git] / energy.c
index 1d0360f..308aebf 100644 (file)
--- a/energy.c
+++ b/energy.c
 #include "common.h"
 #include "minimise.h"
 #include "mgraph.h"
+#include "parallel.h"
 
 double vertex_areas[N], vertex_mean_edge_lengths[N], edge_lengths[N][V6];
 
 static double best_energy= DBL_MAX;
 
 static void addcost(double *energy, double tweight, double tcost, int pr);
-#define COST(weight, compute) addcost(&energy, (weight), (compute), printing)
 
-double density;
+/*---------- main energy computation, weights, etc. ----------*/
+
+typedef double CostComputation(const Vertices vertices, int section);
+typedef void PreComputation(const Vertices vertices, int section);
+
+typedef struct {
+  double weight;
+  CostComputation *fn;
+} CostContribution;
+
+#define NPRECOMPS ((sizeof(precomps)/sizeof(precomps[0])))
+#define NCOSTS ((sizeof(costs)/sizeof(costs[0])))
+#define COST(weight, compute) { (weight),(compute) },
+
+static PreComputation *const precomps[]= {
+  compute_edge_lengths,
+  compute_vertex_areas
+};
+
+static const CostContribution costs[]= {
+
+#if XBITS==3
+#define STOP_EPSILON 1e-6
+    COST(  3e3,   line_bending_cost)
+    COST(  3e3,   edge_length_variation_cost)
+    COST( 0.4e3,  rim_proximity_cost)
+    COST(  1e6,   edge_angle_cost)
+                  #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.7)
+//    COST(  1e1,   small_triangles_cost)
+    COST(  1e12,   noncircular_rim_cost)
+#endif
+
+#if XBITS==4
+#define STOP_EPSILON 1.2e-4
+    COST(  3e5,   line_bending_cost)
+    COST( 10e3,   edge_length_variation_cost)
+    COST( 9.0e3,  rim_proximity_cost) // 5e1 is too much
+                                     // 2.5e1 is too little
+    // 0.2e1 grows compared to previous ?
+    // 0.6e0 shrinks compared to previous ?
+
+//    COST(  1e12,   edge_angle_cost)
+                  #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.3)
+    COST(  1e18,   noncircular_rim_cost)
+#endif
+
+#if XBITS>=5 /* nonsense follows but never mind */
+#define STOP_EPSILON 1e-6
+    COST(  3e5,   line_bending_cost)
+    COST( 10e2,   edge_length_variation_cost)
+    COST( 9.0e1,  rim_proximity_cost) // 5e1 is too much
+                                     // 2.5e1 is too little
+    // 0.2e1 grows compared to previous ?
+    // 0.6e0 shrinks compared to previous ?
+
+    COST(  1e12,   edge_angle_cost)
+                  #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.3)
+    COST(  1e18,   noncircular_rim_cost)
+#endif
+
+};
+
+const double edge_angle_cost_circcircrat= EDGE_ANGLE_COST_CIRCCIRCRAT;
 
 void energy_init(void) {
-  density= sqrt(N);
+  stop_epsilon= STOP_EPSILON;
 }
 
-/*---------- main energy computation and subroutines ----------*/
+/*---------- energy computation machinery ----------*/
+
+void compute_energy_separately(const struct Vertices *vs,
+                        int section, void *energies_v, void *totals_v) {
+  double *energies= energies_v;
+  int ci;
+  
+  for (ci=0; ci<NPRECOMPS; ci++) {
+    precomps[ci](vs->a, section);
+    inparallel_barrier();
+  }
+  for (ci=0; ci<NCOSTS; ci++)
+    energies[ci]= costs[ci].fn(vs->a, section);
+}
+
+void compute_energy_combine(const struct Vertices *vertices,
+                        int section, void *energies_v, void *totals_v) {
+  int ci;
+  double *energies= energies_v;
+  double *totals= totals_v;
+
+  for (ci=0; ci<NCOSTS; ci++)
+    totals[ci] += energies[ci];
+}
 
 double compute_energy(const struct Vertices *vs) {
-  double energy;
-  int printing;
+  static int bests_unprinted;
 
-  compute_edge_lengths(vs->a);
-  compute_vertex_areas(vs->a);
-  energy= 0;
+  double totals[NCOSTS], energy;
+  int ci, printing;
 
   printing= printing_check(pr_cost,0);
 
-  if (printing) printf("cost > energy |");
+  if (printing) printf("%15lld c>e |", evaluations);
+
+  for (ci=0; ci<NCOSTS; ci++)
+    totals[ci]= 0;
+
+  inparallel(vs,
+            compute_energy_separately,
+            compute_energy_combine,
+            sizeof(totals) /* really, size of energies */,
+            totals);
 
-  COST(2.25e3, line_bending_adjcost(vs->a));
-  COST(1e3, edge_length_variation_cost(vs->a));
-  COST(0.2e3, rim_proximity_cost(vs->a));
-//  COST(1e2, graph_layout_cost(vs->a));
-  COST(1e8, noncircular_rim_cost(vs->a));
+  energy= 0;
+  for (ci=0; ci<NCOSTS; ci++)
+    addcost(&energy, costs[ci].weight, totals[ci], printing);
 
   if (printing) printf("| total %# e |", energy);
 
@@ -45,12 +135,18 @@ double compute_energy(const struct Vertices *vs) {
     FILE *best_f;
     int r;
 
-    if (printing) printf(" BEST");
+    if (printing) {
+      printf(" BEST");
+      if (bests_unprinted) printf(" [%4d]",bests_unprinted);
+      bests_unprinted= 0;
+    } else {
+      bests_unprinted++;
+    }
 
-    best_f= fopen(output_file_tmp,"wb");  if (!best_f) diee("fopen new out");
+    best_f= fopen(best_file_tmp,"wb");  if (!best_f) diee("fopen new out");
     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");
+    if (rename(best_file_tmp,best_file)) diee("rename install new best");
 
     best_energy= energy;
   }
@@ -59,29 +155,30 @@ double compute_energy(const struct Vertices *vs) {
     flushoutput();
   }
 
+  evaluations++;
   return energy;
 }
 
 static void addcost(double *energy, double tweight, double tcost, int pr) {
   double tenergy= tweight * tcost;
-  if (pr) printf(" %# e x %# e > %# e* |", tcost, tweight, tenergy);
+  if (pr) printf(" %# e x %g > %# e* |", tcost, tweight, tenergy);
   *energy += tenergy;
 }
 
 /*---------- Precomputations ----------*/
 
-void compute_edge_lengths(const Vertices vertices) {
+void compute_edge_lengths(const Vertices vertices, int section) {
   int v1,e,v2;
 
-  FOR_EDGE(v1,e,v2)
+  FOR_EDGE(v1,e,v2, OUTER)
     edge_lengths[v1][e]= hypotD(vertices[v1],vertices[v2]);
 }
 
-void compute_vertex_areas(const Vertices vertices) {
+void compute_vertex_areas(const Vertices vertices, int section) {
   int v0,v1,v2, e1,e2;
 //  int k;
 
-  FOR_VERTEX(v0) {
+  FOR_VERTEX(v0, OUTER) {
     double total= 0.0, edges_total=0;
     int count= 0;
 
@@ -141,73 +238,21 @@ void compute_vertex_areas(const Vertices vertices) {
    *                     r
    *      cost    = delta
    *          Q,e
-   *
-   * Normalisation:
-   *
-   *    We want the minimum energy to remain unchanged with changes in
-   *    triangle densitiy, when the vertices lie evenly spaced on
-   *    circles, and we do this by normalising the force ie the
-   *    derivative of the energy with respect to linear motions of the
-   *    vertices.
-   *
-   *    We consider only the force on Q due to PQR, wlog.  (Forces on
-   *    P qnd R due to PQR are equal and opposite so normalising
-   *    forces on Q will normalise them too.)
-   *
-   *    Force on Q is in the plnae PQR and normal to PR, so we can
-   *    consider it only linearly in that dimension.  WLOG let that be
-   *    the x dimension.  So with f' representing df'/dx_Q:
-   *
-   *                  ,         d
-   *      F    =  cost      =  --
-   *       Q,e         Q,e           err looks like we can only do
-   *                                 this if we make some kind of
-   *                                 assumption about delta or
-   *                                 something   give up
-   *
-   *
-   *    Interposing M and N so that we have P-M-Q-N-R
-   *    generates half as much delta for each vertex.  So
-   *
+   */
 
-   In that case the force on Q
-   *    due to PQR
-   *
-   *Normalising for equal linear
-   *    forces:
-   *
-   *                                      d
-   *      linear force on Q due to e  =  -------  cost
-   *                                     d coord       Q,e
-   *                                            Q
-   *
-   *       (we will consider only one e and one coord and hope
-   *        that doesn't lead us astray.)
-   *
-   *
-   *           ,       -r
-   *       cost    =  D   . cost
-   *           Q,e              Q,e
-   *
-   *                           where D is the linear density.
-   *
-   *                ,              -r
-   *     Sigma  cost      =   N . D  .  Sigma  cost
-   *      Q,e       Q,e                  Q,e       Q,e
-   *
-   * */
-
-double line_bending_adjcost(const Vertices vertices) {
+double line_bending_cost(const Vertices vertices, int section) {
   static const double axb_epsilon= 1e-6;
-  static const double exponent_r= 3;
+  static const double exponent_r= 4;
 
   int pi,e,qi,ri, k;
   double  a[D3], b[D3], axb[D3];
   double total_cost= 0;
 
-  FOR_EDGE(qi,e,ri) {
+  FOR_EDGE(qi,e,ri, OUTER) {
     pi= EDGE_END2(qi,(e+3)%V6); if (pi<0) continue;
 
+//if (!(qi&XMASK)) fprintf(stderr,"%02x-%02x-%02x (%d)\n",pi,qi,ri,e);
+
     K a[k]= -vertices[pi][k] + vertices[qi][k];
     K b[k]= -vertices[qi][k] + vertices[ri][k];
 
@@ -216,12 +261,9 @@ double line_bending_adjcost(const Vertices vertices) {
     double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
     double cost= pow(delta,exponent_r);
 
-    if (!e && !(qi & YMASK))
-      cost *= 10;
-
     total_cost += cost;
   }
-  return total_cost / (N / density);
+  return total_cost;
 }
 
 /*---------- edge length variation ----------*/
@@ -230,18 +272,19 @@ double line_bending_adjcost(const Vertices vertices) {
    * Definition:
    *
    *    See the diagram above.
-   *
-   *       cost    =
+   *                                r
+   *       cost    = ( |PQ| - |QR| )
    *           Q,e
+   */
 
-double edge_length_variation_cost(const Vertices vertices) {
-  double diff, cost= 0;
+double edge_length_variation_cost(const Vertices vertices, int section) {
+  double diff, cost= 0, exponent_r= 2;
   int q, e,r, eback;
 
-  FOR_EDGE(q,e,r) {
+  FOR_EDGE(q,e,r, OUTER) {
     eback= edge_reverse(q,e);
     diff= edge_lengths[q][e] - edge_lengths[q][eback];
-    cost += diff*diff;
+    cost += pow(diff,exponent_r);
   }
   return cost;
 }
@@ -259,11 +302,11 @@ static void find_nearest_oncircle(double oncircle[D3], const double p[D3]) {
   oncircle[1] *= mult;
 }
 
-double rim_proximity_cost(const Vertices vertices) {
+double rim_proximity_cost(const Vertices vertices, int section) {
   double oncircle[3], cost=0;
   int v;
 
-  FOR_VERTEX(v) {
+  FOR_VERTEX(v, OUTER) {
     int y= v >> YSHIFT;
     int nominal_edge_distance= y <= Y/2 ? y : Y-1-y;
     if (nominal_edge_distance==0) continue;
@@ -280,12 +323,12 @@ double rim_proximity_cost(const Vertices vertices) {
 
 /*---------- noncircular rim cost ----------*/
 
-double noncircular_rim_cost(const Vertices vertices) {
+double noncircular_rim_cost(const Vertices vertices, int section) {
   int vy,vx,v;
   double cost= 0.0;
   double oncircle[3];
 
-  FOR_RIM_VERTEX(vy,vx,v) {
+  FOR_RIM_VERTEX(vy,vx,v, OUTER) {
     find_nearest_oncircle(oncircle, vertices[v]);
 
     double d2= hypotD2(vertices[v], oncircle);
@@ -293,3 +336,128 @@ double noncircular_rim_cost(const Vertices vertices) {
   }
   return cost;
 }
+
+/*---------- overly sharp edge cost ----------*/
+
+  /*
+   *
+   *                       Q `-_
+   *              / |    `-_                          P'Q' ------ S'
+   *             /  |       `-.                             _,' `.       .
+   *            /   |           S                _,'     :      .
+   *           /    |      _,-'                _,'        :r    .r
+   *          /     |  _,-'               R' '           `.   .
+   *         /    , P '                               ` .   r     :  .
+   *        /  ,-'                                 `  .   : 
+   *       /,-'                                                 ` C'
+   *      /'
+   *            R
+   *
+   *
+   *
+   *  Let delta =  angle between two triangles' normals
+   *
+   *  Giving energy contribution:
+   *
+   *                                   2
+   *    E             =  F   .  delta
+   *     vd, edge PQ      vd
+   */
+
+double edge_angle_cost(const Vertices vertices, int section) {
+  double pq1[D3], rp[D3], ps[D3], rp_2d[D3], ps_2d[D3], rs_2d[D3];
+  double a,b,c,s,r;
+  const double minradius_base= 0.2;
+
+  int pi,e,qi,ri,si, k;
+//  double our_epsilon=1e-6;
+  double total_cost= 0;
+
+  FOR_EDGE(pi,e,qi, OUTER) {
+//    if (!(RIM_VERTEX_P(pi) || RIM_VERTEX_P(qi))) continue;
+
+    si= EDGE_END2(pi,(e+V6-1)%V6);  if (si<0) continue;
+    ri= EDGE_END2(pi,(e   +1)%V6);  if (ri<0) continue;
+
+    K {
+      pq1[k]= -vertices[pi][k] + vertices[qi][k];
+      rp[k]=  -vertices[ri][k] + vertices[pi][k];
+      ps[k]=  -vertices[pi][k] + vertices[si][k];
+    }
+
+    normalise(pq1,1,1e-6);
+    xprod(rp_2d, rp,pq1); /* projects RP into plane normal to PQ */
+    xprod(ps_2d, ps,pq1); /* likewise PS */
+    K rs_2d[k]= rp_2d[k] + ps_2d[k];
+    /* radius of circumcircle of R'P'S' from Wikipedia
+     * `Circumscribed circle' */
+    a= magnD(rp_2d);
+    b= magnD(ps_2d);
+    c= magnD(rs_2d);
+    s= 0.5*(a+b+c);
+    r= a*b*c / sqrt((a+b+c)*(a-b+c)*(b-c+a)*(c-a+b) + 1e-6);
+
+    double minradius= minradius_base + edge_angle_cost_circcircrat*(a+b);
+    double deficit= minradius - r;
+    if (deficit < 0) continue;
+    double cost= deficit*deficit;
+
+    total_cost += cost;
+  }
+
+  return total_cost;
+}
+
+/*---------- small triangles cost ----------*/
+
+  /*
+   *
+   *                       Q `-_
+   *              / |    `-_
+   *             /  |       `-.
+   *            /   |           S
+   *           /    |      _,-'
+   *          /     |  _,-'
+   *         /    , P '
+   *        /  ,-'
+   *       /,-'
+   *      /'
+   *            R
+   *
+   *  Let delta =  angle between two triangles' normals
+   *
+   *  Giving energy contribution:
+   *
+   *                                   2
+   *    E             =  F   .  delta
+   *     vd, edge PQ      vd
+   */
+
+double small_triangles_cost(const Vertices vertices, int section) {
+  double pq[D3], ps[D3];
+  double x[D3];
+  int pi,e,qi,si, k;
+//  double our_epsilon=1e-6;
+  double total_cost= 0;
+
+  FOR_EDGE(pi,e,qi, OUTER) {
+//    if (!(RIM_VERTEX_P(pi) || RIM_VERTEX_P(qi))) continue;
+
+    si= EDGE_END2(pi,(e+V6-1)%V6);  if (si<0) continue;
+
+    K {
+      pq[k]= vertices[qi][k] - vertices[pi][k];
+      ps[k]= vertices[si][k] - vertices[pi][k];
+    }
+    xprod(x, pq,ps);
+
+    double cost= 1/(magnD2(x) + 0.01);
+
+//double cost= pow(magnD(spqxpqr), 3);
+//assert(dot>=-1 && dot <=1);
+//double cost= 1-dot;
+    total_cost += cost;
+  }
+
+  return total_cost;
+}