Repository navigation
Expand file tree
/
Copy pathexample.py
More file actions
260 lines (187 loc) · 11.5 KB
/
Copy pathexample.py
File metadata and controls
260 lines (187 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""pyckingsolver's main features, one `Nesting` scenario each, every one saved as a WebP in img/.
Run (from the repo root): uv run python examples/example.py [scenario ...]
"""
import sys
from collections import Counter
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
from shapely.geometry import Point, Polygon, box
import pyckingsolver as pk
from pyckingsolver.shapes import circle, polygon, rectangle, to_shapely, triangle
OUT = Path(__file__).resolve().parent.parent / "img"
QUARTER_TURNS = [0, 90, 180, 270]
SHORT = {"time_limit": 10, "idle_limit": 2} # at most 10 s, stopped 2 s after the last improvement
# MARK: parts, each anchored at the origin
def disc(r):
"""A native circle: one exact arc for the solver."""
return circle(r, pk.shapes.Point(r, r))
def plate(w, h, r, inset):
"""A Shapely polygon: a rectangle with a bolt hole near each corner."""
holes = [Point(x, y).buffer(r, 16).exterior for x in (inset, w - inset) for y in (inset, h - inset)]
return Polygon(box(0, 0, w, h).exterior, holes)
def bracket(w, h, t):
return polygon([(0, 0), (w, 0), (w, t), (t, t), (t, h), (0, h)])
def gusset(a):
return triangle(pk.shapes.Point(0, 0), pk.shapes.Point(a, 0), pk.shapes.Point(0, a))
def slot(length, r):
"""A stadium: `(x, y, 1)` is the centre of an anticlockwise arc between its neighbours."""
return polygon([(r, 0), (r + length, 0), (r + length, r, 1), (r + length, 2 * r), (r, 2 * r), (r, r, 1)])
def arch(w, h):
"""A rectangle with a half-circle on top."""
return polygon([(0, 0), (w, 0), (w, h), (w / 2, h, 1), (0, h)])
# MARK: rendering
SS = 2 # draw at twice the size, then downscale for smooth edges
COLORS = ["#4e79a7", "#f28e2b", "#59a14f", "#e15759", "#76b7b2", "#edc948", "#b07aa1", "#9c755f"]
BG, SHEET, INK, DEFECT, DEFECT_FILL = "#ffffff", "#e9edf2", "#2b2f36", "#c0392b", "#f5c6c0"
def render(name, title, result, outline, defects=(), x_max=None):
"""Every sheet used side by side (wrapping) at one scale: `outline` a Shapely polygon, or a dict of them by
stock key; `defects` as polygons; `x_max` crops an open strip. Parts coloured by key, pinned ones drawn thick."""
colors = {}
outlines = outline if isinstance(outline, dict) else {s.stock: outline for s in result.sheets}
w = max((x_max or o.bounds[2]) for o in outlines.values())
h = max(o.bounds[3] for o in outlines.values())
n = len(result.sheets)
width, pad, gap, head = 1400 * SS, 16 * SS, 24 * SS, 64 * SS
s = min(max((width - (n - 1) * gap) / (n * w), (width - 2 * gap) / (3 * w)), width / w, 500 * SS / h)
per_row = max(1, int((width + gap) // (w * s + gap)))
rows = -(-n // per_row)
font = ImageFont.load_default(22 * SS)
img_w = max(min(n, per_row) * (w * s + gap) - gap, font.getlength(title))
img = Image.new("RGB", (round(img_w) + 2 * pad, round(head + rows * (h * s + gap) - gap + pad)), BG)
d = ImageDraw.Draw(img)
d.text((pad, 14 * SS), title, fill=INK, font=font)
for k, sheet in enumerate(result.sheets):
left, top = pad + (k % per_row) * (w * s + gap), head + (k // per_row) * (h * s + gap)
def pts(ring):
return [(left + x * s, top + (h - y) * s) for x, y, *_ in ring.coords]
sheet_shape = outlines[sheet.stock]
if x_max is not None:
sheet_shape = sheet_shape.intersection(box(0, 0, x_max, h))
d.polygon(pts(sheet_shape.exterior), fill=SHEET, outline=INK, width=SS)
for p in defects:
d.polygon(pts(p.exterior), fill=DEFECT_FILL, outline=DEFECT, width=2 * SS)
for part, poly in sorted(((p, p.polygon) for p in sheet.parts), key=lambda pp: -pp[1].area):
color = COLORS[colors.setdefault(part.key, len(colors)) % len(COLORS)] # big first, small ones on top
d.polygon(pts(poly.exterior), fill=color, outline=INK, width=4 * SS if part.pinned else SS)
for hole in poly.interiors:
d.polygon(pts(hole), fill=SHEET, outline=INK, width=SS)
img.resize((img.width // SS, img.height // SS), Image.LANCZOS).save(OUT / f"{name}.webp", quality=80)
print(f"{name}.webp {title}")
def parts(result):
return [p for s in result.sheets for p in s.parts]
def summary(result):
return f"{len(parts(result))} parts, {len(result.sheets)} sheet(s), {100 - result.waste_percentage * 100:.0f}% used"
# MARK: parts with holes: discs nest in the plates' bolt holes (tree search fills holes; auto-selection: 0)
def laser_sheet():
job = pk.Nesting(pk.Objective.Knapsack, spacing=3)
job.add_sheet(1000, 500)
for key, shape, count in (("plate", plate(220, 140, 18, 40), 12), ("bracket", bracket(160, 120, 40), 6),
("gusset", gusset(120), 6), ("disc", disc(8), 80)):
job.add_part(shape, count=count, key=key, rotations=QUARTER_TURNS)
result = job.solve(**SHORT, use_tree_search=True) # an upstream option, by its upstream name
shapes = [p.polygon for p in parts(result)]
holes = [Polygon(r) for p in shapes for r in p.interiors]
in_holes = sum(any(h.contains(p) for h in holes) for p in shapes)
render("laser_sheet", f"Knapsack, 3 mm spacing, tree search: {summary(result)}, {in_holes} in bolt holes",
result, box(0, 0, 1000, 500))
# MARK: BinPacking: arc-shaped parts over as few sheets as possible
def bin_packing():
job = pk.Nesting(pk.Objective.BinPacking, spacing=2)
job.add_sheet(500, 300, count=None) # as many sheets as needed
for key, shape in (("slot", slot(160, 25)), ("arch", arch(90, 80)), ("gusset", gusset(110))):
job.add_part(shape, count=9, key=key, rotations=QUARTER_TURNS) # 10 each need 2.0 sheets at 88%: never found
result = job.solve(**SHORT)
render("bin_packing", f"BinPacking, slots and arches with exact arcs: {summary(result)}", result, box(0, 0, 500, 300))
# MARK: Knapsack: the sheet is too small, value picks
def knapsack():
job = pk.Nesting(pk.Objective.Knapsack, spacing=3)
job.add_sheet(700, 450)
for key, shape, count, value in (("plate", plate(220, 140, 18, 35), 6, 1), ("bracket", bracket(160, 120, 40), 8, 4),
("gusset", gusset(120), 8, 2), ("disc", disc(25), 12, 3)):
job.add_part(shape, count=count, key=key, value=value, rotations=QUARTER_TURNS)
result = job.solve(**SHORT)
picked = Counter(p.key for p in parts(result))
render("knapsack", f"Knapsack: {', '.join(f'{n} {k}' for k, n in picked.items())}, value {result.value:.0f}",
result, box(0, 0, 700, 450))
# MARK: OpenDimensionX: a 500 mm strip, its used width minimised
def strip():
job = pk.Nesting(pk.Objective.OpenDimensionX, spacing=3)
job.add_sheet(4000, 500)
for key, shape, count in (("bracket", bracket(160, 120, 40), 12), ("gusset", gusset(120), 16),
("plate", plate(140, 90, 12, 22), 8)):
job.add_part(shape, count=count, key=key, rotations=QUARTER_TURNS)
result = job.solve(**SHORT)
x_max = result.metrics["Solution"]["XMax"]
render("strip", f"OpenDimensionX: {len(parts(result))} parts on a 500 mm strip, {x_max:.0f} mm used", result,
box(0, 0, 4000, 500), x_max=x_max)
# MARK: VariableSizedBinPacking: three sheet sizes, the cheapest mix
def variable_sized():
job = pk.Nesting(pk.Objective.VariableSizedBinPacking, spacing=3)
sizes = {f"{w}x{h}": box(0, 0, w, h) for w, h in ((1000, 500), (600, 400), (400, 250))}
for key, outline in sizes.items():
job.add_sheet(outline, count=None, key=key) # the cost defaults to the area
for key, shape, count in (("plate", plate(220, 140, 18, 35), 6), ("bracket", bracket(160, 120, 40), 6),
("disc", disc(40), 8)):
job.add_part(shape, count=count, key=key, rotations=QUARTER_TURNS)
result = job.solve(**SHORT)
render("variable_sized", f"VariableSizedBinPacking: sheets {', '.join(s.stock for s in result.sheets)}, cost {result.cost:.0f}",
result, sizes)
# MARK: BinPackingWithLeftovers: the last sheet keeps its leftover in one piece
def leftovers():
job = pk.Nesting(pk.Objective.BinPackingWithLeftovers, spacing=3, leftover=pk.Nesting.LeftoverMode.BottomLeft)
job.add_sheet(600, 400, count=None)
for key, shape, count in (("bracket", bracket(160, 120, 40), 12), ("gusset", gusset(120), 14),
("disc", disc(30), 14)):
job.add_part(shape, count=count, key=key, rotations=QUARTER_TURNS)
result = job.solve(**SHORT)
render("leftovers", f"BinPackingWithLeftovers: {summary(result)}, the leftover gathered bottom left", result,
box(0, 0, 600, 400))
# MARK: defects: a rust spot and a clamp zone, parts kept 10 mm clear
def defects():
job = pk.Nesting(pk.Objective.Knapsack, spacing=3)
sheet = job.add_sheet(1000, 600)
zones = [circle(70, pk.shapes.Point(430, 300)), rectangle(80, 160)]
for zone in zones:
job.add_defect(sheet, zone, gap=10)
job.add_part(rectangle(120, 80), count=60, key="tile", rotations=[0, 90])
job.add_part(disc(25), count=40, key="disc")
result = job.solve(**SHORT)
render("defects", f"Defects with 10 mm clearance: {summary(result)}", result, box(0, 0, 1000, 600),
[to_shapely(z) for z in zones])
# MARK: a sheet of any shape: an offcut with a hole, parts 5 mm from every edge
def polygon_bin():
offcut = Polygon([(0, 0), (700, 0), (700, 250), (450, 450), (0, 450)], [Point(300, 220).buffer(60, 16).exterior])
job = pk.Nesting(pk.Objective.Knapsack, spacing=3)
job.add_sheet(offcut, edge_gap=5) # its hole becomes a defect
job.add_part(rectangle(100, 60), count=40, key="tile", rotations=[0, 90])
job.add_part(gusset(90), count=20, key="gusset", rotations=QUARTER_TURNS)
result = job.solve(**SHORT)
render("polygon_bin", f"An offcut with a hole: {summary(result)}", result, Polygon(offcut.exterior),
[Polygon(r) for r in offcut.interiors])
# MARK: rotations: mirrored copies and a continuous angle range
def rotations():
job = pk.Nesting(pk.Objective.Knapsack, spacing=3)
job.add_sheet(800, 400)
hook = Polygon([(0, 0), (200, 0), (200, 40), (60, 40), (60, 140), (0, 140)]) # an L, not mirror symmetric
job.add_part(hook, count=20, key="hook", rotations=[0, 180], mirror=True) # more than fit: the sheet fills
job.add_part(gusset(110), count=20, key="gusset", rotations=[(0, 90)]) # any angle from 0 to 90
result = job.solve(**SHORT)
mirrored = sum(p.mirrored for p in parts(result))
angles = sorted({round(p.angle) for p in parts(result) if p.key == "gusset"})
render("rotations", f"Mirroring and a 0-90 range: {mirrored} mirrored, triangle angles {angles}", result,
box(0, 0, 800, 400))
# MARK: pin: a holed frame fixed before the search, the rest packed around and inside it
def fixed_item():
job = pk.Nesting(pk.Objective.Knapsack, spacing=3)
sheet = job.add_sheet(1000, 600)
job.pin(sheet, Polygon(box(0, 0, 400, 300).exterior, [box(60, 60, 340, 240).exterior]), (300, 150), key="frame")
for key, shape in (("plate", plate(120, 80, 10, 20)), ("bracket", bracket(100, 80, 30)), ("disc", disc(20))):
job.add_part(shape, count=30, key=key, rotations=QUARTER_TURNS)
result = job.solve(**SHORT)
render("fixed_item", f"A pinned frame (thick outline): {summary(result)}", result, box(0, 0, 1000, 600))
SCENARIOS = [laser_sheet, bin_packing, knapsack, strip, variable_sized, leftovers, defects, polygon_bin, rotations,
fixed_item]
if __name__ == "__main__":
for scenario in SCENARIOS:
if not sys.argv[1:] or scenario.__name__ in sys.argv[1:]:
scenario()