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