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