Cleaned up rectangular packing problem
@@ -12,6 +12,7 @@ from cpmpy import *
import numpy as np
from PIL import Image, ImageDraw, ImageFont
+def run():
# 2D dimensions of the items to be packed
widths = [5, 6, 4, 3, 2, 4, 3, 1, 2, 1, 7, 3]
heights = [1, 2, 3, 2, 1, 2, 4, 6, 5, 1, 1, 2]
@@ -31,6 +32,18 @@ min_height_rect = max(heights)
min_area = sum([widths[i]*heights[i] for i in range(0,n)])
max_area = max_width_rect*max_height_rect
+ (model, vars) = model_rect_packing(widths, heights, n, max_width_rect,
+ max_height_rect, min_width_rect, min_height_rect,
+ min_area, max_area)
+
+ if model.solve():
+ for v in vars:
+ print(v + ": " + str(vars[v].value()))
+ visualize_rect_packing(vars, widths, heights, n)
+
+def model_rect_packing(widths, heights, n, max_width_rect,
+ max_height_rect, min_width_rect, min_height_rect,
+ min_area, max_area):
# Decision variables
rect_height = intvar(min_height_rect, max_height_rect)
rect_width = intvar(min_width_rect, max_width_rect)
@@ -54,12 +67,14 @@ model = Model(
# Minimize wrt the overall area
model.minimize(rect_area)
-if model.solve():
- print(rect_height.value())
- print(rect_width.value())
- print(rect_area.value())
- print(x.value())
- print(y.value())
+ return (model, {"rect_height": rect_height, "rect_width": rect_width, "rect_area": rect_area, "x": x, "y": y})
+
+def visualize_rect_packing(vars, widths, heights, n):
+ rect_width = vars["rect_width"]
+ rect_height = vars["rect_height"]
+ rect_area = vars["rect_area"]
+ x = vars["x"]
+ y = vars["y"]
# Draw solution
# Define start location image & unit size
@@ -103,3 +118,6 @@ if model.solve():
img1.text((center_x - w / 2, center_y - h / 2), msg, fill="white", font=myFont)
img.show()
+
+if __name__ == "__main__":
+ run()
\ No newline at end of file
