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
8 * The arguments must be ordered so that n > m:
9 * n is the number of (more, shorter) input matches of length m
10 * m is the number of (fewer, longer) output matches of length n
13 * -j<jobs> run in parallel on <jobs> cores
14 * -b<best> search only for better than <best>
18 * matchsticks/main.c Copyright 2014 Ian Jackson
20 * This program is free software: you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation, either version 3 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
44 #include <sys/types.h>
47 #include <sys/fcntl.h>
52 #define VERSION "(unknown-version)"
58 * Each input match contributes, or does not contribute, to each
59 * output match; we do not need to consider multiple fragments
60 * relating to the same input/output pair this gives an n*m adjacency
61 * matrix (bitmap). Given such an adjacency matrix, the problem of
62 * finding the best sizes for the fragments can be expressed as a
63 * linear programming problem.
65 * We search all possible adjacency matrices, and for each one we run
66 * GLPK's simplex solver. We represent the adjacency matrix as an
67 * array of bitmaps: one word per input stick, with one bit per output
70 * However, there are a couple of wrinkles:
72 * To best represent the problem as a standard LP problem, we separate
73 * out the size of each fragment into a common minimum size variable,
74 * plus a fragment-specific extra size variable. This reduces the LP
75 * problem size at the cost of making the problem construction, and
76 * interpretation of the results, a bit fiddly.
78 * Many of the adjacency matrices are equivalent. In particular,
79 * permutations of the columns, or of the rows, do not change the
80 * meaning. It is only necessasry to consider any one permutation.
81 * We make use of this by considering only adjacency matrices whose
82 * bitmap array contains bitmap words whose numerical values are
83 * nondecreasing in array order.
85 * Once we have a solution, we also avoid considering any candidate
86 * which involves dividing one of the input sticks into so many
87 * fragment that the smallest fragment would necessarily be no bigger
88 * than our best solution. That is, we reject candidates where any of
89 * the hamming weights of the adjacency bitmap words are too large.
91 * We further winnow the set of possible adjacency matrices, by
92 * ensuring the same bit is not set in too many entries of adjmatrix
93 * (ie, as above, only considering output sticks); and by ensuring
94 * that it is not set in too few: each output stick must consist
95 * of at least two fragments since the output sticks are longer than
98 * And, we want to do the search in order of increasing maximum
99 * hamming weight. This is because in practice optimal solutions tend
100 * to have low hamming weight, and having found a reasonable solution
101 * early allows us to eliminate a lot of candidates without doing the
105 typedef uint32_t AdjWord;
106 #define PRADJ "08"PRIx32
108 #define FOR_BITS(j,m) for (j=0, j##bit=1; j < (m); j++, j##bit<<=1)
110 static int n, m, maxhamweight;
111 static AdjWord *adjmatrix;
112 static AdjWord adjall;
115 static glp_prob *best_prob;
116 static AdjWord *best_adjmatrix;
118 static int n_max_frags=INT_MAX, m_max_frags=INT_MAX;
121 static unsigned printcounter;
123 static void iterate(void);
124 static void iterate_recurse(int i, AdjWord min);
125 static bool preconsider_ok(int nwords, bool doprint);
126 static bool maxhamweight_ok(void);
127 static void optimise(bool doprint);
129 static void progress_eol(void) {
130 fprintf(stderr," \r");
134 static void set_best(double new_best) {
137 * When computing n_max_frags, we want to set a value that will skip
138 * anything that won't provide strictly better solutions. So we
142 * <=> frags < | n / best |
144 * <=> frags <= | n / best | - 1
146 * But best values from glpk are slightly approximate, so we
147 * subtract a fudge factor from our target.
149 double near_best = best * 0.98 - 0.02;
150 n_max_frags = ceil(n / near_best) - 1;
151 m_max_frags = ceil(m / near_best) - 1;
154 /*----- multicore support -----*/
165 * - one pipe ("work") from generator to workers
166 * - ever-extending file ("bus") containing new "best" values
167 * - one file for each worker giving maxhamweight and adjmatrix for best
169 * generator runs iterate_recurse to a certain depth and writes the
170 * candidates to a pipe
172 * workers read candidates from the pipe and resume iterate_recurse
173 * halfway through the recursion
175 * whenever a worker does a doprint, it checks the bus for new best
176 * value; actual best values are appended
178 * master waits for generator and all workers to finish and then
179 * runs optimise() for each worker's best, then prints
182 static int ncpus = 0, multicore_iteration_boundary = INT_MAX;
184 static int mc_bus, mc_work[2];
185 static off_t mc_bus_read;
192 static Worker *mc_us;
193 static bool mc_am_generator;
195 static void multicore_check_for_new_best(void);
198 static AdjWord mc_iter_min;
200 static size_t mc_iovlen;
201 static struct iovec mc_iov[MAX_NIOVS];
203 #define IOV0 (mc_niovs = mc_iovlen = 0)
205 #define IOV(obj, count) ({ \
206 assert(mc_niovs < MAX_NIOVS); \
207 mc_iov[mc_niovs].iov_base = &(obj); \
208 mc_iov[mc_niovs].iov_len = sizeof(obj) * (count); \
209 mc_iovlen += mc_iov[mc_niovs].iov_len; \
213 static void mc_rwvsetup_outer(void) {
215 IOV(maxhamweight, 1);
217 IOV(*adjmatrix, multicore_iteration_boundary);
221 static void mc_rwvsetup_full(void) {
226 static void vlprintf(const char *fmt, va_list al) {
227 vfprintf(stderr,fmt,al);
231 static void LPRINTF(const char *fmt, ...) {
238 static void mc_awaitpid(int wnum, pid_t pid) {
239 LPRINTF("master awaiting %2d [%ld]",wnum,(long)pid);
241 pid_t got = waitpid(pid, &status, 0);
244 fprintf(stderr,"\nFAILED SUBPROC %2d [%ld] %d\n",
245 wnum, (long)pid, status);
250 static void multicore_outer_iteration(int i, AdjWord min) {
251 static unsigned check_counter;
253 assert(i == multicore_iteration_boundary);
256 ssize_t r = writev(mc_work[1], mc_iov, mc_niovs);
257 assert(r == mc_iovlen);
258 /* effectively, this writev arranges to transfers control
259 * to some worker's instance of iterate_recurse via mc_iterate_worker */
261 if (!(check_counter++ & 0xff))
262 multicore_check_for_new_best();
265 static void mc_iterate_worker(void) {
266 static time_t lastprint;
270 ssize_t r = readv(mc_work[0], mc_iov, mc_niovs);
272 assert(r == mc_iovlen);
274 bool ok = maxhamweight_ok();
277 time_t now = time(0);
278 bool doprint = now != lastprint;
281 ok = preconsider_ok(multicore_iteration_boundary, doprint);
282 if (doprint) progress_eol();
285 /* stop iterate_recurse from trying to run multicore_outer_iteration */
286 int mc_org_it_bound = multicore_iteration_boundary;
287 multicore_iteration_boundary = INT_MAX;
288 iterate_recurse(mc_org_it_bound, mc_iter_min);
289 multicore_iteration_boundary = mc_org_it_bound;
291 if (best_adjmatrix) {
292 LPRINTF("worker %2d reporting",mc_us->w);
293 adjmatrix = best_adjmatrix;
295 ssize_t r = writev(fileno(mc_us->results), mc_iov, mc_niovs);
296 assert(r == mc_iovlen);
298 LPRINTF("worker %2d ending",mc_us->w);
302 static void multicore(void) {
307 multicore_iteration_boundary = n / 2;
309 FILE *busf = tmpfile(); assert(busf);
310 mc_bus = fileno(busf);
311 int r = fcntl(mc_bus, F_GETFL); assert(r >= 0);
313 r = fcntl(mc_bus, F_SETFL, r); assert(r >= 0);
315 r = pipe(mc_work); assert(!r);
317 mc_workers = xmalloc(sizeof(*mc_workers) * ncpus);
318 for (w=0; w<ncpus; w++) {
320 mc_workers[w].results = tmpfile(); assert(mc_workers[w].results);
321 mc_workers[w].pid = fork(); assert(mc_workers[w].pid >= 0);
322 if (!mc_workers[w].pid) {
323 mc_us = &mc_workers[w];
325 LPRINTF("worker %2d running", w);
333 genpid = fork(); assert(genpid >= 0);
336 LPRINTF("generator running");
342 mc_awaitpid(-1, genpid);
343 for (w=0; w<ncpus; w++)
344 mc_awaitpid(w, mc_workers[w].pid);
346 for (w=0; w<ncpus; w++) {
348 LPRINTF("reading report from %2d",w);
349 ssize_t sr = preadv(fileno(mc_workers[w].results), mc_iov, mc_niovs, 0);
351 LPRINTF("got report from %2d",w);
357 static void multicore_check_for_new_best(void) {
358 if (!(mc_us || mc_am_generator))
363 ssize_t got = pread(mc_bus, &msg, sizeof(msg), mc_bus_read);
365 assert(got == sizeof(msg));
368 mc_bus_read += sizeof(msg);
372 static void multicore_found_new_best(void) {
376 if (mc_us /* might be master */) fprintf(stderr," w%-2d ",mc_us->w);
377 ssize_t wrote = write(mc_bus, &best, sizeof(best));
378 assert(wrote == sizeof(best));
381 /*----- end of multicore support -----*/
383 static AdjWord *xalloc_adjmatrix(void) {
384 return xmalloc(sizeof(*adjmatrix)*n);
387 static void prep(void) {
388 adjall = ~((~(AdjWord)0) << m);
389 adjmatrix = xalloc_adjmatrix();
390 glp_term_out(GLP_OFF);
392 weight = calloc(sizeof(*weight), m); assert(weight);
396 static AdjWord one_adj_bit(int bitnum) {
397 return (AdjWord)1 << bitnum;
401 static int count_set_adj_bits(AdjWord w) {
405 total += !!(w & jbit);
409 #define PRINTF(...) if (!doprint) ; else fprintf(stderr, __VA_ARGS__)
411 static int totalfrags;
413 static bool maxhamweight_ok(void) {
414 return maxhamweight <= m_max_frags;
417 static bool preconsider_ok(int nwords, bool doprint) {
420 PRINTF("%2d ", maxhamweight);
423 for (i=0, totalfrags=0; i<nwords; i++) {
424 int frags = count_set_adj_bits(adjmatrix[i]);
425 PRINTF("%"PRADJ" ", adjmatrix[i]);
426 if (frags > m_max_frags) {
430 had_max += (frags >= maxhamweight);
434 /* Skip this candidate as its max hamming weight is lower than
435 * we're currently looking for (which means we must have done it
436 * already). (The recursive iteration ensures that none of the
437 * words have more than the max hamming weight.) */
447 static void optimise(bool doprint) {
448 /* Consider the best answer (if any) for a given adjacency matrix */
454 * Up to a certain point, optimise() can be restarted. We use this
455 * to go back and print the debugging output if it turns out that we
456 * have an interesting case. The HAVE_PRINTED macro does this: its
457 * semantics are to go back in time and make sure that we have
458 * printed the description of the search case.
460 #define HAVE_PRINTED ({ \
461 if (!doprint) { doprint = 1; goto retry_with_print; } \
465 glp_delete_prob(prob);
469 bool ok = preconsider_ok(n, doprint);
474 * We formulate our problem as an LP problem as follows.
475 * In this file "n" and "m" are the matchstick numbers.
477 * Each set bit in the adjacency matrix corresponds to taking a
478 * fragment from old match i and making it part of new match j.
480 * The structural variables (columns) are:
481 * x_minimum minimum size of any fragment (bounded below by 0)
482 * x_morefrag_i_j the amount by which the size of the fragment
483 * i,j exceeds the minimum size (bounded below by 0)
485 * The auxiliary variables (rows) are:
486 * x_total_i total length for each input match (fixed variable)
487 * x_total_j total length for each output match (fixed variable)
489 * The objective function is simply
492 * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
493 * ME_ refers to entries in the list of constraint matrix elements
494 * which we build up as we go.
497 prob = glp_create_prob();
499 int Y_totals_i = glp_add_rows(prob, n);
500 int Y_totals_j = glp_add_rows(prob, m);
501 int X_minimum = glp_add_cols(prob, 1);
504 int next_matrix_entry = 1; /* wtf GLPK! */
505 int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
506 double matrix_entries[matrix_entries_size];
507 int matrix_entries_XY[2][matrix_entries_size];
509 #define ADD_MATRIX_ENTRY(Y,X) ({ \
510 assert(next_matrix_entry < matrix_entries_size); \
511 matrix_entries_XY[0][next_matrix_entry] = (X); \
512 matrix_entries_XY[1][next_matrix_entry] = (Y); \
513 matrix_entries[next_matrix_entry] = 0; \
514 next_matrix_entry++; \
517 int ME_totals_i__minimum = next_matrix_entry;
518 for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
520 int ME_totals_j__minimum = next_matrix_entry;
521 for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
523 /* \forall_i x_total_i = m */
524 /* \forall_i x_total_j = n */
525 for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
526 for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
529 glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
530 glp_set_col_name(prob, X_minimum, "minimum");
532 /* objective is maximising x_minimum */
533 glp_set_obj_dir(prob, GLP_MAX);
534 glp_set_obj_coef(prob, X_minimum, 1);
536 for (i=0; i<n; i++) {
538 if (!(adjmatrix[i] & jbit))
540 /* x_total_i += x_minimum */
541 /* x_total_j += x_minimum */
542 matrix_entries[ ME_totals_i__minimum + i ] ++;
543 matrix_entries[ ME_totals_j__minimum + j ] ++;
545 /* x_morefrag_i_j >= 0 */
546 int X_morefrag_i_j = glp_add_cols(prob, 1);
547 glp_set_col_bnds(prob, X_morefrag_i_j, GLP_LO, 0, 0);
550 snprintf(buf,sizeof(buf),"mf %d,%d",i,j);
551 glp_set_col_name(prob, X_morefrag_i_j, buf);
554 /* x_total_i += x_morefrag_i_j */
555 /* x_total_j += x_morefrag_i_j */
556 int ME_totals_i__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_i+i, X_morefrag_i_j);
557 int ME_totals_j__mf_i_j = ADD_MATRIX_ENTRY(Y_totals_j+j, X_morefrag_i_j);
558 matrix_entries[ME_totals_i__mf_i_j] = 1;
559 matrix_entries[ME_totals_j__mf_i_j] = 1;
563 assert(next_matrix_entry == matrix_entries_size);
565 glp_load_matrix(prob, matrix_entries_size-1,
566 matrix_entries_XY[1], matrix_entries_XY[0],
569 int r = glp_simplex(prob, NULL);
570 PRINTF(" glp=%d", r);
573 case e: PRINTF(" " #e ); goto out;
575 case e: HAVE_PRINTED; printf(" " #e " CRASHING\n"); exit(-1);
577 default: HAVE_PRINTED; printf(" ! CRASHING\n"); exit(-1);
597 r = glp_get_status(prob);
598 PRINTF(" status=%d", r);
610 double got = glp_get_obj_val(prob);
618 multicore_found_new_best();
620 if (best_prob) glp_delete_prob(best_prob);
623 free(best_adjmatrix);
624 best_adjmatrix = xalloc_adjmatrix();
625 memcpy(best_adjmatrix, adjmatrix, sizeof(*adjmatrix)*n);
633 glp_delete_prob(prob);
634 if (doprint) progress_eol();
635 if (doprint) multicore_check_for_new_best();
638 static void iterate_recurse(int i, AdjWord min) {
648 optimise(!(printcounter & 0xfff));
651 if (i >= multicore_iteration_boundary) {
652 multicore_outer_iteration(i, min);
655 for (adjmatrix[i] = min;
658 if (count_set_adj_bits(adjmatrix[i]) > maxhamweight)
660 if (i == 0 && (adjmatrix[i] & (1+adjmatrix[i])))
664 if (adjmatrix[i] & jbit)
666 for (int j = 0; j < m; j++)
667 if (weight[j] >= n_max_frags)
670 iterate_recurse(i+1, adjmatrix[i]);
674 if (adjmatrix[i] & jbit)
678 if (adjmatrix[i] == adjall)
683 static void iterate(void) {
684 for (maxhamweight=1; maxhamweight<=m; maxhamweight++) {
685 if (!maxhamweight_ok())
688 iterate_recurse(0, 1);
692 static void report(void) {
693 fprintf(stderr, "\n");
694 if (best_adjmatrix) {
697 for (i=0; i<n; i++) fprintf(stderr, " %"PRADJ, best_adjmatrix[i]);
699 fprintf(stderr, " best=%-12.8f nf<=%d mf<=%d\n",
700 best, n_max_frags, m_max_frags);
701 printf("%d into %d: ", n, m);
703 double min = glp_get_obj_val(best_prob);
706 for (i = 0; i < n; i++)
707 for (j = 0; j < m; j++)
709 cols = glp_get_num_cols(best_prob);
710 for (i = 1; i <= cols; i++) {
712 if (2 != sscanf(glp_get_col_name(best_prob, i), "mf %d,%d", &x, &y))
714 a[x][y] = min + glp_get_col_prim(best_prob, i);
716 printf("min fragment %g [%s]\n", min, VERSION);
717 for (i = 0; i < n; i++) {
718 for (j = 0; j < m; j++) {
720 printf(" %9.3f", a[i][j]);
727 printf(" none better than %9.3f [%s]\n", best, VERSION);
729 if (ferror(stdout) || fclose(stdout)) { perror("stdout"); exit(-1); }
732 int main(int argc, char **argv) {
734 while ((opt = getopt(argc,argv,"j:b:")) >= 0) {
736 case 'j': ncpus = atoi(optarg); break;
737 case 'b': set_best(atof(optarg)); break;
738 case '+': assert(!"bad option");
751 if (ncpus) multicore();