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