plateful 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plateful/__init__.py ADDED
File without changes
@@ -0,0 +1,24 @@
1
+ """Packing algorithms. Each is one module here that exposes
2
+
3
+ run(engine: plateful.pack.Engine, *, time_budget: float, rng: random.Random) -> layout
4
+
5
+ and a one-line docstring saying what it does. Modules are found by name: adding a file is all it takes.
6
+ `pack` checks whatever an algorithm returns in exact geometry, so an algorithm cannot ship an invalid layout."""
7
+
8
+ import importlib
9
+ import pkgutil
10
+
11
+
12
+ def names() -> list[str]:
13
+ return sorted(m.name for m in pkgutil.iter_modules(__path__) if not m.name.startswith("_"))
14
+
15
+
16
+ def get(name: str):
17
+ # callers check name against names(), this package's own modules
18
+ # nosemgrep: python.lang.security.audit.non-literal-import.non-literal-import
19
+ return importlib.import_module(f"{__name__}.{name}")
20
+
21
+
22
+ def describe(name: str) -> str:
23
+ """The first line of the algorithm's docstring."""
24
+ return (get(name).__doc__ or "").strip().splitlines()[0]
plateful/algos/ga.py ADDED
@@ -0,0 +1,146 @@
1
+ """Genetic search (BRKGA) over part order and a rotation per part, seeded by greedy, decoded on every core in parallel."""
2
+
3
+ import os
4
+ import pickle
5
+ import time
6
+ from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
7
+
8
+ import numpy as np
9
+ from shapely import affinity
10
+
11
+ from plateful.pack import Engine
12
+
13
+ PROCS = os.cpu_count() or 1 # decoder processes
14
+ SHORTLIST = 4 # rotations a gene chooses from: greedy's, then the tightest bounding boxes
15
+ ELITE, MUTANT, BIAS = 0.2, 0.15, 0.7 # BRKGA shares of the population, and the elite parent's gene odds
16
+
17
+ _pool = None
18
+ _worker = {} # in a decoder process: the one engine it holds, by run token
19
+
20
+
21
+ def run(engine, *, time_budget, rng):
22
+ deadline = time.monotonic() + time_budget
23
+ pool = _start() if len(engine.parts) > 2 and time_budget > 1 else None
24
+ t = time.monotonic()
25
+ best = engine.greedy()
26
+ run.stats = {"generations": 0, "evaluations": 0} # read by the bench scripts
27
+ if pool is None:
28
+ return best
29
+ reserve = (time.monotonic() - t) / 4 # time kept for the final decode here; a decode tries one rotation, not all
30
+ n = len(engine.parts)
31
+ seed, shortlist = _seed(engine, best)
32
+ token = f"{os.getpid()}-{time.time()}"
33
+ # pickled here, unpickled in our own decoder processes only
34
+ payload = pickle.dumps( # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle
35
+ (engine.parts, engine.plate, engine.clearance, engine.angles, shortlist, time.time() + time_budget)
36
+ )
37
+
38
+ brood = 2 * PROCS # chromosomes decoded per generation: a whole number of waves over the processes
39
+ elites = max(1, round(brood * ELITE / (1 - ELITE)))
40
+ gen = np.random.default_rng(rng.getrandbits(64))
41
+ pop = [_perturb(seed, gen, n, s) for s in np.linspace(1, max(2, n // 4), brood).astype(int)]
42
+ scored = [(engine.score(best), seed)]
43
+ while True:
44
+ results, slowest = _evaluate(pool, (token, payload), pop, deadline - reserve)
45
+ reserve = max(reserve, 1.5 * slowest)
46
+ run.stats["evaluations"] += len(results)
47
+ scored = sorted(scored + results, key=lambda r: r[0])[: elites + brood]
48
+ if len(results) < len(pop):
49
+ break
50
+ run.stats["generations"] += 1
51
+ elite = [c for _, c in scored[:elites]]
52
+ others = [c for _, c in scored[elites:]] or elite
53
+ pop = [_perturb(elite[gen.integers(elites)], gen, n, gen.integers(1, max(2, n // 4)))
54
+ for _ in range(round(MUTANT * brood))] # fmt: skip
55
+ while len(pop) < brood:
56
+ a, b = elite[gen.integers(elites)], others[gen.integers(len(others))]
57
+ pop.append(np.where(gen.random(2 * n) < BIAS, a, b))
58
+ top_score, top = scored[0]
59
+ if top is seed:
60
+ return best
61
+ layout = _decode(engine, top, shortlist)
62
+ run.stats["redecoded_same"] = engine.score(layout) == top_score
63
+ return layout if engine.score(layout) < engine.score(best) else best
64
+
65
+
66
+ def _seed(engine, greedy):
67
+ """The chromosome of `greedy` (engine.greedy()'s layout), and each part's rotation shortlist. It decodes to
68
+ that layout except where greedy fell back to the conservative raster: one rotation leaves room to check more
69
+ of its tight positions, so the decode can differ there, usually by a better position."""
70
+ n = len(engine.parts)
71
+ where = {it.part: it.angle for p in greedy for it in p.items}
72
+ order = sorted(range(n), key=lambda i: -engine.parts[i].footprint.area) # greedy()'s default order
73
+ seed = np.empty(2 * n)
74
+ seed[order] = (np.arange(n) + 0.5) / n
75
+ seed[n:] = 0.5 / SHORTLIST # every part at greedy's own rotation, first in its shortlist
76
+ return seed, [_shortlist(engine, i, where[i]) for i in range(n)]
77
+
78
+
79
+ def _shortlist(engine, i, first):
80
+ """Greedy's rotation for part i, then the others with the smallest bounding box."""
81
+
82
+ def box(a):
83
+ x0, y0, x1, y1 = affinity.rotate(engine.parts[i].footprint, a, origin=(0, 0)).bounds
84
+ return (x1 - x0) * (y1 - y0)
85
+
86
+ return [first] + sorted((a for a in engine.angles if a != first), key=box)[: SHORTLIST - 1]
87
+
88
+
89
+ def _perturb(c, gen, n, swaps):
90
+ """c with `swaps` pairs of order keys exchanged and as many rotation genes redrawn."""
91
+ c = c.copy()
92
+ for _ in range(swaps):
93
+ i, j = gen.integers(n, size=2)
94
+ c[i], c[j] = c[j], c[i]
95
+ c[n + gen.integers(n)] = gen.random()
96
+ return c
97
+
98
+
99
+ def _decode(engine, c, shortlist):
100
+ """Each part in key order, at its gene's rotation, on the first plate where it fits."""
101
+ n = len(engine.parts)
102
+ layout = []
103
+ for i in np.argsort(c[:n], kind="stable"):
104
+ angle = shortlist[i][min(int(c[n + i] * len(shortlist[i])), len(shortlist[i]) - 1)]
105
+ if not any(engine.insert_on(layout, k, i, [angle]) for k in range(len(layout) + 1)):
106
+ engine.insert(layout, i) # that rotation fits no empty plate: any rotation that does
107
+ return layout
108
+
109
+
110
+ def _evaluate(pool, payload, pop, stop):
111
+ """([(score, chromosome)] for those decoded before monotonic time `stop`, the slowest decode in seconds)."""
112
+ futures = {pool.submit(_remote, *payload, c): c for c in pop}
113
+ out, slowest = [], 0.0
114
+ while futures and (left := stop - time.monotonic()) > 0:
115
+ done, _ = wait(futures, timeout=left, return_when=FIRST_COMPLETED)
116
+ for f in done:
117
+ c = futures.pop(f)
118
+ if (r := f.result()) is not None:
119
+ out.append((r[0], c))
120
+ slowest = max(slowest, r[1])
121
+ for f in futures:
122
+ f.cancel()
123
+ return out, slowest
124
+
125
+
126
+ def _remote(token, payload, c):
127
+ """In a decoder process: (score of chromosome c, seconds it took), or None past the run's deadline."""
128
+ if _worker.get("token") != token:
129
+ # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle
130
+ parts, plate, clearance, angles, shortlist, end = pickle.loads(payload)
131
+ engine = Engine(parts, plate, clearance, 360)
132
+ engine.angles = angles
133
+ _worker.clear()
134
+ _worker.update(token=token, engine=engine, shortlist=shortlist, end=end)
135
+ if (t := time.time()) > _worker["end"]:
136
+ return None
137
+ return _worker["engine"].score(_decode(_worker["engine"], c, _worker["shortlist"])), time.time() - t
138
+
139
+
140
+ def _start():
141
+ global _pool
142
+ if _pool is None or _pool._max_workers != PROCS:
143
+ _pool = ProcessPoolExecutor(PROCS)
144
+ for _ in range(PROCS): # start every process now, while greedy runs here
145
+ _pool.submit(time.sleep, 0)
146
+ return _pool
@@ -0,0 +1,5 @@
1
+ """One fast pass: largest part first, each on the first plate where it fits."""
2
+
3
+
4
+ def run(engine, *, time_budget, rng):
5
+ return engine.greedy()
@@ -0,0 +1,221 @@
1
+ """Overlap minimisation: rr, then empty its least-filled plate into the others, overlaps allowed, and move parts to their least weighted overlap until none is left."""
2
+
3
+ # Guided local search in the spirit of sparrow (Gardeyn and Wauters, 2025), on the engine's tight raster: the
4
+ # overlap of a part with everything else at every translation is one FFT correlation per rotation. Pair weights
5
+ # grow while a pair keeps overlapping, so the search leaves local minima. Left out from sparrow: its pool of
6
+ # infeasible solutions, item swaps, the compression phase, sampling and coordinate descent (the FFT map is exhaustive
7
+ # on the grid), and penetration depth (overlap here is a cell count).
8
+
9
+ import logging
10
+ import math
11
+ import time
12
+
13
+ import numpy as np
14
+ from scipy import fft
15
+
16
+ from plateful.algos import rr
17
+ from plateful.pack import CELLS, TIGHT
18
+
19
+ CELL = CELLS[TIGHT]
20
+
21
+ RR_SHARE = 0.3 # of the budget, for the valid layout the search starts from
22
+ WALL = 1e6 # weight of the area outside the usable plate: a hard limit in practice
23
+ WMAX = 1e4 # pair weights stop growing here, so FFT noise stays far below one cell
24
+ _STEPS = (0, 0.125, -0.125, 0.25, -0.25, 0.375, -0.375, 0.5, -0.5)
25
+ NUDGES = sorted(((x, y) for x in _STEPS for y in _STEPS), key=lambda d: math.hypot(*d)) # mm, nearest first
26
+ log = logging.getLogger(__name__)
27
+
28
+
29
+ def run(engine, *, time_budget, rng):
30
+ deadline = time.monotonic() + time_budget
31
+ best = rr.run(engine, time_budget=time_budget * RR_SHARE, rng=rng)
32
+ area = sum(p.footprint.area for p in engine.parts)
33
+ while len(best) > 1 and area <= (len(best) - 1) * engine.plate.usable.area and time.monotonic() < deadline:
34
+ # stop a fruitless attempt early enough that rr still has time to improve the best layout
35
+ fewer = _attempt(engine, best, deadline - (deadline - time.monotonic()) / 4, rng)
36
+ if fewer is None:
37
+ break
38
+ best = fewer
39
+ return rr.run(engine, time_budget=max(0.0, deadline - time.monotonic()), rng=rng, initial=best)
40
+
41
+
42
+ class _Search:
43
+ """Parts on `plates` raster plates, overlaps allowed. pos[i] = (plate, angle, grid, ti, tj) or None."""
44
+
45
+ def __init__(self, engine, plates):
46
+ self.e, self.plates = engine, plates
47
+ n = len(engine.parts)
48
+ self.pos = [None] * n
49
+ self.w = np.ones((n, n)) # pair weights
50
+ self.o = np.zeros((n, n)) # pair overlaps, in cells
51
+ self.out = np.zeros(n) # cells outside the usable plate
52
+ self.masks = {}
53
+ self.grown = set() # parts the exact rule refused at a raster-feasible position
54
+ self.moves, self.move_s = 0, 0.0
55
+ ny, nx = engine.shapes[TIGHT]
56
+ # ties go toward the front-left; the bias stays under 0.11, below one overlapping cell
57
+ self.bias = 1e-4 * (np.arange(ny)[:, None] + np.arange(nx)[None, :])
58
+
59
+ def mask(self, i, angle):
60
+ """(grid, i0, j0) of part i's tight mask at this rotation, one cell bigger all round once i is in `grown`."""
61
+ key = i, angle, i in self.grown
62
+ if key not in self.masks:
63
+ g, i0, j0 = self.e.stamp(i, angle, 0.0, 0.0)
64
+ if key[2]:
65
+ p = np.pad(g, 1)
66
+ g = np.max([np.roll(p, (dy, dx), (0, 1)) for dy in (-1, 0, 1) for dx in (-1, 0, 1)], axis=0)
67
+ i0, j0 = i0 - 1, j0 - 1
68
+ self.masks[key] = g, i0, j0
69
+ return self.masks[key]
70
+
71
+ def set(self, i, pos):
72
+ self.pos[i] = pos
73
+ q, _, g, ti, tj = pos
74
+ h, w = g.shape
75
+ self.out[i] = (self.e.empty[TIGHT][tj : tj + h, ti : ti + w] * g).sum()
76
+ for j, p in enumerate(self.pos):
77
+ self.o[i, j] = self.o[j, i] = 0.0 if j == i or p is None or p[0] != q else _meet(pos, p)
78
+
79
+ def weighted(self, i, q):
80
+ """The plate grid part i is scored against: the outside wall plus every other part, by pair weight."""
81
+ G = WALL * self.e.empty[TIGHT].astype(float) # the engine's grids are float32: too coarse for these weights
82
+ for j, p in enumerate(self.pos):
83
+ if j != i and p is not None and p[0] == q:
84
+ _, _, g, ti, tj = p
85
+ h, w = g.shape
86
+ G[tj : tj + h, ti : ti + w] += self.w[i, j] * g
87
+ return G
88
+
89
+ def move(self, i):
90
+ """Put part i where its weighted overlap is least, over every rotation and plate; stay if already there."""
91
+ t = time.monotonic()
92
+ ny, nx = self.e.shapes[TIGHT]
93
+ angles = [a for a in self.e.angles if all(s <= m for s, m in zip(self.mask(i, a)[0].shape, (ny, nx)))]
94
+ stack = np.zeros((len(angles), ny, nx))
95
+ for k, a in enumerate(angles):
96
+ g = self.mask(i, a)[0]
97
+ stack[k, : g.shape[0], : g.shape[1]] = g
98
+ spectra = fft.rfft2(stack, workers=-1)
99
+ np.conjugate(spectra, out=spectra)
100
+ cur = self.pos[i]
101
+ best = (math.inf,) # (key, plate, angle, ti, tj, overlap)
102
+ stay = math.inf
103
+ for q in range(self.plates):
104
+ G = self.weighted(i, q)
105
+ if cur is not None and cur[0] == q:
106
+ _, _, g, ti, tj = cur
107
+ stay = (G[tj : tj + g.shape[0], ti : ti + g.shape[1]] * g).sum()
108
+ spectra_q = spectra * fft.rfft2(G, workers=-1)
109
+ corr = fft.irfft2(spectra_q, s=(ny, nx), workers=-1)
110
+ for k, a in enumerate(angles):
111
+ h, w = self.mask(i, a)[0].shape
112
+ corr[k, ny - h + 1 :] = corr[k, :, nx - w + 1 :] = math.inf # the mask would wrap around
113
+ corr += self.bias # FFT noise (about 1e-9) is far below the bias step, a real overlap far above it
114
+ k, tj, ti = np.unravel_index(int(np.argmin(corr)), corr.shape)
115
+ if corr[k, tj, ti] < best[0]:
116
+ best = (corr[k, tj, ti], q, angles[k], int(ti), int(tj), corr[k, tj, ti] - self.bias[tj, ti])
117
+ self.moves += 1
118
+ self.move_s += time.monotonic() - t
119
+ if best[0] == math.inf or (cur is not None and stay <= best[5] + 0.5):
120
+ return False
121
+ _, q, a, ti, tj, _ = best
122
+ self.set(i, (q, a, self.mask(i, a)[0], ti, tj))
123
+ return True
124
+
125
+ def colliding(self):
126
+ return [i for i in range(len(self.pos)) if self.out[i] > 0 or self.o[i].any()]
127
+
128
+ def reweigh(self):
129
+ """sparrow's rule: overlapping pairs gain 1.2x to 2x by relative severity, the others decay to 1."""
130
+ top = self.o.max()
131
+ hit = self.o > 0
132
+ grow = np.minimum(self.w * (1.2 + 0.8 * self.o / max(top, 1.0)), WMAX)
133
+ self.w = np.where(hit, grow, np.maximum(1.0, 0.95 * self.w))
134
+
135
+
136
+ def _attempt(engine, layout, deadline, rng):
137
+ """A valid layout on one plate fewer than `layout`, or None if the search does not reach one by `deadline`."""
138
+ drop = min(range(len(layout)), key=lambda q: layout[q].area)
139
+ keep = [q for q in range(len(layout)) if q != drop]
140
+ s = _Search(engine, len(keep))
141
+ exact = {} # parts still at their transform in `layout`
142
+ for q, k in enumerate(keep):
143
+ for it in layout[k].items:
144
+ s.set(it.part, (q, it.angle, *_crop(engine.stamp(it.part, it.angle, it.dx, it.dy), engine.shapes[TIGHT])))
145
+ exact[it.part] = (it.angle, it.dx, it.dy)
146
+ for i in sorted((it.part for it in layout[drop].items), key=lambda i: -engine.parts[i].footprint.area):
147
+ if not s.move(i): # no on-grid spot at all (a part that fits only centred): not for this search
148
+ return None
149
+ passes = finishes = refused = 0
150
+ while time.monotonic() < deadline:
151
+ hit = s.colliding()
152
+ if not hit:
153
+ finishes += 1
154
+ done, failed = _finish(engine, s, exact)
155
+ if done is not None:
156
+ _log(s, passes, finishes, refused, "converged")
157
+ return done
158
+ refused += len(failed)
159
+ ny, nx = engine.shapes[TIGHT]
160
+ for i in failed: # one cell bigger from now on, so the search moves it clear by the raster's error
161
+ s.grown.add(i)
162
+ q, a, _, ti, tj = s.pos[i]
163
+ g = s.mask(i, a)[0]
164
+ s.set(i, (q, a, g, min(max(ti - 1, 0), nx - g.shape[1]), min(max(tj - 1, 0), ny - g.shape[0])))
165
+ continue
166
+ rng.shuffle(hit)
167
+ for i in hit:
168
+ if time.monotonic() >= deadline:
169
+ break
170
+ if (s.out[i] > 0 or s.o[i].any()) and s.move(i):
171
+ exact.pop(i, None)
172
+ s.reweigh()
173
+ passes += 1
174
+ _log(s, passes, finishes, refused, f"stopped with {s.o.sum() / 2 + s.out.sum():.0f} cells of overlap")
175
+ return None
176
+
177
+
178
+ def _finish(engine, s, exact):
179
+ """(layout, []) built through the engine from the search's positions, or (None, parts the exact rule refused)."""
180
+ layout, index = [], {}
181
+
182
+ def put(i):
183
+ q, a, _, ti, tj = s.pos[i]
184
+ _, i0, j0 = s.mask(i, a)
185
+ angle, dx, dy = exact.get(i) or (a, (ti - i0) * CELL, (tj - j0) * CELL)
186
+ k = index.get(q, len(layout))
187
+ # the tight raster is right to within about half a cell, so a refused spot often has a valid one beside it
188
+ if any(engine.place(layout, k, i, angle, dx + ox, dy + oy) for ox, oy in NUDGES):
189
+ index[q] = k
190
+ return True
191
+ return False
192
+
193
+ order = sorted(range(len(s.pos)), key=lambda i: (i not in exact, -engine.parts[i].footprint.area))
194
+ failed = [i for i in order if not put(i)]
195
+ refused = [i for i in failed if not any(engine.insert_on(layout, k, i) for k in range(len(layout)))]
196
+ return (None, refused) if refused else (layout, [])
197
+
198
+
199
+ def _crop(stamp, shape):
200
+ """The stamp without its cells off the plate grid (a part flush with the usable edge may reach past it)."""
201
+ g, ti, tj = stamp
202
+ (ny, nx), (h, w) = shape, g.shape
203
+ x0, y0 = max(-ti, 0), max(-tj, 0)
204
+ return g[y0 : min(h, ny - tj), x0 : min(w, nx - ti)], ti + x0, tj + y0
205
+
206
+
207
+ def _meet(a, b):
208
+ """Cells two raster positions share."""
209
+ _, _, ga, ia, ja = a
210
+ _, _, gb, ib, jb = b
211
+ x0, x1 = max(ia, ib), min(ia + ga.shape[1], ib + gb.shape[1])
212
+ y0, y1 = max(ja, jb), min(ja + ga.shape[0], jb + gb.shape[0])
213
+ if x0 >= x1 or y0 >= y1:
214
+ return 0.0
215
+ return float((ga[y0 - ja : y1 - ja, x0 - ia : x1 - ia] * gb[y0 - jb : y1 - jb, x0 - ib : x1 - ib]).sum())
216
+
217
+
218
+ def _log(s, passes, finishes, refused, outcome):
219
+ ms = 1000 * s.move_s / max(s.moves, 1)
220
+ log.info(f"{s.plates} plates, {s.moves} moves ({ms:.0f} ms each), {passes} passes, "
221
+ f"{finishes} exact finishes tried ({refused} parts refused): {outcome}") # fmt: skip
plateful/algos/rr.py ADDED
@@ -0,0 +1,56 @@
1
+ """Ruin and recreate: from the greedy layout, keep removing a few parts and re-inserting them, for the whole time."""
2
+
3
+ import math
4
+ import time
5
+
6
+
7
+ def run(engine, *, time_budget, rng, initial=None):
8
+ """`initial`: a layout to start from (it is not changed) instead of greedy's."""
9
+ deadline = time.monotonic() + time_budget
10
+ best = engine.greedy() if initial is None else initial
11
+ best_score = engine.score(best)
12
+ if not best or time_budget <= 0:
13
+ return best
14
+ area = engine.plate.usable.area
15
+
16
+ def energy(s): # scalar stand-in for the lexicographic score, used only for acceptance odds
17
+ return s[0] + 0.5 * s[1] / area + 0.1 * s[2] / (s[0] * area)
18
+
19
+ cur, cur_score, start = best, best_score, time.monotonic()
20
+ while (now := time.monotonic()) < deadline:
21
+ layout = _ruin_recreate(engine, cur, rng)
22
+ s = engine.score(layout)
23
+ temp = 0.02 * (1 - (now - start) / (deadline - start)) + 1e-4
24
+ if s <= cur_score or rng.random() < math.exp(-(energy(s) - energy(cur_score)) / temp):
25
+ cur, cur_score = layout, s
26
+ if s < best_score:
27
+ best, best_score = layout, s
28
+ return best
29
+
30
+
31
+ def _ruin_recreate(engine, layout, rng):
32
+ """A new layout: remove some parts from a copy of `layout` and re-insert them."""
33
+ where = [(k, it) for k, p in enumerate(layout) for it in p.items]
34
+ kind = rng.randrange(3) if len(layout) > 1 else rng.randrange(1, 3)
35
+ if kind == 0: # empty the least-filled plate, plus a part or two from elsewhere
36
+ least = min(range(len(layout)), key=lambda k: layout[k].area)
37
+ others = [it.part for k, it in where if k != least]
38
+ out = {it.part for it in layout[least].items} | set(rng.sample(others, min(len(others), rng.randint(1, 2))))
39
+ elif kind == 1: # a random part and its nearest neighbours on its plate
40
+ k, it = rng.choice(where)
41
+ centre = _centre(it)
42
+ near = sorted(layout[k].items, key=lambda o: math.dist(centre, _centre(o)))
43
+ out = {o.part for o in near[: rng.randint(2, 4)]}
44
+ else:
45
+ n = len(engine.parts)
46
+ out = set(rng.sample(range(n), min(n, rng.randint(2, 4))))
47
+ new = engine.copy(layout)
48
+ engine.remove(new, out)
49
+ for i in sorted(out, key=lambda i: -engine.parts[i].footprint.area * rng.uniform(0.8, 1.25)):
50
+ engine.insert(new, i)
51
+ return new
52
+
53
+
54
+ def _centre(item):
55
+ x0, y0, x1, y1 = item.geom.bounds
56
+ return ((x0 + x1) / 2, (y0 + y1) / 2)