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