chiark / gitweb /
reorganisation is complete, need to implement various things, make it compile, etc.
[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 #define BEST_F "best"
10 #define INITIAL_F "initial"
11
12 static double edgewise_vertex_displacement_cost(const Vertices vertices);
13
14 static void compute_vertex_areas(const Vertices vertices, double areas[N]);
15 static double best_energy= DOUBLE_MAX;
16 static void flushoutput(void);
17
18 static void cost(double *energy, double tweight, double tcost);
19 #define COST(weight, compute) cost(&energy, (weight), (compute))
20
21 /*---------- main energy computation and subroutines ----------*/
22
23 static double compute_energy(Vertices vertices) {
24   double vertex_areas[N], energy;
25
26   compute_vertex_areas(vertices,vertex_areas);
27   energy= 0;
28   printf("cost > energy |");
29
30   COST(1000.0, edgewise_vertex_displacement_cost(vertices));
31   COST(1.0,    graph_layout_cost(vertices,vertex_areas));
32   COST(1e6,    noncircular_edge_cost(vertices));
33   
34   printf("| total %# e |", energy);
35   if (energy < best_energy) {
36     FILE *best;
37     printf(" BEST");
38     
39     best_f= fopen(BEST_F ".new","wb");  if (!best_f) diee("fopen new best");
40     r= fwrite(vertices,sizeof(vertices),1,best_f); if (r!=1) diee("fwrite");
41     if (fclose(best_f)) diee("fclose new best");
42     if (rename(BEST_F ".new", BEST_F)) diee("rename install new best");
43   }
44   putchar('\n');
45   flushoutput();
46
47   return energy;
48 }    
49
50 static void cost(double *energy, double tweight, double tcost) {
51   double tenergy= tweight * tcost;
52   printf(" %# e > %# e |", tcost, tenergy);
53   *energy += tenergy;
54 }
55
56 static void flushoutput(void) {
57   if (fflush(stdout) || ferror(stdout)) { perror("stdout"); exit(-1); }
58 }
59
60 static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
61   FOR_VERTEX(v0) {
62     double total= 0.0;
63     int count= 0;
64     
65     FOR_VEDGE(v0,e1,v1) {
66       e2= (e1+1) % V6;
67       v2= EDGE_END2(v0,e2);
68       if (v2<0) continue;
69       
70       double e1v[D3], e2v[D3], av[D3];
71       K {
72         e1v[k]= vertices[v1][k] - vertices[v0][k];
73         e2v[k]= vertices[v2][k] - vertices[v0][k];
74       }
75       xprod(av, e1v, e2v);
76       total += hypotD1(av);
77       count++;
78     }
79     areas[v0]= total / count;
80   }
81 }
82
83 /*---------- use of GSL ----------*/
84
85   /* We want to do multidimensional minimisation.
86    *
87    * We don't think there are any local minima.  Or at least, if there
88    * are, the local minimum which will be found from the starting
89    * state is the one we want.
90    *
91    * We don't want to try to provide a derivative of the cost
92    * function.  That's too tedious (and anyway the polynomial
93    * approximation to our our cost function sometimes has high degree
94    * in the inputs which means the quadratic model implied by most of
95    * the gradient descent minimisers is not ideal).
96    *
97    * This eliminates most of the algorithms.  Nelder and Mead's
98    * simplex algorithm is still available and we will try that.
99    *
100    * In our application we are searching for the optimal locations of
101    * N actualvertices in D3 (3) dimensions - ie, we are searching for
102    * the optimal metapoint in an N*D3-dimensional space.
103    * 
104    * So eg with X=Y=100, the simplex will contain 300 metavertices
105    * each of which is an array of 300 doubles for the actualvertex
106    * coordinates.  Hopefully this won't be too slow ...
107    */
108
109 static void gsldie(const char *what, int status) {
110   fprintf(stderr,"gsl function failed: %s: %s\n", what, gsl_strerror(status));
111   exit(-1);
112 }
113
114 static gsl_multimin_fminimizer *minimiser;
115
116 static const stop_epsilon= 1e-4;
117
118 #define DIM (N*D3)
119
120 static double minfunc_f(const gsl_vector *x, void *params) {
121   assert(x->size == DIM);
122   assert(x->stride == 1);
123   return compute_energy((Vertices)x->data);
124 }
125
126 int main(int argc, const char *const *argv) {
127   struct gsl_multimin_function multimin_function;
128   double size;
129   Vertices initial;
130   FILE *initial;
131   gsl_vector initial_gsl, *step_size;
132   int r;
133   
134   if (argc>1) { fputs("takes no arguments\n",stderr); exit(8); }
135
136   minimiser= gsl_multimin_fminimizer_alloc
137     (gsl_multimin_fminimizer_nmsimplex, DIM);
138   if (!minimiser) { perror("alloc minimiser"); exit(-1); }
139
140   multimin_function.f= minfunc_f;
141   multimin_function.n= DIM;
142   multimin_function.params= 0;
143
144   initial_f= fopen(INITIAL_F,"rb");  if (!initial_f) diee("fopen initial");
145   errno= 0; r= fread(initial,sizeof(initial),1,initial_f);
146   if (r!=1) diee("fread");
147   fclose(initial_f);
148
149   initial_gsl.size= DIM;
150   initial_gsl.stride= 1;
151   initial_gsl.data= initial;
152   initial_gsl.block= 0;
153   initial_gsl.owner= 0;
154
155   step_size= gsl_vector_alloc(DIM);  if (!step_size) gsldie("alloc step");
156   gsl_vector_set_all(step_size, 1e-3);
157
158   r= gsl_multimin_fminimizer_set(minimiser, &multimin_function,
159                                  &initial_gsl, &step_size);
160   if (r) { gsldie("fminimizer_set",r); }
161   
162   for (;;) {
163     r= gsl_multimin_fminimizer_iterate(minimiser);
164     if (r) { gsldie("fminimizer_iterate",r); }
165
166     size= gsl_multimin_fminimizer_size(minimiser);
167     r= gsl_multimin_test_size(size, stop_epsilon);
168
169     printf("size %# e, r=%d\n", size, r);
170     flushoutput();
171
172     if (r==GSL_SUCCESS) break;
173     assert(r==GSL_CONTINUE);
174   }
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 l3_epsison= 1e-6;
243
244   int pi,e,qi,ri,si, k;
245   double m[D3], mprime[D3], b, d2, l, sigma_bd2_l3;
246
247   FOR_EDGE(pi,e,qi) {
248     ri= EDGE_END2(pi,(e+1)%V6); if (r<0) continue;
249     si= EDGE_END2(pi,(e+5)%V6); if (s<0) continue;
250     assert(ri == EDGE_END2(qi,(e+2)%V6));
251     assert(si == EDGE_END2(qi,(e+4)%V6));
252     
253     K m[k]= (vertices[pi][k] + vertices[qi][k]) * 0.5;
254     K mprime[k]= (vertices[ri][k] + vertices[si][k]) * 0.5;
255     b= hypotD(vertices[pi], vertices[qi]);
256     d2= hypotD2(m, mprime);
257     l= hypotD(vertices[ri][k] - vertices[si][k]);
258     l3 = l*l*l + l3_epsilon;
259
260     sigma_bd2_l3 += b * d2 / l3;
261   }
262   return sigma_bd2_l3;
263 }