chiark / gitweb /
break out set_best
[matchsticks-search.git] / main.c
1 /*
2  * Searches for "good" ways to divide n matchsticks up and reassemble them
3  * into m matchsticks.  "Good" means the smallest fragment is as big
4  * as possible.
5  *
6  * Invoke as   ./main n m
7  *
8  * The algorithm is faster if the arguments are ordered so that n > m.
9  */
10
11 /*
12  * matchsticks/main.c  Copyright 2014 Ian Jackson
13  *
14  * This program is free software: you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation, either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  */
24
25 #define _GNU_SOURCE
26
27 #include <publib.h>
28
29 #include <stdio.h>
30 #include <stdint.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <assert.h>
34 #include <unistd.h>
35 #include <stdbool.h>
36 #include <inttypes.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <sys/uio.h>
40 #include <sys/fcntl.h>
41
42 #include <glpk.h>
43
44 /*
45  * Algorithm.
46  *
47  * Each input match contributes, or does not contribute, to each
48  * output match; we do not need to consider multiple fragments
49  * relating to the same input/output pair this gives an n*m adjacency
50  * matrix (bitmap).  Given such an adjacency matrix, the problem of
51  * finding the best sizes for the fragments can be expressed as a
52  * linear programming problem.
53  *
54  * We search all possible adjacency matrices, and for each one we run
55  * GLPK's simplex solver.  We represent the adjacency matrix as an
56  * array of bitmaps.
57  *
58  * However, there are a couple of wrinkles:
59  *
60  * To best represent the problem as a standard LP problem, we separate
61  * out the size of each fragment into a common minimum size variable,
62  * plus a fragment-specific extra size variable.  This reduces the LP
63  * problem size at the cost of making the problem construction, and
64  * interpretation of the results, a bit fiddly.
65  *
66  * Many of the adjacency matrices are equivalent.  In particular,
67  * permutations of the columns, or of the rows, do not change the
68  * meaning.  It is only necessasry to consider any one permutation.
69  * We make use of this by considering only adjacency matrices whose
70  * bitmap array contains bitmap words whose numerical values are
71  * nondecreasing in array order.
72  *
73  * Once we have a solution, we also avoid considering any candidate
74  * which involves dividing one of the output sticks into so many
75  * fragment that the smallest fragment would necessarily be no bigger
76  * than our best solution.  That is, we reject candidates where any of
77  * the hamming weights of the adjacency bitmap words are too large.
78  *
79  * And, we want to do the search in order of increasing maximum
80  * hamming weight.  This is because in practice optimal solutions tend
81  * to have low hamming weight, and having found a reasonable solution
82  * early allows us to eliminate a lot of candidates without doing the
83  * full LP.
84  */
85
86 typedef uint32_t AdjWord;
87 #define PRADJ "08"PRIx32
88
89 static int n, m, maxhamweight;
90 static AdjWord *adjmatrix;
91 static AdjWord adjall;
92
93 static double best;
94 static glp_prob *best_prob;
95 static AdjWord *best_adjmatrix;
96
97 static unsigned printcounter;
98
99 static void iterate(void);
100 static void iterate_recurse(int i, AdjWord min);
101 static bool preconsider_ok(int nwords, bool doprint);
102 static bool maxhamweight_ok(void);
103 static void optimise(bool doprint);
104
105 static void progress_eol(void) {
106   fprintf(stderr,"        \r");
107   fflush(stderr);
108 }
109
110 static void set_best(double new_best) {
111   best = new_best;
112 }
113
114 /*----- multicore support -----*/
115
116 /*
117  * Multicore protocol
118  *
119  * We fork into:
120  *   - master (parent)
121  *   - generator
122  *   - ncpu workers
123  *
124  * ipc facilities:
125  *   - one pipe ("work") from generator to workers
126  *   - ever-extending file ("bus") containing new "best" values
127  *   - one file for each worker giving maxhamweight and adjmatrix for best
128  *
129  * generator runs iterate_recurse to a certain depth and writes the
130  * candidates to a pipe
131  *
132  * workers read candidates from the pipe and resume iterate_recurse
133  * halfway through the recursion
134  *
135  * whenever a worker does a doprint, it checks the bus for new best
136  * value; actual best values are appended
137  *
138  * master waits for generator and all workers to finish and then
139  * runs optimise() for each worker's best, then prints
140  */ 
141
142 static int ncpus = 0, multicore_iteration_boundary = INT_MAX;
143
144 static int mc_bus, mc_work[2];
145 static off_t mc_bus_read;
146
147 typedef struct {
148   int w;
149   FILE *results;
150   pid_t pid;
151 } Worker;
152 static Worker *mc_us;
153
154 static void multicore_check_for_new_best(void);
155
156 #define MAX_NIOVS 3
157 static AdjWord mc_iter_min;
158 static int mc_niovs;
159 static size_t mc_iovlen;
160 static struct iovec mc_iov[MAX_NIOVS];
161
162 #define IOV0 (mc_niovs = mc_iovlen = 0)
163
164 #define IOV(obj, count) ({                              \
165     assert(mc_niovs < MAX_NIOVS);                       \
166     mc_iov[mc_niovs].iov_base = &(obj);                 \
167     mc_iov[mc_niovs].iov_len = sizeof(obj) * (count);   \
168     mc_iovlen += mc_iov[mc_niovs].iov_len;              \
169     mc_niovs++;                                         \
170   })
171
172 static void mc_rwvsetup_outer(void) {
173   IOV0;
174   IOV(maxhamweight, 1);
175   IOV(mc_iter_min, 1);
176   IOV(*adjmatrix, multicore_iteration_boundary);
177 }
178
179 static void mc_rwvsetup_full(void) {
180   IOV0;
181   IOV(*adjmatrix, n);
182 }
183
184 static void vlprintf(const char *fmt, va_list al) {
185   vfprintf(stderr,fmt,al);
186   progress_eol();
187 }
188
189 static void LPRINTF(const char *fmt, ...) {
190   va_list al;
191   va_start(al,fmt);
192   vlprintf(fmt,al);
193   va_end(al);
194 }
195
196 static void mc_awaitpid(int wnum, pid_t pid) {
197   LPRINTF("master awaiting %2d [%ld]",wnum,(long)pid);
198   int status;
199   pid_t got = waitpid(pid, &status, 0);
200   assert(got == pid);
201   if (status) {
202     fprintf(stderr,"\nFAILED SUBPROC %2d [%ld] %d\n",
203             wnum, (long)pid, status);
204     exit(-1);
205   }
206 }
207
208 static void multicore_outer_iteration(int i, AdjWord min) {
209   static unsigned check_counter;
210
211   assert(i == multicore_iteration_boundary);
212   mc_iter_min = min;
213   mc_rwvsetup_outer();
214   ssize_t r = writev(mc_work[1], mc_iov, mc_niovs);
215   assert(r == mc_iovlen);
216   /* effectively, this writev arranges to transfers control
217    * to some worker's instance of iterate_recurse via mc_iterate_worker */
218
219   if (!(check_counter++ & 0xff))
220     multicore_check_for_new_best();
221 }
222
223 static void mc_iterate_worker(void) {
224   for (;;) {
225     mc_rwvsetup_outer();
226     ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
227     if (r == 0) break;
228     assert(r == mc_iovlen);
229     
230     bool ok = maxhamweight_ok();
231     if (!ok) continue;
232
233     ok = preconsider_ok(multicore_iteration_boundary, 1);
234     progress_eol();
235     if (!ok) continue;
236
237     /* stop iterate_recurse from trying to run multicore_outer_iteration */
238     int mc_org_it_bound = multicore_iteration_boundary;
239     multicore_iteration_boundary = INT_MAX;
240     iterate_recurse(mc_org_it_bound, mc_iter_min);
241     multicore_iteration_boundary = mc_org_it_bound;
242   }
243   LPRINTF("worker %2d reporting",mc_us->w);
244   if (best_adjmatrix) {
245     adjmatrix = best_adjmatrix;
246     mc_rwvsetup_full();
247     ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
248     assert(r == mc_iovlen);
249   }
250   LPRINTF("worker %2d ending",mc_us->w);
251   exit(0);
252 }
253
254 static void multicore(void) {
255   Worker *mc_workers;
256   int w;
257   pid_t genpid;
258
259   multicore_iteration_boundary = n / 2;
260
261   FILE *busf = tmpfile();  assert(busf);
262   mc_bus = fileno(busf);
263   int r = fcntl(mc_bus, F_GETFL);  assert(r >= 0);
264   r |= O_APPEND;
265   r = fcntl(mc_bus, F_SETFL, r);  assert(r >= 0);
266
267   r = pipe(mc_work);  assert(!r);
268
269   mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
270   for (w=0; w<ncpus; w++) {
271     mc_workers[w].w = w;
272     mc_workers[w].results = tmpfile();  assert(mc_workers[w].results);
273     mc_workers[w].pid = fork();  assert(mc_workers[w].pid >= 0);
274     if (!mc_workers[w].pid) {
275       mc_us = &mc_workers[w];
276       close(mc_work[1]);
277       LPRINTF("worker %2d running", w);
278       mc_iterate_worker();
279       exit(0);
280     }
281   }
282
283   close(mc_work[0]);
284
285   genpid = fork();  assert(genpid >= 0);
286   if (!genpid) {
287     LPRINTF("generator running");
288     iterate();
289     exit(0);
290   }
291
292   close(mc_work[1]);
293   mc_awaitpid(-1, genpid);
294   for (w=0; w<ncpus; w++)
295     mc_awaitpid(w, mc_workers[w].pid);
296
297   for (w=0; w<ncpus; w++) {
298     mc_rwvsetup_full();
299     LPRINTF("reading report from %2d",w);
300     ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
301     if (!sr) continue;
302     maxhamweight = 0;
303     optimise(1);
304   }
305 }
306
307 static void multicore_check_for_new_best(void) {
308   if (!ncpus) return;
309
310   for (;;) {
311     double msg;
312     ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
313     if (!got) break;
314     assert(got == sizeof(msg));
315     if (msg > best)
316       set_best(msg);
317     mc_bus_read += sizeof(msg);
318   }
319 }
320
321 static void multicore_found_new_best(void) {
322   if (!ncpus) return;
323
324   if (mc_us /* might be master */) fprintf(stderr,"    w%-2d ",mc_us->w);
325   ssize_t wrote = write(mc_bus, &best, sizeof(best));
326   assert(wrote == sizeof(best));
327 }
328
329 /*----- end of multicore support -----*/
330
331 static AdjWord *xalloc_adjmatrix(void) {
332   return xmalloc(sizeof(*adjmatrix)*n);
333 }
334
335 static void prep(void) {
336   adjall = ~((~(AdjWord)0) << m);
337   adjmatrix = xalloc_adjmatrix();
338   glp_term_out(GLP_OFF);
339   setlinebuf(stderr);
340 }
341
342 static AdjWord one_adj_bit(int bitnum) {
343   return (AdjWord)1 << bitnum;
344 }
345
346 static int count_set_adj_bits(AdjWord w) {
347   int j, total;
348   for (j=0, total=0; j<m; j++)
349     total += !!(w & one_adj_bit(j));
350   return total;
351 }
352
353 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
354
355 static int totalfrags;
356
357 static bool maxhamweight_ok(void) {
358   double maxminsize = (double)m / maxhamweight;
359   return maxminsize > best;
360 }
361
362 static bool preconsider_ok(int nwords, bool doprint) {
363   int i;
364
365   PRINTF("%2d ", maxhamweight);
366
367   bool had_max = 0;
368   for (i=0, totalfrags=0; i<nwords; i++) {
369     int frags = count_set_adj_bits(adjmatrix[i]);
370     had_max += (frags >= maxhamweight);
371     totalfrags += frags;
372     PRINTF("%"PRADJ" ", adjmatrix[i]);
373     double maxminsize = (double)m / frags;
374     if (maxminsize <= best) {
375       PRINTF(" too fine");
376       goto out;
377     }
378   }
379   if (!had_max) {
380     /* Skip this candidate as its max hamming weight is lower than
381      * we're currently looking for (which means we must have done it
382      * already).  (The recursive iteration ensures that none of the
383      * words have more than the max hamming weight.) */
384     PRINTF(" nomaxham");
385     goto out;
386   }
387   return 1;
388
389  out:
390   return 0;
391 }
392
393 static void optimise(bool doprint) {
394   /* Consider the best answer (if any) for a given adjacency matrix */
395   glp_prob *prob = 0;
396   int i, j;
397
398   /*
399    * Up to a certain point, optimise() can be restarted.  We use this
400    * to go back and print the debugging output if it turns out that we
401    * have an interesting case.  The HAVE_PRINTED macro does this: its
402    * semantics are to go back in time and make sure that we have
403    * printed the description of the search case.
404    */
405 #define HAVE_PRINTED ({                                         \
406       if (!doprint) { doprint = 1; goto retry_with_print; }     \
407     })
408  retry_with_print:
409   if (prob) {
410     glp_delete_prob(prob);
411     prob = 0;
412   }
413
414   bool ok = preconsider_ok(n, doprint);
415   if (!ok)
416     goto out;
417
418   /*
419    * We formulate our problem as an LP problem as follows.
420    * In this file "n" and "m" are the matchstick numbers.
421    *
422    * Each set bit in the adjacency matrix corresponds to taking a
423    * fragment from old match i and making it part of new match j.
424    *
425    * The structural variables (columns) are:
426    *   x_minimum        minimum size of any fragment (bounded below by 0)
427    *   x_morefrag_i_j   the amount by which the size of the fragment
428    *                     i,j exceeds the minimum size (bounded below by 0)
429    *
430    * The auxiliary variables (rows) are:
431    *   x_total_i       total length for each input match (fixed variable)
432    *   x_total_j       total length for each output match (fixed variable)
433    *
434    * The objective function is simply
435    *   maximise x_minimum
436    *
437    * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
438    * ME_ refers to entries in the list of constraint matrix elements
439    * which we build up as we go.
440    */
441
442   prob = glp_create_prob();
443
444   int Y_totals_i = glp_add_rows(prob, n);
445   int Y_totals_j = glp_add_rows(prob, m);
446   int X_minimum = glp_add_cols(prob, 1);
447
448   {
449   int next_matrix_entry = 1; /* wtf GLPK! */
450   int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
451   double matrix_entries[matrix_entries_size];
452   int matrix_entries_XY[2][matrix_entries_size];
453
454 #define ADD_MATRIX_ENTRY(Y,X) ({                        \
455       assert(next_matrix_entry < matrix_entries_size);  \
456       matrix_entries_XY[0][next_matrix_entry] = (X);    \
457       matrix_entries_XY[1][next_matrix_entry] = (Y);    \
458       matrix_entries[next_matrix_entry] = 0;            \
459       next_matrix_entry++;                              \
460     })
461
462   int ME_totals_i__minimum = next_matrix_entry;
463   for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
464
465   int ME_totals_j__minimum = next_matrix_entry;
466   for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
467
468   /* \forall_i x_total_i = m */
469   /* \forall_i x_total_j = n */
470   for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
471   for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
472
473   /* x_minimum >= 0 */
474   glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
475   glp_set_col_name(prob, X_minimum, "minimum");
476
477   /* objective is maximising x_minimum */
478   glp_set_obj_dir(prob, GLP_MAX);
479   glp_set_obj_coef(prob, X_minimum, 1);
480
481   for (i=0; i<n; i++) {
482     for (j=0; j<m; j++) {
483       if (!(adjmatrix[i] & one_adj_bit(j)))
484         continue;
485       /* x_total_i += x_minimum */
486       /* x_total_j += x_minimum */
487       matrix_entries[ ME_totals_i__minimum + i ] ++;
488       matrix_entries[ ME_totals_j__minimum + j ] ++;
489
490       /* x_morefrag_i_j >= 0 */
491       int X_morefrag_i_j = glp_add_cols(prob, 1);
492       glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
493       if (doprint) {
494         char buf[255];
495         snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
496         glp_set_col_name(prob, X_morefrag_i_j, buf);
497       }
498
499       /* x_total_i += x_morefrag_i_j */
500       /* x_total_j += x_morefrag_i_j */
501       int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
502       int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
503       matrix_entries[ME_totals_i__mf_i_j] = 1;
504       matrix_entries[ME_totals_j__mf_i_j] = 1;
505     }
506   }
507
508   assert(next_matrix_entry == matrix_entries_size);
509
510   glp_load_matrix(prob, matrix_entries_size-1,
511                   matrix_entries_XY[1], matrix_entries_XY[0],
512                   matrix_entries);
513
514   int r = glp_simplex(prob, NULL);
515   PRINTF(" glp=%d", r);
516
517 #define OKERR(e) \
518   case e: PRINTF(" " #e ); goto out;
519 #define BADERR(e) \
520   case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
521 #define DEFAULT \
522   default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
523
524   switch (r) {
525   OKERR(GLP_ESING);
526   OKERR(GLP_ECOND);
527   OKERR(GLP_EBOUND);
528   OKERR(GLP_EFAIL);
529   OKERR(GLP_ENOPFS);
530   OKERR(GLP_ENODFS);
531   BADERR(GLP_EBADB);
532   BADERR(GLP_EOBJLL);
533   BADERR(GLP_EOBJUL);
534   BADERR(GLP_EITLIM);
535   BADERR(GLP_ETMLIM);
536   BADERR(GLP_EINSTAB);
537   BADERR(GLP_ENOCVG);
538   case 0: break;
539   DEFAULT;
540   }
541
542   r = glp_get_status(prob);
543   PRINTF(" status=%d", r);
544
545   switch (r) {
546   OKERR(GLP_NOFEAS);
547   OKERR(GLP_UNDEF);
548   BADERR(GLP_FEAS);
549   BADERR(GLP_INFEAS);
550   BADERR(GLP_UNBND);
551   case GLP_OPT: break;
552   DEFAULT;
553   }
554
555   double got = glp_get_obj_val(prob);
556   PRINTF("  %g", got);
557   if (got <= best)
558     goto out;
559
560   HAVE_PRINTED;
561
562   set_best(got);
563   multicore_found_new_best();
564
565   if (best_prob) glp_delete_prob(best_prob);
566   best_prob = prob;
567
568   free(best_adjmatrix);
569   best_adjmatrix = xalloc_adjmatrix();
570   memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
571
572   PRINTF(" BEST        \n");
573   return;
574
575   }
576  out:
577   if (prob)
578     glp_delete_prob(prob);
579   if (doprint) progress_eol();
580   if (doprint) multicore_check_for_new_best();
581 }
582
583 static void iterate_recurse(int i, AdjWord min) {
584   if (i >= n) {
585     printcounter++;
586     optimise(!(printcounter & 0xfff));
587     return;
588   }
589   if (i >= multicore_iteration_boundary) {
590     multicore_outer_iteration(i, min);
591     return;
592   }
593   for (adjmatrix[i] = min;
594        ;
595        adjmatrix[i]++) {
596     if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
597       goto again;
598     if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
599       goto again;
600
601     iterate_recurse(i+1, adjmatrix[i]);
602
603   again:
604     if (adjmatrix[i] == adjall)
605       return;
606   }
607 }
608
609 static void iterate(void) {
610   for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
611     if (!maxhamweight_ok())
612       continue;
613
614     iterate_recurse(0, 1);
615   }
616 }
617
618 static void report(void) {
619   fprintf(stderr, "\n");
620   if (best_prob) {
621     double min = glp_get_obj_val(best_prob);
622     double a[n][m];
623     int i, j, cols;
624     for (i = 0; i < n; i++)
625       for (j = 0; j < m; j++)
626         a[i][j] = 0;
627     cols = glp_get_num_cols(best_prob);
628     for (i = 1; i <= cols; i++) {
629       int x, y;
630       if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
631         continue;
632       a[x][y] = min + glp_get_col_prim(best_prob, i);
633     }
634     printf("%d into %d: min fragment %g\n", n, m, min);
635     for (i = 0; i < n; i++) {
636       for (j = 0; j < m; j++) {
637         if (a[i][j])
638           printf(" %9.3f", a[i][j]);
639         else
640           printf("          ");
641       }
642       printf("\n");
643     }
644   }
645   if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
646 }
647  
648 int main(int argc, char **argv) {
649   int opt;
650   while ((opt = getopt(argc,argv,"j:")) >= 0) {
651     switch (opt) {
652     case 'j': ncpus = atoi(optarg); break;
653     case '+': assert(!"bad option");
654     default: abort();
655     }
656   }
657   argc -= optind-1;
658   argv += optind-1;
659   assert(argc==3);
660   n = atoi(argv[1]);
661   m = atoi(argv[2]);
662
663   prep();
664
665   if (ncpus) multicore();
666   else iterate();
667
668   report();
669   return 0;
670 }