Minimum Square Partridge Packing with MiniZincDRAFT
In Solving the Partridge Packing Problem using MiniZinc last year, we modeled and solved the classical Partridge packing puzzle. That version is a hard satisfaction problem. Sizes 2 to 7 have no solution at all, and finding one for the larger sizes takes a fair amount of luck. This year we look at a small variation: pack the same square parts into the smallest square that holds them.
As an optimization problem, the puzzle has an answer at every size, and most solvers produce a sequence of ever tighter packings on the way there. That makes it a good way to watch solvers search and compare search heuristics. This post assumes some familiarity with the previous one.
The Problem
In the original Partridge Packing Problem, the goal is to pack the parts into a square of side , the th triangular number. Size has one part, two parts, and so on up to parts of size . Together they have exactly the area of the square, so a solution is a perfect tiling.
The minimizing variant asks for the smallest square that holds all the parts. For , the satisfaction problem requires a square, and as shown in the original post, the two parts cannot both fit. The smallest square that works is :
The model starts from a generous board with side , so for . The animation steps through tighter packings for on that board, down to the optimal .
Packing 1 of 3
The Model
We adapt the improved Partridge Packing model from the previous post. That takes a wider board, variables for the bounding square, a relaxed fill constraint, and a guard on the edge-placement constraints.
Data and variables
The board grows to twice the triangular number along each side, which leaves the solver plenty of room to find a first packing and then tighten it.
set of int: Pos = 1 .. 2 * triangular_n;New variables track the largest position used along each axis, and the larger of the two is the side of the bounding square.
var Pos: max_pos_x = max (p in Parts) ( x[p] + sizes[p] - 1);var Pos: max_pos_y = max (p in Parts) ( y[p] + sizes[p] - 1);var Pos: max_pos = max(max_pos_x, max_pos_y);
% The minimum possible value for max_pos is the case where the area% equals the sum of the partsconstraint max_pos >= triangular_n;The lower bound is the side of a completely filled square.
We minimize max_pos, and each time branch and bound tightens its upper bound, the parts get less room to move.
Instead of a fixed board side, the packing constraints keep each part within max_pos_x and max_pos_y, while the diffn no-overlap constraint stays unchanged.
constraint :: "Parts fit in x direction"forall (p in Parts) ( x[p] + sizes[p] - 1 <= max_pos_x);
constraint :: "Parts fit in y direction"forall (p in Parts) ( y[p] + sizes[p] - 1 <= max_pos_y);From exact fill to at-most fill
The original model’s exact_fill constraint required every row and column to be completely filled.
That only holds when the board area equals the total area of the parts.
On a larger board, most rows and columns have empty space, so the constraint bounds the fill by max_pos, the current side:
predicate at_most_fill(array[Parts] of var Pos: xy, Pos: rc) = let { % on_rc[p] is true iff the part overlaps the row/column rc array[Parts] of var bool: on_rc = [ rc - sizes[p] < xy[p] /\ xy[p] <= rc | p in Parts ] } in sum (p in Parts) ( sizes[p] * on_rc[p] ) <= max_pos;at_most_fill is much weaker than exact_fill, since it only prevents overfilling, but it stays valid on every board.
Bounding by card(Pos) instead would cap each row and column at the largest allowed side, which says almost nothing.
Edge-placement constraints
The edge-placement constraint relies on the parts filling all available space.
With any slack at all, nearly every placement near the edge becomes possible again.
We keep the constraint unchanged, guarded so it only applies when max_pos reaches the lower bound triangular_n and the packing must be an exact tiling.
MiniZinc compiles the guard into half-reified constraints.
DetailsThe guarded edge-placement constraint
% The amount of available area from parts up to given sizefunction int: available_area(int: size) = let { % t is the triangular number of size int: t = (size * (size + 1)) div 2; } in t * t;
constraint :: "Edge-placement limits"implied_constraint( if max_pos = triangular_n then forall (size in N where size > 1) ( let { % Find the smallest distance from the edge that is possible to place. int: min_distance_from_edge = min({d | d in 1 .. size where d * size > available_area(d), }), % Placing in these positions is not packable for a full packing set of int: forbidden_placements = % Positions at low placement indices 2 .. (1 + min_distance_from_edge) union % positions at high placement indices triangular_n - size - min_distance_from_edge ..< triangular_n - size, set of Pos: allowed_placements = Pos diff forbidden_placements } in forall (p in Parts where sizes[p] = size) ( x[p] in allowed_placements /\ y[p] in allowed_placements ) ) endif,);The full MiniZinc model is available for download. It uses the Chebyshev shell search described below, with the other search strategies included as comments.
Testing the model
As a first test, here is with OR-Tools CP-SAT. In the original problem, the square has no solution.
A constraint programming solver optimizes with branch and bound: once it finds a solution, every later one must be strictly better. CP-SAT is also a portfolio solver that runs several workers in parallel, each with its own strategy, so consecutive solutions can look very different. The animation replays the run down to an optimal square.
Packing 1 of 14
Watching Solvers Search
Given the same model, solvers search in very different ways. I ran six of them on sizes to , with MiniZinc 2.11.0 on an Apple M1 Max (10 cores) and a limit of 300 s per run, compilation included.
- Gecode 6.6.1 is a classical constraint programming solver without learning. It follows the model’s Chebyshev shell search order, described in the next section.
- Chuffed 0.14.0, Huub 100.1.0, and Pumpkin 0.5.0 are single-threaded lazy clause generation (LCG) solvers, which learn a new constraint from each failure.
All three run with free search (
-f), where the solver chooses what to branch on. - OR-Tools CP-SAT 9.15 also learns, uses free search, and adds linear relaxations and a portfolio of 10 parallel workers. Its runs vary, so I ran it five times per size and show the median.
- HiGHS 1.16.0 is a mixed integer programming solver whose branch and bound uses a linear relaxation of the model instead of propagation.
The animation below replays the runs for , where the 21 parts start on a board. The buttons at the top switch to , , or . Each board shows its solver’s best packing so far, on a shared clock. The timeline has a tick for each solution on a logarithmic time scale; drag it to jump to any moment.
21 parts, board 42×42
No solution yet
1 solution, not proved in 300 s
Step 1 of 65 · 0.21 s
Gecode builds outwards from the corner, and its first packing, after 0.26 s, already has the optimal side 22. It never proves optimality, though, and spends the remaining five minutes searching.
Chuffed and CP-SAT start from the other end. Their first packings spread over the whole board, and then each solution is exactly one smaller than the last, 21 solutions from 42 down to 22. Huub does the same with a few larger jumps. All three then prove 22 optimal within a second. Pumpkin reports only the optimal packing after 0.43 s and proves it at once.
HiGHS needs 37 s for its first packing, with side 35, and ends at 23. The model is full of disjunctions (one part is left of, right of, above, or below another), and their linear relaxation says very little about the side of the square.
For the parts can tile the square exactly, so the optimum is the lower bound, 36. Switch the animation above to to watch the 36 parts on a board. Here the race is all about the last step. Gecode again starts close, at 37 after 0.82 s, and gets no further. Huub, CP-SAT, and Chuffed walk down to 37 in 1.1 s, 3.6 s, and 12.5 s. Huub finds the exact tiling at 5.7 s, which also proves it optimal, and CP-SAT finds it at 39 s. Chuffed never closes the last unit. Pumpkin is quiet for 51 s, then reports 37, and finds the tiling at 92 s.
The chart covers all sizes, plotting the side of each solver’s best packing so far against time. A line stops before the right edge where its solver proved optimality. Use the slider to change , and tap or hover over a solver to highlight it.
36 parts, board 72×72
Side of the best packing
Time since MiniZinc started, compilation included, log scale. The dashed line is the optimal side, 36. A line that stops before the right edge ends where its solver proved optimality.
Table for n = 8
| Solver | First packing | Best packing | Packings | Optimality proved |
|---|---|---|---|---|
| GecodeChebyshev shell order | 37 after 0.82 s | 37 after 0.82 s | 1 | no, 300 s limit |
| Chuffedfree search (-f) | 72 after 1.02 s | 37 after 12.5 s | 36 | no, 300 s limit |
| CP-SATfree search, 10 threads, median of 5 | 72 after 1.98 s | 36 after 39.2 s | 28 | after 39.2 s |
| Huubfree search (-f) | 72 after 0.40 s | 36 after 5.67 s | 32 | after 5.67 s |
| Pumpkinfree search (-f) | 37 after 50.9 s | 36 after 92.1 s | 2 | after 92.1 s |
| HiGHSdefault settings | 70 after 272 s | 70 after 272 s | 1 | no, 300 s limit |
Up to , every learning solver proves the optimum in under a second. At the proofs start to cost real time, and at only Huub proves the exact tiling, after 292 s. For to , the optimum is always one more than the lower bound: 4, 7, 11, 16, 22, and 29. At no solver gets below 56 within five minutes, one more than the 55 achieved in the original post.
The two kinds of curves come from how the solvers search. Gecode’s order places the largest parts first, each as close to the corner as possible, much like a greedy bottom-left packing, so its first solution is already near the optimum. Proving that nothing better exists is another matter: without learning, Gecode meets the same failing arrangements again in every subtree.
With free search, Chuffed, Huub, and CP-SAT instead start with a packing that uses the whole board.
After each solution, the new bound max_pos ≤ best − 1 is usually met at its largest allowed value, so each step is an easy problem while there is slack.
The constraints learned under earlier bounds stay valid, so by the time the board is tight, the solver already knows much of why smaller boards fail.
Pumpkin is the exception.
Up to it reports at most two packings, and the first is at most two above the optimum, while at it walks down from 72 like the others.
Gecode and Search Heuristics
Gecode has no automatic search heuristics, which makes it a good testbed for guiding search explicitly from MiniZinc.
The benchmark setup is the same as above.
In the tables, a plain time (such as 10.2s) means the solver proved optimality, best@t (such as 22@0.26s) means it hit the time limit with its best square of side best found at t seconds, and none means no solution at all.
No heuristic, and interleaved search
Without a search annotation, Gecode proves optimality up to (11.5 s), but falls behind quickly after . At it needs 73 s just to find a first packing, of side 110.
Branching on each part’s x and y together, so each part is placed completely before the next, makes a large difference.
Since sizes is reversed, the parts are placed largest first.
solve :: int_search([[x[p], y[p]][i] | p in Parts, i in 1 .. 2], input_order, indomain_min) minimize max_pos;Interleaved search proves in 10.2 s, finds the optimal 29 at in 0.35 s, and gets within one or two units of the optimum on the larger sizes. Its first packing still stacks parts up column 1 and reaches the edge of the board, so branch and bound has to shrink the square from there.
Left-bottom position
Another way to guide search is to branch on an auxiliary variable that encodes the placement order. Numbering cells column by column, bottom to top, gives the left-bottom strategy I tried for Gecode in the previous post:
array[Parts] of var int: position = [ x[p] * card(Pos) + y[p]| p in Parts];
solve :: int_search(position, smallest, indomain_min) minimize max_pos;This did much worse than interleaved search. Proving went from 0.17 s to 2.59 s, and no longer finished. The clearest symptom showed up before optimization even started. The board has four times the area of the parts, so a first packing should be trivial, and interleaved search finds one for with 0 failures. The left-bottom model needed 3,064.
The reason is that diffn prunes x and y separately, so it never removes individual occupied cells from position.
After a part is placed in the corner, x = 1 is still possible above it and y = 1 to its right, so cell stays in every other part’s position domain.
The same holds for the other cells that part covers, so indomain_min tries them and fails one cell at a time.
On top of that, smallest jumps to whichever part has the smallest possible position, often a small part that fits an early gap, which breaks the largest-first order.
Both problems can be fixed in MiniZinc.
In the column-major numbering, a square of size covers vertical strips of length , spaced card(Pos) apart, so an implied 1D disjunctive over those strips prunes occupied cells from position directly.
Switching to input_order restores largest-first order.
constraint implied_constraint( disjunctive( [position[p] + dx * card(Pos) | p in Parts, dx in 0 .. sizes[p] - 1], [sizes[p] | p in Parts, dx in 0 .. sizes[p] - 1], ),);
solve :: int_search(position, input_order, indomain_min) minimize max_pos;First-packing failures drop to 0, proves in 0.16 s again, and reaches 57 in 4.6 s instead of 71 after 299 s.
IllustrationHow the disjunctive sees the board
Number the cells column by column, bottom to top, and lay the columns end to end. The board becomes one line, and a square of size becomes strips of length , one per column it covers. Two squares overlap on the board exactly when two of their strips overlap on the line.
Number the cells column by column, bottom to top: column 1 is 0 to 5, column 2 is 6 to 11, and so on. Laying the columns end to end turns the board into one line of 36 cells. Point at a cell to find it on the line.
Keeping strips apart on a line is what disjunctive does.
It is the classic constraint for tasks that share a single machine, here with the first cell of a strip as the start time and the part’s size as the duration.
The starts are built from position, so every start disjunctive rules out is a cell removed from position.
Search places the parts largest first and tries the smallest remaining position for each; the illustration below shows the difference:
With diffn alone, the overlap rule reasons about whole columns and rows, not single cells. Cells under the placed squares still look possible, so search tries them one at a time, failing 3 times before it reaches cell 3.
Wasted tries: –First good cell: –
Click the board to place or remove squares of the chosen size.
- crossed off before search tries it
- ✕tried by search, overlaps
- ✓tried by search, fits
The board here is instead of wide, and the cells are numbered from 0, whereas the model’s x * card(Pos) + y shifts every number by the same amount.
The “diffn alone” mode is simplified: it crosses off a cell only when the part fits nowhere in that cell’s whole column or row.
Gecode’s diffn reasons in more detail, but it too never removes a single occupied cell from position.
Chebyshev shells
The objective rewards packings close to the corner, which suggests ordering cells by Chebyshev (chessboard) distance from that corner. Cell belongs to shell , the outer edge of a square at the origin. Within a shell, the top strip is numbered left to right, followed by the right strip bottom to top:
My first encoding channeled (x[p], y[p]) into a cell number position[p] through a 2D lookup table and branched with smallest.
It was painfully slow: proving took 112 s, and at Gecode found no packing at all in 300 s.
The encoding has both problems of the naive left-bottom model, plus a third.
The table compiles to a 2D element constraint over entries (12,100 at ), which makes every search node expensive.
Even so, the geometric idea showed promise: the first packing for had side 30, against 56 for interleaved search.
DetailsThe lookup-table encoding
array[Pos, Pos] of int: mapping = array2d(Pos, Pos, [ let { % 1. Normalize 1-based MiniZinc indices to 0-based coordinates int: i0 = i - 1, int: j0 = j - 1,
% 2. Identify which "Shell" (layer) we are in. % This effectively groups (0,0) in shell 0, % (0,1), (1,1), (1,0) in shell 1, etc. int: k = max(i0, j0),
% 3. The starting value of this shell is the area of the inner square int: base = k * k } in % Add offset based on position within the shell if i0 < j0 then base + i0 else base + k + j0 endif| i in Pos, j in Pos]);
array[Parts] of var int: position = [mapping[x[p], y[p]] | p in Parts];
solve :: int_search(position, smallest, indomain_min) minimize max_pos;The shell order does not need the table.
Branching on the shell max(x[p], y[p]), then x[p] and y[p], all in input_order, gives the same shell order while placing parts largest first:
array[Parts] of var Pos: shell = [max(x[p], y[p]) | p in Parts];
solve :: int_search([[shell[p], x[p], y[p]][i] | p in Parts, i in 1 .. 3], input_order, indomain_min) minimize max_pos;That turns the heuristic around. Proving takes 0.16 s instead of 112 s, proves in 33 s, and Gecode reaches 37, 47, and 57 on to within 4.3 s. This is the search in the downloadable model.
A black-box Chebyshev propagator
The shell search avoids the problem with position rather than fixing it.
In Chebyshev order, a square covers cells from several shells, so there is no simple disjunctive that prunes occupied cells as in the left-bottom case.
MiniZinc 2.11 adds an experimental black-box propagator interface that offers another way: keep the table-based position variables and attach a custom bounds propagator to them.
Each time Gecode runs the propagator, it passes the current bounds of every position and of max_pos.
The propagator collects the already placed parts, and for each remaining one scans inward from both bounds past every cell where it would overlap a placed part or stick out beyond the current max_pos.
IllustrationHow the Chebyshev propagator sees the board
Number the cells shell by shell and lay the shells end to end. The first numbers always fill the square in the corner, which is why taking the smallest number first packs outward. But a square no longer has a fixed shape on the line. It breaks into pieces whose number and lengths depend on where it sits:
Shell k holds the cells whose larger coordinate is k, an L-shaped band around the corner. Each shell is numbered along its top edge left to right, then up its right edge from the bottom, ending in the outer corner. Shell k starts at k², so the first k² numbers always fill the k × k corner square, and taking the smallest numbers first packs outward from the corner.
Without a fixed shape there is no disjunctive to state, so the propagator checks cells one at a time instead.
It only moves the two ends of each position range, stopping at the first cell from each end where the part fits.
The board below starts with two parts placed and a part to place next:
Press Play to watch search place the 2 × 2 part, trying the cells that are still possible in shell order, smallest first.
Propagator checks: –Wasted search tries: –
A part at a cell has its bottom-left corner there. Click the board to place or remove squares of the chosen size.
- next part being checked or tried (green where it fits)
- crossed off before search tries it
- ✕tried by search, overlaps
- ✓tried by search, fits
- largest side still allowed
The “largest side allowed” stands for the current upper bound of max_pos, and the board is with cells numbered from 0.
As in the disjunctive illustration, the “table alone” mode is simplified: it crosses off a cell only when the part fits nowhere in that cell’s whole column or row.
The propagator is declared in MiniZinc and implemented outside it, either as a subprocess (:: blackbox_exec) or as a shared library (:: blackbox_dll):
include "experimental/blackbox.mzn";
% Subprocess variant (Python):% predicate chebyshev_bounds(list of var int: vs)% :: minizinc_bounds_propagator% :: blackbox_exec("chebyshev_bounds.py");
% Shared-library variant (C++):predicate chebyshev_bounds(list of var int: vs) :: minizinc_bounds_propagator :: blackbox_dll( "libchebyshev_bounds.dylib",);
constraint implied_constraint(chebyshev_bounds(position ++ [max_pos]));
solve :: int_search(position, input_order, indomain_min) minimize max_pos;I wrote the same propagator in C++ and in Python. With the C++ library, first-packing failures drop to 0, proves in 23.6 s, and Gecode reaches 37, 47, and 57 on to in under a second each, faster than any other Gecode variant. The Python subprocess explores the same search tree, but every propagation is a round trip to another process, so proving takes 138 s instead of 23.6 s. It also needs Gecode 6.6.1, since with 6.6.0 the subprocess failed partway through longer runs.
SourceThe propagator in C++ (blackbox_dll)
MiniZinc loads the library through a C interface: one function, fzn_blackbox, which gets the bounds as pairs of int64_t and writes the tightened bounds back.
Signaling failure means writing an empty interval, [1, 0], for the first variable.
Behind that function the propagator is ordinary C++, and the cell coordinates for each instance size are computed once and shared across calls.
Build it with c++ -std=c++17 -O3 -dynamiclib, or -shared on Linux.
Download chebyshev_bounds.cpp.
// Chebyshev bounds propagator for Minimizing Partridge Packing, loaded by// MiniZinc through :: blackbox_dll.//// Build (macOS):// c++ -std=c++17 -O3 -Wall -Wextra -dynamiclib \// -o libchebyshev_bounds.dylib chebyshev_bounds.cpp//// The propagator gets the bounds of position[1..P] ++ [max_pos], one// [lb, ub] pair per variable, where position[p] is the Chebyshev cell number// of part p's lower-left corner. Parts with lb == ub are placed. For every// other part, the bounds are tightened past cells where the part would// overlap a placed part or extend beyond the upper bound of max_pos.
#include <algorithm>#include <array>#include <cmath>#include <cstddef>#include <cstdint>#include <memory>#include <mutex>#include <vector>
namespace {
// A cell of the board, with 0-based coordinates.struct Cell { int x; int y;};
// The cells covered by a square part, as half-open ranges [x0, x1) x [y0, y1).struct Square { Square(Cell corner, int size) : x0(corner.x), y0(corner.y), x1(corner.x + size), y1(corner.y + size) {}
bool overlaps(const Square& other) const { return x0 < other.x1 && other.x0 < x1 && y0 < other.y1 && other.y0 < y1; }
int x0, y0, x1, y1;};
struct Interval { std::int64_t lb; std::int64_t ub;
bool fixed() const { return lb == ub; }};
// Shell k holds the cells with max(x, y) = k and starts at k * k. Within a// shell, the top strip (x < y) is numbered left to right, followed by the// right strip (x >= y) bottom to top.std::int64_t cell_number(Cell cell) { const std::int64_t k = std::max(cell.x, cell.y); return cell.x < cell.y ? k * k + cell.x : k * k + k + cell.y;}
Cell cell_at(std::int64_t number) { auto k = static_cast<std::int64_t>(std::sqrt(static_cast<double>(number))); while ((k + 1) * (k + 1) <= number) ++k; while (k * k > number) --k; const std::int64_t offset = number - k * k; if (offset < k) return {static_cast<int>(offset), static_cast<int>(k)}; return {static_cast<int>(k), static_cast<int>(offset - k)};}
// The instance size n with n (n + 1) / 2 parts, or 0 if there is none.int instance_size(std::int64_t parts) { int n = 1; while (std::int64_t{n} * (n + 1) / 2 < parts) ++n; return std::int64_t{n} * (n + 1) / 2 == parts ? n : 0;}
// Part sizes and cell coordinates for one instance size.struct Instance { explicit Instance(int n) : parts(n * (n + 1) / 2), board_side(n * (n + 1)) { for (int size = n; size >= 1; --size) sizes.insert(sizes.end(), size, size); cells.reserve(static_cast<std::size_t>(board_side) * board_side); for (std::int64_t number = 0; number < std::int64_t{board_side} * board_side; ++number) { cells.push_back(cell_at(number)); } }
// The number of parts, which is also the side of a perfect tiling. int parts; // The board in the model is twice the side of a perfect tiling. int board_side; // Largest first, matching the model's sizes. std::vector<int> sizes; // The cell for each cell number, so that the hot loops avoid sqrt. std::vector<Cell> cells;};
constexpr int max_instance_size = 31;
// Instances are built once and shared by every propagator call, including// calls from parallel search threads.const Instance* instance_for(std::int64_t parts) { const int n = instance_size(parts); if (n < 1 || n > max_instance_size) return nullptr; static std::array<std::once_flag, max_instance_size + 1> built; static std::array<std::unique_ptr<const Instance>, max_instance_size + 1> instances; std::call_once(built[n], [n] { instances[n] = std::make_unique<const Instance>(n); }); return instances[n].get();}
// Tightens the position bounds of the unplaced parts, given the upper bound// of max_pos. Returns false when no packing is possible.bool propagate(const Instance& instance, std::vector<Interval>& positions, std::int64_t max_side) { const int side = static_cast<int>(std::min<std::int64_t>(max_side, instance.board_side)); if (side < instance.parts) return false;
std::vector<Square> placed; placed.reserve(positions.size()); const auto overlaps_placed = [&placed](const Square& square) { return std::any_of(placed.begin(), placed.end(), [&square](const Square& other) { return square.overlaps(other); }); };
// Keep every part inside the side, and collect the placed parts. for (std::size_t p = 0; p < positions.size(); ++p) { Interval& position = positions[p]; const int size = instance.sizes[p]; const int last = side - size; if (last < 0) return false; position.lb = std::max<std::int64_t>(position.lb, 0); position.ub = std::min(position.ub, cell_number({last, last})); if (position.lb > position.ub) return false;
if (position.fixed()) { const Square square(instance.cells[position.lb], size); if (square.x1 > side || square.y1 > side || overlaps_placed(square)) return false; placed.push_back(square); } } if (placed.empty()) return true;
// Move the bounds of every unplaced part past the cells where it cannot go. for (std::size_t p = 0; p < positions.size(); ++p) { Interval& position = positions[p]; if (position.fixed()) continue; const int size = instance.sizes[p]; const int last = side - size; const auto fits = [&](std::int64_t number) { const Cell cell = instance.cells[number]; return cell.x <= last && cell.y <= last && !overlaps_placed(Square(cell, size)); };
while (position.lb <= position.ub && !fits(position.lb)) ++position.lb; if (position.lb > position.ub) return false; while (position.ub > position.lb && !fits(position.ub)) --position.ub; } return true;}
} // namespace
#if defined(_WIN32)#define FZN_BLACKBOX_EXPORT __declspec(dllexport)#define FZN_BLACKBOX_CALL __stdcall#else#define FZN_BLACKBOX_EXPORT __attribute__((visibility("default")))#define FZN_BLACKBOX_CALL#endif
// The entry point MiniZinc's blackbox_dll calls. Integer variables arrive as// lb, ub pairs, and the result is written in the same layout. An empty// interval for the first variable signals failure. The propagator has no// float variables.extern "C" FZN_BLACKBOX_EXPORT void FZN_BLACKBOX_CALL fzn_blackbox( void* /*instance*/, const std::int64_t* int_in, std::size_t int_in_size, const double* /*float_in*/, std::size_t /*float_in_size*/, std::int64_t* int_out, std::size_t int_out_size, double* /*float_out*/, std::size_t /*float_out_size*/) noexcept { std::copy(int_in, int_in + int_in_size, int_out); if (int_in_size < 4 || int_out_size < int_in_size) return;
// No exception may cross the C interface. Without an answer, the bounds // stay as they were, which is always sound. try { const std::size_t parts = int_in_size / 2 - 1; const Instance* instance = instance_for(static_cast<std::int64_t>(parts)); if (instance == nullptr) return;
std::vector<Interval> positions(parts); for (std::size_t p = 0; p < parts; ++p) positions[p] = {int_in[2 * p], int_in[2 * p + 1]};
if (!propagate(*instance, positions, int_in[2 * parts + 1])) { int_out[0] = 1; int_out[1] = 0; return; } for (std::size_t p = 0; p < parts; ++p) { int_out[2 * p] = positions[p].lb; int_out[2 * p + 1] = positions[p].ub; } } catch (...) { std::copy(int_in, int_in + int_in_size, int_out); }}SourceThe propagator in Python (blackbox_exec)
For each propagator call, the subprocess reads one line of comma-separated integer bounds from standard input and writes back a line of tightened bounds.
The logic is the same as in the C++ version.
Download chebyshev_bounds.py.
#!/usr/bin/env python3"""Chebyshev bounds propagator for Minimizing Partridge Packing (MiniZinc blackbox_exec).
Input / output (bounds propagator): position[1..P] ++ [max_pos] (two comma-separated ints [lb, ub] per variable)"""
from __future__ import annotations
import mathimport sys
def cheb_map(i0: int, j0: int) -> int: k = i0 if i0 > j0 else j0 base = k * k return base + i0 if i0 < j0 else base + k + j0
def find_n(P: int) -> int: if P <= 0: return -1 n = (math.isqrt(1 + 8 * P) - 1) // 2 return n if n * (n + 1) // 2 == P else -1
_CACHE: dict[int, tuple[int, list[int], list[int], list[int]]] = {}
def get_tables(P: int) -> tuple[int, list[int], list[int], list[int]]: tbl = _CACHE.get(P) if tbl is not None: return tbl n = find_n(P) L = 2 * P sizes = [s for s in range(n, 0, -1) for _ in range(s)] inv_x = [0] * (L * L) inv_y = [0] * (L * L) for v in range(L * L): k = math.isqrt(v) r = v - k * k if r < k: inv_x[v] = r inv_y[v] = k else: inv_x[v] = k inv_y[v] = r - k tbl = (L, sizes, inv_x, inv_y) _CACHE[P] = tbl return tbl
def propagate(vals: list[int]) -> list[int]: out = vals[:] P = len(vals) // 2 - 1 if P <= 0 or find_n(P) < 0: return out
L, sizes, inv_x, inv_y = get_tables(P) M = min(L, vals[2 * P + 1]) if M < P: out[0], out[1] = 1, 0 return out
fixed: list[tuple[int, int, int, int]] = [] for p in range(P): lp = max(0, out[2 * p]) s = sizes[p] max_coord = M - s if max_coord < 0: out[0], out[1] = 1, 0 return out up = min(out[2 * p + 1], cheb_map(max_coord, max_coord)) if lp > up: out[0], out[1] = 1, 0 return out out[2 * p] = lp out[2 * p + 1] = up
if lp == up: ix, iy = inv_x[lp], inv_y[lp] ix1, iy1 = ix + s, iy + s if ix1 > M or iy1 > M: out[0], out[1] = 1, 0 return out for fx0, fy0, fx1, fy1 in fixed: if ix < fx1 and fx0 < ix1 and iy < fy1 and fy0 < iy1: out[0], out[1] = 1, 0 return out fixed.append((ix, iy, ix1, iy1))
if not fixed: return out
for q in range(P): lp = out[2 * q] up = out[2 * q + 1] if lp == up: continue s = sizes[q] max_coord = M - s
while lp <= up: ix, iy = inv_x[lp], inv_y[lp] if ix <= max_coord and iy <= max_coord: ix1, iy1 = ix + s, iy + s for fx0, fy0, fx1, fy1 in fixed: if ix < fx1 and fx0 < ix1 and iy < fy1 and fy0 < iy1: break else: break lp += 1 if lp > up: out[0], out[1] = 1, 0 return out
while up > lp: ix, iy = inv_x[up], inv_y[up] if ix <= max_coord and iy <= max_coord: ix1, iy1 = ix + s, iy + s for fx0, fy0, fx1, fy1 in fixed: if ix < fx1 and fx0 < ix1 and iy < fy1 and fy0 < iy1: break else: break up -= 1
out[2 * q] = lp out[2 * q + 1] = up
return out
def main() -> None: write = sys.stdout.write flush = sys.stdout.flush for line in sys.stdin: int_seg, _, _ = line.partition(";") ints = [int(tok) for tok in int_seg.split(",") if tok.strip()] write(",".join(map(str, propagate(ints))) + ";\n") flush()
if __name__ == "__main__": main()Neither variant is pure MiniZinc. In Defining Propagators in MiniZinc (Dekker, Stuckey, Tack, Tran, and Wagner, ModRef 2026), the authors propose writing bounds propagators directly in MiniZinc as functions from variable bounds to tightened bounds. With that feature, the Chebyshev propagator could live in the model itself, in about 80 lines of MiniZinc. MiniZinc 2.11.0 does not support it yet, so the version below cannot run.
DetailsThe Chebyshev propagator written in MiniZinc (proposed syntax)
The predicate keeps the :: minizinc_bounds_propagator annotation, and an overloaded function with the same name maps the bounds (a list of tuple(int, int)) to the new bounds.
predicate chebyshev_bounds(list of var int: vs, list of int: part_sizes) :: minizinc_bounds_propagator;
function tuple(int, int): cheb_inv(int: v) = let { int: k = floor(sqrt(int2float(v))), int: r = v - k * k, } in if r < k then (r, k) else (k, r - k) endif;
test valid_pos( int: v, int: s, int: m, array[int] of tuple(int, int, int): fixed_parts,) = let { tuple(int, int): xy = cheb_inv(v), } in xy.1 + s <= m /\ xy.2 + s <= m /\ forall (fp in fixed_parts) ( xy.1 + s <= fp.1 \/ fp.1 + fp.3 <= xy.1 \/ xy.2 + s <= fp.2 \/ fp.2 + fp.3 <= xy.2 );
function int: first_valid( int: v, int: limit, int: step, int: s, int: m, array[int] of tuple(int, int, int): fixed_parts,) = if (step > 0 /\ v > limit) \/ (step < 0 /\ v < limit) then v elseif valid_pos(v, s, m, fixed_parts) then v else first_valid(v + step, limit, step, s, m, fixed_parts) endif;
function list of tuple(int, int): chebyshev_bounds( list of tuple(int, int): bounds, list of int: part_sizes,) = let { int: num_parts = length(part_sizes), int: m = bounds[num_parts + 1].2, array[int] of tuple(int, int, int): fixed_parts = [ let { tuple(int, int): xy = cheb_inv(bounds[p].1), } in (xy.1, xy.2, part_sizes[p]) | p in 1 .. num_parts where bounds[p].1 == bounds[p].2 ], } in [ if bounds[p].1 == bounds[p].2 then bounds[p] else let { int: lo = first_valid(bounds[p].1, bounds[p].2, 1, part_sizes[p], m, fixed_parts), int: hi = if lo <= bounds[p].2 then first_valid(bounds[p].2, lo, -1, part_sizes[p], m, fixed_parts) else bounds[p].2 endif, } in (lo, hi) endif | p in 1 .. num_parts ] ++ [bounds[num_parts + 1]];
constraint implied_constraint(chebyshev_bounds(position ++ [max_pos], sizes));Comparing Gecode strategies
| Gecode variant | n=2 | n=3 | n=4 | n=5 | n=6 | n=7 | n=8 | n=9 | n=10 |
|---|---|---|---|---|---|---|---|---|---|
| Optimum (LB) | 4 (3) | 7 (6) | 11 (10) | 16 (15) | 22 (21) | 29 (28) | 36 (36) | 45 (45) | ≤56 (55) |
| Default (no annotation) | 0.15s | 0.16s | 0.17s | 11.5s | 22@0.28s | 30@0.77s | 58@10.7s | 74@259s | 104@196s |
| Interleaved | 0.15s | 0.15s | 0.17s | 10.2s | 22@0.26s | 29@0.35s | 37@0.65s | 47@27.8s | 57@2.57s |
| Left-bottom (disjunctive) | 0.14s | 0.14s | 0.16s | 44.7s | 22@0.29s | 29@0.47s | 37@0.94s | 47@79.6s | 57@4.57s |
| Chebyshev (shell) | 0.14s | 0.14s | 0.16s | 33.1s | 22@0.26s | 30@12.0s | 37@0.82s | 47@1.78s | 57@4.28s |
| Chebyshev black-box (C++ DLL) | 0.27s | 0.14s | 0.16s | 23.6s | 22@0.23s | 30@11.1s | 37@0.45s | 47@0.76s | 57@0.98s |
| Chebyshev black-box (Python) | 0.20s | 0.18s | 0.20s | 138s | 22@0.32s | 30@45.8s | 37@1.08s | 47@1.42s | 57@2.48s |
| Left-bottom (naive) | 0.18s | 0.15s | 2.59s | 16@0.34s | 22@1.27s | 29@5.97s | 37@101s | 70@294s | 71@299s |
| Chebyshev (naive) | 0.15s | 0.16s | 112s | 16@1.18s | 22@1.41s | 30@5.80s | 38@45.9s | 49@140s | none |
For , 56 is the best result across all solver runs; the exact packing from the original post gives the true optimum of 55.
The animation replays the eight variants on one shared clock, as for the solvers above, starting at .
36 parts, board 72×72
No solution yet
15 solutions, not proved in 300 s
Step 1 of 128 · 0.43 s
The chart plots the side of each variant’s best packing so far against time, across all sizes.
36 parts, board 72×72
Side of the best packing
Time since MiniZinc started, compilation included, log scale. A line that stops before the right edge ends where its solver proved optimality.
Table for n = 8
| Solver | First packing | Best packing | Packings | Optimality proved |
|---|---|---|---|---|
| Defaultno search annotation | 72 after 9.78 s | 58 after 10.7 s | 15 | no, 300 s limit |
| Interleavedinterleaved (x, y) | 72 after 0.56 s | 37 after 0.65 s | 36 | no, 300 s limit |
| Left-bottomdisjunctive | 72 after 0.43 s | 37 after 0.94 s | 36 | no, 300 s limit |
| Chebyshevshell order | 37 after 0.82 s | 37 after 0.82 s | 1 | no, 300 s limit |
| Black-box C++Chebyshev, blackbox_dll | 37 after 0.45 s | 37 after 0.45 s | 1 | no, 300 s limit |
| Black-box PythonChebyshev, blackbox_exec, Gecode 6.6.1 | 37 after 1.08 s | 37 after 1.08 s | 1 | no, 300 s limit |
| Left-bottom naivenaive encoding | 72 after 7.84 s | 37 after 101 s | 36 | no, 300 s limit |
| Chebyshev naivenaive encoding | 39 after 45.9 s | 38 after 45.9 s | 2 | no, 300 s limit |
How a heuristic is expressed matters as much as the geometric idea behind it. Both naive encodings were far worse than plain interleaved search, whereas the fixed versions all search cleanly. Interleaved search is still Gecode’s fastest proof of and finds the best packing at . On to the C++ propagator gets close to tight packings soonest, each in under a second, and at all three Chebyshev variants reach 47 within 1.8 s, against 27.8 s for interleaved search. No Gecode variant proves optimality beyond .
Summary
Minimizing the bounding square turns Partridge Packing from an all-or-nothing puzzle into an optimization problem with an answer for every .
For to , where the satisfaction problem is infeasible, the minimum side is always , and at and the exact tiling is optimal.
Adapting the model takes three changes: widen Pos and minimize max_pos with triangular_n as its lower bound, relax exact_fill to at_most_fill, and guard the edge-placement constraint so it only applies to an exact tiling.
| Solver | n=2 | n=3 | n=4 | n=5 | n=6 | n=7 | n=8 | n=9 | n=10 |
|---|---|---|---|---|---|---|---|---|---|
| Optimum (LB) | 4 (3) | 7 (6) | 11 (10) | 16 (15) | 22 (21) | 29 (28) | 36 (36) | 45 (45) | ≤56 (55) |
| Huub | 0.13s | 0.14s | 0.15s | 0.20s | 0.28s | 6.86s | 5.67s | 292s | 56@5.97s |
| OR-Tools CP-SAT (10t, med) | 0.15s | 0.18s | 0.24s | 0.39s | 0.81s | 12.6s | 39.2s | 46@11.3s | 56@14.5s |
| Pumpkin | 0.13s | 0.14s | 0.17s | 0.23s | 0.43s | 73.4s | 92.1s | 46@77.0s | 56@90.7s |
| Chuffed | 0.13s | 0.14s | 0.15s | 0.21s | 0.68s | 29@1.46s | 37@12.5s | 46@105s | 57@144s |
| Gecode (interleaved) | 0.15s | 0.15s | 0.17s | 10.2s | 22@0.26s | 29@0.35s | 37@0.65s | 47@27.8s | 57@2.57s |
| Gecode (Chebyshev shell) | 0.14s | 0.14s | 0.16s | 33.1s | 22@0.26s | 30@12.0s | 37@0.82s | 47@1.78s | 57@4.28s |
| Gecode (Chebyshev DLL) | 0.27s | 0.14s | 0.16s | 23.6s | 22@0.23s | 30@11.1s | 37@0.45s | 47@0.76s | 57@0.98s |
| HiGHS | 0.14s | 0.27s | 4.11s | 53.3s | 23@223s | 55@245s | 70@272s | none | none |
The Huub v100.1.0 release was the biggest surprise for me. Running on a single core, it beat the 10-thread CP-SAT median on to and was the only solver to prove optimal within five minutes. In the satisfaction post a year ago, OR-Tools was clearly the fastest MiniZinc backend; here it is still strong, but no longer first.
For Gecode, the lesson is to look at how hard a search works for its first solution on a loose board.
Thousands of failures there pointed to weak propagation on the auxiliary search variables, not to anything hard about the puzzle.
Fixing that (with an implied disjunctive, direct shell branching, or a black-box propagator) turned both naive heuristics into competitive ones.