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