chiark / gitweb /
machinery for checking that our OUTER parallel iteration works - before we delete it
[moebius2.git] / energy.c
1 /*
2  * We try to find an optimal triangle grid
3  */
4
5 #include "common.h"
6 #include "minimise.h"
7 #include "mgraph.h"
8 #include "parallel.h"
9
10 double vertex_areas[N], vertex_mean_edge_lengths[N], edge_lengths[N][V6];
11
12 static double best_energy= DBL_MAX;
13
14 static void addcost(double *energy, double tweight, double tcost, int pr);
15
16 /*---------- main energy computation, weights, etc. ----------*/
17
18 typedef double CostComputation(const Vertices vertices, int section);
19 typedef void PreComputation(const Vertices vertices, int section);
20
21 typedef struct {
22   double weight;
23   CostComputation *fn;
24 } CostContribution;
25
26 #define NPRECOMPS ((sizeof(precomps)/sizeof(precomps[0])))
27 #define NCOSTS ((sizeof(costs)/sizeof(costs[0])))
28 #define COST(weight, compute) { (weight),(compute) },
29
30 static PreComputation *const precomps[]= {
31   compute_edge_lengths,
32   compute_vertex_areas
33 };
34
35 static const CostContribution costs[]= {
36
37 #if XBITS==3
38 #define STOP_EPSILON 1e-6
39     COST(  3e3,   line_bending_cost)
40     COST(  3e3,   edge_length_variation_cost)
41     COST( 0.4e3,  rim_proximity_cost)
42     COST(  1e6,   edge_angle_cost)
43                   #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.7)
44 //    COST(  1e1,   small_triangles_cost)
45     COST(  1e12,   noncircular_rim_cost)
46 #endif
47
48 #if XBITS==4
49 #define STOP_EPSILON 1e-6
50     COST(  3e5,   line_bending_cost)
51     COST( 10e2,   edge_length_variation_cost)
52     COST( 9.0e1,  rim_proximity_cost) // 5e1 is too much
53                                       // 2.5e1 is too little
54     // 0.2e1 grows compared to previous ?
55     // 0.6e0 shrinks compared to previous ?
56
57     COST(  1e12,   edge_angle_cost)
58                   #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.3)
59     COST(  1e18,   noncircular_rim_cost)
60 #endif
61
62 #if XBITS==5
63 #define STOP_EPSILON 1e-6
64     COST(  3e5,   line_bending_cost)
65     COST( 10e2,   edge_length_variation_cost)
66     COST( 9.0e1,  rim_proximity_cost) // 5e1 is too much
67                                       // 2.5e1 is too little
68     // 0.2e1 grows compared to previous ?
69     // 0.6e0 shrinks compared to previous ?
70
71     COST(  1e12,   edge_angle_cost)
72                   #define EDGE_ANGLE_COST_CIRCCIRCRAT (0.5/1.3)
73     COST(  1e18,   noncircular_rim_cost)
74 #endif
75
76 };
77
78 const double edge_angle_cost_circcircrat= EDGE_ANGLE_COST_CIRCCIRCRAT;
79
80 void energy_init(void) {
81   stop_epsilon= STOP_EPSILON;
82 }
83
84 /*---------- energy computation machinery ----------*/
85
86 void compute_energy_separately(const struct Vertices *vs,
87                          int section, void *energies_v, void *totals_v) {
88   double *energies= energies_v;
89   int ci;
90   
91   for (ci=0; ci<NPRECOMPS; ci++) {
92     costs[ci].fn(vs->a, section);
93     inparallel_barrier();
94   }
95   for (ci=0; ci<NCOSTS; ci++)
96     energies[ci]= costs[ci].fn(vs->a, section);
97 }
98
99 void compute_energy_combine(const struct Vertices *vertices,
100                          int section, void *energies_v, void *totals_v) {
101   int ci;
102   double *energies= energies_v;
103   double *totals= totals_v;
104
105   for (ci=0; ci<NCOSTS; ci++)
106     totals[ci] += energies[ci];
107 }
108
109 double compute_energy(const struct Vertices *vs) {
110   static int bests_unprinted;
111
112   double totals[NCOSTS], energy;
113   int ci, printing;
114
115   printing= printing_check(pr_cost,0);
116
117   if (printing) printf("%15lld c>e |", evaluations);
118
119   for (ci=0; ci<NCOSTS; ci++)
120     totals[ci]= 0;
121
122   inparallel(vs,
123              compute_energy_separately,
124              compute_energy_combine,
125              sizeof(totals) /* really, size of energies */,
126              totals);
127
128   energy= 0;
129   for (ci=0; ci<NCOSTS; ci++)
130     addcost(&energy, costs[ci].weight, totals[ci], printing);
131
132   if (printing) printf("| total %# e |", energy);
133
134   if (energy < best_energy) {
135     FILE *best_f;
136     int r;
137
138     if (printing) {
139       printf(" BEST");
140       if (bests_unprinted) printf(" [%4d]",bests_unprinted);
141       bests_unprinted= 0;
142     } else {
143       bests_unprinted++;
144     }
145
146     best_f= fopen(best_file_tmp,"wb");  if (!best_f) diee("fopen new out");
147     r= fwrite(vs->a,sizeof(vs->a),1,best_f); if (r!=1) diee("fwrite");
148     if (fclose(best_f)) diee("fclose new best");
149     if (rename(best_file_tmp,best_file)) diee("rename install new best");
150
151     best_energy= energy;
152   }
153   if (printing) {
154     putchar('\n');
155     flushoutput();
156   }
157
158   evaluations++;
159   return energy;
160 }
161
162 static void addcost(double *energy, double tweight, double tcost, int pr) {
163   double tenergy= tweight * tcost;
164   if (pr) printf(" %# e x %g > %# e* |", tcost, tweight, tenergy);
165   *energy += tenergy;
166 }
167
168 /*---------- Precomputations ----------*/
169
170 void compute_edge_lengths(const Vertices vertices, int section) {
171   int v1,e,v2;
172
173   FOR_EDGE(v1,e,v2, OUTER)
174     edge_lengths[v1][e]= hypotD(vertices[v1],vertices[v2]);
175 }
176
177 #include <pthread.h>
178
179 void compute_vertex_areas(const Vertices vertices, int section) {
180   int v0,v1,v2, e1,e2;
181 //  int k;
182
183   FOR_VERTEX(v0, OUTER) {
184     double total= 0.0, edges_total=0;
185     int count= 0;
186
187     FOR_VEDGE(v0,e1,v1) {
188       e2= (e1+1) % V6;
189       v2= EDGE_END2(v0,e2);
190       if (v2<0) continue;
191
192       edges_total += edge_lengths[v0][e1];
193
194 //      double e1v[D3], e2v[D3], av[D3];
195 //      K {
196 //      e1v[k]= vertices[v1][k] - vertices[v0][k];
197 //      e2v[k]= vertices[v2][k] - vertices[v0][k];
198 //      }
199 //      xprod(av, e1v, e2v);
200 //      total += magnD(av);
201
202       count++;
203     }
204     vertex_areas[v0]= total / count;
205     vertex_mean_edge_lengths[v0]= edges_total / count;
206   }
207 }
208
209 /*---------- Edgewise vertex displacement ----------*/
210
211   /*
212    * Definition:
213    *
214    *    At each vertex Q, in each direction e:
215    *
216    *                                  e
217    *                           Q ----->----- R
218    *                      _,-'\__/
219    *                  _,-'       delta
220    *               P '
221    *
222    *                      r
223    *       cost    = delta          (we use r=3)
224    *           Q,e
225    *
226    *
227    * Calculation:
228    *
229    *      Let vector A = PQ
230    *                 B = QR
231    *
232    *                   -1   A . B
233    *      delta =  tan     -------
234    *                      | A x B |
235    *
236    *      which is always in the range 0..pi because the denominator
237    *      is nonnegative.  We add epsilon to |AxB| to avoid division
238    *      by zero.
239    *
240    *                     r
241    *      cost    = delta
242    *          Q,e
243    */
244
245 double line_bending_cost(const Vertices vertices, int section) {
246   static const double axb_epsilon= 1e-6;
247   static const double exponent_r= 4;
248
249   int pi,e,qi,ri, k;
250   double  a[D3], b[D3], axb[D3];
251   double total_cost= 0;
252
253   if (quitting_last_iteration) {
254     char buf[100];
255     int n= sprintf(buf,
256                    "section=%d thr=%#08lx qi=0x%03x START\n",
257                    section,(unsigned long)pthread_self(), N);
258     write(2,buf,n);
259     quitting_reported_threads= 1;
260   }
261
262   FOR_EDGE(qi,e,ri, OUTER) {
263     if (quitting_last_iteration) {
264       char buf[100];
265       int n= sprintf(buf,
266                      "section=%d thr=%#08lx qi=0x%03x,e=%d,ri=0x%03x\n",
267                      section,(unsigned long)pthread_self(),qi,e,ri);
268       write(2,buf,n);
269     }
270
271     pi= EDGE_END2(qi,(e+3)%V6); if (pi<0) continue;
272
273 //if (!(qi&XMASK)) fprintf(stderr,"%02x-%02x-%02x (%d)\n",pi,qi,ri,e);
274
275     K a[k]= -vertices[pi][k] + vertices[qi][k];
276     K b[k]= -vertices[qi][k] + vertices[ri][k];
277
278     xprod(axb,a,b);
279
280     double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
281     double cost= pow(delta,exponent_r);
282
283     total_cost += cost;
284   }
285   return total_cost;
286 }
287
288 /*---------- edge length variation ----------*/
289
290   /*
291    * Definition:
292    *
293    *    See the diagram above.
294    *                                r
295    *       cost    = ( |PQ| - |QR| )
296    *           Q,e
297    */
298
299 double edge_length_variation_cost(const Vertices vertices, int section) {
300   double diff, cost= 0, exponent_r= 2;
301   int q, e,r, eback;
302
303   FOR_EDGE(q,e,r, OUTER) {
304     eback= edge_reverse(q,e);
305     diff= edge_lengths[q][e] - edge_lengths[q][eback];
306     cost += pow(diff,exponent_r);
307   }
308   return cost;
309 }
310
311 /*---------- rim proximity cost ----------*/
312
313 static void find_nearest_oncircle(double oncircle[D3], const double p[D3]) {
314   /* By symmetry, nearest point on circle is the one with
315    * the same angle subtended at the z axis. */
316   oncircle[0]= p[0];
317   oncircle[1]= p[1];
318   oncircle[2]= 0;
319   double mult= 1.0/ magnD(oncircle);
320   oncircle[0] *= mult;
321   oncircle[1] *= mult;
322 }
323
324 double rim_proximity_cost(const Vertices vertices, int section) {
325   double oncircle[3], cost=0;
326   int v;
327
328   FOR_VERTEX(v, OUTER) {
329     int y= v >> YSHIFT;
330     int nominal_edge_distance= y <= Y/2 ? y : Y-1-y;
331     if (nominal_edge_distance==0) continue;
332
333     find_nearest_oncircle(oncircle, vertices[v]);
334
335     cost +=
336       vertex_mean_edge_lengths[v] *
337       (nominal_edge_distance*nominal_edge_distance) /
338       (hypotD2(vertices[v], oncircle) + 1e-6);
339   }
340   return cost;
341 }
342
343 /*---------- noncircular rim cost ----------*/
344
345 double noncircular_rim_cost(const Vertices vertices, int section) {
346   int vy,vx,v;
347   double cost= 0.0;
348   double oncircle[3];
349
350   FOR_RIM_VERTEX(vy,vx,v, OUTER) {
351     find_nearest_oncircle(oncircle, vertices[v]);
352
353     double d2= hypotD2(vertices[v], oncircle);
354     cost += d2*d2;
355   }
356   return cost;
357 }
358
359 /*---------- overly sharp edge cost ----------*/
360
361   /*
362    *
363    *                Q `-_
364    *              / |    `-_                           P'Q' ------ S'
365    *             /  |       `-.                      _,' `.       .
366    *            /   |           S                 _,'     :      .
367    *           /    |      _,-'                _,'        :r    .r
368    *          /     |  _,-'                R' '           `.   .
369    *         /    , P '                        ` .   r     :  .
370    *        /  ,-'                                  `  .   : 
371    *       /,-'                                          ` C'
372    *      /'
373    *     R
374    *
375    *
376    *
377    *  Let delta =  angle between two triangles' normals
378    *
379    *  Giving energy contribution:
380    *
381    *                                   2
382    *    E             =  F   .  delta
383    *     vd, edge PQ      vd
384    */
385
386 double edge_angle_cost(const Vertices vertices, int section) {
387   double pq1[D3], rp[D3], ps[D3], rp_2d[D3], ps_2d[D3], rs_2d[D3];
388   double a,b,c,s,r;
389   const double minradius_base= 0.2;
390
391   int pi,e,qi,ri,si, k;
392 //  double our_epsilon=1e-6;
393   double total_cost= 0;
394
395   FOR_EDGE(pi,e,qi, OUTER) {
396 //    if (!(RIM_VERTEX_P(pi) || RIM_VERTEX_P(qi))) continue;
397
398     si= EDGE_END2(pi,(e+V6-1)%V6);  if (si<0) continue;
399     ri= EDGE_END2(pi,(e   +1)%V6);  if (ri<0) continue;
400
401     K {
402       pq1[k]= -vertices[pi][k] + vertices[qi][k];
403       rp[k]=  -vertices[ri][k] + vertices[pi][k];
404       ps[k]=  -vertices[pi][k] + vertices[si][k];
405     }
406
407     normalise(pq1,1,1e-6);
408     xprod(rp_2d, rp,pq1); /* projects RP into plane normal to PQ */
409     xprod(ps_2d, ps,pq1); /* likewise PS */
410     K rs_2d[k]= rp_2d[k] + ps_2d[k];
411     /* radius of circumcircle of R'P'S' from Wikipedia
412      * `Circumscribed circle' */
413     a= magnD(rp_2d);
414     b= magnD(ps_2d);
415     c= magnD(rs_2d);
416     s= 0.5*(a+b+c);
417     r= a*b*c / sqrt((a+b+c)*(a-b+c)*(b-c+a)*(c-a+b) + 1e-6);
418
419     double minradius= minradius_base + edge_angle_cost_circcircrat*(a+b);
420     double deficit= minradius - r;
421     if (deficit < 0) continue;
422     double cost= deficit*deficit;
423
424     total_cost += cost;
425   }
426
427   return total_cost;
428 }
429
430 /*---------- small triangles cost ----------*/
431
432   /*
433    *
434    *                Q `-_
435    *              / |    `-_
436    *             /  |       `-.
437    *            /   |           S
438    *           /    |      _,-'
439    *          /     |  _,-'
440    *         /    , P '
441    *        /  ,-'
442    *       /,-'
443    *      /'
444    *     R
445    *
446    *  Let delta =  angle between two triangles' normals
447    *
448    *  Giving energy contribution:
449    *
450    *                                   2
451    *    E             =  F   .  delta
452    *     vd, edge PQ      vd
453    */
454
455 double small_triangles_cost(const Vertices vertices, int section) {
456   double pq[D3], ps[D3];
457   double x[D3];
458   int pi,e,qi,si, k;
459 //  double our_epsilon=1e-6;
460   double total_cost= 0;
461
462   FOR_EDGE(pi,e,qi, OUTER) {
463 //    if (!(RIM_VERTEX_P(pi) || RIM_VERTEX_P(qi))) continue;
464
465     si= EDGE_END2(pi,(e+V6-1)%V6);  if (si<0) continue;
466
467     K {
468       pq[k]= vertices[qi][k] - vertices[pi][k];
469       ps[k]= vertices[si][k] - vertices[pi][k];
470     }
471     xprod(x, pq,ps);
472
473     double cost= 1/(magnD2(x) + 0.01);
474
475 //double cost= pow(magnD(spqxpqr), 3);
476 //assert(dot>=-1 && dot <=1);
477 //double cost= 1-dot;
478     total_cost += cost;
479   }
480
481   return total_cost;
482 }