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