chiark / gitweb /
fixed XBITS==4
[moebius2.git] / minimise.c
1 /*
2  * use of GSL
3  */
4
5   /* We want to do multidimensional minimisation.
6    *
7    * We don't think there are any local minima.  Or at least, if there
8    * are, the local minimum which will be found from the starting
9    * state is the one we want.
10    *
11    * We don't want to try to provide a derivative of the cost
12    * function.  That's too tedious (and anyway the polynomial
13    * approximation to our our cost function sometimes has high degree
14    * in the inputs which means the quadratic model implied by most of
15    * the gradient descent minimisers is not ideal).
16    *
17    * This eliminates most of the algorithms.  Nelder and Mead's
18    * simplex algorithm is still available and we will try that.
19    *
20    * In our application we are searching for the optimal locations of
21    * N actualvertices in D3 (3) dimensions - ie, we are searching for
22    * the optimal metapoint in an N*D3-dimensional space.
23    *
24    * So eg with X=Y=100, the simplex will contain 300 metavertices
25    * each of which is an array of 300 doubles for the actualvertex
26    * coordinates.  Hopefully this won't be too slow ...
27    */
28
29 #include "common.h"
30
31 #include <gsl/gsl_errno.h>
32 #include <gsl/gsl_multimin.h>
33
34 #include <signal.h>
35 #include <sys/time.h>
36
37 #include "half.h"
38 #include "minimise.h"
39
40 const char *input_file, *best_file;
41 char *best_file_tmp;
42 long long evaluations;
43 double stop_epsilon= 1e-20;
44
45 static void printing_init(void);
46
47 static gsl_multimin_fminimizer *minimiser;
48 static const char *final_file;
49 static char *final_file_tmp;
50
51 static double minfunc_f(const gsl_vector *x, void *params) {
52   struct Vertices vs;
53   
54   assert(x->size == DIM);
55   assert(x->stride == 1);
56   map_dimensions(x->data, vs.a);
57   return compute_energy(&vs);
58 }
59
60 static void badusage(void) {
61   fputs("usage: minimise <input> [-i<intermediate>] -o<output\n",stderr);
62   exit(8);
63 }
64
65 static sig_atomic_t quit_requested;
66
67 static void sigint_handler(int ignored) {
68   quit_requested= 1;
69 }
70
71 int main(int argc, const char *const *argv) {
72   gsl_multimin_function multimin_function;
73   double size;
74   struct Vertices initial_full;
75   double initial_half[DIM], step_size[DIM];
76   FILE *initial_f;
77   gsl_vector initial_gsl, step_size_gsl;
78   int r, i, size_check_counter= 0;
79   struct sigaction sa;
80
81   if (argc==3) {
82     input_file= argv[1];
83     if (strncmp(argv[2],"-o",2)) badusage();   best_file= argv[2]+2;
84     final_file= 0;
85   } else if (argc==4) {
86     input_file= argv[1];
87     if (strncmp(argv[2],"-i",2)) badusage();   best_file= argv[2]+2;
88     if (strncmp(argv[3],"-o",2)) badusage();   final_file= argv[3]+2;
89   } else {
90     badusage();
91   }
92   if (argv[1][0]=='-') badusage();
93
94   if (asprintf(&best_file_tmp,"%s.new",best_file) <= 0) diee("asprintf");
95   if (final_file)
96     if (asprintf(&final_file_tmp,"%s.new",final_file) <= 0) diee("asprintf");
97
98   memset(&sa,0,sizeof(sa));
99   sa.sa_handler= sigint_handler;
100   sa.sa_flags= SA_RESETHAND;
101   r= sigaction(SIGINT,&sa,0);
102   if (r) diee("sigaction SIGINT");
103
104   mgraph_prepare();
105   graph_layout_prepare();
106   printing_init();
107   energy_init();
108
109   printf("X=%d=0x%x  Y=%d=0x%x  DIM=%d\n",X,X,Y,Y,DIM);
110   
111   minimiser= gsl_multimin_fminimizer_alloc
112     (gsl_multimin_fminimizer_nmsimplex, DIM);
113   if (!minimiser) { perror("alloc minimiser"); exit(-1); }
114
115   multimin_function.f= minfunc_f;
116   multimin_function.n= DIM;
117   multimin_function.params= 0;
118
119   initial_f= fopen(input_file,"rb");  if (!initial_f) diee("fopen initial");
120   errno= 0; r= fread(&initial_full,sizeof(initial_full),1,initial_f);
121   if (r!=1) diee("fread");
122   fclose(initial_f);
123
124   pmap_dimensions(&initial_full);
125   unmap_dimensions(initial_half,&initial_full);
126   for (i=0; i<DIM; i++) step_size[i]= 0.03;
127
128   initial_gsl.size= DIM;
129   initial_gsl.stride= 1;
130   initial_gsl.block= 0;
131   initial_gsl.owner= 0;
132   step_size_gsl= initial_gsl;
133
134   initial_gsl.data= initial_half;
135   step_size_gsl.data= step_size;
136
137   GA( gsl_multimin_fminimizer_set(minimiser, &multimin_function,
138                                   &initial_gsl, &step_size_gsl) );
139
140   for (;;) {
141     if (quit_requested) {
142       fprintf(stderr,"SIGINT caught.\n");
143       exit(1);
144     }
145
146     GA( gsl_multimin_fminimizer_iterate(minimiser) );
147
148     if (!(size_check_counter++ % DIM)) {
149       size= gsl_multimin_fminimizer_size(minimiser);
150       r= gsl_multimin_test_size(size, stop_epsilon);
151
152       if (printing_check(pr_size,215))
153         printf("r=%2d, size %# e\n", r, size);
154       flushoutput();
155
156       if (r==GSL_SUCCESS) break;
157       assert(r==GSL_CONTINUE);
158     }
159   }
160
161   if (final_file) {
162     if (unlink(final_file_tmp) && errno != ENOENT) diee("unlink final .tmp");
163     if (link(best_file,final_file_tmp)) diee("link final .tmp");
164     if (rename(final_file_tmp,final_file)) diee("install final");
165   }
166   printf("FINISHED (%lld evaluations)\n",evaluations);
167   
168   return 0;
169 }
170
171 /*---------- printing rate limit ----------*/
172
173 static volatile unsigned print_todo;
174 static sigset_t print_alarmset;
175
176 int printing_check(enum printing_instance which, int indent) {
177   static int skipped[pr__max];
178   
179   unsigned bits= 1u << which;
180   int sk;
181
182   if (!(print_todo & bits)) {
183     skipped[which]++;
184     return 0;;
185   }
186
187   sigprocmask(SIG_BLOCK,&print_alarmset,0);
188   print_todo &= ~bits;
189   sigprocmask(SIG_UNBLOCK,&print_alarmset,0);
190
191   printf("%*s",indent,"");
192   sk= skipped[which];
193   if (sk) printf("[%4d] ",sk);
194   else printf("      ");
195   skipped[which]= 0;
196
197   return 1;
198 }
199
200 static void alarmhandler(int ignored) {
201   print_todo= ~0u;
202 }
203
204 static void printing_init(void) {
205   struct sigaction sa;
206   struct itimerval itv;
207
208   sigemptyset(&print_alarmset);
209   sigaddset(&print_alarmset,SIGALRM);
210
211   sa.sa_handler= alarmhandler;
212   sa.sa_mask= print_alarmset;
213   sa.sa_flags= SA_RESTART;
214   if (sigaction(SIGALRM,&sa,0)) diee("sigaction ALRM");
215   
216   itv.it_interval.tv_sec= 0;
217   itv.it_interval.tv_usec= 200000;
218   itv.it_value= itv.it_interval;
219
220   if (setitimer(ITIMER_REAL,&itv,0)) diee("setitimer REAL");
221
222   raise(SIGALRM);
223 }