chiark / gitweb /
78b8f31ff44be4942efb40cb91f61d21718217b2
[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
9 #include <gsl/gsl_errno.h>
10 #include <gsl/gsl_multimin.h>
11
12 #include <signal.h>
13 #include <sys/time.h>
14
15 static const char *input_file, *output_file;
16 static char *output_file_tmp;
17
18 static void compute_vertex_areas(const Vertices vertices, double areas[N]);
19 static double best_energy= DBL_MAX;
20
21 enum printing_instance { pr_cost, pr_size, pr__max };
22
23 static void addcost(double *energy, double tweight, double tcost, int pr);
24 #define COST(weight, compute) addcost(&energy, (weight), (compute), printing)
25 static int printing_check(enum printing_instance);
26 static void printing_init(void);
27
28 /*---------- main energy computation and subroutines ----------*/
29
30 static double compute_energy(const Vertices vertices) {
31   double vertex_areas[N], energy;
32   int printing;
33
34   compute_vertex_areas(vertices,vertex_areas);
35   energy= 0;
36
37   printing= printing_check(pr_cost);
38
39   if (printing) printf("cost > energy |");
40
41   COST(1e2, edgewise_vertex_displacement_cost(vertices));
42   COST(1e2, graph_layout_cost(vertices,vertex_areas));
43 //  COST(1e4, noncircular_rim_cost(vertices));
44
45   if (printing) printf("| total %# e |", energy);
46
47   if (energy < best_energy) {
48     FILE *best_f;
49     int r;
50
51     if (printing) printf(" BEST");
52
53     best_f= fopen(output_file_tmp,"wb");  if (!best_f) diee("fopen new out");
54     r= fwrite(vertices,sizeof(Vertices),1,best_f); if (r!=1) diee("fwrite");
55     if (fclose(best_f)) diee("fclose new best");
56     if (rename(output_file_tmp,output_file)) diee("rename install new best");
57
58     best_energy= energy;
59   }
60   if (printing) {
61     putchar('\n');
62     flushoutput();
63   }
64
65   return energy;
66 }
67
68 static void addcost(double *energy, double tweight, double tcost, int pr) {
69   double tenergy= tweight * tcost;
70   if (pr) printf(" %# e > %# e |", tcost, tenergy);
71   *energy += tenergy;
72 }
73
74 static void compute_vertex_areas(const Vertices vertices, double areas[N]) {
75   int v0,v1,v2, e1,e2, k;
76
77   FOR_VERTEX(v0) {
78     double total= 0.0;
79     int count= 0;
80
81     FOR_VEDGE(v0,e1,v1) {
82       e2= (e1+1) % V6;
83       v2= EDGE_END2(v0,e2);
84       if (v2<0) continue;
85
86       double e1v[D3], e2v[D3], av[D3];
87       K {
88         e1v[k]= vertices[v1][k] - vertices[v0][k];
89         e2v[k]= vertices[v2][k] - vertices[v0][k];
90       }
91       xprod(av, e1v, e2v);
92       total += magnD(av);
93       count++;
94     }
95     areas[v0]= total / count;
96   }
97 }
98
99 /*---------- use of GSL ----------*/
100
101   /* We want to do multidimensional minimisation.
102    *
103    * We don't think there are any local minima.  Or at least, if there
104    * are, the local minimum which will be found from the starting
105    * state is the one we want.
106    *
107    * We don't want to try to provide a derivative of the cost
108    * function.  That's too tedious (and anyway the polynomial
109    * approximation to our our cost function sometimes has high degree
110    * in the inputs which means the quadratic model implied by most of
111    * the gradient descent minimisers is not ideal).
112    *
113    * This eliminates most of the algorithms.  Nelder and Mead's
114    * simplex algorithm is still available and we will try that.
115    *
116    * In our application we are searching for the optimal locations of
117    * N actualvertices in D3 (3) dimensions - ie, we are searching for
118    * the optimal metapoint in an N*D3-dimensional space.
119    *
120    * So eg with X=Y=100, the simplex will contain 300 metavertices
121    * each of which is an array of 300 doubles for the actualvertex
122    * coordinates.  Hopefully this won't be too slow ...
123    */
124
125 static gsl_multimin_fminimizer *minimiser;
126
127 static const double stop_epsilon= 1e-6;
128
129 static double minfunc_f(const gsl_vector *x, void *params) {
130   assert(x->size == DIM);
131   assert(x->stride == 1);
132   return compute_energy((const double(*)[D3])x->data);
133 }
134
135 int main(int argc, const char *const *argv) {
136   gsl_multimin_function multimin_function;
137   double size;
138   Vertices initial, step_size;
139   FILE *initial_f;
140   gsl_vector initial_gsl, step_size_gsl;
141   int r, v, k;
142
143   if (argc!=3 || argv[1][0]=='-' || strncmp(argv[2],"-o",2))
144     { fputs("usage: minimise <input> -o<output\n",stderr); exit(8); }
145
146   input_file= argv[1];
147   output_file= argv[2]+2;
148   if (asprintf(&output_file_tmp,"%s.new",output_file) <= 0) diee("asprintf");
149
150   graph_layout_prepare();
151   printing_init();
152   
153   minimiser= gsl_multimin_fminimizer_alloc
154     (gsl_multimin_fminimizer_nmsimplex, DIM);
155   if (!minimiser) { perror("alloc minimiser"); exit(-1); }
156
157   multimin_function.f= minfunc_f;
158   multimin_function.n= DIM;
159   multimin_function.params= 0;
160
161   initial_f= fopen(input_file,"rb");  if (!initial_f) diee("fopen initial");
162   errno= 0; r= fread(initial,sizeof(initial),1,initial_f);
163   if (r!=1) diee("fread");
164   fclose(initial_f);
165
166   initial_gsl.size= DIM;
167   initial_gsl.stride= 1;
168   initial_gsl.block= 0;
169   initial_gsl.owner= 0;
170   step_size_gsl= initial_gsl;
171
172   initial_gsl.data= &initial[0][0];
173   step_size_gsl.data= &step_size[0][0];
174
175   FOR_VERTEX(v)
176     K step_size[v][k]= 0.03;
177 //int vx,vy;
178 //  FOR_RIM_VERTEX(vx,vy,v)
179 //    step_size[v][3] *= 0.1;
180
181   GA( gsl_multimin_fminimizer_set(minimiser, &multimin_function,
182                                   &initial_gsl, &step_size_gsl) );
183
184   for (;;) {
185     GA( gsl_multimin_fminimizer_iterate(minimiser) );
186
187     size= gsl_multimin_fminimizer_size(minimiser);
188     r= gsl_multimin_test_size(size, stop_epsilon);
189
190     if (printing_check(pr_size))
191       printf("%*s size %# e, r=%d\n", 135,"", size, r);
192     flushoutput();
193
194     if (r==GSL_SUCCESS) break;
195     assert(r==GSL_CONTINUE);
196   }
197   return 0;
198 }
199
200 /*---------- Edgewise vertex displacement ----------*/
201
202   /*
203    *
204    *
205    *
206    *                Q `-_
207    *              / |    `-_
208    *             /  |       `-.
209    *            /   M - - - - - S
210    *           /  ' |      _,-'
211    *          /  '  |  _,-'
212    *         / '  , P '
213    *        / ',-'
214    *       /,-'
215    *      /'
216    *     R
217    *
218    *  Let delta =  180deg - angle RMS
219    *
220    *  Let  l = |PQ|
221    *       d = |RS|
222    *
223    *  Giving energy contribution:
224    *
225    *                                   3
226    *                            l delta
227    *    E             =  F   .  --------
228    *     vd, edge PQ      vd       d
229    *
230    *
231    *  (The dimensions of this are those of F_vd.)
232    *
233    *  We calculate delta as  atan2(|AxB|, A.B)
234    *  where A = PQ, B = QR
235    *
236    *  In practice to avoid division by zero we'll add epsilon to d and
237    *  |AxB| and the huge energy ought then to be sufficient for the
238    *  model to avoid being close to R=S.
239    */
240
241 double edgewise_vertex_displacement_cost(const Vertices vertices) {
242   static const double axb_epsilon= 1e-6;
243
244   int pi,e,qi,ri, k; //,si
245   double  a[D3], b[D3], axb[D3]; //m[D3],
246   double total_cost= 0;
247
248   FOR_EDGE(qi,e,ri) {
249     pi= EDGE_END2(qi,(e+3)%V6); if (pi<0) continue;
250
251 //    K m[k]= (vertices[pi][k] + vertices[qi][k]) * 0.5;
252     K a[k]= -vertices[pi][k] + vertices[qi][k];
253     K b[k]= -vertices[qi][k] + vertices[ri][k];
254
255     xprod(axb,a,b);
256     
257     double delta= atan2(magnD(axb) + axb_epsilon, dotprod(a,b));
258     double cost= pow(delta,3);
259
260     if (!e && !(qi & YMASK))
261       cost *= 10;
262
263     total_cost += cost;
264   }
265   return total_cost;
266 }
267
268 /*---------- noncircular rim cost ----------*/
269
270 double noncircular_rim_cost(const Vertices vertices) {
271   int vy,vx,v;
272   double cost= 0.0;
273
274   FOR_RIM_VERTEX(vy,vx,v) {
275     double oncircle[3];
276     /* By symmetry, nearest point on circle is the one with
277      * the same angle subtended at the z axis. */
278     oncircle[0]= vertices[v][0];
279     oncircle[1]= vertices[v][1];
280     oncircle[2]= 0;
281     double mult= 1.0/ magnD(oncircle);
282     oncircle[0] *= mult;
283     oncircle[1] *= mult;
284     double d2= hypotD2(vertices[v], oncircle);
285     cost += d2*d2;
286   }
287   return cost;
288 }
289
290 /*---------- printing rate limit ----------*/
291
292 static volatile unsigned print_todo;
293 static sigset_t print_alarmset;
294
295 static int printing_check(enum printing_instance which) {
296   static int skipped[pr__max];
297   
298   unsigned bits= 1u << which;
299   int sk;
300
301   if (!(print_todo & bits)) {
302     skipped[which]++;
303     return 0;;
304   }
305
306   sigprocmask(SIG_BLOCK,&print_alarmset,0);
307   print_todo &= ~bits;
308   sigprocmask(SIG_UNBLOCK,&print_alarmset,0);
309
310   sk= skipped[which];
311   if (sk) printf("[%4d] ",sk);
312   else printf("       ");
313   skipped[which]= 0;
314
315   return 1;
316 }
317
318 static void alarmhandler(int ignored) {
319   print_todo= ~0u;
320 }
321
322 static void printing_init(void) {
323   struct sigaction sa;
324   struct itimerval itv;
325
326   sigemptyset(&print_alarmset);
327   sigaddset(&print_alarmset,SIGALRM);
328
329   sa.sa_handler= alarmhandler;
330   sa.sa_mask= print_alarmset;
331   sa.sa_flags= SA_RESTART;
332   if (sigaction(SIGALRM,&sa,0)) diee("sigaction ALRM");
333   
334   itv.it_interval.tv_sec= 0;
335   itv.it_interval.tv_usec= 200000;
336   itv.it_value= itv.it_interval;
337
338   if (setitimer(ITIMER_REAL,&itv,0)) diee("setitimer REAL");
339
340   raise(SIGALRM);
341 }