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