plateful 1.2.0__tar.gz

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.
Files changed (34) hide show
  1. plateful-1.2.0/.gitignore +13 -0
  2. plateful-1.2.0/LICENSE +21 -0
  3. plateful-1.2.0/PKG-INFO +72 -0
  4. plateful-1.2.0/README.md +45 -0
  5. plateful-1.2.0/pyproject.toml +87 -0
  6. plateful-1.2.0/src/plateful/__init__.py +0 -0
  7. plateful-1.2.0/src/plateful/algos/__init__.py +24 -0
  8. plateful-1.2.0/src/plateful/algos/ga.py +146 -0
  9. plateful-1.2.0/src/plateful/algos/greedy.py +5 -0
  10. plateful-1.2.0/src/plateful/algos/overlap.py +221 -0
  11. plateful-1.2.0/src/plateful/algos/rr.py +56 -0
  12. plateful-1.2.0/src/plateful/cli.py +477 -0
  13. plateful-1.2.0/src/plateful/estimate.py +73 -0
  14. plateful-1.2.0/src/plateful/footprint.py +44 -0
  15. plateful-1.2.0/src/plateful/model.py +47 -0
  16. plateful-1.2.0/src/plateful/pack.py +416 -0
  17. plateful-1.2.0/src/plateful/printer.py +181 -0
  18. plateful-1.2.0/src/plateful/printers/bambu.json +18298 -0
  19. plateful-1.2.0/src/plateful/printers/h2d.toml +23 -0
  20. plateful-1.2.0/src/plateful/printers/x1c.toml +10 -0
  21. plateful-1.2.0/src/plateful/report.py +80 -0
  22. plateful-1.2.0/src/plateful/retarget.py +192 -0
  23. plateful-1.2.0/src/plateful/threemf.py +481 -0
  24. plateful-1.2.0/tests/fixtures/h2d.3mf +0 -0
  25. plateful-1.2.0/tests/fixtures/x1c.3mf +0 -0
  26. plateful-1.2.0/tests/make_fixtures.py +69 -0
  27. plateful-1.2.0/tests/make_printers.py +198 -0
  28. plateful-1.2.0/tests/test_cli.py +68 -0
  29. plateful-1.2.0/tests/test_estimate.py +14 -0
  30. plateful-1.2.0/tests/test_footprint.py +59 -0
  31. plateful-1.2.0/tests/test_pack.py +160 -0
  32. plateful-1.2.0/tests/test_printer.py +25 -0
  33. plateful-1.2.0/tests/test_retarget.py +126 -0
  34. plateful-1.2.0/tests/test_threemf.py +253 -0
@@ -0,0 +1,13 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ *.packed.3mf
6
+ *.packed.html
7
+ *.failed.3mf
8
+ .coverage
9
+ coverage.xml
10
+ .mypy_cache/
11
+ .ruff_cache/
12
+ dist/
13
+ .claude/worktrees/
plateful-1.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dmytro Gaivoronsky
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.5
2
+ Name: plateful
3
+ Version: 1.2.0
4
+ Summary: Re-pack the parts of a Bambu Studio project onto fewer build plates, by their true outlines
5
+ Project-URL: Homepage, https://github.com/dreamiurg/plateful
6
+ Project-URL: Repository, https://github.com/dreamiurg/plateful
7
+ Project-URL: Issues, https://github.com/dreamiurg/plateful/issues
8
+ Author: Dmytro Gaivoronsky
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: 3d-printing,3mf,bambu-lab,bambu-studio,bin-packing,nesting
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
22
+ Requires-Python: <3.15,>=3.11
23
+ Requires-Dist: numpy
24
+ Requires-Dist: scipy
25
+ Requires-Dist: shapely>=2.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # Plateful
29
+
30
+ [![CI](https://github.com/dreamiurg/plateful/actions/workflows/ci.yml/badge.svg)](https://github.com/dreamiurg/plateful/actions/workflows/ci.yml)
31
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
32
+
33
+ **The same 3D prints on fewer build plates.** Plateful is an open-source plate optimizer for Bambu Lab 3D printers. It re-packs a Bambu Studio project so parts nest inside and between each other, in the gaps the slicer's auto-arrange leaves empty, and saves a new project with the same colours and settings.
34
+
35
+ **[Try it in your browser](https://dreamiurg.net/plateful/)**: nothing to install, and your file is never uploaded. Or [run it on your computer](#run-it-on-your-computer).
36
+
37
+ ![An example of packing: 55 parts of one colour, as downloaded on 3 plates, then arranged by Plateful (1 plate), Orca Slicer (2 plates) and Bambu Studio (2 plates), all with 2 mm between parts.](docs/images/demo-three-way.gif)
38
+
39
+ An example of packing: the 55 one-colour parts of a [printable action figure](https://makerworld.com/en/models/638587-dummy-13-version-1-0), arranged by Plateful, Orca Slicer and Bambu Studio with 2 mm between parts and rotations on: 1, 2 and 2 plates. [Still image](docs/images/demo-three-way.png) · [Model credits](docs/credits.md#animated-layouts)
40
+
41
+ What to expect: on multi-plate projects where parts can fit together, about one plate in four is saved. About half the projects we tried were already packed tightly and kept the same plate count.
42
+
43
+ ## Run it on your computer
44
+
45
+ The [browser version](https://dreamiurg.net/plateful/) needs no setup. The command line is faster and has more options; [install uv](https://docs.astral.sh/uv/getting-started/installation/) once, then:
46
+
47
+ 1. Save your project as a `.3mf` file in Bambu Studio.
48
+ 2. Open a terminal in the project folder. Run this command with your file name in place of `your-project.3mf`.
49
+ ```sh
50
+ uvx --from git+https://github.com/dreamiurg/plateful plateful your-project.3mf
51
+ ```
52
+ 3. Open the new `.packed.3mf` file in Bambu Studio and slice it. Your original file stays as you saved it.
53
+
54
+ ## Example plate counts
55
+
56
+ These are whole projects. Each filament has its own plates, and both tools use the same spacing between parts.
57
+
58
+ <!-- BENCHMARK RESULTS: night run of 28 Nov 2026, default algorithm, 20 s, Bambu's own measured gap. Update after the next full run. -->
59
+ In our last run on 33 real projects, 15 fit on fewer plates (94 plates became 72) and 18 kept the same count.
60
+
61
+ | Project | Bambu Studio | Plateful |
62
+ | --- | ---: | ---: |
63
+ | Action figure (the example above) | 3 | 2 |
64
+ | Bathroom drawer inserts | 3 | 2 |
65
+ | Harry Potter Chess Set | 4 | 2 |
66
+ | BentoBox V2 | 4 | 3 |
67
+ | Card Shuffler | 5 | 4 |
68
+ | Himitsu Bako puzzle box | 6 | 6 |
69
+
70
+ <!-- END BENCHMARK RESULTS -->
71
+
72
+ [More examples](docs/examples.md) · [Benchmark method](docs/benchmark.md) · [How it works](docs/how-it-works.md) · [Options](docs/options.md) · [FAQ](docs/faq.md) · [Credits](docs/credits.md)
@@ -0,0 +1,45 @@
1
+ # Plateful
2
+
3
+ [![CI](https://github.com/dreamiurg/plateful/actions/workflows/ci.yml/badge.svg)](https://github.com/dreamiurg/plateful/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
+
6
+ **The same 3D prints on fewer build plates.** Plateful is an open-source plate optimizer for Bambu Lab 3D printers. It re-packs a Bambu Studio project so parts nest inside and between each other, in the gaps the slicer's auto-arrange leaves empty, and saves a new project with the same colours and settings.
7
+
8
+ **[Try it in your browser](https://dreamiurg.net/plateful/)**: nothing to install, and your file is never uploaded. Or [run it on your computer](#run-it-on-your-computer).
9
+
10
+ ![An example of packing: 55 parts of one colour, as downloaded on 3 plates, then arranged by Plateful (1 plate), Orca Slicer (2 plates) and Bambu Studio (2 plates), all with 2 mm between parts.](docs/images/demo-three-way.gif)
11
+
12
+ An example of packing: the 55 one-colour parts of a [printable action figure](https://makerworld.com/en/models/638587-dummy-13-version-1-0), arranged by Plateful, Orca Slicer and Bambu Studio with 2 mm between parts and rotations on: 1, 2 and 2 plates. [Still image](docs/images/demo-three-way.png) · [Model credits](docs/credits.md#animated-layouts)
13
+
14
+ What to expect: on multi-plate projects where parts can fit together, about one plate in four is saved. About half the projects we tried were already packed tightly and kept the same plate count.
15
+
16
+ ## Run it on your computer
17
+
18
+ The [browser version](https://dreamiurg.net/plateful/) needs no setup. The command line is faster and has more options; [install uv](https://docs.astral.sh/uv/getting-started/installation/) once, then:
19
+
20
+ 1. Save your project as a `.3mf` file in Bambu Studio.
21
+ 2. Open a terminal in the project folder. Run this command with your file name in place of `your-project.3mf`.
22
+ ```sh
23
+ uvx --from git+https://github.com/dreamiurg/plateful plateful your-project.3mf
24
+ ```
25
+ 3. Open the new `.packed.3mf` file in Bambu Studio and slice it. Your original file stays as you saved it.
26
+
27
+ ## Example plate counts
28
+
29
+ These are whole projects. Each filament has its own plates, and both tools use the same spacing between parts.
30
+
31
+ <!-- BENCHMARK RESULTS: night run of 28 Nov 2026, default algorithm, 20 s, Bambu's own measured gap. Update after the next full run. -->
32
+ In our last run on 33 real projects, 15 fit on fewer plates (94 plates became 72) and 18 kept the same count.
33
+
34
+ | Project | Bambu Studio | Plateful |
35
+ | --- | ---: | ---: |
36
+ | Action figure (the example above) | 3 | 2 |
37
+ | Bathroom drawer inserts | 3 | 2 |
38
+ | Harry Potter Chess Set | 4 | 2 |
39
+ | BentoBox V2 | 4 | 3 |
40
+ | Card Shuffler | 5 | 4 |
41
+ | Himitsu Bako puzzle box | 6 | 6 |
42
+
43
+ <!-- END BENCHMARK RESULTS -->
44
+
45
+ [More examples](docs/examples.md) · [Benchmark method](docs/benchmark.md) · [How it works](docs/how-it-works.md) · [Options](docs/options.md) · [FAQ](docs/faq.md) · [Credits](docs/credits.md)
@@ -0,0 +1,87 @@
1
+ [project]
2
+ name = "plateful"
3
+ # Releases take their version from the git tag (.github/workflows/release.yml); this is what a source checkout reports
4
+ version = "1.2.0"
5
+ description = "Re-pack the parts of a Bambu Studio project onto fewer build plates, by their true outlines"
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Dmytro Gaivoronsky" }]
10
+ # Upper bound: lift it only once numpy, scipy and shapely publish wheels for the next Python (check PyPI), or
11
+ # installs fall back to compiling them from source.
12
+ requires-python = ">=3.11,<3.15"
13
+ keywords = ["3d-printing", "bambu-lab", "bambu-studio", "3mf", "nesting", "bin-packing"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: Console",
17
+ "Intended Audience :: End Users/Desktop",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Topic :: Multimedia :: Graphics :: 3D Modeling",
25
+ ]
26
+ dependencies = ["numpy", "scipy", "shapely>=2.0"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/dreamiurg/plateful"
30
+ Repository = "https://github.com/dreamiurg/plateful"
31
+ Issues = "https://github.com/dreamiurg/plateful/issues"
32
+
33
+ [project.scripts]
34
+ plateful = "plateful.cli:main"
35
+
36
+ [dependency-groups]
37
+ dev = [
38
+ "mypy>=2.4.1",
39
+ "pytest",
40
+ "pytest-cov>=7.1.0",
41
+ "ruff>=0.17.6",
42
+ ]
43
+
44
+ [build-system]
45
+ requires = ["hatchling>=1.27"]
46
+ build-backend = "hatchling.build"
47
+
48
+ [tool.hatch.build.targets.sdist]
49
+ # pyproject.toml, README.md and LICENSE are always included
50
+ include = ["src", "tests"]
51
+
52
+ [tool.ruff]
53
+ # The code is written to about 120 columns; 88 would rewrap far more of it
54
+ line-length = 120
55
+
56
+ [tool.ruff.lint]
57
+ select = ["E", "W", "F", "I", "UP", "B", "C4", "SIM", "RUF"]
58
+ ignore = [
59
+ "E501", # the formatter owns line length; long strings stay as written
60
+ "B905", # zip() lengths match by construction; strict= would add a runtime check to 21 calls
61
+ "RUF001", # "×" in plate sizes (256 × 256 mm) is intended typography
62
+ "RUF002", # same, in docstrings
63
+ "RUF005", # plate_origin() returns ndarrays, where + adds elementwise; the suggested unpacking is wrong
64
+ ]
65
+
66
+ [tool.mypy]
67
+ files = ["src/plateful"]
68
+ # Pragmatic, not strict. Most None errors come from XML and settings lookups whose None cases the code
69
+ # checks at run time, and annotating every empty dict would churn the code for no caught bug.
70
+ strict_optional = false
71
+ disable_error_code = ["var-annotated"]
72
+
73
+ [[tool.mypy.overrides]]
74
+ module = ["shapely.*", "scipy.*"]
75
+ ignore_missing_imports = true
76
+
77
+ [tool.pytest.ini_options]
78
+ testpaths = ["tests"]
79
+ addopts = "--strict-markers"
80
+
81
+ [tool.coverage.run]
82
+ source = ["plateful"]
83
+
84
+ [tool.coverage.report]
85
+ # A guard against big drops, not a target (85% locally, 83% on CI where the Bambu Studio tests skip)
86
+ fail_under = 75
87
+ show_missing = true
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]
@@ -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