文章标题:Minimum Square Partridge Packing with MiniZinc
正文: 在去年的 Solving the Partridge Packing Problem using MiniZinc 中,我们建模并求解了经典的 Partridge 装箱谜题。那个版本是一个困难的满足性问题。尺寸 2 到 7 完全无解,而要为更大尺寸找到一个解,需要相当程度的运气。今年我们看一个小变体:把同样的正方形部件装入能容纳它们的最小正方形中。
作为一个优化问题,该谜题在每个尺寸下都有答案,而且大多数求解器在求解过程中会产出一系列越来越紧凑的装箱方案。这使得它成为观察求解器搜索并比较搜索启发式方法的好方式。本文假定读者对上一篇有一定了解。
问题
在原始的 Partridge 装箱问题中,目标是把部件装入一个边长为 Tn=n(n+1)2T_n = \frac{n(n+1)}{2}Tn=2n(n+1) 的正方形,即第 nnn 个三角数。尺寸 nnn 有一个 1×11 \times 11×1 的部件、两个 2×22 \times 22×2 的部件,依此类推,直到 nnn 个尺寸为 n×nn \times nn×n 的部件。它们合起来恰好具有 Tn×TnT_n \times T_nTn×Tn 正方形的面积,因此一个解就是完美铺砌。
最小化变体要求找到能容纳所有部件的最小正方形。对于 n=2n=2n=2,满足性问题需要一个 3×33 \times 33×3 的正方形,而如原文章所示,两个 2×22 \times 22×2 的部件无法同时放入。能容纳它们的最小正方形是 4×44 \times 44×4:
该模型从一个边长为 2Tn2 T_n2Tn 的宽裕棋盘开始,因此对于 n=2n=2n=2 是 666。动画在那个棋盘上逐步展示 n=2n=2n=2 越来越紧凑的装箱方案,直到最优的 4×44 \times 44×4。
Packing 1 of 3
模型
我们改编上一篇中改进后的 Partridge 装箱模型。该模型采用一个更宽的棋盘、用于边界正方形的变量、一个放宽的填充约束,以及对边缘放置约束的守卫。
数据与变量
棋盘每边增长到三角数的两倍,这为求解器留出了充足空间来找到第一个装箱方案,然后再将其收紧。
set of int: Pos = 1 .. 2 * triangular_n;
新变量跟踪每个轴上使用的最大位置,两者中较大的那个就是边界正方形的边长。
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;
下界是完全填满的正方形的边长。我们最小化 max_pos,而每次分支定界收紧其上界时,部件可移动的空间就会变小。装箱约束不再使用固定的棋盘边长,而是让每个部件保持在 max_pos_x 和 max_pos_y 之内,而 diffn 不重叠约束保持不变。
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);
从精确填充到至多填充
原模型的 exact_fill 约束要求每一行和每一列都被完全填满。这只有在棋盘面积等于部件总面积时才成立。在更大的棋盘上,大多数行和列都有空余空间,因此该约束以 max_pos(当前边长)为填充上界:
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 比 exact_fill 弱得多,因为它只防止过度填充,但它在每个棋盘上都保持有效。若改为以 card(Pos) 为界,则会把每一行和每一列的上限设为允许的最大边长,这几乎说明不了任何问题。
边缘放置约束
文章标题:用 MiniZinc 实现最小正方形鹧鸪打包
正文: 边缘放置约束依赖于部件填满所有可用空间。只要存在任何空隙,边缘附近的几乎每一种放置都会再次变得可行。我们保持该约束不变,但为其加上守卫,使其仅在 max_pos 达到下界 triangular_n 且打包必须是精确密铺时生效。MiniZinc 会将守卫编译为半具体化约束。
% 从部件到给定 size 的可用面积量
function int: available_area(int: size) =
let {
% t 是 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 {
% 找到从边缘起可放置的最小距离。
int: min_distance_from_edge = min({d |
d in 1 .. size
where d * size > available_area(d),
}),
% 放置在这些位置对于完整打包是不可打包的
set of int: forbidden_placements =
% 低放置索引处的位置
2 .. (1 + min_distance_from_edge) union
% 高放置索引处的位置
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,
);
完整的 MiniZinc 模型可供下载。它使用下文描述的 Chebyshev shell 搜索,其他搜索策略以注释形式包含在内。
测试模型
作为第一个测试,这里是使用 OR-Tools CP-SAT 的 n=5n=5n=5。在原始问题中,15×1515 \times 1515×15 的正方形无解。
约束编程求解器使用分支定界进行优化:一旦找到一个解,之后的每个解都必须严格更优。CP-SAT 还是一个投资组合求解器,并行运行多个工作线程,每个线程有自己的策略,因此连续的解可能看起来非常不同。动画回放了 n=5n=5n=5 的运行过程,直至最优的 16×1616 \times 1616×16 正方形。
打包 14 个中的第 1 个
观察求解器搜索
给定相同的模型,求解器的搜索方式却大不相同。我在 n=2n = 2n=2 到 101010 的规模上运行了其中六个,使用 MiniZinc 2.11.0,在 Apple M1 Max(10 核)上,每次运行限时 300 秒,包含编译时间。
- Gecode 6.6.1 是一个经典约束编程求解器,不具备学习能力。它遵循模型的 Chebyshev shell 搜索顺序,详见下一节。
- Chuffed 0.14.0、Huub 100.1.0 和 Pumpkin 0.5.0 是单线程惰性子句生成(LCG)求解器,会从每次失败中学习一条新约束。三者均以自由搜索(-f)运行,由求解器选择分支对象。
- OR-Tools CP-SAT 9.15 也会学习,使用自由搜索,并加入线性松弛和由 10 个并行工作线程组成的投资组合。其运行结果有波动,因此我对每个规模运行五次并取中位数。
- HiGHS 1.16.0 是一个混合整数规划求解器,其分支定界使用模型的线性松弛而非传播。
下面的动画回放了 n=6n = 6n=6 的运行,其中 21 个部件从 42×4242 \times 4242×42 的棋盘开始。顶部的按钮可切换到 n=5n = 5n=5、777 或 888。每个棋盘在共享时钟上显示其求解器目前最好的打包。时间线在对数时间刻度上为每个解标记一个刻度;拖动它可跳转到任意时刻。
21 个部件,棋盘 42×42
图表:Gecode 6.6.0 Chebyshev shell 顺序
尚无解
1 个解,300 秒内未证明
图表:Chuffed 0.14.0 自由搜索(-f)
尚无解
21 个解,0.68 秒证明最优
图表:OR-Tools CP-SAT 9.15 自由搜索,10 线程
尚无解
21 个解,0.81 秒证明最优
图表:Huub 100.1.0 自由搜索(-f)
0.21 秒后边长为 42
14 个解,在 0.28 秒内证明最优
图表:Pumpkin 0.5.0 自由搜索 (-f)
暂无解
1 个解,在 0.43 秒内证明最优
图表:HiGHS 1.16.0 默认设置
暂无解
7 个解,300 秒内未证明最优
第 1 步,共 65 步 · 0.21 秒
Gecode 从角落向外构建,其第一个布局在 0.26 秒后边长为最优的 22。然而它从未证明最优性,并将剩余的五分钟用于搜索。
Chuffed 和 CP-SAT 从另一端开始。它们的第一个布局铺满整个棋盘,随后每个解恰好比前一个小一,从 42 到 22 共 21 个解。Huub 也是如此,只是有几次较大的跳跃。三者随后都在一秒内证明 22 为最优。Pumpkin 在 0.43 秒后仅报告最优布局并立即证明。
HiGHS 需要 37 秒才得到第一个布局,边长为 35,最终停在 23。该模型充满析取约束(一个部件位于另一个的左侧、右侧、上方或下方),其线性松弛对正方形的边长几乎不提供信息。
对于 n=8,各部件可以恰好铺满正方形,因此最优值就是下界 36。将上方的动画切换到 n=8,观看 72×72 棋盘上的 36 个部件。这里的竞赛全在最后一步。Gecode 再次起步接近,在 0.82 秒后达到 37,此后毫无进展。Huub、CP-SAT 和 Chuffed 分别在 1.1 秒、3.6 秒和 12.5 秒内降到 37。Huub 在 5.7 秒找到精确铺法,这同时证明了最优性,CP-SAT 在 39 秒找到。Chuffed 始终未能跨过最后一个单位。Pumpkin 沉默 51 秒后报告 37,并在 92 秒找到铺法。
图表涵盖所有尺寸,将每个求解器迄今最佳布局的边长对时间作图。线条在其求解器证明最优性处提前终止,未到达右边缘。使用滑块改变 n,点击或悬停在求解器上以高亮显示。
36 个部件,棋盘 72×72
最佳布局的边长
自 MiniZinc 启动以来的时间,包括编译,对数刻度。虚线为最优边长 36。线条在右边缘之前终止之处即其求解器证明最优性的位置。
| 求解器 | 第一个布局 | 最佳布局 | 布局数 | 是否证明最优 |
|---|---|---|---|---|
| Gecode Chebyshev 壳序 | 0.82 秒后 37 | 0.82 秒后 37 | 1 | 否,300 秒限制 |
| Chuffed 自由搜索 (-f) | 1.02 秒后 72 | 12.5 秒后 37 | 36 | 否,300 秒限制 |
| CP-SAT 自由搜索,10 线程,5 次中位数 | 1.98 秒后 72 | 39.2 秒后 36 | 28 | 39.2 秒后 |
| Huub 自由搜索 (-f) | 0.40 秒后 72 | 5.67 秒后 36 | 32 | 5.67 秒后 |
| Pumpkin 自由搜索 (-f) | 50.9 秒后 37 | 92.1 秒后 36 | 2 | 92.1 秒后 |
| HiGHS 默认设置 | 272 秒后 70 | 272 秒后 70 | 1 | 否,300 秒限制 |
对于 n=6 及以下,每个学习型求解器都在一秒内证明最优。在 n=7 时,证明开始耗费真实时间,而在 n=9 时,只有 Huub 在 292 秒后证明了精确的 45×45 铺法。对于 n=2 到 7,最优值总是比下界大 1:4、7、11、16、22 和 29。在 n=10 时,没有求解器在五分钟内低于 56,比原帖中达到的 55 大一。
两类曲线源于求解器的搜索方式。Gecode 的次序将最大的部件放在最前,每个都尽可能靠近角落,很像贪心的左下布局,因此其第一个解已接近最优。证明不存在更好的解则是另一回事:没有学习机制,Gecode 会在每个子树中再次遇到相同的失败排列。
文章标题:Minimum Square Partridge Packing with MiniZinc
正文: 在自由搜索下,Chuffed、Huub 和 CP-SAT 反而从一个使用整块棋盘的布局开始。每得到一个解之后,新的界 max_pos ≤ best − 1 通常在其允许的最大值处即被满足,因此在仍有松弛时每一步都是容易的问题。在更早的界下学到的约束仍然有效,所以当棋盘变得紧凑时,求解器已经知道了较小棋盘为何失败的大部分原因。Pumpkin 是个例外。直到 n=9n = 9n=9 它最多报告两个布局,且第一个最多比最优值高两,而在 n=10n = 10n=10 时它像其他求解器一样从 72 开始逐步下降。
Gecode and Search Heuristics
Gecode 没有自动搜索启发式,这使它成为从 MiniZinc 显式引导搜索的良好试验台。基准设置与上面相同。在表格中,一个普通的时长(如 10.2s)表示求解器证明了最优性,best@t(如 [email protected])表示它达到时间限制,其找到的最佳正方形边长为 best、时刻为 t 秒,none 表示完全没有解。
No heuristic, and interleaved search
没有搜索注解时,Gecode 能证明到 n=5n = 5n=5 的最优性(11.5 s),但在 n=6n = 6n=6 之后很快落后。在 n=10n = 10n=10 时,它仅找到一个边长为 110 的首个布局就需要 73 s。
对每个部件的 x 和 y 一起分支,使每个部件在下一个之前被完整放置,会带来很大差别。由于 sizes 是反向的,部件按从大到小的顺序放置。
solve :: int_search([[x[p], y[p]][i] | p in Parts, i in 1 .. 2], input_order, indomain_min) minimize max_pos;
交错搜索在 10.2 s 内证明 n=5n = 5n=5,在 0.35 s 内找到 n=7n = 7n=7 的最优值 29,并在较大规模上达到距最优值一到两个单位以内。它的首个布局仍然把部件堆叠在第 1 列,并触及 2Tn2 T_n2Tn 棋盘的边缘,因此分支定界必须从那里开始缩小正方形。
Left-bottom position
引导搜索的另一种方法是对一个编码放置顺序的辅助变量进行分支。按列、从下到上给单元格编号,得到我在上一篇博文中为 Gecode 尝试过的左下策略:
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;
这比交错搜索差得多。证明 n=4n = 4n=4 从 0.17 s 变成 2.59 s,而 n=5n = 5n=5 不再能完成。最明显的症状甚至在优化开始之前就出现了。棋盘的面积是部件的四倍,因此首个布局本应轻而易举,而交错搜索在 n=7n = 7n=7 时以 0 次失败找到一个。左下模型需要 3,064 次。
原因在于 diffn 分别对 x 和 y 进行剪枝,因此它从不从 position 中移除单个被占据的单元格。一个 3×33 \times 33×3 的部件被放在角落后,x = 1 在其上方仍然可能,y = 1 在其右侧仍然可能,因此单元格 (1,1)(1, 1)(1,1) 留在其他每个部件的 position 域中。该部件覆盖的其他单元格也是如此,所以 indomain_min 会尝试它们并一次失败一个单元格。除此之外,smallest 会跳到可能 position 最小的那个部件,往往是一个能填入早期空隙的小部件,这打破了从大到小的顺序。
这两个问题都可以在 MiniZinc 中修复。在按列主序编号中,一个大小为 sss 的正方形覆盖 sss 条长度为 sss 的竖直条带,间隔为 card(Pos),因此对这些条带施加一个隐含的 1D disjunctive 可直接从 position 中剪掉被占据的单元格。切换到 input_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;
首个布局的失败次数降到 0,n=4n = 4n=4 再次在 0.16 s 内得到证明,而 n=10n = 10n=10 在 4.6 s 内达到 57,而非 299 s 后的 71。
文章标题:用 MiniZinc 实现最小方形鹧鸪打包
正文: 按列编号格子,从下到上,再把各列首尾相接。棋盘就变成了一条线,一个尺寸为 sss 的正方形会变成 sss 条长度为 sss 的条带,它覆盖的每一列对应一条。两个正方形在棋盘上重叠,当且仅当它们的两条条带在这条线上重叠。
按列编号格子,从下到上:第 1 列是 0 到 5,第 2 列是 6 到 11,依此类推。把各列首尾相接,棋盘就变成了一条由 36 个格子组成的线。指向一个格子,就能在这条线上找到它。
让条带在一条线上彼此分开,正是 disjunctive 所做的事。它是共享单台机器的任务的经典约束,这里把条带的第一个格子作为开始时间,把部件的尺寸作为持续时间。开始时间由 position 构建,因此 disjunctive 排除的每一个开始时间,都是从 position 中移除的一个格子。搜索按最大优先放置部件,并为每个部件尝试剩余的最小 position;下图展示了区别:
仅使用 diffn 时,重叠规则针对整列和整行推理,而非单个格子。已放置正方形下方的格子看起来仍然可能,因此搜索会逐个尝试它们,失败 3 次后才到达格子 3。
浪费的尝试:–第一个可用格子:–
点击棋盘以放置或移除所选尺寸的正方形。
- 搜索尝试前已划掉
- ✕搜索尝试过,重叠
- ✓搜索尝试过,可放置
这里的棋盘是 6×66 \times 66×6,而不是 2Tn2 T_n2Tn 宽,并且格子从 0 开始编号,而模型的 x * card(Pos) + y 会将每个编号平移相同的量。“仅 diffn”模式是简化版:只有当部件在该格子所在的整列或整行中都放不下时,它才会划掉该格子。Gecode 的 diffn 推理更细致,但它同样从不会从 position 中移除单个被占用的格子。
Chebyshev 壳层
目标奖励接近角落的打包,这暗示按到该角落的 Chebyshev(棋盘)距离对格子排序。格子 (i,j)(i, j)(i,j) 属于壳层 k=max(i−1,j−1)k = \max(i-1, j-1)k=max(i−1,j−1),即原点处 (k+1)×(k+1)(k+1) \times (k+1)(k+1)×(k+1) 正方形的外边缘。在一个壳层内,顶部条带从左到右编号,随后右侧条带从下到上编号:
我的第一个编码通过一个 2D 查找表将 (x[p], y[p]) 映射为格子编号 position[p],并用 smallest 分支。它慢得令人痛苦:证明 n=4n = 4n=4 花了 112 秒,而在 n=10n = 10n=10 时,Gecode 在 300 秒内根本没有找到任何打包。该编码具有朴素左下模型的两个问题,还多了第三个问题。该表会编译成对 (2Tn)2(2 T_n)^2(2Tn)2 个条目的 2D element 约束(n=10n = 10n=10 时为 12,100),这使得每个搜索节点都很昂贵。即便如此,这个几何思路仍显示出潜力:n=7n = 7n=7 的第一个打包边长为 30,而交错搜索为 56。
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;
壳层顺序并不需要这张表。对壳层 max(x[p], y[p]) 分支,然后对 x[p] 和 y[p] 分支,全部使用 input_order,就能在按最大优先放置部件的同时得到相同的壳层顺序:
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;
这反过来改变了启发式方法的思路。证明 n=4n = 4n=4 只需 0.16 s 而不是 112 s,n=5n = 5n=5 在 33 s 内完成证明,而 Gecode 在 4.3 s 内就在 n=8n = 8n=8 到 101010 上达到了 37、47 和 57。这就是可下载模型中的搜索过程。
黑盒 Chebyshev propagator
外壳搜索通过位置绕开了问题,而不是去修复它。在 Chebyshev 序下,一个正方形会覆盖来自多个外壳的格子,因此不存在像左下角情形那样能剪除已占用格子的简单析取约束。MiniZinc 2.11 新增了一个实验性的黑盒 propagator 接口,提供了另一条路:保留基于表格的位置变量,并为它们附加一个自定义的 bounds propagator。
Gecode 每次运行该 propagator 时,都会传入每个位置及 max_pos 的当前边界。propagator 收集已经放置的部件,然后对每个剩余部件,从两端边界向内扫描,跳过每一个会与已放置部件重叠或超出当前 max_pos 的格子。
逐壳为格子编号,并把各壳首尾相接。前 k2k^2k2 个编号总是填满角落处的 k×kk \times kk×k 正方形,这就是为什么取最小编号会向外填充。但正方形在数轴上不再有固定形状。它会碎成若干片段,片段的数量和长度取决于它所在的位置:
外壳 k 包含较大坐标为 k 的格子,即角落周围的一条 L 形带。每个外壳沿其上边缘从左到右编号,再沿其右边缘从下往上编号,最后终止于外角。外壳 k 从 k² 开始,因此前 k² 个编号总是填满 k × k 的角落正方形,取最小编号就会从角落向外填充。
没有固定形状,就无法陈述析取约束,因此 propagator 改为逐个检查格子。它只移动每个位置区间的两端,从每一端出发,在第一个该部件能够放下的格子处停下。下面的棋盘初始时已放置两个 3×33 \times 33×3 部件,接下来要放置一个 2×22 \times 22×2 部件:
按 Play 观看搜索放置 2 × 2 部件的过程,按外壳顺序、从小到大尝试仍然可能的格子。
Propagator 检查次数:–浪费的搜索尝试次数:–
一个部件位于某格子时,其左下角就在该格子处。点击棋盘可放置或移除所选尺寸的正方形。
- 正在检查或尝试的下一个部件(绿色表示可以放下)
- 在搜索尝试之前就被划掉
- ✕搜索尝试过,重叠
- ✓搜索尝试过,可以放下
- 仍然允许的最大边长
“仍然允许的最大边长”代表 max_pos 的当前上界,棋盘为 6×66 \times 66×6,格子从 0 开始编号。与析取约束的示例一样,“仅表格”模式经过了简化:只有当部件在该格子所在的整列或整行中都放不下时,它才会划掉该格子。
propagator 在 MiniZinc 中声明,在 MiniZinc 之外实现,可以作为子进程(:: blackbox_exec),也可以作为共享库(:: 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;
我用 C++ 和 Python 编写了同一个 propagator。使用 C++ 库时,首次放置失败次数降为 0,n=5n = 5n=5 在 23.6 s 内完成证明,Gecode 在 n=8n = 8n=8 到 101010 上各自不到一秒就达到了 37、47 和 57,比其他任何 Gecode 变体都快。Python 子进程探索的是同一棵搜索树,但每次传播都要与另一个进程往返通信,因此证明 n=5n = 5n=5 需要 138 s 而不是 23.6 s。它还要求 Gecode 6.6.1,因为在 6.6.0 下子进程在较长的运行中会中途失败。
文章标题:用 MiniZinc 实现最小方形鹧鸪打包
正文: MiniZinc 通过 C 接口加载该库:只有一个函数 fzn_blackbox,它接收以 int64_t 对形式给出的边界,并把收紧后的边界写回。表示失败的方式是为第一个变量写入空区间 [1, 0]。在这个函数背后,传播器是普通的 C++ 代码,每个实例规模对应的单元格坐标只计算一次,并在各次调用之间共享。用 c++ -std=c++17 -O3 -dynamiclib 构建,在 Linux 上则用 -shared。下载 chebyshev_bounds.cpp。
图表:chebyshev_bounds.cpp
文章标题:Minimum Square Partridge Packing with MiniZinc
正文:
// Chebyshev bounds propagator for Minimizing Partridge Packing, loaded by// MiniZinc through :: blackbox_dll.//// 构建(macOS):// c++ -std=c++17 -O3 -Wall -Wextra -dynamiclib \// -o libchebyshev_bounds.dylib chebyshev_bounds.cpp//// 该传播器获得 position[1..P] ++ [max_pos] 的边界,每个变量对应一对// [lb, ub],其中 position[p] 是部件 p 左下角所在的 Chebyshev 单元格编号。// lb == ub 的部件已放置。对于其他每个部件,边界将收紧以跳过该部件会与// 已放置部件重叠或超出 max_pos 上界的单元格。
#include <algorithm>#include <array>#include <cmath>#include <cstddef>#include <cstdint>#include <memory>#include <mutex>#include <vector>
namespace {
// 棋盘的一个单元格,坐标从 0 开始。struct Cell { int x; int y;};
// 正方形部件覆盖的单元格,以半开区间 [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 包含满足 max(x, y) = k 的单元格,起始于 k * k。在一个// shell 内,顶部条带(x < y)从左到右编号,然后是// 右侧条带(x >= y)从下到上编号。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)};}
// 具有 n (n + 1) / 2 个部件的实例规模 n,若不存在则返回 0。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;}
// 某一实例规模的部件尺寸与单元格坐标。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)); } }
// 部件数量,同时也是完美密铺的边长。 int parts; // 模型中的棋盘是完美密铺边长的两倍。 int board_side; // 尺寸从大到小,与模型中的 sizes 一致。 std::vector<int> sizes; // 每个单元格编号对应的单元格,使热循环避免使用 sqrt。 std::vector<Cell> cells;};
constexpr int max_instance_size = 31;
// 实例只构建一次,并由每次传播器调用共享,包括来自并行搜索线程的// 调用。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();}
// 给定 max_pos 的上界,收紧未放置部件的位置边界。// 若无法进行任何放置则返回 false。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); }); };
// 让每个部件都留在边长范围内,并收集已放置的部件。 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;
// 把每个未放置部件的边界移过它不能放置的单元格。 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
// MiniZinc 的 blackbox_dll 所调用的入口点。整数变量以// lb、ub 对的形式传入,结果按相同的布局写出。第一个变量的// 空区间表示失败。该传播器没有// 浮点变量。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;
// 不允许任何异常穿过 C 接口。如果没有结果,边界 // 保持原样,这始终是可靠的。 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); }}
文章标题:用 MiniZinc 进行最小方形 Partridge 装箱
正文: 每次传播器调用时,子进程从标准输入读取一行以逗号分隔的整数边界,并写回一行收紧后的边界。其逻辑与 C++ 版本相同。下载 chebyshev_bounds.py。
图表: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()
文章标题:Minimum Square Partridge Packing with MiniZinc
正文: 两种变体都不是纯 MiniZinc。在 Defining Propagators in MiniZinc(Dekker、Stuckey、Tack、Tran 和 Wagner,ModRef 2026)中,作者提出直接用 MiniZinc 编写边界传播器,将其作为从变量边界到收紧边界的函数。有了这一特性,Chebyshev 传播器就可以存在于模型本身之中,大约 80 行 MiniZinc 代码。MiniZinc 2.11.0 尚不支持该特性,因此下面的版本无法运行。
该谓词保留了 :: minizinc_bounds_propagator 注解,而一个同名的重载函数将边界(一个 tuple(int, int) 列表)映射到新的边界。
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));
比较 Gecode 策略
| Gecode 变体 | n=2 | n=3 | n=4 | n=5 | n=6 | n=7 | n=8 | n=9 | n=10 |
|---|---|---|---|---|---|---|---|---|---|
| 最优值 (LB) | 4 (3) | 7 (6) | 11 (10) | 16 (15) | 22 (21) | 29 (28) | 36 (36) | 45 (45) | ≤56 (55) |
| 默认(无注解) | 0.15s | 0.16s | 0.17s | 11.5s | [email protected] | [email protected] | [email protected] | 74@259s | 104@196s |
| 交错 | 0.15s | 0.15s | 0.17s | 10.2s | [email protected] | [email protected] | [email protected] | [email protected] | [email protected] |
| 左下(析取) | 0.14s | 0.14s | 0.16s | 44.7s | [email protected] | [email protected] | [email protected] | [email protected] | [email protected] |
| Chebyshev(壳) | 0.14s | 0.14s | 0.16s | 33.1s | [email protected] | [email protected] | [email protected] | [email protected] | [email protected] |
| Chebyshev 黑盒(C++ DLL) | 0.27s | 0.14s | 0.16s | 23.6s | [email protected] | [email protected] | [email protected] | [email protected] | [email protected] |
| Chebyshev 黑盒(Python) | 0.20s | 0.18s | 0.20s | 138s | [email protected] | [email protected] | [email protected] | [email protected] | [email protected] |
| 左下(朴素) | 0.18s | 0.15s | 2.59s | [email protected] | [email protected] | [email protected] | 37@101s | 70@294s | 71@299s |
| Chebyshev(朴素) | 0.15s | 0.16s | 112s | [email protected] | [email protected] | [email protected] | [email protected] | 49@140s | none |
对于 n=10n = 10n=10,56 是所有求解器运行中的最佳结果;原帖中精确的 55×5555 \times 5555×55 包装给出了真实最优值 55。
文章标题:用 MiniZinc 进行最小正方形鹧鸪打包
正文: 该动画在同一个时钟上重放八个变体,与上面的求解器一样,从 n=8n = 8n=8 开始。
36 个部件,棋盘 72×72
图表:Default(无注解)
暂无解
15 个解,300 秒内未证明
图表:Interleaved
暂无解
36 个解,300 秒内未证明
图表:Left-bottom(析取式)
0.43 秒后边长为 72
36 个解,300 秒内未证明
图表:Chebyshev 壳顺序
暂无解
1 个解,300 秒内未证明
图表:Chebyshev 黑盒(C++ DLL)
暂无解
1 个解,300 秒内未证明
图表:Chebyshev 黑盒(Python)
暂无解
1 个解,300 秒内未证明
图表:Left-bottom(朴素)
暂无解
36 个解,300 秒内未证明
图表:Chebyshev(朴素)
暂无解
2 个解,300 秒内未证明
第 1 步,共 128 步 · 0.43 秒
该图表绘制了所有尺寸下,每个变体目前最佳打包的边长随时间的变化。
36 个部件,棋盘 72×72
最佳打包的边长
自 MiniZinc 启动以来的时间,包含编译,对数刻度。在右边缘之前停止的线,其终点即该求解器证明最优的位置。
| 求解器 | 首次打包 | 最佳打包 | 打包数 | 已证明最优 |
|---|---|---|---|---|
| Default 无搜索注解 | 9.78 秒后为 72 | 10.7 秒后为 58 | 15 | 否,300 秒上限 |
| Interleaved 交错 (x, y) | 0.56 秒后为 72 | 0.65 秒后为 37 | 36 | 否,300 秒上限 |
| Left-bottom 析取式 | 0.43 秒后为 72 | 0.94 秒后为 37 | 36 | 否,300 秒上限 |
| Chebyshev 壳顺序 | 0.82 秒后为 37 | 0.82 秒后为 37 | 1 | 否,300 秒上限 |
| 黑盒 C++ Chebyshev,blackbox_dll | 0.45 秒后为 37 | 0.45 秒后为 37 | 1 | 否,300 秒上限 |
| 黑盒 Python Chebyshev,blackbox_exec,Gecode 6.6.1 | 1.08 秒后为 37 | 1.08 秒后为 37 | 1 | 否,300 秒上限 |
| Left-bottom 朴素 朴素编码 | 7.84 秒后为 72 | 101 秒后为 37 | 36 | 否,300 秒上限 |
| Chebyshev 朴素 朴素编码 | 45.9 秒后为 39 | 45.9 秒后为 38 | 2 | 否,300 秒上限 |
启发式如何表达,与其背后的几何思想同样重要。两种朴素编码都远不如单纯的交错搜索,而修正后的版本都能干净地搜索。交错搜索仍是 Gecode 证明 n=5n = 5n=5 的最快方式,并在 n=7n = 7n=7 时找到最佳打包。在 n=8n = 8n=8 到 101010 上,C++ 传播器最快接近紧密打包,每个都在一秒以内,而在 n=9n = 9n=9 时,三个 Chebyshev 变体都在 1.8 秒内达到 47,相比之下交错搜索需要 27.8 秒。没有 Gecode 变体能在 n=5n = 5n=5 之后证明最优性。
总结
最小化边界正方形,将鹧鸪打包从一个全有或全无的谜题变成了一个对每个 nnn 都有答案的优化问题。对于 n=2n = 2n=2 到 777,在满足性问题不可行的情况下,最小边长始终是 Tn+1T_n + 1Tn+1,而在 n=8n = 8n=8 和 n=9n = 9n=9 时,精确铺砌是最优的。调整模型需要三处改动:将 Pos 加宽,并以 triangular_n 作为其下界来最小化 max_pos;将 exact_fill 放宽为 at_most_fill;并对边缘放置约束加保护,使其仅适用于精确铺砌。
| 求解器 | n=2 | n=3 | n=4 | n=5 | n=6 | n=7 | n=8 | n=9 | n=10 |
|---|---|---|---|---|---|---|---|---|---|
| 最优值 (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 | [email protected] |
| OR-Tools CP-SAT (10t, med) | 0.15s | 0.18s | 0.24s | 0.39s | 0.81s | 12.6s | 39.2s | [email protected] | [email protected] |
| Pumpkin | 0.13s | 0.14s | 0.17s | 0.23s | 0.43s | 73.4s | 92.1s | [email protected] | [email protected] |
| Chuffed | 0.13s | 0.14s | 0.15s | 0.21s | 0.68s | [email protected] | [email protected] | 46@105s | 57@144s |
| Gecode (interleaved) | 0.15s | 0.15s | 0.17s | 10.2s | [email protected] | [email protected] | [email protected] | [email protected] | [email protected] |
| Gecode (Chebyshev shell) | 0.14s | 0.14s | 0.16s | 33.1s | [email protected] | [email protected] | [email protected] | [email protected] | [email protected] |
| Gecode (Chebyshev DLL) | 0.27s | 0.14s | 0.16s | 23.6s | [email protected] | [email protected] | [email protected] | [email protected] | [email protected] |
| HiGHS | 0.14s | 0.27s | 4.11s | 53.3s | 23@223s | 55@245s | 70@272s | none | none |
Huub v100.1.0 的发布对我来说是最大的惊喜。它在单核上运行,却在 n=6n = 6n=6 到 888 上击败了 10 线程 CP-SAT 的中位成绩,并且是唯一在五分钟内证明 n=9n = 9n=9 最优的求解器。在一年前的 satisfaction 帖子中,OR-Tools 显然是最快的 MiniZinc 后端;如今它依然强劲,但已不再位列第一。
对 Gecode 而言,教训在于要考察它在宽松棋盘上为获得第一个解所付出的搜索代价。那里的成千上万次失败表明,问题在于辅助搜索变量上的传播较弱,而不是谜题本身有多难。修复这一点(通过隐含的 disjunctive、直接的 shell 分支,或黑盒传播器)后,两种朴素启发式都变得具有竞争力。