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