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