chiark / gitweb /
apparently-useless patch
[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 void compute_vertex_areas(const Vertices vertices, int section) {
178   int v0,v1,v2, e1,e2;
179 //  int k;
180
181   FOR_VERTEX(v0, OUTER) {
182     double total= 0.0, edges_total=0;
183     int count= 0;
184
185     FOR_VEDGE(v0,e1,v1) {
186       e2= (e1+1) % V6;
187       v2= EDGE_END2(v0,e2);
188       if (v2<0) continue;
189
190       edges_total += edge_lengths[v0][e1];
191
192 //      double e1v[D3], e2v[D3], av[D3];
193 //      K {
194 //      e1v[k]= vertices[v1][k] - vertices[v0][k];
195 //      e2v[k]= vertices[v2][k] - vertices[v0][k];
196 //      }
197 //      xprod(av, e1v, e2v);
198 //      total += magnD(av);
199
200       count++;
201     }
202     vertex_areas[v0]= total / count;
203     vertex_mean_edge_lengths[v0]= edges_total / count;
204   }
205 }
206
207 /*---------- Edgewise vertex displacement ----------*/
208
209   /*
210    * Definition:
211    *
212    *    At each vertex Q, in each direction e:
213    *
214    *                                  e
215    *                           Q ----->----- R
216    *                      _,-'\__/
217    *                  _,-'       delta
218    *               P '
219    *
220    *                      r
221    *       cost    = delta          (we use r=3)
222    *           Q,e
223    *
224    *
225    * Calculation:
226    *
227    *      Let vector A = PQ
228    *                 B = QR
229    *
230    *                   -1   A . B
231    *      delta =  tan     -------
232    *                      | A x B |
233    *
234    *      which is always in the range 0..pi because the denominator
235    *      is nonnegative.  We add epsilon to |AxB| to avoid division
236    *      by zero.
237    *
238    *                     r
239    *      cost    = delta
240    *          Q,e
241    */
242
243 double line_bending_cost(const Vertices vertices, int section) {
244   static const double axb_epsilon= 1e-6;
245   static const double exponent_r= 4;
246
247   int pi,e,qi,ri, k;
248   double  a[D3], b[D3], axb[D3];
249   double total_cost= 0;
250
251   FOR_EDGE(qi,e,ri, OUTER) {
252     pi= EDGE_END2(qi,(e+3)%V6); if (pi<0) continue;
253
254 //if (!(qi&XMASK)) fprintf(stderr,"%02x-%02x-%02x (%d)\n",pi,qi,ri,e);
255
256     K a[k]= -vertices[pi][k] + vertices[qi][k];
257     K b[k]= -vertices[qi][k] + vertices[ri][k];
258
259     xprod(axb,a,b);
260
261     double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
262     double cost= pow(delta,exponent_r);
263
264     total_cost += cost;
265   }
266   return total_cost;
267 }
268
269 /*---------- edge length variation ----------*/
270
271   /*
272    * Definition:
273    *
274    *    See the diagram above.
275    *                                r
276    *       cost    = ( |PQ| - |QR| )
277    *           Q,e
278    */
279
280 double edge_length_variation_cost(const Vertices vertices, int section) {
281   double diff, cost= 0, exponent_r= 2;
282   int q, e,r, eback;
283
284   FOR_EDGE(q,e,r, OUTER) {
285     eback= edge_reverse(q,e);
286     diff= edge_lengths[q][e] - edge_lengths[q][eback];
287     cost += pow(diff,exponent_r);
288   }
289   return cost;
290 }
291
292 /*---------- rim proximity cost ----------*/
293
294 static void find_nearest_oncircle(double oncircle[D3], const double p[D3]) {
295   /* By symmetry, nearest point on circle is the one with
296    * the same angle subtended at the z axis. */
297   oncircle[0]= p[0];
298   oncircle[1]= p[1];
299   oncircle[2]= 0;
300   double mult= 1.0/ magnD(oncircle);
301   oncircle[0] *= mult;
302   oncircle[1] *= mult;
303 }
304
305 double rim_proximity_cost(const Vertices vertices, int section) {
306   double oncircle[3], cost=0;
307   int v;
308
309   FOR_VERTEX(v, OUTER) {
310     int y= v >> YSHIFT;
311     int nominal_edge_distance= y <= Y/2 ? y : Y-1-y;
312     if (nominal_edge_distance==0) continue;
313
314     find_nearest_oncircle(oncircle, vertices[v]);
315
316     cost +=
317       vertex_mean_edge_lengths[v] *
318       (nominal_edge_distance*nominal_edge_distance) /
319       (hypotD2(vertices[v], oncircle) + 1e-6);
320   }
321   return cost;
322 }
323
324 /*---------- noncircular rim cost ----------*/
325
326 double noncircular_rim_cost(const Vertices vertices, int section) {
327   int vy,vx,v;
328   double cost= 0.0;
329   double oncircle[3];
330
331   FOR_RIM_VERTEX(vy,vx,v, OUTER) {
332     find_nearest_oncircle(oncircle, vertices[v]);
333
334     double d2= hypotD2(vertices[v], oncircle);
335     cost += d2*d2;
336   }
337   return cost;
338 }
339
340 /*---------- overly sharp edge cost ----------*/
341
342   /*
343    *
344    *                Q `-_
345    *              / |    `-_                           P'Q' ------ S'
346    *             /  |       `-.                      _,' `.       .
347    *            /   |           S                 _,'     :      .
348    *           /    |      _,-'                _,'        :r    .r
349    *          /     |  _,-'                R' '           `.   .
350    *         /    , P '                        ` .   r     :  .
351    *        /  ,-'                                  `  .   : 
352    *       /,-'                                          ` C'
353    *      /'
354    *     R
355    *
356    *
357    *
358    *  Let delta =  angle between two triangles' normals
359    *
360    *  Giving energy contribution:
361    *
362    *                                   2
363    *    E             =  F   .  delta
364    *     vd, edge PQ      vd
365    */
366
367 double edge_angle_cost(const Vertices vertices, int section) {
368   double pq1[D3], rp[D3], ps[D3], rp_2d[D3], ps_2d[D3], rs_2d[D3];
369   double a,b,c,s,r;
370   const double minradius_base= 0.2;
371
372   int pi,e,qi,ri,si, k;
373 //  double our_epsilon=1e-6;
374   double total_cost= 0;
375
376   FOR_EDGE(pi,e,qi, OUTER) {
377 //    if (!(RIM_VERTEX_P(pi) || RIM_VERTEX_P(qi))) continue;
378
379     si= EDGE_END2(pi,(e+V6-1)%V6);  if (si<0) continue;
380     ri= EDGE_END2(pi,(e   +1)%V6);  if (ri<0) continue;
381
382     K {
383       pq1[k]= -vertices[pi][k] + vertices[qi][k];
384       rp[k]=  -vertices[ri][k] + vertices[pi][k];
385       ps[k]=  -vertices[pi][k] + vertices[si][k];
386     }
387
388     normalise(pq1,1,1e-6);
389     xprod(rp_2d, rp,pq1); /* projects RP into plane normal to PQ */
390     xprod(ps_2d, ps,pq1); /* likewise PS */
391     K rs_2d[k]= rp_2d[k] + ps_2d[k];
392     /* radius of circumcircle of R'P'S' from Wikipedia
393      * `Circumscribed circle' */
394     a= magnD(rp_2d);
395     b= magnD(ps_2d);
396     c= magnD(rs_2d);
397     s= 0.5*(a+b+c);
398     r= a*b*c / sqrt((a+b+c)*(a-b+c)*(b-c+a)*(c-a+b) + 1e-6);
399
400     double minradius= minradius_base + edge_angle_cost_circcircrat*(a+b);
401     double deficit= minradius - r;
402     if (deficit < 0) continue;
403     double cost= deficit*deficit;
404
405     total_cost += cost;
406   }
407
408   return total_cost;
409 }
410
411 /*---------- small triangles cost ----------*/
412
413   /*
414    *
415    *                Q `-_
416    *              / |    `-_
417    *             /  |       `-.
418    *            /   |           S
419    *           /    |      _,-'
420    *          /     |  _,-'
421    *         /    , P '
422    *        /  ,-'
423    *       /,-'
424    *      /'
425    *     R
426    *
427    *  Let delta =  angle between two triangles' normals
428    *
429    *  Giving energy contribution:
430    *
431    *                                   2
432    *    E             =  F   .  delta
433    *     vd, edge PQ      vd
434    */
435
436 double small_triangles_cost(const Vertices vertices, int section) {
437   double pq[D3], ps[D3];
438   double x[D3];
439   int pi,e,qi,si, k;
440 //  double our_epsilon=1e-6;
441   double total_cost= 0;
442
443   FOR_EDGE(pi,e,qi, OUTER) {
444 //    if (!(RIM_VERTEX_P(pi) || RIM_VERTEX_P(qi))) continue;
445
446     si= EDGE_END2(pi,(e+V6-1)%V6);  if (si<0) continue;
447
448     K {
449       pq[k]= vertices[qi][k] - vertices[pi][k];
450       ps[k]= vertices[si][k] - vertices[pi][k];
451     }
452     xprod(x, pq,ps);
453
454     double cost= 1/(magnD2(x) + 0.01);
455
456 //double cost= pow(magnD(spqxpqr), 3);
457 //assert(dot>=-1 && dot <=1);
458 //double cost= 1-dot;
459     total_cost += cost;
460   }
461
462   return total_cost;
463 }