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