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