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