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