chiark / gitweb /
assertions are not true near the join
[moebius2.git] / energy.c
1 /*
2  * We try to find an optimal triangle grid
3  */
4
5 #include "common.h"
6 #include "bgl.h"
7 #include "mgraph.h"
8
9 #include <gsl/gsl_errno.h>
10 #include <gsl/gsl_multimin.h>
11
12 #define BEST_F "best"
13 #define INITIAL_F "initial"
14
15 static double edgewise_vertex_displacement_cost(const Vertices vertices);
16 static double noncircular_rim_cost(const Vertices vertices);
17
18 static void compute_vertex_areas(const Vertices vertices, double areas[N]);
19 static double best_energy= DBL_MAX;
20
21 static void cost(double *energy, double tweight, double tcost);
22 #define COST(weight, compute) cost(&energy, (weight), (compute))
23
24 /*---------- main energy computation and subroutines ----------*/
25
26 static double compute_energy(const Vertices vertices) {
27   double vertex_areas[N], energy;
28
29   compute_vertex_areas(vertices,vertex_areas);
30   energy= 0;
31   printf("cost > energy |");
32
33   COST(1000.0, edgewise_vertex_displacement_cost(vertices));
34   COST(1.0,    graph_layout_cost(vertices,vertex_areas));
35   COST(1e3,    noncircular_rim_cost(vertices));
36   
37   printf("| total %# e |", energy);
38   if (energy < best_energy) {
39     FILE *best_f;
40     int r;
41     
42     printf(" BEST");
43     
44     best_f= fopen(BEST_F ".new","wb");  if (!best_f) diee("fopen new best");
45     r= fwrite(vertices,sizeof(vertices),1,best_f); if (r!=1) diee("fwrite");
46     if (fclose(best_f)) diee("fclose new best");
47     if (rename(BEST_F ".new", BEST_F)) diee("rename install new best");
48   }
49   putchar('\n');
50   flushoutput();
51
52   return energy;
53 }    
54
55 static void cost(double *energy, double tweight, double tcost) {
56   double tenergy= tweight * tcost;
57   printf(" %# e > %# e |", tcost, tenergy);
58   *energy += tenergy;
59 }
60
61 static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
62   int v0,v1,v2, e1,e2, k;
63   
64   FOR_VERTEX(v0) {
65     double total= 0.0;
66     int count= 0;
67     
68     FOR_VEDGE(v0,e1,v1) {
69       e2= (e1+1) % V6;
70       v2= EDGE_END2(v0,e2);
71       if (v2<0) continue;
72       
73       double e1v[D3], e2v[D3], av[D3];
74       K {
75         e1v[k]= vertices[v1][k] - vertices[v0][k];
76         e2v[k]= vertices[v2][k] - vertices[v0][k];
77       }
78       xprod(av, e1v, e2v);
79       total += magnD(av);
80       count++;
81     }
82     areas[v0]= total / count;
83   }
84 }
85
86 /*---------- use of GSL ----------*/
87
88   /* We want to do multidimensional minimisation.
89    *
90    * We don't think there are any local minima.  Or at least, if there
91    * are, the local minimum which will be found from the starting
92    * state is the one we want.
93    *
94    * We don't want to try to provide a derivative of the cost
95    * function.  That's too tedious (and anyway the polynomial
96    * approximation to our our cost function sometimes has high degree
97    * in the inputs which means the quadratic model implied by most of
98    * the gradient descent minimisers is not ideal).
99    *
100    * This eliminates most of the algorithms.  Nelder and Mead's
101    * simplex algorithm is still available and we will try that.
102    *
103    * In our application we are searching for the optimal locations of
104    * N actualvertices in D3 (3) dimensions - ie, we are searching for
105    * the optimal metapoint in an N*D3-dimensional space.
106    * 
107    * So eg with X=Y=100, the simplex will contain 300 metavertices
108    * each of which is an array of 300 doubles for the actualvertex
109    * coordinates.  Hopefully this won't be too slow ...
110    */
111
112 static gsl_multimin_fminimizer *minimiser;
113
114 static const double stop_epsilon= 1e-4;
115
116 static double minfunc_f(const gsl_vector *x, void *params) {
117   assert(x->size == DIM);
118   assert(x->stride == 1);
119   return compute_energy((const double(*)[D3])x->data);
120 }
121
122 int main(int argc, const char *const *argv) {
123   gsl_multimin_function multimin_function;
124   double size;
125   Vertices initial, step_size;
126   FILE *initial_f;
127   gsl_vector initial_gsl, step_size_gsl;
128   int r, v, vx,vy, k;
129   
130   if (argc>1) { fputs("takes no arguments\n",stderr); exit(8); }
131
132   minimiser= gsl_multimin_fminimizer_alloc
133     (gsl_multimin_fminimizer_nmsimplex, DIM);
134   if (!minimiser) { perror("alloc minimiser"); exit(-1); }
135
136   multimin_function.f= minfunc_f;
137   multimin_function.n= DIM;
138   multimin_function.params= 0;
139
140   initial_f= fopen(INITIAL_F,"rb");  if (!initial_f) diee("fopen initial");
141   errno= 0; r= fread(initial,sizeof(initial),1,initial_f);
142   if (r!=1) diee("fread");
143   fclose(initial_f);
144
145   initial_gsl.size= DIM;
146   initial_gsl.stride= 1;
147   initial_gsl.block= 0;
148   initial_gsl.owner= 0;
149   step_size_gsl= initial_gsl;
150
151   initial_gsl.data= (double*)initial;
152   step_size_gsl.data= (double*)step_size;
153
154   FOR_VERTEX(v)
155     K step_size[v][k]= 1e-3;
156   FOR_RIM_VERTEX(vx,vy,v)
157     step_size[v][3] *= 0.1;
158
159   GA( gsl_multimin_fminimizer_set(minimiser, &multimin_function,
160                                   &initial_gsl, &step_size_gsl) );
161   
162   for (;;) {
163     GA( gsl_multimin_fminimizer_iterate(minimiser) );
164
165     size= gsl_multimin_fminimizer_size(minimiser);
166     r= gsl_multimin_test_size(size, stop_epsilon);
167
168     printf("size %# e, r=%d\n", size, r);
169     flushoutput();
170
171     if (r==GSL_SUCCESS) break;
172     assert(r==GSL_CONTINUE);
173   }
174   return 0;
175 }
176
177 /*---------- Edgewise vertex displacement ----------*/
178
179   /*
180    *  
181    *
182    *
183    *                Q `-_
184    *              / |    `-_
185    *   R' - _ _ _/_ |       `-.
186    *    .       /   M - - - - - S
187    *    .      /    |      _,-'
188    *    .     /     |  _,-'
189    *    .    /    , P '
190    *    .   /  ,-'
191    *    .  /,-'
192    *    . /'
193    *     R
194    *
195    *
196    *
197    *  Find R', the `expected' location of R, by
198    *  reflecting S in M (the midpoint of QP).
199    *
200    *  Let 2d = |RR'|
201    *       b = |PQ|
202    *       l = |RS|
203    *
204    *  Giving energy contribution:
205    *
206    *                               2
207    *                            b d
208    *    E             =  F   .  ----
209    *     vd, edge PQ      vd      3
210    *                             l
211    *
212    *  (The dimensions of this are those of F_vd.)
213    *
214    *  By symmetry, this calculation gives the same answer with R and S
215    *  exchanged.  Looking at the projection in the RMS plane:
216    *
217    *
218    *                           S'
219    *                         ,'
220    *                       ,'
221    *    R'               ,'             2d" = |SS'| = |RR'| = 2d
222    *      `-._         ,'
223    *          `-._   ,'                 By congruent triangles,
224    *              ` M                   with M' = midpoint of RS,
225    *              ,'  `-._              |MM'| = |RR'|/2 = d
226    *            ,'        `-._
227    *          ,'              ` S       So use
228    *        ,'       M' _ , - '            d = |MM'|
229    *      ,'   _ , - '
230    *     R - '
231    *
232    *  We choose this value for l (rather than |RM|+|MS|, say, or |RM|)
233    *  because we want this symmetry and because we're happy to punish
234    *  bending more than uneveness in the metric.
235    *
236    *  In practice to avoid division by zero we'll add epsilon to l^3
237    *  and the huge energy ought then to be sufficient for the model to
238    *  avoid being close to R=S.
239    */
240
241 static double edgewise_vertex_displacement_cost(const Vertices vertices) {
242   static const double l3_epsilon= 1e-6;
243
244   int pi,e,qi,ri,si, k;
245   double m[D3], mprime[D3], b, d2, l, sigma_bd2_l3=0;
246
247   FOR_EDGE(pi,e,qi) {
248     ri= EDGE_END2(pi,(e+1)%V6); if (ri<0) continue;
249     si= EDGE_END2(pi,(e+5)%V6); if (si<0) continue;
250     
251     K m[k]= (vertices[pi][k] + vertices[qi][k]) * 0.5;
252     K mprime[k]= (vertices[ri][k] + vertices[si][k]) * 0.5;
253     b= hypotD(vertices[pi], vertices[qi]);
254     d2= hypotD2(m, mprime);
255     l= hypotD(vertices[ri], vertices[si]);
256     double l3 = l*l*l + l3_epsilon;
257
258     sigma_bd2_l3 += b * d2 / l3;
259   }
260   return sigma_bd2_l3;
261 }
262
263 /*---------- noncircular rim cost ----------*/
264
265 static double noncircular_rim_cost(const Vertices vertices) {
266   int vy,vx,v;
267   double cost= 0.0;
268   
269   FOR_RIM_VERTEX(vy,vx,v) {
270     double oncircle[3];
271     /* By symmetry, nearest point on circle is the one with
272      * the same angle subtended at the z axis. */
273     oncircle[0]= vertices[v][0];
274     oncircle[1]= vertices[v][1];
275     oncircle[2]= 0;
276     double mult= 1.0/ magnD(oncircle);
277     oncircle[0] *= mult;
278     oncircle[1] *= mult;
279     double d2= hypotD2(vertices[v], oncircle);
280     cost += d2*d2;
281   }
282   return cost;
283 }