From ca677947b7a87519192c702e5ef53d95c5f01253 Mon Sep 17 00:00:00 2001 From: Igor Kuvychko Date: Thu, 12 Nov 2026 10:53:31 -0800 Subject: [PATCH 1/2] Add the edge-to-edge assumption, and cor1 to the corpus (phase 8) Tropical puzzles are cut from a polyhedral complex, so by the balancing condition their pieces meet edge to edge: no T inside the tray. The search did not use this. It is added as an assumption, separate from the regime: it narrows what a whole search finds, so a result records it, names its own candidate set (corner-contact[-relief]-edge-to-edge/1) and is compared only with results under the same assumption. - tiling-geometry: Meeting; Assembly refuses a placement that makes a T (rejected_junction). Two rules follow, each a switch: equal_edges (arcs of the edge graph need equal lengths and end heights) and wall_edges (an edge with no partner stays on the tray, rejected_wall). - rust.contact_dfs declares the assumption; the prototype and cp_sat.placements refuse it. maxplus-solve --assume, `assume` in manifests, an `assumes` column, proxies.static(..., edge_to_edge=True). - Exit test: on every corpus fixture, the assumed search finds exactly the plain search's assemblies that an independent twin-edge check calls edge to edge, rules on and off, the key among them. Proptests on chord-cut and line-arrangement tilings. - benchmarks/manifests/edge_to_edge.toml and results/edge_to_edge.md. Findings: the footprints take 14 to 80 nodes instead of 45 to 1 064 878, fewer than the relief searches assuming nothing; of rat1-flat's 101 assemblies and rat2-flat's 2, only the answer has no T. cor1 is re-imported from tropical-puzzle-lab main (b1a1792); the other 16 fixtures change only in source commit and hashes. Its plain footprint search does not end, so the corpus and edge-to-edge manifests stop searches that assume nothing at 1 500 000 nodes (new1-flat needs 1 064 878), and tests that need the end of that search leave cor1-flat out by name (support.corpus.UNFINISHED) and test it apart. corpus.md moves because of the two cor1 rows each for rust.contact_dfs and cp_sat.placements and the node_limit column, regenerated with the command; no existing count changed. With roofs cor1 takes 1 529 nodes, 967 assuming edge to edge; without, 48 edge-to-edge assemblies in 44 539 nodes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jfg9fgTR9LYn4D2rTtfifs --- CLAUDE.md | 3 + README.md | 2 +- benchmarks/fixtures/cor1-flat.json | 280 ++++++++++++ benchmarks/fixtures/cor1.json | 417 ++++++++++++++++++ benchmarks/fixtures/index.json | 60 ++- benchmarks/fixtures/new1-flat.json | 2 +- benchmarks/fixtures/new1.json | 2 +- benchmarks/fixtures/new2-flat.json | 2 +- benchmarks/fixtures/new2.json | 2 +- benchmarks/fixtures/new3-flat.json | 2 +- benchmarks/fixtures/new3.json | 2 +- benchmarks/fixtures/new4-flat.json | 2 +- benchmarks/fixtures/new4.json | 2 +- benchmarks/fixtures/new5-flat.json | 2 +- benchmarks/fixtures/new5.json | 2 +- benchmarks/fixtures/rat1-flat.json | 2 +- benchmarks/fixtures/rat1.json | 2 +- benchmarks/fixtures/rat2-flat.json | 2 +- benchmarks/fixtures/rat2.json | 2 +- benchmarks/fixtures/rev2-flat.json | 2 +- benchmarks/fixtures/rev2.json | 2 +- benchmarks/manifests/corpus.toml | 9 + benchmarks/manifests/edge_to_edge.toml | 28 ++ benchmarks/manifests/tolerance.toml | 2 +- benchmarks/results/corpus.md | 68 +-- benchmarks/results/edge_to_edge.md | 92 ++++ crates/tiling-geometry/src/assembly.rs | 176 +++++++- crates/tiling-geometry/src/graph.rs | 83 +++- crates/tiling-geometry/src/lib.rs | 2 +- crates/tiling-geometry/src/testing.rs | 167 +++++-- crates/tiling-py/src/lib.rs | 38 +- crates/tiling-search/src/contact_dfs.rs | 135 +++++- docs/algorithms.md | 65 ++- docs/architecture.md | 4 + docs/experiments.md | 19 +- docs/roadmap.md | 23 +- docs/solver-contract.md | 17 + python/maxplus_solvers/__init__.py | 2 + python/maxplus_solvers/_native.pyi | 11 + python/maxplus_solvers/api.py | 13 +- python/maxplus_solvers/cli.py | 22 +- .../maxplus_solvers/experiments/benchmark.py | 18 +- .../maxplus_solvers/experiments/manifest.py | 21 +- python/maxplus_solvers/experiments/proxies.py | 14 +- python/maxplus_solvers/experiments/report.py | 10 +- python/maxplus_solvers/metrics.py | 4 + python/maxplus_solvers/models.py | 54 ++- python/maxplus_solvers/solvers/__init__.py | 5 +- python/maxplus_solvers/solvers/contact_dfs.py | 41 +- tests/architecture/test_layering.py | 36 +- tests/corpus/test_benchmark.py | 23 +- tests/corpus/test_cp_sat.py | 12 +- tests/corpus/test_edge_to_edge.py | 201 +++++++++ tests/corpus/test_fixtures.py | 9 +- tests/corpus/test_rust_contact_dfs.py | 52 ++- ...est_search_geometry_agrees_with_shapely.py | 7 +- tests/keys/cor1-flat.json | 174 ++++++++ tests/keys/cor1.json | 174 ++++++++ tests/keys/new1-flat.json | 2 +- tests/keys/new1.json | 2 +- tests/keys/new2-flat.json | 2 +- tests/keys/new2.json | 2 +- tests/keys/new3-flat.json | 2 +- tests/keys/new3.json | 2 +- tests/keys/new4-flat.json | 2 +- tests/keys/new4.json | 2 +- tests/keys/new5-flat.json | 2 +- tests/keys/new5.json | 2 +- tests/keys/rat1-flat.json | 2 +- tests/keys/rat1.json | 2 +- tests/keys/rat2-flat.json | 2 +- tests/keys/rat2.json | 2 +- tests/keys/rev2-flat.json | 2 +- tests/keys/rev2.json | 2 +- tests/support/corpus.py | 5 + tests/support/documents.py | 20 + tests/support/geometry.py | 45 ++ tests/unit/test_edge_to_edge.py | 221 ++++++++++ 78 files changed, 2779 insertions(+), 169 deletions(-) create mode 100644 benchmarks/fixtures/cor1-flat.json create mode 100644 benchmarks/fixtures/cor1.json create mode 100644 benchmarks/manifests/edge_to_edge.toml create mode 100644 benchmarks/results/edge_to_edge.md create mode 100644 tests/corpus/test_edge_to_edge.py create mode 100644 tests/keys/cor1-flat.json create mode 100644 tests/keys/cor1.json create mode 100644 tests/unit/test_edge_to_edge.py diff --git a/CLAUDE.md b/CLAUDE.md index 3c34ebb..69f7fe2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,9 @@ cargo test -p tiling-search # the search, on random tili uv run maxplus-solve new5-flat --max-solutions all --validate # run a solver from the command line uv run maxplus-solve new5 --mode relief --option lookahead=true --option order=random --seed 3 uv run maxplus-solve rat1-flat --solver cp_sat.placements --max-solutions all --option coverage=false # CP-SAT, needs the cp-sat extra +uv run maxplus-solve new1-flat --assume edge-to-edge --max-solutions all --validate # assume no T between pieces uv run maxplus-bench run benchmarks/manifests/corpus.toml --no-times # every solver on the corpus: the table in benchmarks/results/corpus.md +uv run maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times # the table in benchmarks/results/edge_to_edge.md uv run maxplus-bench run benchmarks/manifests/tolerance.toml # an experiment; records go to benchmarks/results/.jsonl uv run maxplus-bench proxies --results benchmarks/results/corpus.jsonl # difficulty proxies against what the searches cost uv run python scripts/import_fixtures.py --source ../tropical-puzzle-lab # regenerate fixtures and keys @@ -85,6 +87,7 @@ Rules: ## Invariants that are easy to break - **Solver instances carry no answer.** The source `puzzle.json` leaks the solution three ways: `reference.poses`; local polygons stored in their solved orientation (every reference `theta` is 0); and piece ids and order that encode the tropical construction. Instances must be sanitized: seeded random rotation per piece (roof gradient rotated with it), random starting vertex, shuffled order, opaque ids, no `reference`, `tropical` or `provenance`. The sanitizer seed is part of the answer, since the rotations can be recomputed from it: it is recorded in the answer key and never in an instance. Answer keys live under `tests/` and only tests load them. +- **An assumption is not a rule.** A pruning rule leaves what a whole search finds unchanged; an assumption (`SolverConfig.assumptions`, today only `edge-to-edge`) narrows it. A solver declares the assumptions it can make, a result records them and names a candidate set that says so, and results under different assumptions are not compared. Rules that follow from an assumption are options, tested not to change what the search finds under it. - **Three information regimes stay separate:** footprint (polygons only), relief (polygons and roof planes), tropical-aware (construction data as well). A solver declares which one it uses; results from different regimes are not comparable. - **The validator is independent of the search.** `validation.py` must not import `_native` or reuse the Rust geometry, so one bug cannot affect both. It follows the browser's completion rules and may only depart from them on the stricter side; the three places it does are listed in its module docstring. - **Solvers never call the validator.** `api.solve(..., validate=True)` is the only place the two meet, after the search has returned. A search that consulted the validator would be checking its answer with its own oracle. diff --git a/README.md b/README.md index 6589e46..10a938a 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Python owns orchestration and analysis. Rust owns the geometry and the search. ## Status -**Contracts and fixtures.** The instance format, the sanitizing importer and the benchmark corpus exist: 16 puzzles from Tropical Puzzle Lab and 4 synthetic ones with known solution counts, each with an answer key that only tests read. An independent validator checks an assembly against the browser player's completion rules. The Rust geometry kernel (separating-axis depth, convex clipping, containment, edge signatures, roof continuity) is in place and agrees with the validator on random poses of every fixture's pieces. Three solvers exist. `python.contact_dfs` is a Python prototype of the contact search. `rust.contact_dfs` is that search in Rust with roofs, pruning and symmetry handling: it solves all 16 corpus puzzles, runs every search to its end, and returns assemblies that pass the validator. `cp_sat.placements` hands the placements that search reaches to OR-Tools CP-SAT as a plain choice problem, and returns the same assemblies by other means. `maxplus-bench` runs experiment manifests over the corpus and writes the results table; [docs/experiments.md](docs/experiments.md) has what the first experiments found about tolerance, heuristics and difficulty proxies. Each rule of either can be switched off, because the question here is what makes a puzzle hard and what helps, not how fast one solver is; [docs/algorithms.md](docs/algorithms.md) has the measurements. The work is laid out in [docs/roadmap.md](docs/roadmap.md), and the design in [docs/architecture.md](docs/architecture.md). +**Contracts and fixtures.** The instance format, the sanitizing importer and the benchmark corpus exist: 18 puzzles from Tropical Puzzle Lab (nine constructions, each with its roofs and without) and 4 synthetic ones with known solution counts, each with an answer key that only tests read. An independent validator checks an assembly against the browser player's completion rules. The Rust geometry kernel (separating-axis depth, convex clipping, containment, edge signatures, roof continuity) is in place and agrees with the validator on random poses of every fixture's pieces. Three solvers exist. `python.contact_dfs` is a Python prototype of the contact search. `rust.contact_dfs` is that search in Rust with roofs, pruning and symmetry handling: it runs the search to its end on 17 of the 18 corpus puzzles, and every assembly it returns passes the validator. The eighteenth, `cor1-flat`, was built to be hard and has not been seen to end without roofs. `cp_sat.placements` hands the placements that search reaches to OR-Tools CP-SAT as a plain choice problem, and returns the same assemblies by other means. `maxplus-bench` runs experiment manifests over the corpus and writes the results table; [docs/experiments.md](docs/experiments.md) has what the first experiments found about tolerance, heuristics and difficulty proxies. Each rule of either can be switched off, because the question here is what makes a puzzle hard and what helps, not how fast one solver is; [docs/algorithms.md](docs/algorithms.md) has the measurements. `rust.contact_dfs` can also be told to assume that the pieces meet edge to edge, as every tropical cut does (`--assume edge-to-edge`); then the footprint puzzles that took a million nodes take about fifty. The work is laid out in [docs/roadmap.md](docs/roadmap.md), and the design in [docs/architecture.md](docs/architecture.md). ```python from maxplus_solvers import load_puzzle diff --git a/benchmarks/fixtures/cor1-flat.json b/benchmarks/fixtures/cor1-flat.json new file mode 100644 index 0000000..d848103 --- /dev/null +++ b/benchmarks/fixtures/cor1-flat.json @@ -0,0 +1,280 @@ +{ + "formatVersion": 1, + "id": "cor1-flat", + "regime": "footprint", + "units": "mm", + "spanMm": 144.0, + "target": { + "vertices": [ + [-72.0, -72.0], + [72.0, -72.0], + [72.0, 72.0], + [-72.0, 72.0] + ] + }, + "pieces": [ + { + "id": "p00", + "polygon": [ + [15.811873776259539, 5.414209046770245], + [-3.2015020654401622, 16.40363973158016], + [-15.811873776259539, -5.414209046770245], + [3.2015020654401622, -16.40363973158016] + ] + }, + { + "id": "p01", + "polygon": [ + [-10.172575805661928, -18.07094292765794], + [20.10305969758872, -5.089918232328805], + [10.172575805661928, 18.07094292765794], + [-20.10305969758872, 5.089918232328805] + ] + }, + { + "id": "p02", + "polygon": [ + [-19.33920159602142, 12.63786209946332], + [-12.31580348208042, -19.54587581581815], + [19.33920159602142, -12.63786209946332], + [12.31580348208042, 19.54587581581815] + ] + }, + { + "id": "p03", + "polygon": [ + [-3.960665521198517, -17.670374657818726], + [18.08850691930801, 0.857280204273442], + [3.960665521198517, 17.670374657818726], + [-18.08850691930801, -0.857280204273442] + ] + }, + { + "id": "p04", + "polygon": [ + [-5.684983804332803, -13.520671798842406], + [15.509811472086938, -13.852048250073873], + [15.921784169227195, 12.497672567182047], + [-16.4742565141312, 13.004178285005379], + [-16.798664577975522, -7.744919828781215] + ] + }, + { + "id": "p05", + "polygon": [ + [-17.18946261113986, 2.7094994110938195], + [-6.1540056909537535, -16.2771995710012], + [17.18946261113986, -2.7094994110938195], + [6.1540056909537535, 16.2771995710012] + ] + }, + { + "id": "p06", + "polygon": [ + [-3.5788798818224112, -25.064470201172384], + [19.83218831002089, -15.739134490493505], + [3.5788798818224112, 25.064470201172384], + [-19.83218831002089, 15.739134490493505] + ] + }, + { + "id": "p07", + "polygon": [ + [18.459899557293806, 11.741907219495175], + [-14.101968516293422, 16.72646886769823], + [-18.459899557293806, -11.741907219495175], + [14.101968516293422, -16.72646886769823] + ] + }, + { + "id": "p08", + "polygon": [ + [-13.039000219794794, -8.793508295730668], + [12.1317101991555, -10.008142810861521], + [13.039000219794794, 8.793508295730668], + [-12.1317101991555, 10.008142810861521] + ] + }, + { + "id": "p09", + "polygon": [ + [-25.87911542288911, -6.82916046104896], + [15.37207303401124, -21.910395211200456], + [25.87911542288911, 6.82916046104896], + [-15.37207303401124, 21.910395211200456] + ] + }, + { + "id": "p10", + "polygon": [ + [23.146056328376815, -11.348397425080744], + [-0.32427273530226763, 25.776363103958463], + [-23.146056328376815, 11.348397425080744], + [0.32427273530226763, -25.776363103958463] + ] + }, + { + "id": "p11", + "polygon": [ + [11.723840254429945, 14.738065734929428], + [-17.715303448070415, 6.389603717076468], + [-11.723840254429945, -14.738065734929428], + [17.715303448070415, -6.389603717076468] + ] + }, + { + "id": "p12", + "polygon": [ + [-8.778487752024896, -15.978658577933839], + [16.35513458018583, -8.055367777242665], + [8.778487752024896, 15.978658577933839], + [-16.35513458018583, 8.055367777242665] + ] + }, + { + "id": "p13", + "polygon": [ + [-17.16582795880929, 1.129453570295814], + [5.855168004089374, -16.17585616042566], + [17.16582795880929, -1.129453570295814], + [-5.855168004089374, 16.17585616042566] + ] + }, + { + "id": "p14", + "polygon": [ + [3.1470773247262347, -19.2633143948497], + [18.908906767083145, 4.840725362627694], + [-3.1470773247262347, 19.2633143948497], + [-18.908906767083145, -4.840725362627694] + ] + }, + { + "id": "p15", + "polygon": [ + [13.099432656491729, -5.985862125702378], + [6.602929697437574, 14.191466896365334], + [-13.179317421789484, 3.977001493436167], + [-7.804558930258247, -12.716328930839882] + ] + }, + { + "id": "p16", + "polygon": [ + [4.961693795127983, -17.264208917940064], + [17.64663124953175, -3.356742531375059], + [-4.961693795127983, 17.264208917940064], + [-17.64663124953175, 3.356742531375059] + ] + }, + { + "id": "p17", + "polygon": [ + [14.785265230853653, -22.937131026509864], + [17.550459823610836, 20.897306229602737], + [-14.785265230853653, 22.937131026509864], + [-17.550459823610836, -20.897306229602737] + ] + }, + { + "id": "p18", + "polygon": [ + [1.6170516557415997, -22.422208204351158], + [22.480411007273133, -0.0373866377435359], + [-1.6170516557415997, 22.422208204351158], + [-22.480411007273133, 0.0373866377435359] + ] + }, + { + "id": "p19", + "polygon": [ + [-11.72687143372898, 6.390624815450257], + [-11.86661177893315, -8.47146334487267], + [10.127614611567893, -5.017970904285675], + [15.834001816966614, 6.1314845182972295] + ] + }, + { + "id": "p20", + "polygon": [ + [10.23693773557185, 5.523998387739964], + [-2.4387564155430637, 12.356770723138766], + [-11.370484958548033, -4.212764114919944], + [4.06679833224333, -12.534157874152907] + ] + }, + { + "id": "p21", + "polygon": [ + [3.894743686739261, -19.81263104126341], + [19.01583749008507, 6.790235762718771], + [-3.894743686739261, 19.81263104126341], + [-19.01583749008507, -6.790235762718771] + ] + }, + { + "id": "p22", + "polygon": [ + [-10.544243883036525, -15.642515721509648], + [15.38219347927097, -10.920508272461651], + [10.544243883036525, 15.642515721509648], + [-15.38219347927097, 10.920508272461651] + ] + }, + { + "id": "p23", + "polygon": [ + [-13.348240166183128, -0.32075630215115236], + [2.0658695197996133, -11.571216311588142], + [12.682590341572308, -1.169945675659716], + [-0.49052286488057817, 12.27603320151942] + ] + }, + { + "id": "p24", + "polygon": [ + [-25.835304128377956, 4.708833004916235], + [5.9804607587122085, -25.570884552308215], + [25.835304128377956, -4.708833004916235], + [-5.9804607587122085, 25.570884552308215] + ] + }, + { + "id": "p25", + "polygon": [ + [5.754156472129492, 20.50414494951836], + [-21.234763162509214, 1.617130251015869], + [-5.754156472129492, -20.50414494951836], + [21.234763162509214, -1.617130251015869] + ] + }, + { + "id": "p26", + "polygon": [ + [12.72010748714181, 10.441751787628913], + [-5.398037716497224, 15.546462738840827], + [-12.72010748714181, -10.441751787628913], + [5.398037716497224, -15.546462738840827] + ] + } + ], + "rules": { + "translate": true, + "rotate": "continuous-z", + "flip": false + }, + "validation": { + "contactNoise": 1e-06, + "overlapDepth": 0.006, + "outsideDepth": 0.006, + "areaError": 0.012, + "edgeAngleDeg": 3.0, + "edgeMinOverlap": 0.02 + }, + "source": { + "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", + "puzzleId": "cor1-flat", + "geometryHash": "049804fdb45e2f37430c7616cd461063ac9d71eedc67e963f2c77ac1ce95bcf5" + } +} diff --git a/benchmarks/fixtures/cor1.json b/benchmarks/fixtures/cor1.json new file mode 100644 index 0000000..601932f --- /dev/null +++ b/benchmarks/fixtures/cor1.json @@ -0,0 +1,417 @@ +{ + "formatVersion": 1, + "id": "cor1", + "regime": "relief", + "units": "mm", + "spanMm": 144.0, + "reliefMm": 35.0, + "target": { + "vertices": [ + [-72.0, -72.0], + [72.0, -72.0], + [72.0, 72.0], + [-72.0, 72.0] + ] + }, + "pieces": [ + { + "id": "p00", + "polygon": [ + [8.045284365229305, 17.027401780691317], + [-18.70674480527382, 2.1717989568221414], + [-8.045284365229305, -17.027401780691317], + [18.70674480527382, -2.1717989568221414] + ], + "roof": { + "z0": 16.539502164502164, + "gx": -0.05355573382967893, + "gy": 0.2859298050005368 + } + }, + { + "id": "p01", + "polygon": [ + [-4.853628961523799, 12.438677021425216], + [-10.173049583421282, -5.888117354099917], + [3.2252848740939237, -12.321298963059006], + [11.372849972511766, 4.647567896063153] + ], + "roof": { + "z0": 12.954260470370256, + "gx": -0.12933016481552084, + "gy": 0.3682350261632032 + } + }, + { + "id": "p02", + "polygon": [ + [10.623915467844272, -11.494730679404167], + [8.681133404066058, 10.684047519731731], + [-8.80310688633251, 12.046637320057174], + [-10.509391072786554, -9.847760181336383] + ], + "roof": { + "z0": 15.2274815417364, + "gx": -0.021442317799971827, + "gy": -0.2751397645191937 + } + }, + { + "id": "p03", + "polygon": [ + [-5.768098951021858, -16.207107989092727], + [17.159506219895523, 1.2217451322839805], + [5.768098951021858, 16.207107989092727], + [-17.159506219895523, -1.2217451322839805] + ], + "roof": { + "z0": 20.596320346320347, + "gx": -0.3413140588423493, + "gy": 0.14497871226077297 + } + }, + { + "id": "p04", + "polygon": [ + [16.23131645753793, -2.7158204900455285], + [-3.0654806589441366, 16.16892523356244], + [-16.23131645753793, 2.7158204900455285], + [3.0654806589441366, -16.16892523356244] + ], + "roof": { + "z0": 26.971320346320347, + "gx": -0.027959298864455806, + "gy": -0.4231364158118265 + } + }, + { + "id": "p05", + "polygon": [ + [-3.7048819466432743, -17.002731006515678], + [17.40092343911607, -0.1639371358593884], + [3.7048819466432743, 17.002731006515678], + [-17.40092343911607, 0.1639371358593884] + ], + "roof": { + "z0": 26.971320346320347, + "gx": 0.043614235062982204, + "gy": 0.38784162299126135 + } + }, + { + "id": "p06", + "polygon": [ + [5.0427525842174115, -21.288751095143592], + [20.424623727601634, 7.8406008954991], + [-5.0427525842174115, 21.288751095143592], + [-20.424623727601634, -7.8406008954991] + ], + "roof": { + "z0": 20.596320346320347, + "gx": -0.24860357695063734, + "gy": -0.07678227359418865 + } + }, + { + "id": "p07", + "polygon": [ + [-17.03486051648911, -11.825980043969688], + [6.956813825511743, -19.535685762567375], + [17.03486051648911, 11.825980043969688], + [-6.956813825511743, 19.535685762567375] + ], + "roof": { + "z0": 35.333333333333336, + "gx": 0.40660942968983615, + "gy": 0.06258523559648062 + } + }, + { + "id": "p08", + "polygon": [ + [-9.61113103036925, -15.175555185757327], + [17.879069710361758, -1.7349873690945063], + [9.61113103036925, 15.175555185757327], + [-17.879069710361758, 1.7349873690945063] + ], + "roof": { + "z0": 16.539502164502164, + "gx": 0.22406261453538623, + "gy": -0.2488429977630342 + } + }, + { + "id": "p09", + "polygon": [ + [14.587344031753517, -5.877985112107535], + [1.4975223192434521, 15.655629715289656], + [-14.587344031753517, 5.877985112107535], + [-1.4975223192434521, -15.655629715289656] + ], + "roof": { + "z0": 35.333333333333336, + "gx": -0.08399088799977852, + "gy": -0.48167263625999746 + } + }, + { + "id": "p10", + "polygon": [ + [8.391408257579355, 8.055663836354993], + [-5.648061306697748, 11.257740405354687], + [-9.833782311926107, -7.094507391085972], + [7.264395218424438, -10.994204127623727] + ], + "roof": { + "z0": 15.032810564244748, + "gx": 0.07159525156906935, + "gy": 0.31390859452955433 + } + }, + { + "id": "p11", + "polygon": [ + [-21.299828396636244, -7.189407979135502], + [5.602456727573958, -21.771145018860864], + [21.299828396636244, 7.189407979135502], + [-5.602456727573958, 21.771145018860864] + ], + "roof": { + "z0": 16.539502164502164, + "gx": -0.16854785715386278, + "gy": -0.11791376024739972 + } + }, + { + "id": "p12", + "polygon": [ + [20.012419945889672, -2.6855958504560906], + [5.624093714676107, 19.392755014467916], + [-20.012419945889672, 2.6855958504560906], + [-5.624093714676107, -19.392755014467916] + ], + "roof": { + "z0": 16.539502164502164, + "gx": -0.20263471491881713, + "gy": 0.14244866819204732 + } + }, + { + "id": "p13", + "polygon": [ + [25.663528815058385, -9.278972811288947], + [16.441207153396732, 21.780788668298207], + [-25.663528815058385, 9.278972811288947], + [-16.441207153396732, -21.780788668298207] + ], + "roof": { + "z0": 15.132034632034632, + "gx": -0.13227912687213947, + "gy": -0.0392765623116703 + } + }, + { + "id": "p14", + "polygon": [ + [-1.1579301916851659, 21.264747223698496], + [-20.623688890806413, -5.3097771470973285], + [1.1579301916851659, -21.264747223698496], + [20.623688890806413, 5.3097771470973285] + ], + "roof": { + "z0": 26.971320346320347, + "gx": 0.3313555306660875, + "gy": -0.014656169853684842 + } + }, + { + "id": "p15", + "polygon": [ + [0.29256918379119945, 26.763416279441365], + [-25.207262945827416, -8.997774305565114], + [-0.29256918379119945, -26.763416279441365], + [25.207262945827416, 8.997774305565114] + ], + "roof": { + "z0": 16.539502164502164, + "gx": 0.005212148865975735, + "gy": 0.16575782412497167 + } + }, + { + "id": "p16", + "polygon": [ + [12.352161308199811, -13.769641454075321], + [14.595647151676573, -1.4473047264809593], + [8.665272379259687, 18.903612015043407], + [-16.6353246550972, 11.530871794771794], + [-7.570803866423977, -19.575308666218767] + ], + "roof": { + "z0": 15.032816976856667, + "gx": 0.22079469790365608, + "gy": 0.06434085122364717 + } + }, + { + "id": "p17", + "polygon": [ + [16.606414508797666, 10.257015858651291], + [-11.687423382283516, 15.632770446913186], + [-16.606414508797666, -10.257015858651291], + [11.687423382283516, -15.632770446913186] + ], + "roof": { + "z0": 20.596320346320347, + "gx": -0.13782184161098138, + "gy": 0.2602783351317969 + } + }, + { + "id": "p18", + "polygon": [ + [16.098697201068656, 4.490095805970851], + [-2.246851354952468, 16.56142116206339], + [-16.098697201068656, -4.490095805970851], + [2.246851354952468, -16.56142116206339] + ], + "roof": { + "z0": 35.333333333333336, + "gx": 0.028280648284255278, + "gy": -0.45908646240857853 + } + }, + { + "id": "p19", + "polygon": [ + [18.414862549252142, 17.37610097133769], + [-5.707378181207783, 24.66702012750314], + [-18.414862549252142, -17.37610097133769], + [5.707378181207783, -24.66702012750314] + ], + "roof": { + "z0": 35.333333333333336, + "gx": 0.31230543770808766, + "gy": -0.23854609901007925 + } + }, + { + "id": "p20", + "polygon": [ + [-8.288307523756904, -16.100713347865295], + [17.72018945984773, -3.731473894534753], + [8.288307523756904, 16.100713347865295], + [-17.72018945984773, 3.731473894534753] + ], + "roof": { + "z0": 20.596320346320347, + "gx": -0.04762237052870595, + "gy": -0.32824289915093546 + } + }, + { + "id": "p21", + "polygon": [ + [7.570185583450527, -24.641800622237195], + [25.405160822750684, -4.3707952644965395], + [-7.570185583450527, 24.641800622237195], + [-25.405160822750684, 4.3707952644965395] + ], + "roof": { + "z0": 26.971320346320347, + "gx": 0.2858935333146334, + "gy": 0.11604725922771755 + } + }, + { + "id": "p22", + "polygon": [ + [15.799441545339967, -9.09708876608419], + [9.794324357022624, 15.37694987805004], + [-15.799441545339967, 9.09708876608419], + [-9.794324357022624, -15.37694987805004] + ], + "roof": { + "z0": 35.333333333333336, + "gx": -0.13566761869763222, + "gy": -0.41216847649638705 + } + }, + { + "id": "p23", + "polygon": [ + [-2.2736988226703754, -13.160163100009239], + [11.841646849516936, -8.506325070602575], + [1.489188909661487, 11.204058465932881], + [-10.903969258030052, 13.015919881351309] + ], + "roof": { + "z0": 13.528016428725602, + "gx": 0.1612807013295745, + "gy": 0.3921921520858257 + } + }, + { + "id": "p24", + "polygon": [ + [26.112617747328514, -2.78697722557531], + [-7.853557769386294, 25.05908374296402], + [-26.112617747328514, 2.78697722557531], + [7.853557769386294, -25.05908374296402] + ], + "roof": { + "z0": 20.596320346320347, + "gx": 0.2233545942015857, + "gy": 0.0547975273857792 + } + }, + { + "id": "p25", + "polygon": [ + [-10.740295251597377, -20.454005346756016], + [20.27330247949115, -11.077611809034785], + [10.740295251597377, 20.454005346756016], + [-20.27330247949115, 11.077611809034785] + ], + "roof": { + "z0": 15.132034632034632, + "gx": -0.053243643492217455, + "gy": 0.17611002933718967 + } + }, + { + "id": "p26", + "polygon": [ + [16.106915459005773, 9.820216472108475], + [-10.207956543674953, 15.864015896521076], + [-16.106915459005773, -9.820216472108475], + [10.207956543674953, -15.864015896521076] + ], + "roof": { + "z0": 26.971320346320347, + "gx": 0.21749178222686819, + "gy": -0.28591787533248625 + } + } + ], + "rules": { + "translate": true, + "rotate": "continuous-z", + "flip": false + }, + "validation": { + "contactNoise": 1e-06, + "overlapDepth": 0.006, + "outsideDepth": 0.006, + "areaError": 0.012, + "edgeAngleDeg": 3.0, + "edgeMinOverlap": 0.02, + "roofMismatch": 0.05 + }, + "source": { + "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", + "puzzleId": "cor1", + "geometryHash": "78efff393692b812602735262414c51f99283649055de578ec070a3c7497c0e1" + } +} diff --git a/benchmarks/fixtures/index.json b/benchmarks/fixtures/index.json index 40547be..82d8faf 100644 --- a/benchmarks/fixtures/index.json +++ b/benchmarks/fixtures/index.json @@ -2,7 +2,7 @@ "formatVersion": 1, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0" + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c" }, "sanitizerVersion": 1, "sourceDifficulty": { @@ -13,12 +13,38 @@ "thresholds": [0.25, 0.3, 0.45, 0.62] }, "fixtures": [ + { + "id": "cor1", + "kind": "corpus", + "regime": "relief", + "pieceCount": 27, + "instanceHash": "026f6a52f04e26483d652f366c471c142c75244b7e203dedefdd281098beadff", + "construction": "cor1", + "sourceDifficulty": { + "diversity": 3.998651, + "x": 0.115333, + "rating": 5 + } + }, + { + "id": "cor1-flat", + "kind": "corpus", + "regime": "footprint", + "pieceCount": 27, + "instanceHash": "f6faf9abc88d94dedb1b5a5ea5bcf1a66c75e56095785034c623db24e1aeceb0", + "construction": "cor1", + "sourceDifficulty": { + "diversity": 4.09575, + "x": 0.119067, + "rating": 5 + } + }, { "id": "new1", "kind": "corpus", "regime": "relief", "pieceCount": 16, - "instanceHash": "316f47096c88b5d96a5ebd517f536a39fea14f5b8991126f11abf05a63af91f7", + "instanceHash": "8f77d45bb31789eaabbb58b51acc1a82686961655370bd64235d27b674c88694", "construction": "new1", "sourceDifficulty": { "diversity": 5.446444, @@ -31,7 +57,7 @@ "kind": "corpus", "regime": "footprint", "pieceCount": 16, - "instanceHash": "5cea41e18add833a84afe209351b407bea5c41f3b998c9c76f41b567b6cb66a1", + "instanceHash": "e2c6b3360c87150ede3e059afbdf07e2c690e06b60d17c15374363fb4d38915f", "construction": "new1", "sourceDifficulty": { "diversity": 6.426513, @@ -44,7 +70,7 @@ "kind": "corpus", "regime": "relief", "pieceCount": 16, - "instanceHash": "182cebb40e07f854b46e39d819b3b45a54838ff0345e998915a6f3ade2d1ef70", + "instanceHash": "3e241af54d54f34251097f97c88d4c048dac2f4aa92636995f1e58e96fb831c6", "construction": "new2", "sourceDifficulty": { "diversity": 4.496934, @@ -57,7 +83,7 @@ "kind": "corpus", "regime": "footprint", "pieceCount": 16, - "instanceHash": "59a938c00227006b4c39007dbf87b40dde7fb11b50eb546cd065b9cc4df03785", + "instanceHash": "806c33e986132b3e09b3d08dcd455e5dbc79dd57caa73c7056363329a5552569", "construction": "new2", "sourceDifficulty": { "diversity": 4.78389, @@ -70,7 +96,7 @@ "kind": "corpus", "regime": "relief", "pieceCount": 9, - "instanceHash": "f323c0f36ee5c67a4ed9909df8647c76b7a8b5daaf1185d58b0cb599d73d4077", + "instanceHash": "ffa7dd51d43a0bd68ac3842eecef7b0b3444479c5e1e6f1eded8b8124c79358c", "construction": "new3", "sourceDifficulty": { "diversity": 5.681002, @@ -83,7 +109,7 @@ "kind": "corpus", "regime": "footprint", "pieceCount": 9, - "instanceHash": "3bef95861401962974a94cc7bd3af623140579de81ce8c4a1752d3e88cb8a19b", + "instanceHash": "0375980860cc4864066b5705a43b295deadecf188ddcb900a867f2204c98d9b2", "construction": "new3", "sourceDifficulty": { "diversity": 6.633686, @@ -96,7 +122,7 @@ "kind": "corpus", "regime": "relief", "pieceCount": 9, - "instanceHash": "72113b0654c26918d6d5245a37490c80a627a30303190223603de35003c32498", + "instanceHash": "262293f93491b1cd363f52d0957d362edf45f76e0a18463594034f0051d0354b", "construction": "new4", "sourceDifficulty": { "diversity": 3.500216, @@ -109,7 +135,7 @@ "kind": "corpus", "regime": "footprint", "pieceCount": 9, - "instanceHash": "e9b5924cff70660da1d21edfbbfc0afc4379f2c2b70b27c446b9589e8aef3e0b", + "instanceHash": "b760c7313023cc5096b8445bf49e0c70863cdc697e4cef6ea8c875786e038952", "construction": "new4", "sourceDifficulty": { "diversity": 3.939849, @@ -122,7 +148,7 @@ "kind": "corpus", "regime": "relief", "pieceCount": 6, - "instanceHash": "dadb5297b3ba835bc2da28201a5430cc796afbe59dac4474a0f90f2c0fe597ac", + "instanceHash": "d972897b43f6db974556e2d37ab9ae9c7cd850ceda56fdba9cdb741083d7dc6a", "construction": "new5", "sourceDifficulty": { "diversity": 4.466807, @@ -135,7 +161,7 @@ "kind": "corpus", "regime": "footprint", "pieceCount": 6, - "instanceHash": "2b719a8e0e9e1b04e870a73388b596e5c7b21ed2a983a7363d5deddd31fdf692", + "instanceHash": "08a9a7d6f35079f33abc0b6bf205b800330ea87f76d9b50536be3568080d3bf3", "construction": "new5", "sourceDifficulty": { "diversity": 4.186563, @@ -148,7 +174,7 @@ "kind": "corpus", "regime": "relief", "pieceCount": 11, - "instanceHash": "3b8ac23d1a3395c8b30313ea53253973ec1e515a9dfae59b1eb7702f5546b41d", + "instanceHash": "f895d290552212be413b5e187759a8ec76161cc46bba7fa6cf4ab8b4cb242664", "construction": "rat1", "sourceDifficulty": { "diversity": 4.891978, @@ -161,7 +187,7 @@ "kind": "corpus", "regime": "footprint", "pieceCount": 11, - "instanceHash": "ce4e5d5431c8a8daa8bd2ff3dce519e0ba669b9507868ace5376295a495c7577", + "instanceHash": "9b7eeef268cd4e79418c51a2853bc7359aae7346308ebd847c6cfd77a6a6ab26", "construction": "rat1", "sourceDifficulty": { "diversity": 4.538006, @@ -174,7 +200,7 @@ "kind": "corpus", "regime": "relief", "pieceCount": 20, - "instanceHash": "ea656bb60309a5582eecf701870916707c8ee154182fb232845c4242e08e0ddb", + "instanceHash": "b4a9cbd44edc4f9425df0cc11069679078abd8d1b487163d7ba5fbbab8a13741", "construction": "rat2", "sourceDifficulty": { "diversity": 5.709562, @@ -187,7 +213,7 @@ "kind": "corpus", "regime": "footprint", "pieceCount": 20, - "instanceHash": "dbac49368deabed47b3a50c6ed255c12dec8fe5f6442c36d25794a49114033d0", + "instanceHash": "76df43b7888c5aa0c009afa24e8e9f974e6382bedc282802346f1cd8cd664c73", "construction": "rat2", "sourceDifficulty": { "diversity": 6.063062, @@ -200,7 +226,7 @@ "kind": "corpus", "regime": "relief", "pieceCount": 9, - "instanceHash": "bcd0168ea567cf80cdda0ffeef4fbae9a35e7db78336a6cdebe69edaadb486c5", + "instanceHash": "d45bf8b85e80fb55123833cc59745b7545334614476d7c30c62f2c1d26e97218", "construction": "rev2", "sourceDifficulty": { "diversity": 5.09878, @@ -213,7 +239,7 @@ "kind": "corpus", "regime": "footprint", "pieceCount": 9, - "instanceHash": "2acb913456ef45663e8622a80085cd69b1d99b12bf3d4f5cd530881350576608", + "instanceHash": "4d35562a36ca9ad667d3afbf464c37a0e123fdcd2639175e7ecfeaf8fab7a272", "construction": "rev2", "sourceDifficulty": { "diversity": 4.482502, diff --git a/benchmarks/fixtures/new1-flat.json b/benchmarks/fixtures/new1-flat.json index eea7e21..692395c 100644 --- a/benchmarks/fixtures/new1-flat.json +++ b/benchmarks/fixtures/new1-flat.json @@ -191,7 +191,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new1-flat", "geometryHash": "ae39042ff2d2f2a108aed7d0e08138b84171d5f6d7dd8af38a922402fb24eded" } diff --git a/benchmarks/fixtures/new1.json b/benchmarks/fixtures/new1.json index 5f86d9d..e66d877 100644 --- a/benchmarks/fixtures/new1.json +++ b/benchmarks/fixtures/new1.json @@ -273,7 +273,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new1", "geometryHash": "aca54e06186bcecf28e618580f22ee080a3019f32322121d3848305200d83437" } diff --git a/benchmarks/fixtures/new2-flat.json b/benchmarks/fixtures/new2-flat.json index 223ad6b..8653863 100644 --- a/benchmarks/fixtures/new2-flat.json +++ b/benchmarks/fixtures/new2-flat.json @@ -191,7 +191,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new2-flat", "geometryHash": "8213c7bbd3d6f0f31ef393013f4a55c0b7f741b64318c80c308a29a8ecb3cc09" } diff --git a/benchmarks/fixtures/new2.json b/benchmarks/fixtures/new2.json index cabfa76..a0f5fda 100644 --- a/benchmarks/fixtures/new2.json +++ b/benchmarks/fixtures/new2.json @@ -273,7 +273,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new2", "geometryHash": "27f66cb4de8390c31be5e78d64d3ca4bd4db2dd37187acf7a9f39c630cd0236d" } diff --git a/benchmarks/fixtures/new3-flat.json b/benchmarks/fixtures/new3-flat.json index 779b75f..8d649c0 100644 --- a/benchmarks/fixtures/new3-flat.json +++ b/benchmarks/fixtures/new3-flat.json @@ -118,7 +118,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new3-flat", "geometryHash": "60679aece595a9cbae5e0d888f153b0fc674f5a0e05cdf2f6c5be531064d1c1b" } diff --git a/benchmarks/fixtures/new3.json b/benchmarks/fixtures/new3.json index 1b3e4b8..4259e91 100644 --- a/benchmarks/fixtures/new3.json +++ b/benchmarks/fixtures/new3.json @@ -165,7 +165,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new3", "geometryHash": "adad00a1e9896ab0c87e5fdac0eab3eb4554f56f73cda103c0558087cfd56212" } diff --git a/benchmarks/fixtures/new4-flat.json b/benchmarks/fixtures/new4-flat.json index 8894995..e8c0af1 100644 --- a/benchmarks/fixtures/new4-flat.json +++ b/benchmarks/fixtures/new4-flat.json @@ -118,7 +118,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new4-flat", "geometryHash": "cdef8a3777943864f1225d3d9c4778d7bd5fd8c4e18bcebf55c4336ef62aefef" } diff --git a/benchmarks/fixtures/new4.json b/benchmarks/fixtures/new4.json index 205bee7..0b339d0 100644 --- a/benchmarks/fixtures/new4.json +++ b/benchmarks/fixtures/new4.json @@ -165,7 +165,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new4", "geometryHash": "232a0c31a6b15fbb06565d36dc0a6b97611815b1b77561d86671ebbd7695a25d" } diff --git a/benchmarks/fixtures/new5-flat.json b/benchmarks/fixtures/new5-flat.json index 920c286..82c5c57 100644 --- a/benchmarks/fixtures/new5-flat.json +++ b/benchmarks/fixtures/new5-flat.json @@ -87,7 +87,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new5-flat", "geometryHash": "7e0a0b140e6b303e7f104fac7d8a67f74b7bd1b364a8a5131512ba649c996101" } diff --git a/benchmarks/fixtures/new5.json b/benchmarks/fixtures/new5.json index 56a3fac..af0e7c4 100644 --- a/benchmarks/fixtures/new5.json +++ b/benchmarks/fixtures/new5.json @@ -119,7 +119,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "new5", "geometryHash": "754f8fc1f37b130d44fde65fc85c66f0913264f64f6bfe8ac6f15e17ec05f9bc" } diff --git a/benchmarks/fixtures/rat1-flat.json b/benchmarks/fixtures/rat1-flat.json index 04b1bca..51f232c 100644 --- a/benchmarks/fixtures/rat1-flat.json +++ b/benchmarks/fixtures/rat1-flat.json @@ -131,7 +131,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "rat1-flat", "geometryHash": "fac3e2c7d4d285e0061bf9aa317b8cafb52299a7e06b7a2e1976535a8b479b1d" } diff --git a/benchmarks/fixtures/rat1.json b/benchmarks/fixtures/rat1.json index 1b725d5..87aee16 100644 --- a/benchmarks/fixtures/rat1.json +++ b/benchmarks/fixtures/rat1.json @@ -188,7 +188,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "rat1", "geometryHash": "e91d5fba6e065bd5063286f3b2b3d22511aa0ffe7ce62706494f55972e8cd04a" } diff --git a/benchmarks/fixtures/rat2-flat.json b/benchmarks/fixtures/rat2-flat.json index e40e408..f247310 100644 --- a/benchmarks/fixtures/rat2-flat.json +++ b/benchmarks/fixtures/rat2-flat.json @@ -218,7 +218,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "rat2-flat", "geometryHash": "fa6e7a9ae160b7887e911042f1260e942790d2537ef75912c86751abc88b46fa" } diff --git a/benchmarks/fixtures/rat2.json b/benchmarks/fixtures/rat2.json index c5911d3..9103275 100644 --- a/benchmarks/fixtures/rat2.json +++ b/benchmarks/fixtures/rat2.json @@ -320,7 +320,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "rat2", "geometryHash": "e04fdc109a7c76ccd7b966af949ff7218bae47a4140cfd61013504fa8d4e013b" } diff --git a/benchmarks/fixtures/rev2-flat.json b/benchmarks/fixtures/rev2-flat.json index 8da0110..a0ab6d5 100644 --- a/benchmarks/fixtures/rev2-flat.json +++ b/benchmarks/fixtures/rev2-flat.json @@ -121,7 +121,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "rev2-flat", "geometryHash": "c5b5216b0fcc1031c9a09243d60eb99d4fc3a29c754e906214c8b875f4693cc4" } diff --git a/benchmarks/fixtures/rev2.json b/benchmarks/fixtures/rev2.json index 3b346eb..3bcecf7 100644 --- a/benchmarks/fixtures/rev2.json +++ b/benchmarks/fixtures/rev2.json @@ -168,7 +168,7 @@ }, "source": { "repository": "https://github.com/maxpluslab/tropical-puzzle-lab", - "commit": "9f9ed10715042c9472a91dd849fde979f048cba0", + "commit": "b1a17926b6cb32eacfb9f24a4e3ac36241e73f7c", "puzzleId": "rev2", "geometryHash": "96192e2a2eaacbd09c73761150a0373c7aa46bdbbbe876fa01d7761b04b5fcbc" } diff --git a/benchmarks/manifests/corpus.toml b/benchmarks/manifests/corpus.toml index 1c76eb8..2ea4e4a 100644 --- a/benchmarks/manifests/corpus.toml +++ b/benchmarks/manifests/corpus.toml @@ -1,6 +1,9 @@ name = "corpus" description = """ Every registered solver on the whole corpus, each search run to its end where it can be. +The two searches that would not end, cor1-flat's, stop at a node limit well above what +any other corpus puzzle needs (new1-flat: 1 064 878), so that where they stop does not +depend on the machine. `maxplus-bench run benchmarks/manifests/corpus.toml --no-times` reproduces benchmarks/results/corpus.md; a test holds the two together. """ @@ -10,10 +13,16 @@ fixtures = ["corpus"] [[runs]] solver = "rust.contact_dfs" +[runs.options] +node_limit = 1500000 + # CP-SAT choosing among the placements that search reaches. [[runs]] solver = "cp_sat.placements" +[runs.options] +node_limit = 1500000 + # The Python prototype knows footprints only, and counts every orientation of the tray. # It is given a node limit, not a time limit, so that where it stops does not depend on # the machine: the three largest puzzles are beyond it. diff --git a/benchmarks/manifests/edge_to_edge.toml b/benchmarks/manifests/edge_to_edge.toml new file mode 100644 index 0000000..9217438 --- /dev/null +++ b/benchmarks/manifests/edge_to_edge.toml @@ -0,0 +1,28 @@ +name = "edge_to_edge" +description = """ +What the edge-to-edge assumption is worth. Every corpus puzzle is searched to its end by +rust.contact_dfs in its own regime, assuming nothing and assuming that the pieces meet +edge to edge, and under the assumption with each of its two rules on and off. +`maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times` reproduces +benchmarks/results/edge_to_edge.md; a test holds the two together. Rows that assume +nothing are the corpus table's, for comparison; rows under the assumption answer a +narrower question and are not comparable with them. As there, a search that assumes +nothing stops at 1 500 000 nodes: only cor1-flat's reaches the limit. +""" +fixtures = ["corpus"] + +# The search as it is: nothing assumed. +[[runs]] +solver = "rust.contact_dfs" + +[runs.options] +node_limit = 1500000 + +# The assumption, with its two rules crossed. +[[runs]] +solver = "rust.contact_dfs" +assume = "edge-to-edge" + +[runs.options] +equal_edges = [true, false] +wall_edges = [true, false] diff --git a/benchmarks/manifests/tolerance.toml b/benchmarks/manifests/tolerance.toml index fd49b73..256fd4b 100644 --- a/benchmarks/manifests/tolerance.toml +++ b/benchmarks/manifests/tolerance.toml @@ -17,7 +17,7 @@ contact_scale = [1.0, 10.0, 100.0, 1000.0, 3000.0, 6000.0, 12000.0] [[runs]] solver = "rust.contact_dfs" time_limit_s = 30.0 -fixtures = ["new1", "new2", "new3", "new4", "new5", "rat1", "rat2", "rev2"] +fixtures = ["cor1", "new1", "new2", "new3", "new4", "new5", "rat1", "rat2", "rev2"] contact_scale = [1.0, 100.0, 1000.0, 6000.0] [runs.options] diff --git a/benchmarks/results/corpus.md b/benchmarks/results/corpus.md index 2dd10e4..4d6605a 100644 --- a/benchmarks/results/corpus.md +++ b/benchmarks/results/corpus.md @@ -1,37 +1,41 @@ | Fixture | Pieces | Solver | Mode | node_limit | Status | Whole search | Solutions | Valid | Nodes | Backtracks | Mean dead-end depth | Candidates per node | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | -| `new1` | 16 | `rust.contact_dfs` | relief | | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 106.01 | -| `new1-flat` | 16 | `rust.contact_dfs` | footprint | | solved | yes | 1 | 1 | 1 064 878 | 935 271 | 6.03 | 32.48 | -| `new2` | 16 | `rust.contact_dfs` | relief | | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 98.35 | -| `new2-flat` | 16 | `rust.contact_dfs` | footprint | | solved | yes | 1 | 1 | 909 750 | 820 554 | 5.72 | 22.05 | -| `new3` | 9 | `rust.contact_dfs` | relief | | solved | yes | 1 | 1 | 44 | 27 | 1.26 | 65.84 | -| `new3-flat` | 9 | `rust.contact_dfs` | footprint | | solved | yes | 1 | 1 | 6 104 | 5 355 | 4.14 | 12.42 | -| `new4` | 9 | `rust.contact_dfs` | relief | | solved | yes | 1 | 1 | 45 | 26 | 1.35 | 54.62 | -| `new4-flat` | 9 | `rust.contact_dfs` | footprint | | solved | yes | 1 | 1 | 510 | 462 | 2.88 | 9.10 | -| `new5` | 6 | `rust.contact_dfs` | relief | | solved | yes | 1 | 1 | 26 | 16 | 1.19 | 37.85 | -| `new5-flat` | 6 | `rust.contact_dfs` | footprint | | solved | yes | 1 | 1 | 90 | 70 | 2.13 | 10.76 | -| `rat1` | 11 | `rust.contact_dfs` | relief | | solved | yes | 1 | 1 | 90 | 52 | 1.90 | 72.24 | -| `rat1-flat` | 11 | `rust.contact_dfs` | footprint | | solved | yes | 101 | 101 | 17 425 | 13 436 | 5.29 | 21.70 | -| `rat2` | 20 | `rust.contact_dfs` | relief | | solved | yes | 1 | 1 | 94 | 49 | 1.49 | 118.35 | -| `rat2-flat` | 20 | `rust.contact_dfs` | footprint | | solved | yes | 2 | 2 | 128 230 | 109 786 | 6.00 | 50.03 | -| `rev2` | 9 | `rust.contact_dfs` | relief | | solved | yes | 1 | 1 | 26 | 13 | 1.23 | 18.46 | -| `rev2-flat` | 9 | `rust.contact_dfs` | footprint | | solved | yes | 1 | 1 | 45 | 25 | 2.72 | 26.09 | -| `new1` | 16 | `cp_sat.placements` | relief | | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 106.01 | -| `new1-flat` | 16 | `cp_sat.placements` | footprint | | solved | yes | 1 | 1 | 1 064 878 | 935 271 | 6.03 | 32.48 | -| `new2` | 16 | `cp_sat.placements` | relief | | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 98.35 | -| `new2-flat` | 16 | `cp_sat.placements` | footprint | | solved | yes | 1 | 1 | 909 750 | 820 554 | 5.72 | 22.05 | -| `new3` | 9 | `cp_sat.placements` | relief | | solved | yes | 1 | 1 | 44 | 27 | 1.26 | 65.84 | -| `new3-flat` | 9 | `cp_sat.placements` | footprint | | solved | yes | 1 | 1 | 6 104 | 5 355 | 4.14 | 12.42 | -| `new4` | 9 | `cp_sat.placements` | relief | | solved | yes | 1 | 1 | 45 | 26 | 1.35 | 54.62 | -| `new4-flat` | 9 | `cp_sat.placements` | footprint | | solved | yes | 1 | 1 | 510 | 462 | 2.88 | 9.10 | -| `new5` | 6 | `cp_sat.placements` | relief | | solved | yes | 1 | 1 | 26 | 16 | 1.19 | 37.85 | -| `new5-flat` | 6 | `cp_sat.placements` | footprint | | solved | yes | 1 | 1 | 90 | 70 | 2.13 | 10.76 | -| `rat1` | 11 | `cp_sat.placements` | relief | | solved | yes | 1 | 1 | 90 | 52 | 1.90 | 72.24 | -| `rat1-flat` | 11 | `cp_sat.placements` | footprint | | solved | yes | 101 | 101 | 17 425 | 13 436 | 5.29 | 21.70 | -| `rat2` | 20 | `cp_sat.placements` | relief | | solved | yes | 1 | 1 | 94 | 49 | 1.49 | 118.35 | -| `rat2-flat` | 20 | `cp_sat.placements` | footprint | | solved | yes | 2 | 2 | 128 230 | 109 786 | 6.00 | 50.03 | -| `rev2` | 9 | `cp_sat.placements` | relief | | solved | yes | 1 | 1 | 26 | 13 | 1.23 | 18.46 | -| `rev2-flat` | 9 | `cp_sat.placements` | footprint | | solved | yes | 1 | 1 | 45 | 25 | 2.72 | 26.09 | +| `cor1` | 27 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 1 529 | 357 | 5.84 | 256.12 | +| `cor1-flat` | 27 | `rust.contact_dfs` | footprint | 1500000 | interrupted | no | 0 | 0 | 1 500 000 | 1 426 301 | 11.14 | 19.44 | +| `new1` | 16 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 106.01 | +| `new1-flat` | 16 | `rust.contact_dfs` | footprint | 1500000 | solved | yes | 1 | 1 | 1 064 878 | 935 271 | 6.03 | 32.48 | +| `new2` | 16 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 98.35 | +| `new2-flat` | 16 | `rust.contact_dfs` | footprint | 1500000 | solved | yes | 1 | 1 | 909 750 | 820 554 | 5.72 | 22.05 | +| `new3` | 9 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 44 | 27 | 1.26 | 65.84 | +| `new3-flat` | 9 | `rust.contact_dfs` | footprint | 1500000 | solved | yes | 1 | 1 | 6 104 | 5 355 | 4.14 | 12.42 | +| `new4` | 9 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 45 | 26 | 1.35 | 54.62 | +| `new4-flat` | 9 | `rust.contact_dfs` | footprint | 1500000 | solved | yes | 1 | 1 | 510 | 462 | 2.88 | 9.10 | +| `new5` | 6 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 26 | 16 | 1.19 | 37.85 | +| `new5-flat` | 6 | `rust.contact_dfs` | footprint | 1500000 | solved | yes | 1 | 1 | 90 | 70 | 2.13 | 10.76 | +| `rat1` | 11 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 90 | 52 | 1.90 | 72.24 | +| `rat1-flat` | 11 | `rust.contact_dfs` | footprint | 1500000 | solved | yes | 101 | 101 | 17 425 | 13 436 | 5.29 | 21.70 | +| `rat2` | 20 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 94 | 49 | 1.49 | 118.35 | +| `rat2-flat` | 20 | `rust.contact_dfs` | footprint | 1500000 | solved | yes | 2 | 2 | 128 230 | 109 786 | 6.00 | 50.03 | +| `rev2` | 9 | `rust.contact_dfs` | relief | 1500000 | solved | yes | 1 | 1 | 26 | 13 | 1.23 | 18.46 | +| `rev2-flat` | 9 | `rust.contact_dfs` | footprint | 1500000 | solved | yes | 1 | 1 | 45 | 25 | 2.72 | 26.09 | +| `cor1` | 27 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 1 529 | 357 | 5.84 | 256.12 | +| `cor1-flat` | 27 | `cp_sat.placements` | footprint | 1500000 | interrupted | no | 0 | 0 | 1 500 000 | 1 435 891 | 9.40 | 19.19 | +| `new1` | 16 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 106.01 | +| `new1-flat` | 16 | `cp_sat.placements` | footprint | 1500000 | solved | yes | 1 | 1 | 1 064 878 | 935 271 | 6.03 | 32.48 | +| `new2` | 16 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 98.35 | +| `new2-flat` | 16 | `cp_sat.placements` | footprint | 1500000 | solved | yes | 1 | 1 | 909 750 | 820 554 | 5.72 | 22.05 | +| `new3` | 9 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 44 | 27 | 1.26 | 65.84 | +| `new3-flat` | 9 | `cp_sat.placements` | footprint | 1500000 | solved | yes | 1 | 1 | 6 104 | 5 355 | 4.14 | 12.42 | +| `new4` | 9 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 45 | 26 | 1.35 | 54.62 | +| `new4-flat` | 9 | `cp_sat.placements` | footprint | 1500000 | solved | yes | 1 | 1 | 510 | 462 | 2.88 | 9.10 | +| `new5` | 6 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 26 | 16 | 1.19 | 37.85 | +| `new5-flat` | 6 | `cp_sat.placements` | footprint | 1500000 | solved | yes | 1 | 1 | 90 | 70 | 2.13 | 10.76 | +| `rat1` | 11 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 90 | 52 | 1.90 | 72.24 | +| `rat1-flat` | 11 | `cp_sat.placements` | footprint | 1500000 | solved | yes | 101 | 101 | 17 425 | 13 436 | 5.29 | 21.70 | +| `rat2` | 20 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 94 | 49 | 1.49 | 118.35 | +| `rat2-flat` | 20 | `cp_sat.placements` | footprint | 1500000 | solved | yes | 2 | 2 | 128 230 | 109 786 | 6.00 | 50.03 | +| `rev2` | 9 | `cp_sat.placements` | relief | 1500000 | solved | yes | 1 | 1 | 26 | 13 | 1.23 | 18.46 | +| `rev2-flat` | 9 | `cp_sat.placements` | footprint | 1500000 | solved | yes | 1 | 1 | 45 | 25 | 2.72 | 26.09 | | `new1-flat` | 16 | `python.contact_dfs` | footprint | 50000 | interrupted | no | 0 | 0 | 50 000 | 41 838 | 6.38 | 79.49 | | `new2-flat` | 16 | `python.contact_dfs` | footprint | 50000 | interrupted | no | 0 | 0 | 50 000 | 43 026 | 7.07 | 90.36 | | `new3-flat` | 9 | `python.contact_dfs` | footprint | 50000 | solved | yes | 4 | 4 | 9 080 | 7 346 | 4.42 | 37.84 | diff --git a/benchmarks/results/edge_to_edge.md b/benchmarks/results/edge_to_edge.md new file mode 100644 index 0000000..df422f2 --- /dev/null +++ b/benchmarks/results/edge_to_edge.md @@ -0,0 +1,92 @@ +| Fixture | Pieces | Solver | Mode | assumes | equal_edges | node_limit | wall_edges | Status | Whole search | Solutions | Valid | Nodes | Backtracks | Mean dead-end depth | Candidates per node | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `cor1` | 27 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 1 529 | 357 | 5.84 | 256.12 | +| `cor1-flat` | 27 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | interrupted | no | 0 | 0 | 1 500 000 | 1 426 301 | 11.14 | 19.44 | +| `new1` | 16 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 106.01 | +| `new1-flat` | 16 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | solved | yes | 1 | 1 | 1 064 878 | 935 271 | 6.03 | 32.48 | +| `new2` | 16 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 68 | 43 | 1.19 | 98.35 | +| `new2-flat` | 16 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | solved | yes | 1 | 1 | 909 750 | 820 554 | 5.72 | 22.05 | +| `new3` | 9 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 44 | 27 | 1.26 | 65.84 | +| `new3-flat` | 9 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | solved | yes | 1 | 1 | 6 104 | 5 355 | 4.14 | 12.42 | +| `new4` | 9 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 45 | 26 | 1.35 | 54.62 | +| `new4-flat` | 9 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | solved | yes | 1 | 1 | 510 | 462 | 2.88 | 9.10 | +| `new5` | 6 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 26 | 16 | 1.19 | 37.85 | +| `new5-flat` | 6 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | solved | yes | 1 | 1 | 90 | 70 | 2.13 | 10.76 | +| `rat1` | 11 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 90 | 52 | 1.90 | 72.24 | +| `rat1-flat` | 11 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | solved | yes | 101 | 101 | 17 425 | 13 436 | 5.29 | 21.70 | +| `rat2` | 20 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 94 | 49 | 1.49 | 118.35 | +| `rat2-flat` | 20 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | solved | yes | 2 | 2 | 128 230 | 109 786 | 6.00 | 50.03 | +| `rev2` | 9 | `rust.contact_dfs` | relief | nothing | | 1500000 | | solved | yes | 1 | 1 | 26 | 13 | 1.23 | 18.46 | +| `rev2-flat` | 9 | `rust.contact_dfs` | footprint | nothing | | 1500000 | | solved | yes | 1 | 1 | 45 | 25 | 2.72 | 26.09 | +| `cor1` | 27 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 967 | 200 | 5.92 | 257.41 | +| `cor1` | 27 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 1 378 | 255 | 6.62 | 264.05 | +| `cor1` | 27 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 967 | 200 | 5.92 | 261.53 | +| `cor1` | 27 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 1 378 | 255 | 6.62 | 268.21 | +| `cor1-flat` | 27 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 48 | 48 | 44 539 | 7 254 | 15.65 | 95.96 | +| `cor1-flat` | 27 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 48 | 48 | 50 470 | 10 231 | 15.40 | 93.36 | +| `cor1-flat` | 27 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 48 | 48 | 44 539 | 7 254 | 15.65 | 145.00 | +| `cor1-flat` | 27 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 48 | 48 | 50 470 | 10 231 | 15.40 | 140.60 | +| `new1` | 16 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 49 | 25 | 1.28 | 100.04 | +| `new1` | 16 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 67 | 43 | 1.16 | 101.37 | +| `new1` | 16 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 49 | 25 | 1.28 | 103.82 | +| `new1` | 16 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 67 | 43 | 1.16 | 104.48 | +| `new1-flat` | 16 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 1 | 1 | 49 | 25 | 1.28 | 78.06 | +| `new1-flat` | 16 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 1 | 1 | 57 | 31 | 1.29 | 70.63 | +| `new1-flat` | 16 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 1 | 1 | 49 | 25 | 1.28 | 119.41 | +| `new1-flat` | 16 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 1 | 1 | 57 | 31 | 1.29 | 109.61 | +| `new2` | 16 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 48 | 26 | 1.19 | 96.15 | +| `new2` | 16 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 65 | 43 | 1.12 | 95.08 | +| `new2` | 16 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 48 | 26 | 1.19 | 100.58 | +| `new2` | 16 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 65 | 43 | 1.12 | 98.88 | +| `new2-flat` | 16 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 1 | 1 | 59 | 27 | 1.56 | 72.54 | +| `new2-flat` | 16 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 1 | 1 | 65 | 33 | 1.45 | 65.85 | +| `new2-flat` | 16 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 1 | 1 | 59 | 27 | 1.56 | 132.12 | +| `new2-flat` | 16 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 1 | 1 | 65 | 33 | 1.45 | 119.92 | +| `new3` | 9 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 24 | 11 | 1.27 | 73.00 | +| `new3` | 9 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 40 | 27 | 1.11 | 61.80 | +| `new3` | 9 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 24 | 11 | 1.27 | 75.42 | +| `new3` | 9 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 40 | 27 | 1.11 | 63.92 | +| `new3-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 1 | 1 | 24 | 11 | 1.27 | 52.38 | +| `new3-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 1 | 1 | 36 | 23 | 1.30 | 39.31 | +| `new3-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 1 | 1 | 24 | 11 | 1.27 | 70.21 | +| `new3-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 1 | 1 | 36 | 23 | 1.30 | 52.47 | +| `new4` | 9 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 24 | 11 | 1.27 | 63.62 | +| `new4` | 9 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 39 | 26 | 1.12 | 54.56 | +| `new4` | 9 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 24 | 11 | 1.27 | 66.54 | +| `new4` | 9 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 39 | 26 | 1.12 | 56.79 | +| `new4-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 1 | 1 | 28 | 14 | 1.36 | 48.39 | +| `new4-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 1 | 1 | 38 | 23 | 1.39 | 36.87 | +| `new4-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 1 | 1 | 28 | 14 | 1.36 | 67.36 | +| `new4-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 1 | 1 | 38 | 23 | 1.39 | 51.26 | +| `new5` | 6 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 14 | 6 | 1.17 | 44.29 | +| `new5` | 6 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 26 | 16 | 1.19 | 36.73 | +| `new5` | 6 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 14 | 6 | 1.17 | 45.43 | +| `new5` | 6 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 26 | 16 | 1.19 | 37.85 | +| `new5-flat` | 6 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 1 | 1 | 14 | 6 | 1.17 | 35.57 | +| `new5-flat` | 6 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 1 | 1 | 24 | 14 | 1.36 | 28.25 | +| `new5-flat` | 6 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 1 | 1 | 14 | 6 | 1.17 | 48.50 | +| `new5-flat` | 6 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 1 | 1 | 24 | 14 | 1.36 | 36.54 | +| `rat1` | 11 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 48 | 18 | 2.39 | 67.67 | +| `rat1` | 11 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 83 | 42 | 1.95 | 78.01 | +| `rat1` | 11 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 48 | 18 | 2.39 | 71.83 | +| `rat1` | 11 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 83 | 42 | 1.95 | 81.67 | +| `rat1-flat` | 11 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 1 | 1 | 72 | 29 | 2.76 | 60.01 | +| `rat1-flat` | 11 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 1 | 1 | 101 | 41 | 3.02 | 56.24 | +| `rat1-flat` | 11 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 1 | 1 | 72 | 29 | 2.76 | 76.08 | +| `rat1-flat` | 11 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 1 | 1 | 101 | 41 | 3.02 | 73.03 | +| `rat2` | 20 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 67 | 31 | 1.48 | 121.36 | +| `rat2` | 20 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 92 | 49 | 1.45 | 114.63 | +| `rat2` | 20 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 67 | 31 | 1.48 | 124.66 | +| `rat2` | 20 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 92 | 49 | 1.45 | 117.76 | +| `rat2-flat` | 20 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 1 | 1 | 80 | 39 | 1.72 | 111.66 | +| `rat2-flat` | 20 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 1 | 1 | 94 | 50 | 1.62 | 103.82 | +| `rat2-flat` | 20 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 1 | 1 | 80 | 39 | 1.72 | 149.44 | +| `rat2-flat` | 20 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 1 | 1 | 94 | 50 | 1.62 | 137.91 | +| `rev2` | 9 | `rust.contact_dfs` | relief | edge-to-edge | true | | true | solved | yes | 1 | 1 | 22 | 9 | 1.33 | 22.18 | +| `rev2` | 9 | `rust.contact_dfs` | relief | edge-to-edge | true | | false | solved | yes | 1 | 1 | 26 | 13 | 1.23 | 18.46 | +| `rev2` | 9 | `rust.contact_dfs` | relief | edge-to-edge | false | | true | solved | yes | 1 | 1 | 22 | 9 | 1.33 | 22.18 | +| `rev2` | 9 | `rust.contact_dfs` | relief | edge-to-edge | false | | false | solved | yes | 1 | 1 | 26 | 13 | 1.23 | 18.46 | +| `rev2-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | true | | true | solved | yes | 1 | 1 | 21 | 9 | 1.22 | 23.67 | +| `rev2-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | true | | false | solved | yes | 1 | 1 | 25 | 13 | 1.15 | 20.72 | +| `rev2-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | false | | true | solved | yes | 1 | 1 | 21 | 9 | 1.22 | 38.10 | +| `rev2-flat` | 9 | `rust.contact_dfs` | footprint | edge-to-edge | false | | false | solved | yes | 1 | 1 | 25 | 13 | 1.15 | 34.52 | diff --git a/crates/tiling-geometry/src/assembly.rs b/crates/tiling-geometry/src/assembly.rs index b78ff49..b70eb2f 100644 --- a/crates/tiling-geometry/src/assembly.rs +++ b/crates/tiling-geometry/src/assembly.rs @@ -36,7 +36,7 @@ use tiling_core::{Pose, Vec2}; use crate::cavity::{Cavity, cavities}; use crate::contact::{ContactTolerance, Corner, EdgeRef, free_corners, pose_at_corner}; -use crate::graph::{EdgeGraph, Shape}; +use crate::graph::{EdgeGraph, Meeting, Shape}; use crate::polygon::{is_convex_ccw, outside_depth, transform}; use crate::relief::{roof_height, seam_step}; use crate::sat::penetration_depth; @@ -82,6 +82,12 @@ pub struct CandidateStats { /// before the other checks, or along a shared edge after them. Always zero /// for pieces without roofs. pub rejected_roof: u64, + /// Rejected for putting a vertex strictly inside an edge of a placed piece, + /// or the reverse. Always zero unless pieces are assumed to meet edge to edge. + pub rejected_junction: u64, + /// Rejected for taking an edge that no other piece's edge can lie against + /// off the tray. Always zero unless that rule is on. + pub rejected_wall: u64, } /// Smallest axis-aligned box around a polygon, as `[min x, min y, max x, max y]`. @@ -101,6 +107,22 @@ fn bounds(polygon: &[Vec2]) -> [f64; 4] { b } +/// Whether a point of `vertices` lies on an edge of `polygon`, more than +/// `tolerance` from both of its ends. +fn vertex_inside_an_edge(vertices: &[Vec2], polygon: &[Vec2], tolerance: f64) -> bool { + let n = polygon.len(); + vertices.iter().any(|v| { + (0..n).any(|i| { + let (a, b) = (polygon[i], polygon[(i + 1) % n]); + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let length = dx.hypot(dy); + let along = ((v[0] - a[0]) * dx + (v[1] - a[1]) * dy) / length; + let off = ((v[0] - a[0]) * dy - (v[1] - a[1]) * dx) / length; + off.abs() <= tolerance && along > tolerance && along < length - tolerance + }) + }) +} + /// Whether two boxes are further apart than `slack` along an axis. fn apart(a: &[f64; 4], b: &[f64; 4], slack: f64) -> bool { a[2] + slack < b[0] || b[2] + slack < a[0] || a[3] + slack < b[1] || b[3] + slack < a[1] @@ -143,6 +165,7 @@ pub struct Assembly { shapes: Vec, graph: EdgeGraph, tolerance: ContactTolerance, + meeting: Meeting, poses: Vec>, world: Vec>>, boxes: Vec<[f64; 4]>, @@ -152,10 +175,21 @@ pub struct Assembly { } impl Assembly { + /// An assembly in which nothing is assumed about how pieces meet. pub fn new( target: Vec, shapes: Vec, tolerance: ContactTolerance, + ) -> Result { + Assembly::meeting(target, shapes, tolerance, Meeting::default()) + } + + /// An assembly whose candidates respect `meeting`. + pub fn meeting( + target: Vec, + shapes: Vec, + tolerance: ContactTolerance, + meeting: Meeting, ) -> Result { let positive = |v: f64| v.is_finite() && v > 0.0; if ![ @@ -175,13 +209,14 @@ impl Assembly { if let Some(piece) = shapes.iter().position(|s| !is_convex_ccw(&s.polygon)) { return Err(AssemblyError::NotConvex(Some(piece))); } - let graph = EdgeGraph::build(&shapes, &tolerance); + let graph = EdgeGraph::build_for(&shapes, &tolerance, meeting.uses_equal_edges()); let count = shapes.len(); Ok(Assembly { target, shapes, graph, tolerance, + meeting, poses: vec![None; count], world: vec![None; count], boxes: vec![[0.0; 4]; count], @@ -334,6 +369,40 @@ impl Assembly { }) } + /// Whether `world` and a placed piece meet in a T: a vertex of one strictly + /// inside an edge of the other. + fn makes_a_junction(&self, world: &[Vec2]) -> bool { + let reach = bounds(world); + let tolerance = self.tolerance.length; + self.stack.iter().any(|&other| { + !apart(&reach, &self.boxes[other], tolerance) + && self.world[other].as_ref().is_some_and(|polygon| { + vertex_inside_an_edge(world, polygon, tolerance) + || vertex_inside_an_edge(polygon, world, tolerance) + }) + }) + } + + /// Whether `world`, a placement of `piece`, has an edge off the tray's + /// boundary that no other piece's edge could lie against. + fn strands_an_edge(&self, piece: usize, world: &[Vec2]) -> bool { + let n = world.len(); + let tolerance = self.tolerance.length; + let on_the_tray = |a: Vec2, b: Vec2| { + let m = self.target.len(); + (0..m).any(|j| { + let (s, e) = (self.target[j], self.target[(j + 1) % m]); + let (dx, dy) = (e[0] - s[0], e[1] - s[1]); + let length = dx.hypot(dy); + let off = |p: Vec2| ((p[0] - s[0]) * dy - (p[1] - s[1]) * dx) / length; + off(a).abs() <= tolerance && off(b).abs() <= tolerance + }) + }; + (0..n).any(|i| { + !self.graph.has_partner(piece, i) && !on_the_tray(world[i], world[(i + 1) % n]) + }) + } + /// Measure a placement of `piece` against the target and the other placed pieces. pub fn check_placement( &self, @@ -383,6 +452,11 @@ impl Assembly { /// placement is known to fit, the heights along every edge it shares with a /// placed piece. /// + /// If the pieces are assumed to meet edge to edge ([`Meeting`]), a + /// placement that meets a placed piece in a T is left out, and so, by the + /// rules that follow from the assumption, are placements that no assembly + /// of that kind contains. + /// /// For a convex corner the list is complete in the sense of the module /// documentation. For any other corner it is a list of legal placements and /// nothing more. @@ -422,6 +496,10 @@ impl Assembly { self.stats.rejected_outside += 1; } else if self.enters_a_placed_piece(&world) { self.stats.rejected_overlap += 1; + } else if self.meeting.edge_to_edge && self.makes_a_junction(&world) { + self.stats.rejected_junction += 1; + } else if self.meeting.uses_wall_edges() && self.strands_an_edge(piece, &world) { + self.stats.rejected_wall += 1; } else if self.roof_step_of(piece, &pose, &world) > self.tolerance.height { self.stats.rejected_roof += 1; } else { @@ -458,6 +536,7 @@ impl Assembly { #[cfg(test)] mod tests { use super::*; + use crate::graph::Meeting; use crate::polygon::{centroid, signed_area}; use crate::testing::{TOL, Tiling, close, tiling}; use proptest::prelude::*; @@ -644,7 +723,9 @@ mod tests { generated: 5, rejected_outside: 1, rejected_overlap: 0, - rejected_roof: 0 + rejected_roof: 0, + rejected_junction: 0, + rejected_wall: 0, } ); } @@ -853,4 +934,93 @@ mod tests { } } } + + /// A 4 by 2 block and two 2 by 2 squares fill a 4 by 4 tray in one way, and + /// in it the squares' shared corner stands in the middle of the block's long + /// edge: a T. + fn block_and_squares(meeting: Meeting) -> Assembly { + let shapes = vec![ + bare(rectangle(4.0, 2.0)), + bare(rectangle(2.0, 2.0)), + bare(rectangle(2.0, 2.0)), + ]; + Assembly::meeting(tray(), shapes, TOL, meeting).unwrap() + } + + #[test] + fn a_placement_that_makes_a_t_is_refused_only_under_the_assumption() { + // The junction check alone: neither rule that follows from the assumption. + let only = Meeting { + edge_to_edge: true, + equal_edges: false, + wall_edges: false, + }; + for (meeting, offered) in [(Meeting::default(), true), (only, false)] { + let mut assembly = block_and_squares(meeting); + assembly.place(0, at(2.0, 1.0, 0.0)).unwrap(); + // The corner over the block's top-left vertex. A square there has its + // bottom-right vertex at (2, 2), inside the block's top edge. + let corner = corner_at(&assembly, 0.0, 2.0); + let candidates = assembly.propose(&corner); + let square = candidates.iter().any(|c| c.piece == 1); + assert_eq!(square, offered, "{meeting:?}"); + assert_eq!( + assembly.stats().rejected_junction > 0, + !offered, + "{meeting:?}" + ); + } + // Two pieces meeting along a whole edge are no T: one square on another. + // The block lying over the square is one: the square's top-right vertex, + // (2, 2), is inside its bottom edge. Standing, it reaches outside. + let mut assembly = block_and_squares(only); + assembly.place(1, at(1.0, 1.0, 0.0)).unwrap(); + let corner = corner_at(&assembly, 0.0, 2.0); + let pieces: Vec = assembly.propose(&corner).iter().map(|c| c.piece).collect(); + assert_eq!(pieces, vec![2]); + assert_eq!(assembly.stats().rejected_junction, 1); + } + + #[test] + fn an_edge_no_other_piece_matches_is_kept_on_the_tray() { + let assembly = block_and_squares(Meeting::edge_to_edge()); + // The block's long edges (0 and 2, 4 long) have no partner; its short ones + // match a square's side, and every side of a square matches the other square. + let partners: Vec = (0..4).map(|e| assembly.graph().has_partner(0, e)).collect(); + assert_eq!(partners, vec![false, true, false, true]); + assert!((0..4).all(|e| assembly.graph().has_partner(1, e))); + + // In the empty tray's corner the block, lying or standing, puts a long edge + // off the wall; only the square is offered. + for (wall_edges, block) in [(true, false), (false, true)] { + let meeting = Meeting { + wall_edges, + ..Meeting::edge_to_edge() + }; + let mut assembly = block_and_squares(meeting); + let corner = corner_at(&assembly, 0.0, 0.0); + let candidates = assembly.propose(&corner); + assert_eq!(candidates.iter().any(|c| c.piece == 0), block); + assert!(candidates.iter().any(|c| c.piece == 1)); + assert_eq!( + assembly.stats().rejected_wall, + if wall_edges { 2 } else { 0 } + ); + } + } + + #[test] + fn without_the_assumption_its_rules_do_nothing() { + let rules_alone = Meeting { + edge_to_edge: false, + equal_edges: true, + wall_edges: true, + }; + let mut plain = block_and_squares(Meeting::default()); + let mut alone = block_and_squares(rules_alone); + assert_eq!(plain.graph().arc_count(), alone.graph().arc_count()); + let corner = corner_at(&plain, 0.0, 0.0); + assert_eq!(plain.propose(&corner), alone.propose(&corner)); + assert_eq!(plain.stats(), alone.stats()); + } } diff --git a/crates/tiling-geometry/src/graph.rs b/crates/tiling-geometry/src/graph.rs index 50d467c..f8592a4 100644 --- a/crates/tiling-geometry/src/graph.rs +++ b/crates/tiling-geometry/src/graph.rs @@ -12,6 +12,12 @@ //! continuous along a shared edge if their slopes along it agree, and the two //! edges run in opposite directions, so the slopes along them must cancel. //! +//! If the pieces are known to meet edge to edge (see [`Meeting`]), lengths do +//! prove something: a piece edge lies against the whole of one edge of one +//! other piece, or on the tray. Arcs can then ask for equal lengths and, with +//! roofs, equal heights at both ends; and an edge with no such partner on any +//! other piece can only lie on the tray. +//! //! The same signatures say which pieces are interchangeable and which //! placements of one piece are the same placement, so that the search does not //! count one assembly many times. @@ -21,6 +27,44 @@ use tiling_core::{Roof, Vec2}; use crate::contact::{ContactTolerance, EdgeRef}; use crate::edges::{EdgeSignature, edge_signatures}; +/// What is assumed about how pieces meet, and which consequences are used. +/// +/// The default assumes nothing: a vertex of one piece may lie anywhere along +/// an edge of another. With `edge_to_edge`, no vertex of a piece lies strictly +/// inside an edge of another piece, as in a puzzle cut from a polyhedral +/// complex. That is an assumption about the assembly sought, not a pruning +/// rule: it changes what a search can find. The other two fields are pruning +/// rules that follow from it, and are ignored without it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Meeting { + /// Refuse a placement that puts a vertex strictly inside another piece's edge. + pub edge_to_edge: bool, + /// Let a piece edge lie against a piece edge only if the two are equally + /// long and, with roofs, equally high at both ends. + pub equal_edges: bool, + /// Keep a piece edge that no other piece's edge can lie against on the tray. + pub wall_edges: bool, +} + +impl Meeting { + /// The assumption with both of its rules. + pub fn edge_to_edge() -> Meeting { + Meeting { + edge_to_edge: true, + equal_edges: true, + wall_edges: true, + } + } + + pub(crate) fn uses_equal_edges(&self) -> bool { + self.edge_to_edge && self.equal_edges + } + + pub(crate) fn uses_wall_edges(&self) -> bool { + self.edge_to_edge && self.wall_edges + } +} + /// A piece as the candidate generator sees it: a local polygon and its roof, if any. #[derive(Debug, Clone, PartialEq)] pub struct Shape { @@ -36,6 +80,9 @@ pub struct EdgeGraph { edge_count: usize, /// `arcs[fixed * edge_count + mover]` over piece edges. Tray edges accept every piece edge. arcs: Vec, + /// For each piece edge, whether some edge of another piece could lie + /// against the whole of it: slopes cancelling, equal length, equal heights. + partnered: Vec, classes: Vec, /// For each piece, the turn that takes its class's first piece onto it. turns: Vec, @@ -76,7 +123,19 @@ pub fn rotation_order(polygon: &[Vec2], tolerance: &ContactTolerance) -> usize { } impl EdgeGraph { + /// The graph when nothing is assumed about how pieces meet. pub fn build(shapes: &[Shape], tolerance: &ContactTolerance) -> EdgeGraph { + EdgeGraph::build_for(shapes, tolerance, false) + } + + /// With `equal_edges`, an arc also needs the two edges to be equally long + /// and, with roofs, equally high at both ends: what holds for every + /// contact between pieces that meet edge to edge. + pub fn build_for( + shapes: &[Shape], + tolerance: &ContactTolerance, + equal_edges: bool, + ) -> EdgeGraph { let signatures: Vec> = shapes .iter() .map(|s| edge_signatures(&s.polygon, s.roof.as_ref())) @@ -88,6 +147,17 @@ impl EdgeGraph { edge_count += piece.len(); } + // The mover's edge runs the other way, so its start meets the fixed edge's end. + let level = |x: Option, y: Option| match (x, y) { + (Some(x), Some(y)) => (x - y).abs() <= tolerance.height, + _ => true, + }; + let whole = |a: &EdgeSignature, b: &EdgeSignature| { + (a.length - b.length).abs() <= tolerance.length + && level(a.height_start, b.height_end) + && level(a.height_end, b.height_start) + }; + let mut partnered = vec![false; edge_count]; let mut arcs = vec![false; edge_count * edge_count]; for (p, fixed) in signatures.iter().enumerate() { for (q, mover) in signatures.iter().enumerate() { @@ -101,7 +171,10 @@ impl EdgeGraph { (Some(x), Some(y)) => (x + y).abs() <= tolerance.slope, _ => true, }; - arcs[(offsets[p] + i) * edge_count + offsets[q] + j] = fits; + let fits_whole = fits && whole(a, b); + partnered[offsets[p] + i] |= fits_whole; + arcs[(offsets[p] + i) * edge_count + offsets[q] + j] = + if equal_edges { fits_whole } else { fits }; } } } @@ -143,6 +216,7 @@ impl EdgeGraph { offsets, edge_count, arcs, + partnered, classes, turns, symmetry, @@ -164,6 +238,13 @@ impl EdgeGraph { } } + /// Whether some edge of another piece could lie against the whole of this + /// one. An edge without such a partner lies on the tray in every assembly + /// whose pieces meet edge to edge. + pub fn has_partner(&self, piece: usize, edge: usize) -> bool { + self.partnered[self.offsets[piece] + edge] + } + /// Number of piece edges. pub fn edge_count(&self) -> usize { self.edge_count diff --git a/crates/tiling-geometry/src/lib.rs b/crates/tiling-geometry/src/lib.rs index a51c0a8..f4a1a68 100644 --- a/crates/tiling-geometry/src/lib.rs +++ b/crates/tiling-geometry/src/lib.rs @@ -40,7 +40,7 @@ pub use clip::{intersection, intersection_area, outside_area}; pub use conflict::{Conflict, Conflicts, Placed, conflict, conflicts}; pub use contact::{ContactTolerance, Corner, EdgeRef, free_corners, pose_at_corner}; pub use edges::{Edge, EdgeSignature, edge_signatures, edges}; -pub use graph::{EdgeGraph, Shape, rotation_order}; +pub use graph::{EdgeGraph, Meeting, Shape, rotation_order}; pub use polygon::{ ConvexPolygon, NotConvex, centroid, contains_point, distance_to_segment, is_convex_ccw, outside_depth, point_outside_depth, signed_area, transform, diff --git a/crates/tiling-geometry/src/testing.rs b/crates/tiling-geometry/src/testing.rs index cd787ec..ee18906 100644 --- a/crates/tiling-geometry/src/testing.rs +++ b/crates/tiling-geometry/src/testing.rs @@ -7,7 +7,7 @@ use proptest::prelude::*; use tiling_core::{Pose, Roof, Vec2}; use crate::contact::ContactTolerance; -use crate::polygon::{centroid, is_convex_ccw}; +use crate::polygon::{centroid, distance_to_segment, is_convex_ccw}; /// Coincidence bounds for tests on exact constructions. pub const TOL: ContactTolerance = ContactTolerance { @@ -157,33 +157,146 @@ pub fn tiling() -> impl Strategy { world.push(two); } } - let mut local = Vec::new(); - let mut poses = Vec::new(); - for (piece, turn) in world.iter().zip(turns) { - let [cx, cy] = centroid(piece); - let back = Pose { - x: 0.0, - y: 0.0, - theta: -turn, - }; - local.push( - piece - .iter() - .map(|p| back.apply([p[0] - cx, p[1] - cy])) - .collect(), - ); - poses.push(Pose { - x: cx, - y: cy, - theta: turn, - }); + handed_out(target, world, &turns) + }) + .prop_filter("at least one cut succeeded", |t| t.world.len() >= 2) +} + +/// The pieces of a tiling as a solver receives them: each about its centroid, +/// turned by its own angle. +fn handed_out(target: Vec, world: Vec>, turns: &[f64]) -> Tiling { + let mut local = Vec::new(); + let mut poses = Vec::new(); + for (piece, &turn) in world.iter().zip(turns) { + let [cx, cy] = centroid(piece); + let back = Pose { + x: 0.0, + y: 0.0, + theta: -turn, + }; + local.push( + piece + .iter() + .map(|p| back.apply([p[0] - cx, p[1] - cy])) + .collect(), + ); + poses.push(Pose { + x: cx, + y: cy, + theta: turn, + }); + } + Tiling { + target, + world, + local, + poses, + } +} + +/// The two sides of a convex polygon cut by the line through `at` in direction +/// `angle`, or `None` if the line does not pass through its interior. +fn split(polygon: &[Vec2], at: Vec2, angle: f64) -> Option<[Vec; 2]> { + let (s, c) = angle.sin_cos(); + let side: Vec = polygon + .iter() + .map(|p| (p[1] - at[1]) * c - (p[0] - at[0]) * s) + .collect(); + if side.iter().all(|&v| v > 0.0) || side.iter().all(|&v| v < 0.0) { + return None; + } + let (mut left, mut right) = (Vec::new(), Vec::new()); + let n = polygon.len(); + for i in 0..n { + let (p, q) = (polygon[i], polygon[(i + 1) % n]); + let (a, b) = (side[i], side[(i + 1) % n]); + if a > 0.0 { + left.push(p) + } else { + right.push(p) + } + if (a > 0.0) != (b > 0.0) { + let t = a / (a - b); + let crossing = [p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]; + left.push(crossing); + right.push(crossing); + } + } + Some([left, right]) +} + +/// Tilings of 2 to 8 pieces that meet edge to edge: a convex polygon cut by +/// up to three whole lines, so that the pieces are the cells of a line +/// arrangement. Every cell a line crosses is cut, and a line whose cuts would +/// leave a badly shaped piece is not drawn at all. +pub fn line_tiling() -> impl Strategy { + let lines = prop::collection::vec((-15.0f64..15.0, -15.0f64..15.0, 0.0f64..PI), 1..=3); + let turns = prop::collection::vec(-PI..PI, 8); + (convex_polygon(), pose(), lines, turns) + .prop_map(|(polygon, at, lines, turns)| { + let target: Vec = polygon + .iter() + .map(|p| at.apply([3.0 * p[0], 3.0 * p[1]])) + .collect(); + let middle = centroid(&target); + let mut world = vec![target.clone()]; + for (dx, dy, angle) in lines { + let through = [middle[0] + dx, middle[1] + dy]; + let mut cut = Vec::new(); + let mut drawn = true; + for cell in &world { + match split(cell, through, angle) { + Some([one, two]) if well_shaped(&one) && well_shaped(&two) => { + cut.push(one); + cut.push(two); + } + Some(_) => drawn = false, + None => cut.push(cell.clone()), + } + } + if drawn && cut.len() <= 8 { + world = cut; + } } - Tiling { - target, - world, - local, - poses, + handed_out(target, world, &turns) + }) + .prop_filter("at least one line was drawn", |t| t.world.len() >= 2) +} + +/// Whether placed pieces meet edge to edge, decided by twin edges: every piece +/// edge either lies on the target's boundary or is, reversed, exactly one edge +/// of exactly one other piece. For pieces that cover the target this is the +/// same as no vertex lying strictly inside another piece's edge, which is how +/// the candidate generator decides it; the two are written differently so that +/// one can check the other. +pub fn is_edge_to_edge(target: &[Vec2], world: &[Vec], tolerance: f64) -> bool { + let near = |a: Vec2, b: Vec2| (a[0] - b[0]).hypot(a[1] - b[1]) <= tolerance; + let m = target.len(); + let on_boundary = |a: Vec2, b: Vec2| { + (0..m).any(|j| { + let (s, e) = (target[j], target[(j + 1) % m]); + distance_to_segment(a, s, e) <= tolerance && distance_to_segment(b, s, e) <= tolerance + }) + }; + world.iter().enumerate().all(|(p, piece)| { + let n = piece.len(); + (0..n).all(|i| { + let (a, b) = (piece[i], piece[(i + 1) % n]); + if on_boundary(a, b) { + return true; } + let twins: usize = world + .iter() + .enumerate() + .filter(|&(q, _)| q != p) + .map(|(_, other)| { + let k = other.len(); + (0..k) + .filter(|&j| near(a, other[(j + 1) % k]) && near(b, other[j])) + .count() + }) + .sum(); + twins == 1 }) - .prop_filter("at least one cut succeeded", |t| t.world.len() >= 2) + }) } diff --git a/crates/tiling-py/src/lib.rs b/crates/tiling-py/src/lib.rs index 69da459..addd003 100644 --- a/crates/tiling-py/src/lib.rs +++ b/crates/tiling-py/src/lib.rs @@ -429,7 +429,11 @@ impl Assembly { #[pymethods] impl Assembly { #[new] - #[pyo3(signature = (target, pieces, roofs=None, *, length_tol, angle_tol, slope_tol, height_tol=None))] + #[pyo3(signature = ( + target, pieces, roofs=None, *, length_tol, angle_tol, slope_tol, height_tol=None, + edge_to_edge=false, equal_edges=true, wall_edges=true, + ))] + #[allow(clippy::too_many_arguments)] fn new( target: Vec<[f64; 2]>, pieces: Vec>, @@ -438,10 +442,18 @@ impl Assembly { angle_tol: f64, slope_tol: f64, height_tol: Option, + edge_to_edge: bool, + equal_edges: bool, + wall_edges: bool, ) -> PyResult { let (shapes, tolerance) = puzzle_parts(pieces, roofs, length_tol, angle_tol, slope_tol, height_tol)?; - tiling_geometry::Assembly::new(target, shapes, tolerance) + let meeting = tiling_geometry::Meeting { + edge_to_edge, + equal_edges, + wall_edges, + }; + tiling_geometry::Assembly::meeting(target, shapes, tolerance, meeting) .map(|inner| Assembly { inner }) .map_err(refused) } @@ -451,6 +463,15 @@ impl Assembly { self.inner.piece_count() } + /// Whether some edge of another piece could lie against the whole of this + /// one: slopes cancelling, equal lengths, equal heights at both ends. + fn has_partner(&self, piece: usize, edge: usize) -> PyResult { + if piece >= self.inner.piece_count() || edge >= self.inner.shape(piece).polygon.len() { + return Err(PyValueError::new_err("no such piece edge")); + } + Ok(self.inner.graph().has_partner(piece, edge)) + } + /// Number of piece edges, the nodes of the compatibility graph besides the tray's. #[getter] fn edge_count(&self) -> usize { @@ -723,6 +744,8 @@ struct ContactDfsOutcome { rejected_outside: u64, rejected_overlap: u64, rejected_roof: u64, + rejected_junction: u64, + rejected_wall: u64, pruned_cavity: u64, pruned_closure: u64, pruned_anchor: u64, @@ -743,6 +766,7 @@ struct ContactDfsOutcome { max_solutions=Some(1), time_limit_s=None, node_limit=None, all_tray_rotations=false, anchor=true, cavity_pruning=true, closure_pruning=true, lookahead=false, order="matched-edges", seed=0, + edge_to_edge=false, equal_edges=true, wall_edges=true, ))] #[allow(clippy::too_many_arguments)] fn contact_dfs( @@ -764,6 +788,9 @@ fn contact_dfs( lookahead: bool, order: &str, seed: u64, + edge_to_edge: bool, + equal_edges: bool, + wall_edges: bool, ) -> PyResult { use tiling_search::contact_dfs::{Options, Order, TrayRotations, solve}; @@ -796,6 +823,11 @@ fn contact_dfs( lookahead, order, seed, + meeting: tiling_geometry::Meeting { + edge_to_edge, + equal_edges, + wall_edges, + }, ..Options::default() }; let outcome = py @@ -818,6 +850,8 @@ fn contact_dfs( rejected_outside: stats.candidates.rejected_outside, rejected_overlap: stats.candidates.rejected_overlap, rejected_roof: stats.candidates.rejected_roof, + rejected_junction: stats.candidates.rejected_junction, + rejected_wall: stats.candidates.rejected_wall, pruned_cavity: stats.pruned_cavity, pruned_closure: stats.pruned_closure, pruned_anchor: stats.pruned_anchor, diff --git a/crates/tiling-search/src/contact_dfs.rs b/crates/tiling-search/src/contact_dfs.rs index 83a1f61..a8c4bd5 100644 --- a/crates/tiling-search/src/contact_dfs.rs +++ b/crates/tiling-search/src/contact_dfs.rs @@ -54,7 +54,7 @@ use std::time::{Duration, Instant}; use tiling_core::{Pose, Vec2}; use tiling_geometry::{ Assembly, AssemblyError, CandidatePlacement, CandidateStats, Cavity, ContactTolerance, Corner, - Shape, centroid, least_width, signed_area, transform, + Meeting, Shape, centroid, least_width, signed_area, transform, }; use crate::canonical::{Placement, Symmetry}; @@ -96,6 +96,11 @@ pub struct Options { pub collect_placements: bool, /// Stop once this many distinct placements have been collected. pub max_placements: Option, + /// What is assumed about how pieces meet. Unlike the rules above, assuming + /// that they meet edge to edge changes what the search can find: only + /// assemblies without a T between pieces. Its two rules, like the others, + /// change only the work. + pub meeting: Meeting, } /// The order in which the candidates of a node are tried. It decides how soon @@ -126,6 +131,7 @@ impl Default for Options { seed: 0, collect_placements: false, max_placements: None, + meeting: Meeting::default(), } } } @@ -804,7 +810,7 @@ pub fn solve( .sum(); let symmetry_shapes = shapes.clone(); // Refuses anything that is not a convex counter-clockwise polygon. - let assembly = Assembly::new(target, shapes, tolerance)?; + let assembly = Assembly::meeting(target, shapes, tolerance, options.meeting)?; let widths: Vec = symmetry_shapes .iter() .map(|s| least_width(&s.polygon)) @@ -878,7 +884,7 @@ mod tests { use proptest::prelude::*; use tiling_core::Roof; use tiling_geometry::EdgeGraph; - use tiling_geometry::testing::{TOL, Tiling, tiling}; + use tiling_geometry::testing::{TOL, Tiling, is_edge_to_edge, line_tiling, tiling}; fn rectangle(w: f64, h: f64) -> Vec { vec![ @@ -1287,4 +1293,127 @@ mod tests { prop_assert!(!outcome.solutions.iter().any(|s| same.same(s, &tiling.poses))); } } + + /// The assumption, with the rules that follow from it switched as given. + fn assuming(equal_edges: bool, wall_edges: bool) -> Options { + Options { + meeting: Meeting { + edge_to_edge: true, + equal_edges, + wall_edges, + }, + ..whole() + } + } + + /// Every way of switching the two rules. + fn every_assumed() -> [Options; 4] { + [ + assuming(true, true), + assuming(true, false), + assuming(false, true), + assuming(false, false), + ] + } + + fn world_of(shapes: &[Shape], poses: &[Pose]) -> Vec> { + shapes + .iter() + .zip(poses) + .map(|(shape, pose)| transform(&shape.polygon, pose)) + .collect() + } + + /// The assemblies among `found` whose pieces meet edge to edge, by the twin-edge check. + fn without_a_t(target: &[Vec2], shapes: &[Shape], found: &[Vec]) -> Vec> { + found + .iter() + .filter(|poses| is_edge_to_edge(target, &world_of(shapes, poses), 1e-6)) + .cloned() + .collect() + } + + #[test] + fn a_block_and_two_squares_fit_only_in_a_t() { + // A 4 by 4 tray: the block along one wall, the squares beside each other on + // it. Turns of the tray and the squares' exchange make that one assembly. + let target = tray(4.0, 4.0); + let shapes = bare(&[ + rectangle(4.0, 2.0), + rectangle(2.0, 2.0), + rectangle(2.0, 2.0), + ]); + let plain = run(&target, &shapes, &whole()); + assert!(plain.exhausted); + assert_eq!(plain.solutions.len(), 1); + assert!(without_a_t(&target, &shapes, &plain.solutions).is_empty()); + for options in every_assumed() { + let assumed = run(&target, &shapes, &options); + assert!( + assumed.exhausted && assumed.solutions.is_empty(), + "{options:?}" + ); + } + } + + #[test] + fn two_strips_meet_edge_to_edge_and_are_found_either_way() { + let target = tray(4.0, 4.0); + let shapes = bare(&[rectangle(2.0, 4.0), rectangle(2.0, 4.0)]); + let plain = run(&target, &shapes, &whole()); + assert_eq!(plain.solutions.len(), 1); + for options in every_assumed() { + let assumed = run(&target, &shapes, &options); + assert_eq!(assumed.solutions, plain.solutions, "{options:?}"); + } + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + /// Assuming edge to edge narrows the search to exactly the assemblies + /// without a T, as a separately written check decides them; and the two + /// rules that follow from the assumption change the work only. Chord-cut + /// tilings have T's, so the narrowed set is often empty. + #[test] + fn the_assumption_keeps_exactly_the_assemblies_without_a_t(tiling in tiling()) { + let shapes = bare(&tiling.local); + let symmetry = symmetry(&tiling.target, &shapes); + let plain = run(&tiling.target, &shapes, &whole()); + prop_assert!(plain.exhausted); + let kept = without_a_t(&tiling.target, &shapes, &plain.solutions); + for options in every_assumed() { + let assumed = run(&tiling.target, &shapes, &options); + prop_assert!(assumed.exhausted); + prop_assert!( + same_sets(&symmetry, &assumed.solutions, &kept), + "{} found against {} kept with {:?}", + assumed.solutions.len(), kept.len(), options.meeting + ); + } + } + + /// The cells of a line arrangement meet edge to edge, so the assumption + /// holds of the tiling they were cut from, which is found, once, with + /// the rules on or off; and what is found is what the plain search finds + /// without a T. + #[test] + fn a_line_arrangement_is_found_under_the_assumption(tiling in line_tiling()) { + prop_assert!(is_edge_to_edge(&tiling.target, &tiling.world, 1e-6)); + let shapes = bare(&tiling.local); + let symmetry = symmetry(&tiling.target, &shapes); + let plain = run(&tiling.target, &shapes, &whole()); + prop_assert!(plain.exhausted); + let kept = without_a_t(&tiling.target, &shapes, &plain.solutions); + for options in every_assumed() { + let assumed = run(&tiling.target, &shapes, &options); + prop_assert!(assumed.exhausted); + let hits = assumed.solutions.iter().filter(|s| symmetry.same(s, &tiling.poses)).count(); + prop_assert_eq!(hits, 1); + prop_assert!(same_sets(&symmetry, &assumed.solutions, &kept), "{:?}", options.meeting); + // The assumption can only take work away from the plain search. + prop_assert!(assumed.stats.nodes <= plain.stats.nodes); + } + } + } } diff --git a/docs/algorithms.md b/docs/algorithms.md index ac6d469..5f742af 100644 --- a/docs/algorithms.md +++ b/docs/algorithms.md @@ -86,7 +86,7 @@ Rotations of the whole tray are *not* removed where candidates are generated. A Nodes are the oriented edges of the tray and of every piece; an arc from a fixed edge to a piece edge says the two may lie flush. It is built once from the edge signatures. -Without roofs the graph rules out nothing between different pieces. Pieces need not meet edge to edge, so lengths prove nothing, and whether an angle fits depends on the corner, which only the state knows. With roofs it prunes: two roofs are continuous along a shared edge only if their slopes along it agree, and the two edges run in opposite directions, so the slopes along them must cancel. On the corpus this removes more than half of all edge pairs, and it keeps every contact present in the answer keys. Poses are not stored on arcs; a pose is computed when a corner asks for one. +Without roofs the graph rules out nothing between different pieces. Pieces need not meet edge to edge, so lengths prove nothing, and whether an angle fits depends on the corner, which only the state knows. Unless the search is told to [assume they do](#assuming-the-pieces-meet-edge-to-edge). With roofs it prunes: two roofs are continuous along a shared edge only if their slopes along it agree, and the two edges run in opposite directions, so the slopes along them must cancel. On the corpus this removes more than half of all edge pairs, and it keeps every contact present in the answer keys. Poses are not stored on arcs; a pose is computed when a corner asks for one. The prototype works in the footprint regime and so sees the unpruned graph. The relief search of `rust.contact_dfs` uses the pruned one. @@ -263,6 +263,69 @@ What the tables say: These are eight constructions. They are enough to say what happens on this corpus and not enough to say why; the difficulty proxies of phase 7 are meant for that. +## Assuming the pieces meet edge to edge + +Every tropical puzzle is cut from a polyhedral complex. By the balancing condition, at a vertex of a tropical curve the weighted directions of its edges add up to zero, so they cannot all lie on one side of a line, and no cell has a straight angle there. In a rational puzzle the same holds of the common refinement of the two curves. So inside the tray two pieces meet along a whole edge of both, or at a single point, and never in a T: no vertex of a piece lies strictly inside an edge of another piece. The tray's wall is the exception, where creases end and several pieces may share one side. In the nine source puzzles, `cor1` included, each of the 446 edges inside the tray coincides with exactly one whole edge of one other piece. + +The search above does not use this. `rust.contact_dfs` can be told to, with `SolverConfig(assumptions=("edge-to-edge",))` or `maxplus-solve --assume edge-to-edge`. + +### An assumption, not a rule + +Every rule of the previous section leaves what a whole search finds unchanged. This one does not: it narrows the search to the assemblies without a T, and a puzzle that is not cut from a complex may have assemblies it no longer finds. So it is not an option but a declared assumption. It is separate from the regime, since it can be made with roofs or without; the result records it and names its own candidate set, `corner-contact-edge-to-edge/1` or `corner-contact-relief-edge-to-edge/1`; and its results are not comparable with results that assume nothing. + +Under the assumption a placement is refused if a vertex of it lies strictly inside an edge of a placed piece, or a vertex of a placed piece inside an edge of it, by more than the contact noise from either end (`rejected_junction`). Every pair of pieces is checked when the later one goes down, so every assembly found is without a T. + +**Argument.** The corner-filling argument never used how the pieces meet, so it holds unchanged for the assemblies without a T: in such an assembly, branching on any convex corner still reaches it, and the extra refusal removes only placements that make a T with a piece already down, which no such assembly contains. + +### Two rules that follow (`equal_edges`, `wall_edges`) + +If no assembly sought has a T, then every edge of a piece that is not on the tray lies against the whole of one edge of one other piece. Two rules follow, each an option that is on by default and only means something under the assumption: + +- **`equal_edges`.** In the [edge compatibility graph](#the-edge-compatibility-graph) a piece edge may lie against another piece's edge only if the two are equally long and, with roofs, equally high at both ends, besides the slopes that already had to cancel. Decided once, before any pose exists. +- **`wall_edges`.** An edge with no such partner on any other piece can only lie on the tray. A placement that puts it anywhere else is refused (`rejected_wall`). + +**Argument.** In an assembly without a T, two pieces that share an edge share the whole of it, so the two edges are equally long, and with continuous roofs equally high at both ends. An edge that is not on the tray is shared with some other piece. A placement that breaks either is part of no assembly without a T. Both rules therefore change the work and not what a whole search under the assumption finds. + +That is tested on the corpus (`tests/corpus/test_edge_to_edge.py`): for every fixture, with the two rules in all four combinations, the assumed search finds exactly the assemblies of the plain search that a separately written check by twin edges (`support.geometry.is_edge_to_edge`) calls edge to edge, the answer key among them. In Rust it is tested on random convex polygons cut by chords, which leave T's, and on random cells of line arrangements, which have none and whose tiling is always found (`the_assumption_keeps_exactly_the_assemblies_without_a_t`, `a_line_arrangement_is_found_under_the_assumption`). Switching the junction check off, or turning the length comparison round, makes them fail. + +### What it changes + +Whole searches with `rust.contact_dfs`, default rules, from `benchmarks/results/edge_to_edge.md`. Nodes are deterministic. + +| Fixture | Pieces | Assemblies | Nodes, nothing assumed | Nodes, edge to edge | No `wall_edges` | No `equal_edges` | +| --- | --- | --- | --- | --- | --- | --- | +| `new5-flat` | 6 | 1 | 90 | 14 | 24 | 14 | +| `new3-flat` | 9 | 1 | 6 104 | 24 | 36 | 24 | +| `new4-flat` | 9 | 1 | 510 | 28 | 38 | 28 | +| `rev2-flat` | 9 | 1 | 45 | 21 | 25 | 21 | +| `rat1-flat` | 11 | 101 → 1 | 17 425 | 72 | 101 | 72 | +| `new1-flat` | 16 | 1 | 1 064 878 | 49 | 57 | 49 | +| `new2-flat` | 16 | 1 | 909 750 | 59 | 65 | 59 | +| `rat2-flat` | 20 | 2 → 1 | 128 230 | 80 | 94 | 80 | +| `cor1-flat` | 27 | ? → 48 | stopped at 1 500 000 | 44 539 | 50 470 | 44 539 | +| `new5` | 6 | 1 | 26 | 14 | 26 | 14 | +| `new3` | 9 | 1 | 44 | 24 | 40 | 24 | +| `new4` | 9 | 1 | 45 | 24 | 39 | 24 | +| `rev2` | 9 | 1 | 26 | 22 | 26 | 22 | +| `rat1` | 11 | 1 | 90 | 48 | 83 | 48 | +| `new1` | 16 | 1 | 68 | 49 | 67 | 49 | +| `new2` | 16 | 1 | 68 | 48 | 65 | 48 | +| `rat2` | 20 | 1 | 94 | 67 | 92 | 67 | +| `cor1` | 27 | 1 | 1 529 | 967 | 1 378 | 967 | + +"No `wall_edges`" and "no `equal_edges`" are the assumption with that rule off. `cor1` and `cor1-flat` were built to be hard (below) and joined the corpus in this phase; the findings that follow are about the other eight constructions, and the last paragraph about `cor1`. + +- **Without roofs, it is worth more than the roofs.** The two 16-piece footprints that are hard for every configuration in the previous section take 49 and 59 nodes, against a million, and their dead ends come 1.3 and 1.6 pieces deep instead of six. On all eight constructions the footprint search under the assumption visits fewer nodes than the relief search of the same pieces that assumes nothing: 49 against 68 on `new1`, 80 against 94 on `rat2`. +- **Most of what the roofs did was this.** A roof refuses a wrong neighbour because two planes rarely agree in height along an edge by accident. Under the assumption a wrong neighbour is already refused for meeting in a T or for a length that does not match, and adding the roofs saves at most a third of the nodes (72 to 48 on `rat1`), on four of the eight none or one. The mean degree of the edge graph says the same without a search: 0.8 to 2.4 for the footprints under the assumption, against 23 to 84 without it, and 1.2 to 6.7 for the relief puzzles without it. +- **It decides uniqueness where the roofs did.** Of `rat1-flat`'s 101 footprint assemblies and `rat2-flat`'s 2, one each meets edge to edge: the one the roofs single out. The rearrangements that blocks of commensurable rectangles allow all make T's. +- **`wall_edges` removes nodes; `equal_edges` only removes work.** With `equal_edges` off the node counts are the same: the junction check refuses each placement it would have kept out, after the placement has been computed and checked. What it saves is those computations, a third of the candidates per node on the footprints. `wall_edges` removes up to half the nodes of the small relief puzzles, by keeping the edges with no partner, 10 to 36 % of all edges in the corpus, on the tray from the start. + +The obvious consequence for the question this laboratory asks: in this corpus, a puzzle with roofs, or a puzzle that a solver may assume to be a tropical cut, is easy for this search. What remains hard has to defeat both: pieces whose equal edges and level creases leave many neighbours possible, as `cor1` in Tropical Puzzle Lab is built to. + +`cor1`, a 27-piece puzzle built in Tropical Puzzle Lab for exactly this, bears it out. With its roofs it takes 1 529 nodes assuming nothing and 967 assuming edge to edge, against 48 to 67 for the other relief puzzles under the assumption, and its dead ends stay almost six pieces deep. Without its roofs, assuming edge to edge, it has 48 assemblies and takes 44 539 nodes, with dead ends almost sixteen pieces deep; assuming nothing, the search has not been seen to end (stopped at 1 500 000 nodes in the table, and at 3 000 000 by hand), so how many of its assemblies have a T is not known. Its level creases give many walls of one length and one height profile, which neither the lengths nor the roofs can tell apart, and its columns change places without making a T. `wall_edges` still pays on it: without it, 1 378 nodes with the roofs and 50 470 without. + +Not built, and noted for later: a counting bound during the search (every exposed edge needs an unplaced edge of its length), and the further consequences of a tropical construction, such as edge directions with small rational slopes and, for polynomials, a convex roof. + ## Choosing from a list (CP-SAT) `cp_sat.placements` is a solver of another kind. It knows no geometry: it is handed a finite list of placements and what they exclude among themselves, and chooses. The list and the exclusions are built in Rust (`tiling-search::enumerate`, `tiling-geometry::conflict`) in one call; the choosing is OR-Tools CP-SAT with one worker and no objective, asked for every solution. diff --git a/docs/architecture.md b/docs/architecture.md index a5f7dc7..b4f5f1e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -90,6 +90,10 @@ Coordinates are millimetres and radians, as in the browser player; there are no They are separate because construction metadata could make a puzzle computationally trivial for reasons unrelated to its physical difficulty. +### Assumptions + +Across the regimes runs a second axis: what a solver may take for granted about the assembly, without being told anything more about the pieces. The one so far is `edge-to-edge`, that pieces never meet in a T, which every tropical cut satisfies and which can be made with roofs or without. An assumption narrows what is looked for, so unlike a pruning rule it can change what a search finds. A solver declares the assumptions it can make, a result records the ones it made and names a candidate set that says so, and results under different assumptions are not compared. The contract is in [solver-contract.md](solver-contract.md#assumptions). + ### Sanitization The source `puzzle.json` reveals the answer in three ways: diff --git a/docs/experiments.md b/docs/experiments.md index 9ba51e0..eee1a49 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -78,12 +78,13 @@ One metric was added for this. `backtrack_depth` is the sum, over dead ends, of ## The corpus table -[`benchmarks/results/corpus.md`](../benchmarks/results/corpus.md) has all 40 rows. What it shows: +[`benchmarks/results/corpus.md`](../benchmarks/results/corpus.md) has all 44 rows. What it shows: -- Both production solvers finish every corpus puzzle and agree on the assemblies; every assembly passes the validator. `cp_sat.placements` shows the search counts of the listing search it starts from, which is `rust.contact_dfs`. -- With roofs a whole search takes 26 to 94 nodes. Without, 45 to 1 064 878. +- Both production solvers finish every corpus puzzle but `cor1-flat` and agree on the assemblies; every assembly passes the validator. `cp_sat.placements` shows the search counts of the listing search it starts from, which is `rust.contact_dfs` taking candidates in the order they are generated. A whole search visits the same nodes in any order, so where both finish the counts are the same; stopped at the limit on `cor1-flat` they are not, since the two have gone down different branches by then. +- `cor1-flat`, 27 pieces without their roofs, is stopped at the manifest's node limit of 1 500 000 without an assembly, by both. The limit is there so that the table is the same on any machine; by hand the search was stopped at 3 000 000 nodes, also without one. +- With roofs a whole search takes 26 to 94 nodes, except on `cor1`, built to be hard with its roofs on: 1 529. Without roofs, 45 to 1 064 878 where it ends. - The footprints have one assembly each, except `rat1-flat` (101) and `rat2-flat` (2). -- The prototype, without tray symmetry or pruning, finishes five of the eight footprints within 50 000 nodes and returns each assembly in the tray's four orientations. +- The prototype, without tray symmetry or pruning, finishes five of the eight footprints it is given within 50 000 nodes and returns each assembly in the tray's four orientations. It is not given `cor1-flat`. ## Tolerance @@ -249,12 +250,18 @@ What it shows, with eight points behind each coefficient: Correlations are taken within a regime only. Across both, any number that differs between footprints and reliefs correlates with the cost, because the roofs change the cost a thousandfold. +## Edge to edge + +`maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times` reproduces `benchmarks/results/edge_to_edge.md`: every corpus puzzle in its own regime, assuming nothing and assuming that the pieces meet edge to edge, with the assumption's two rules crossed. A manifest says `assume = "edge-to-edge"`, or a list with `"none"` to cross it with the other factors; the table then shows an `assumes` column on every row. What the numbers say is in [algorithms.md](algorithms.md#assuming-the-pieces-meet-edge-to-edge): the footprints that took up to a million nodes take 14 to 80, fewer than their relief twins took assuming nothing, and of `rat1-flat`'s 101 assemblies and `rat2-flat`'s 2 only the answer has no T. `cor1` stays hard under it: 967 nodes with its roofs, and 44 539 and 48 assemblies without them, where the search that assumes nothing does not end. + +`proxies.static(instance, edge_to_edge=True)` gives the edge-graph proxies under the assumption: mean degree 0.8 to 2.4 on the footprints, against 23 to 84 without it. + ## Figures and the notebook `maxplus_solvers.experiments.plotting` draws from records: `nodes_by_tolerance` (whole-search nodes against the contact tolerance, a line per fixture) and `proxy_against_cost` (one proxy against the nodes, a point per fixture). It needs the `analysis` extra and is the only module that imports matplotlib. `notebooks/first-look.ipynb` runs a manifest, prints its table and the proxies and draws both; a test runs it from top to bottom. ## What this leaves open -- The corpus is 16 puzzles from three constructions. Every statement about what predicts difficulty rests on eight points a regime. Generated families of graded size are the next thing these tools should be pointed at. -- The 16-piece footprints are where the search is hard, and they sit at the time limit. Remembering dead ends is the lead from phase 6; the manifests here are what to measure it with. +- The corpus is 18 puzzles from four kinds of construction. Every statement about what predicts difficulty rests on nine points a regime, and the proxy correlations above were measured on eight, before `cor1` joined. Generated families of graded size are the next thing these tools should be pointed at. +- Assuming nothing, the 16-piece footprints are where the search is hard, and they sit at the time limit; `cor1-flat` does not finish at all. Remembering dead ends is the lead from phase 6; the manifests here are what to measure it with. - Nothing here measures a person. In the hand these puzzles are simple with wall matching, which is the unique-mate structure above; the footprint regime removes exactly that. diff --git a/docs/roadmap.md b/docs/roadmap.md index 06354c2..4a2cf85 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -12,6 +12,7 @@ Each phase is sized for one working session and ends with an exit criterion that | 5 | Rust contact DFS | Done | | 6 | CP-SAT backend | Done | | 7 | Benchmark and research platform | Done | +| 8 | The edge-to-edge assumption | In progress | The source corpus is 8 constructions in two variants each (relief and flat), 16 puzzles of 6 to 20 convex pieces with 3 to 8 vertices, in a 144 mm square tray. @@ -184,6 +185,25 @@ Done, with these decisions: - Findings, in [experiments.md](experiments.md). There is no transition in tolerance: costs grow smoothly, solution counts do not change, and the roofs hold at 5 mm. The expected opposition between time to a first solution and time to exhaust is not there: both rise, because widening admits wrong placements and no new assemblies. Roofs move the cost more than ten thousandfold on the 16-piece puzzles; order, luck and looking ahead by ten to a hundred. The degree of the edge compatibility graph separates the regimes and ranks the relief puzzles; nothing static explains the footprints beyond their size. - For later phases: the corpus is too small to settle what predicts difficulty. Graded generated families, and nogood learning on the 16-piece footprints, are what the platform is for next. +## Phase 8: the edge-to-edge assumption + +Tropical puzzles are cut from a polyhedral complex, so their pieces meet edge to edge: the balancing condition leaves no T inside the tray. The search did not use this; a piece edge could lie against any part of a longer one. + +- `Assumption.EDGE_TO_EDGE` in the models: a declared assumption, separate from the regime, recorded in `SolverConfig` and `SolveResult`, with its own candidate sets. Solvers declare the assumptions they can make; `rust.contact_dfs` declares this one, the prototype and `cp_sat.placements` do not. +- In `tiling-geometry`: `Meeting`, the junction check in `Assembly::propose`, and two rules that follow, `equal_edges` (equal lengths and end heights in the edge graph) and `wall_edges` (an edge with no partner stays on the tray), each an option. +- `maxplus-solve --assume`, `assume` in manifests, an `assumes` column in tables, `proxies.static(..., edge_to_edge=True)`. +- `benchmarks/manifests/edge_to_edge.toml` and the committed `benchmarks/results/edge_to_edge.md`. + +**Exit:** on every corpus fixture, the search under the assumption finds exactly the assemblies of the plain search that an independent check calls edge to edge, with the two rules on and off, and the answer key among them. On `cor1-flat`, whose plain search does not end, everything the assumed search finds is edge to edge by that check and valid, and the answer key is among it. + +Decisions so far: + +- The exit criterion is `tests/corpus/test_edge_to_edge.py::test_the_assumption_finds_exactly_the_edge_to_edge_assemblies`. The independent check is `support.geometry.is_edge_to_edge`, by twin edges, where the search decides by vertices inside edges. +- An assumption is not a pruning rule, because it changes what a whole search finds. The two rules that follow from it are pruning rules within it, tested as such. +- Instances are not changed: whether a puzzle satisfies the assumption is a property of its assembly, which a solver is not told. +- `cor1` joined the corpus in this phase, re-imported from Tropical Puzzle Lab's main branch, so the corpus is 18 fixtures. `cor1-flat` is the first corpus puzzle whose plain search has not been seen to end. Tests that compare against the end of that search leave it out by name (`support.corpus.UNFINISHED`) and test it apart; the corpus and edge-to-edge manifests stop a search that assumes nothing at 1 500 000 nodes, well above the 1 064 878 of `new1-flat`, so where it stops does not depend on the machine. The exit criteria of phases 5 and 6 cover the corpus minus that one fixture. +- Findings, in [algorithms.md](algorithms.md#assuming-the-pieces-meet-edge-to-edge): the 16-piece footprints drop from a million nodes to about fifty; footprint and relief costs nearly coincide; only the answer of `rat1-flat` and `rat2-flat` is edge to edge. + ## Backlog Unordered, to be scheduled once phase 7 shows where the interesting questions are: @@ -193,7 +213,8 @@ Unordered, to be scheduled once phase 7 shows where the interesting questions ar - nogood learning and memoization of partial states by canonical contact graph; - branch and bound in `tiling-search`; - tolerance-aware search with continuous refinement of poses, including loop-closure checks on relative transforms; -- a solver for the tropical-aware regime, and tropical pruning beyond roof continuity (balancing conditions, admissible gradient sequences), experimental until proved; +- a solver for the tropical-aware regime, and tropical pruning beyond roof continuity and edge to edge (edge directions of small rational slope, convex roofs for polynomials, admissible gradient sequences), experimental until proved; +- under the edge-to-edge assumption, a counting bound during the search: every exposed edge needs an unplaced edge of its length; - exact or adaptive geometric predicates; - Z3, DLX exact-cover and MILP soft-mismatch backends; - comparison with human solve times from the browser player's report lines; diff --git a/docs/solver-contract.md b/docs/solver-contract.md index 60c1d9a..c1dedc5 100644 --- a/docs/solver-contract.md +++ b/docs/solver-contract.md @@ -27,6 +27,7 @@ maxplus-solve new5 --mode relief --max-solutions all --option closure_pruning=fa | `seed` | For solvers that randomize. A deterministic solver ignores it and says so. A solver that uses it gives the same result for the same seed. | | `tolerances` | A `TolerancePolicy`, or `None` for the instance's published ones. | | `options` | Solver-specific. An option a solver does not know is an error, not ignored. | +| `assumptions` | What the solver is to take for granted about the assemblies it looks for. Today one: `edge-to-edge`. Default none. See [Assumptions](#assumptions). | Before the solver runs, the instance is reduced to `config.mode`. A relief puzzle solved in `footprint` mode is handed over without its roofs, and the result's `instance_hash` is that of the reduced instance. Asking for a mode with more information than the instance has is an error, and so is a mode the solver does not declare. Results from different regimes are not comparable. @@ -42,6 +43,16 @@ Before the solver runs, the instance is reduced to `config.mode`. A relief puzzl `no_solution_found` is not "the puzzle has no solution". It says the solver's candidates contain none. The next section says when the stronger statement is allowed. +## Assumptions + +An assumption narrows what a solver looks for, where a regime limits what it is told. It is a statement about the assembly sought, such as "the pieces meet edge to edge", and a solver that makes it does not look for assemblies that break it. That makes it unlike an option: a pruning rule must not change what a whole search finds, an assumption does by design. + +| Assumption | Meaning | Solvers | +| --- | --- | --- | +| `edge-to-edge` | No vertex of a piece lies strictly inside an edge of another piece. Inside the tray two pieces share a whole edge of both, or a point, and never meet in a T. True of every puzzle cut from a tropical curve, which is a polyhedral complex. | `rust.contact_dfs` | + +A solver declares the assumptions it can make, and `solve` refuses one it has not declared. The result's `assumptions` repeat what was assumed, and its `candidate_set` names a set that says so. Every claim of the result, `no_solution_found` and solution counts included, is about the assemblies that satisfy its assumptions: "one assembly, assuming edge to edge" leaves open how many there are with a T. Results under different assumptions are not comparable, any more than results in different regimes; benchmark tables show the assumption on every row whenever one is made. + ## Completeness claims A result carries three fields that bound what may be concluded from it. @@ -62,6 +73,8 @@ No solver in this repository sets `candidates_proven_complete` today, and a solv | `corner-contact-relief/1` | `rust.contact_dfs` (relief) | The placements of `corner-contact/1` whose roofs continue the roofs already down: at the corner, and along every edge stretch shared with a placed piece, the two roofs differ in height by no more than the contact noise times the steepest roof gradient (at least the contact noise). Complete, in exact arithmetic, for exact assemblies whose roofs are exactly continuous. The validator allows a roof step of 1.75 mm on the corpus; assemblies that need any of that allowance are not in the set. | | `corner-contact-reachable/1` | `cp_sat.placements` (footprint) | The placements of `corner-contact/1` that the search of `rust.contact_dfs` puts down somewhere in its tree, with the listing options the result records. A finite list, built by running that search to its end. It holds every assembly that search finds and, being a subset of `corner-contact/1`, no more. If the listing was cut short by a limit the list is a part of this set and the result is not `exhaustive`. | | `corner-contact-relief-reachable/1` | `cp_sat.placements` (relief) | The same, of `corner-contact-relief/1`. | +| `corner-contact-edge-to-edge/1` | `rust.contact_dfs` (footprint, assuming `edge-to-edge`) | The placements of `corner-contact/1` that put no vertex strictly inside an edge of a placed piece, and no vertex of a placed piece strictly inside one of theirs, by more than the contact noise from either end. Complete, in exact arithmetic, for exact assemblies without a T. | +| `corner-contact-relief-edge-to-edge/1` | `rust.contact_dfs` (relief, assuming `edge-to-edge`) | The same, of `corner-contact-relief/1`. | A change to what a candidate set contains gets a new name. A rule that only removes candidates which cannot be part of any assembly in the set (the pruning rules of `rust.contact_dfs`) does not change the set: by the arguments in [algorithms.md](algorithms.md#the-rust-contact-search), and by test, the whole search finds the same assemblies with the rule on or off. @@ -105,6 +118,8 @@ In the relief regime "congruent" and "onto itself" include the roof: two pieces | `rejected_outside` | Of those, refused for reaching outside the target. | | `rejected_overlap` | Of the rest, refused for entering a placed piece. | | `rejected_roof` | Refused because the roof would not continue a neighbour's: at the corner, before any polygon work, or along a shared edge, after the two checks above. Zero in the footprint regime. | +| `rejected_junction` | Assuming `edge-to-edge`: refused for meeting a placed piece in a T. Absent without the assumption. | +| `rejected_wall` | Assuming `edge-to-edge`: refused for taking an edge that no other piece's edge can lie against off the tray. Absent without the assumption. | | `pruned_cavity` | Nodes abandoned because a cavity could not be filled: its area is no sum of areas of remaining pieces that fit it, or some remaining piece fits no cavity. | | `pruned_closure` | Nodes abandoned because a straight run or a convex corner of the uncovered region could not be closed by the remaining pieces. | | `pruned_anchor` | Placements of the anchor piece left out for lying outside its sector of the tray. | @@ -167,6 +182,8 @@ Every rule the search adds to the prototype's can be switched off, so that its e | `closure_pruning` | `true` | Abandon a state with a straight run or a convex corner the remaining pieces cannot close. | | `lookahead` | `false` | Count a placement towards a corner only if the state it leads to is not a dead end by the pruning rules that are on. Fewer nodes, usually more states examined. | | `order` | `matched-edges` | The order in which a node's placements are tried: `matched-edges` (most whole edges shared with placed pieces first), `generated` (the prototype's order) or `random` (shuffled, from `seed`). It changes which solution comes first and how soon. | +| `equal_edges` | `true` | Only assuming `edge-to-edge`, an error otherwise: let a piece edge lie against another piece's edge only if the two are equally long and, with roofs, equally high at both ends. | +| `wall_edges` | `true` | Only assuming `edge-to-edge`, an error otherwise: keep an edge that no other piece's edge can lie against on the tray. | ### Options of `cp_sat.placements` diff --git a/python/maxplus_solvers/__init__.py b/python/maxplus_solvers/__init__.py index 04b90f4..88a8a07 100644 --- a/python/maxplus_solvers/__init__.py +++ b/python/maxplus_solvers/__init__.py @@ -8,6 +8,7 @@ from maxplus_solvers import _native from maxplus_solvers.api import available_solvers, load_puzzle, solve from maxplus_solvers.models import ( + Assumption, InstanceError, Piece, Pose, @@ -24,6 +25,7 @@ __version__: str = _native.version() __all__ = [ + "Assumption", "InstanceError", "Piece", "Pose", diff --git a/python/maxplus_solvers/_native.pyi b/python/maxplus_solvers/_native.pyi index a13e63a..ab43efa 100644 --- a/python/maxplus_solvers/_native.pyi +++ b/python/maxplus_solvers/_native.pyi @@ -112,7 +112,11 @@ class Assembly: angle_tol: float, slope_tol: float, height_tol: float | None = None, + edge_to_edge: bool = False, + equal_edges: bool = True, + wall_edges: bool = True, ) -> Assembly: ... + def has_partner(self, piece: int, edge: int) -> bool: ... @property def piece_count(self) -> int: ... @property @@ -186,6 +190,10 @@ class ContactDfsOutcome: @property def rejected_roof(self) -> int: ... @property + def rejected_junction(self) -> int: ... + @property + def rejected_wall(self) -> int: ... + @property def pruned_cavity(self) -> int: ... @property def pruned_closure(self) -> int: ... @@ -225,6 +233,9 @@ def contact_dfs( lookahead: bool = False, order: str = "matched-edges", seed: int = 0, + edge_to_edge: bool = False, + equal_edges: bool = True, + wall_edges: bool = True, ) -> ContactDfsOutcome: ... @final diff --git a/python/maxplus_solvers/api.py b/python/maxplus_solvers/api.py index 860c7dc..e5b08a6 100644 --- a/python/maxplus_solvers/api.py +++ b/python/maxplus_solvers/api.py @@ -48,7 +48,7 @@ def solve(instance: PuzzleInstance, config: SolverConfig, *, validate: bool = Fa The solver sees the instance reduced to ``config.mode``: asking for ``footprint`` on a relief puzzle hides the roofs from it. A mode with more information than the instance has, or one the solver does not declare, is - an error. + an error. So is an assumption the solver does not declare. With ``validate``, every returned solution is checked by the independent validator against the instance in that same regime, and comes back with its @@ -61,8 +61,19 @@ def solve(instance: PuzzleInstance, config: SolverConfig, *, validate: bool = Fa raise ValueError( f"solver {spec.name!r} does not work in {config.mode} mode; it has {offered}" ) + undeclared = [a.value for a in config.assumptions if a not in spec.assumptions] + if undeclared: + raise ValueError( + f"solver {spec.name!r} cannot assume {', '.join(undeclared)}; " + f"it can assume {', '.join(sorted(spec.assumptions)) or 'nothing'}" + ) seen = instance.as_regime(config.mode) result = spec.run(seen, config) + if result.assumptions != config.assumptions: + raise RuntimeError( + f"solver {spec.name!r} was asked to assume {list(config.assumptions)} " + f"and reports {list(result.assumptions)}" + ) if not validate: return result diff --git a/python/maxplus_solvers/cli.py b/python/maxplus_solvers/cli.py index 5674508..a2668a5 100644 --- a/python/maxplus_solvers/cli.py +++ b/python/maxplus_solvers/cli.py @@ -6,7 +6,14 @@ from collections.abc import Sequence from maxplus_solvers.api import available_solvers, load_puzzle, solve -from maxplus_solvers.models import InstanceError, Regime, SolverConfig, SolveResult, SolveStatus +from maxplus_solvers.models import ( + Assumption, + InstanceError, + Regime, + SolverConfig, + SolveResult, + SolveStatus, +) # Exit codes. SOLVED = 0 @@ -47,6 +54,14 @@ def _parser() -> argparse.ArgumentParser: choices=[regime.value for regime in Regime], help="the information the solver may use (default: footprint)", ) + parser.add_argument( + "--assume", + action="append", + default=[], + choices=[assumption.value for assumption in Assumption], + help="something to take for granted about the assembly, such as edge-to-edge; " + "it narrows what the search looks for", + ) parser.add_argument("--time-limit", type=float, metavar="SECONDS") parser.add_argument( "--max-solutions", @@ -81,6 +96,10 @@ def _summary(result: SolveResult) -> str: reach = "the search was stopped before its end" proven = "proven" if result.candidates_proven_complete else "not proven" lines.append(f" {reach}; candidates {result.candidate_set}, {proven} complete") + if result.assumptions: + lines.append( + f" assuming {', '.join(result.assumptions)}: other assemblies are not looked for" + ) for index, solution in enumerate(result.solutions): verdict = {None: "not validated", True: "valid", False: "INVALID"}[solution.valid] lines.append(f" solution {index + 1}: {len(solution.poses)} pieces, {verdict}") @@ -116,6 +135,7 @@ def main(argv: Sequence[str] | None = None) -> int: max_solutions=args.max_solutions, seed=args.seed, options=dict(args.option), + assumptions=tuple(args.assume), ) result = solve(puzzle, config, validate=args.validate) except (FileNotFoundError, InstanceError, ValueError) as error: diff --git a/python/maxplus_solvers/experiments/benchmark.py b/python/maxplus_solvers/experiments/benchmark.py index c7ef13a..8e48305 100644 --- a/python/maxplus_solvers/experiments/benchmark.py +++ b/python/maxplus_solvers/experiments/benchmark.py @@ -21,9 +21,22 @@ from typing import Any from maxplus_solvers.api import solve -from maxplus_solvers.experiments.manifest import OWN, Manifest, Run, expand, fixture_ids +from maxplus_solvers.experiments.manifest import ( + NOTHING, + OWN, + Manifest, + Run, + expand, + fixture_ids, +) from maxplus_solvers.io.instance import load_instance -from maxplus_solvers.models import PuzzleInstance, Regime, SolverConfig, TolerancePolicy +from maxplus_solvers.models import ( + Assumption, + PuzzleInstance, + Regime, + SolverConfig, + TolerancePolicy, +) FORMAT_VERSION = 1 # Regimes from least to most information. A puzzle can be solved in its own or a lower one. @@ -83,6 +96,7 @@ def run_one( seed=run.seed, tolerances=tolerances, options=dict(run.options), + assumptions=() if run.assume == NOTHING else (Assumption(run.assume),), ) record: dict[str, Any] = { "formatVersion": FORMAT_VERSION, diff --git a/python/maxplus_solvers/experiments/manifest.py b/python/maxplus_solvers/experiments/manifest.py index 0c400d5..3636b55 100644 --- a/python/maxplus_solvers/experiments/manifest.py +++ b/python/maxplus_solvers/experiments/manifest.py @@ -10,6 +10,7 @@ [[runs]] solver = "rust.contact_dfs" mode = "own" # "own": the fixture's regime; or "footprint", "relief" + assume = ["none", "edge-to-edge"] # optional: what the solver takes for granted max_solutions = "all" # or a number time_limit_s = 60.0 # optional seeds = [0] @@ -20,7 +21,7 @@ order = ["matched-edges", "random"] lookahead = false -Every list among ``mode``, ``seeds``, ``contact_scale`` and the option values +Every list among ``mode``, ``assume``, ``seeds``, ``contact_scale`` and the option values is a factor, and a ``[[runs]]`` block stands for the product of its factors on each fixture. The order of the product is fixed, so a manifest names the same runs in the same order every time. @@ -34,13 +35,15 @@ from typing import Any from maxplus_solvers import solvers -from maxplus_solvers.models import Regime +from maxplus_solvers.models import Assumption, Regime GROUPS = ("corpus", "synthetic", "all") OWN = "own" +NOTHING = "none" _RUN_KEYS = { "solver", "mode", + "assume", "max_solutions", "time_limit_s", "seeds", @@ -61,6 +64,8 @@ class RunBlock: solver: str modes: tuple[str, ...] = (OWN,) + # Each is "none" or an assumption's name. + assumes: tuple[str, ...] = (NOTHING,) max_solutions: int | None = None time_limit_s: float | None = None seeds: tuple[int, ...] = (0,) @@ -88,6 +93,8 @@ class Run: solver: str # A regime, or "own" for the fixture's. mode: str + # "none", or the assumption the solver is to make. + assume: str max_solutions: int | None time_limit_s: float | None seed: int @@ -122,6 +129,10 @@ def _block(data: Any, where: str) -> RunBlock: for mode in modes: if mode != OWN and mode not in {regime.value for regime in Regime}: raise ManifestError(f"{where}.mode: {mode!r} is neither 'own' nor a regime") + assumes = tuple(str(a) for a in _listed(data.get("assume", NOTHING), f"{where}.assume")) + for assume in assumes: + if assume != NOTHING and assume not in {a.value for a in Assumption}: + raise ManifestError(f"{where}.assume: {assume!r} is neither 'none' nor an assumption") limit = data.get("max_solutions", "all") if limit == "all": max_solutions = None @@ -149,6 +160,7 @@ def _block(data: Any, where: str) -> RunBlock: return RunBlock( solver=solver, modes=modes, + assumes=assumes, max_solutions=max_solutions, time_limit_s=time_limit, seeds=tuple(seeds), @@ -228,13 +240,14 @@ def expand(manifest: Manifest, fixtures: Sequence[str]) -> Iterator[Run]: if block.fixtures and fixture not in block.fixtures: continue settings = itertools.product(*(block.options[name] for name in names)) - for mode, scale, seed, values in itertools.product( - block.modes, block.contact_scales, block.seeds, list(settings) + for mode, assume, scale, seed, values in itertools.product( + block.modes, block.assumes, block.contact_scales, block.seeds, list(settings) ): yield Run( fixture=fixture, solver=block.solver, mode=mode, + assume=assume, max_solutions=block.max_solutions, time_limit_s=block.time_limit_s, seed=seed, diff --git a/python/maxplus_solvers/experiments/proxies.py b/python/maxplus_solvers/experiments/proxies.py index 5f37d84..10eef33 100644 --- a/python/maxplus_solvers/experiments/proxies.py +++ b/python/maxplus_solvers/experiments/proxies.py @@ -85,8 +85,17 @@ def tray_turns(target: Sequence[Sequence[float]], tolerance_mm: float) -> int: return turns -def static(instance: PuzzleInstance, tolerances: TolerancePolicy | None = None) -> StaticProxies: - """The static proxies of an instance, with the tolerances the solvers fit to.""" +def static( + instance: PuzzleInstance, + tolerances: TolerancePolicy | None = None, + *, + edge_to_edge: bool = False, +) -> StaticProxies: + """The static proxies of an instance, with the tolerances the solvers fit to. + + With ``edge_to_edge`` the edge graph is the one the search uses under that + assumption, where a piece edge lies only against an equally long one. + """ policy = tolerances or TolerancePolicy.from_instance(instance) fit = policy.contact_noise_mm roofs = None @@ -103,6 +112,7 @@ def static(instance: PuzzleInstance, tolerances: TolerancePolicy | None = None) length_tol=fit, angle_tol=fit / instance.span_mm, slope_tol=fit / instance.span_mm, + edge_to_edge=edge_to_edge, ) degrees: list[int] = [] tray_degrees: list[int] = [] diff --git a/python/maxplus_solvers/experiments/report.py b/python/maxplus_solvers/experiments/report.py index 55d9ac3..8a2d002 100644 --- a/python/maxplus_solvers/experiments/report.py +++ b/python/maxplus_solvers/experiments/report.py @@ -29,10 +29,14 @@ def _ratio(top: Any, bottom: Any) -> str: def varied(records: Sequence[Mapping[str, Any]]) -> list[str]: """Names of the settings that differ between records: the factors of the experiment. - Option names, then ``seed`` and ``contactScale`` if they vary. + ``assumes`` first if any record makes an assumption, then option names, + then ``seed`` and ``contactScale`` if they vary. The assumption is shown + whenever one is made, varied or not: rows under different assumptions do not + say the same thing. """ every = sorted({name for record in records for name in record["config"]["options"]}) - names = [ + names = ["assumes"] if any(record["config"].get("assumptions") for record in records) else [] + names += [ name for name in every if len({repr(record["config"]["options"].get(name)) for record in records}) > 1 @@ -45,6 +49,8 @@ def varied(records: Sequence[Mapping[str, Any]]) -> list[str]: def _setting(record: Mapping[str, Any], name: str) -> str: + if name == "assumes": + return ", ".join(record["config"].get("assumptions") or ["nothing"]) if name == "seed": return str(record["config"]["seed"]) if name == "contactScale": diff --git a/python/maxplus_solvers/metrics.py b/python/maxplus_solvers/metrics.py index ccdabe3..afa8ab3 100644 --- a/python/maxplus_solvers/metrics.py +++ b/python/maxplus_solvers/metrics.py @@ -28,6 +28,10 @@ class SearchMetrics: rejected_outside: int = 0 rejected_overlap: int = 0 rejected_roof: int = 0 + # Under the edge-to-edge assumption: placements refused for making a T with a placed + # piece, and for taking an edge that can only lie on the tray off it. Absent otherwise. + rejected_junction: int | None = None + rejected_wall: int | None = None # Nodes given up by a pruning rule, and candidates dropped before they became nodes. pruned_cavity: int = 0 pruned_closure: int = 0 diff --git a/python/maxplus_solvers/models.py b/python/maxplus_solvers/models.py index 3e80772..c260f8e 100644 --- a/python/maxplus_solvers/models.py +++ b/python/maxplus_solvers/models.py @@ -40,6 +40,33 @@ class Regime(StrEnum): TROPICAL_AWARE = "tropical-aware" +class Assumption(StrEnum): + """Something a solver is told to take for granted about the assembly it looks for. + + An assumption is not a pruning rule. A rule leaves what a whole search finds + unchanged; an assumption narrows it to the assemblies that satisfy it, and a + result says which were made. It is separate from the regime: it can be made + with or without roofs. Results under different assumptions are not comparable. + + * ``edge-to-edge``: no vertex of a piece lies strictly inside an edge of + another piece. Inside the tray two pieces then share a whole edge of both, + or a vertex, and never meet in a T. Every puzzle cut from a tropical curve + is like this; a puzzle cut some other way need not be. + """ + + EDGE_TO_EDGE = "edge-to-edge" + + +def _assumptions(given: Any) -> tuple[Assumption, ...]: + """Assumptions in a fixed order, each once. + + A single string is refused: it would be read letter by letter. + """ + if isinstance(given, str): + raise ValueError("assumptions is a sequence of names, not one string") + return tuple(sorted({Assumption(a) for a in given})) + + class SolveStatus(StrEnum): """Outcome of a solve. ``docs/solver-contract.md`` says what each value claims. @@ -533,9 +560,11 @@ class SolverConfig: seed: int = 0 tolerances: TolerancePolicy | None = None options: Mapping[str, Any] = field(default_factory=dict) + assumptions: tuple[Assumption, ...] = () def __post_init__(self) -> None: object.__setattr__(self, "mode", Regime(self.mode)) + object.__setattr__(self, "assumptions", _assumptions(self.assumptions)) if self.time_limit_s is not None and not self.time_limit_s > 0: raise ValueError("time_limit_s must be positive") if self.max_solutions is not None and self.max_solutions < 1: @@ -550,12 +579,22 @@ def to_dict(self) -> dict[str, Any]: "seed": self.seed, "tolerances": None if self.tolerances is None else self.tolerances.to_dict(), "options": dict(self.options), + "assumptions": [a.value for a in self.assumptions], } @classmethod def from_dict(cls, data: Any) -> Self: - keys = ("solver", "mode", "timeLimitS", "maxSolutions", "seed", "tolerances", "options") - d = _mapping(data, "config", keys) + keys = ( + "solver", + "mode", + "timeLimitS", + "maxSolutions", + "seed", + "tolerances", + "options", + ) + # Absent in records written before assumptions existed: then none was made. + d = _mapping(data, "config", keys, ("assumptions",)) tolerances = d["tolerances"] return cls( solver=_string(d["solver"], "config.solver"), @@ -565,6 +604,7 @@ def from_dict(cls, data: Any) -> Self: seed=d["seed"], tolerances=None if tolerances is None else TolerancePolicy.from_dict(tolerances), options=dict(d["options"]), + assumptions=_assumptions(d.get("assumptions", ())), ) @@ -604,6 +644,10 @@ class SolveResult: or "exactly these solutions" a claim about the puzzle; otherwise the result is relative to the candidate set, which ``candidate_set`` names. + ``assumptions`` are what the solver took for granted about the assemblies + it looked for. Everything the result says is about assemblies that satisfy + them, and the candidate set's name says so too. + ``config`` and ``solver_version`` record what produced the result, so that it can be reproduced. """ @@ -619,10 +663,12 @@ class SolveResult: candidate_set: str = "" config: SolverConfig | None = None solver_version: str = "" + assumptions: tuple[Assumption, ...] = () def __post_init__(self) -> None: object.__setattr__(self, "status", SolveStatus(self.status)) object.__setattr__(self, "regime", Regime(self.regime)) + object.__setattr__(self, "assumptions", _assumptions(self.assumptions)) object.__setattr__(self, "solutions", tuple(self.solutions)) if (self.status is SolveStatus.SOLVED) != bool(self.solutions): raise ValueError("status is 'solved' exactly when there is at least one solution") @@ -644,6 +690,7 @@ def to_dict(self) -> dict[str, Any]: "candidateSet": self.candidate_set, "config": None if self.config is None else self.config.to_dict(), "solverVersion": self.solver_version, + "assumptions": [a.value for a in self.assumptions], } @classmethod @@ -661,7 +708,7 @@ def from_dict(cls, data: Any) -> Self: "config", "solverVersion", ) - d = _mapping(data, "result", keys) + d = _mapping(data, "result", keys, ("assumptions",)) return cls( status=SolveStatus(d["status"]), solver=d["solver"], @@ -674,4 +721,5 @@ def from_dict(cls, data: Any) -> Self: candidate_set=d["candidateSet"], config=None if d["config"] is None else SolverConfig.from_dict(d["config"]), solver_version=d["solverVersion"], + assumptions=_assumptions(d.get("assumptions", ())), ) diff --git a/python/maxplus_solvers/solvers/__init__.py b/python/maxplus_solvers/solvers/__init__.py index 948ff97..c219b5b 100644 --- a/python/maxplus_solvers/solvers/__init__.py +++ b/python/maxplus_solvers/solvers/__init__.py @@ -9,7 +9,7 @@ from collections.abc import Callable, Mapping from dataclasses import dataclass -from maxplus_solvers.models import PuzzleInstance, Regime, SolverConfig, SolveResult +from maxplus_solvers.models import Assumption, PuzzleInstance, Regime, SolverConfig, SolveResult SolverFunction = Callable[[PuzzleInstance, SolverConfig], SolveResult] @@ -25,6 +25,9 @@ class SolverSpec: # not comparable. candidate_sets: Mapping[Regime, str] description: str + # The assumptions it can be asked to make. Making one changes what it looks + # for, so a solver that has not declared it is not handed it. + assumptions: frozenset[Assumption] = frozenset() @property def regimes(self) -> frozenset[Regime]: diff --git a/python/maxplus_solvers/solvers/contact_dfs.py b/python/maxplus_solvers/solvers/contact_dfs.py index 25cb0dd..9fd4e33 100644 --- a/python/maxplus_solvers/solvers/contact_dfs.py +++ b/python/maxplus_solvers/solvers/contact_dfs.py @@ -13,6 +13,12 @@ its effect can be measured. None of them changes what a whole search finds; ``tray_rotations`` changes how the same assemblies are counted. +The solver can also be told to assume that the pieces meet edge to edge +(``SolverConfig.assumptions``). That is not one of the additions: it changes +what the search looks for, to the assemblies with no T between pieces, and the +result names another candidate set. Two rules follow from it, ``equal_edges`` +and ``wall_edges``, and those are switches like the others. + This module converts the instance, makes one call into ``_native`` and converts the answer back. The search does not return to Python until it is finished. """ @@ -25,6 +31,7 @@ from maxplus_solvers import _native from maxplus_solvers.metrics import SearchMetrics from maxplus_solvers.models import ( + Assumption, Pose, PuzzleInstance, Regime, @@ -44,6 +51,16 @@ Regime.RELIEF: "corner-contact-relief/1", } +# Under the assumption that pieces meet edge to edge: the placements above that +# make no T with a placed piece. +EDGE_TO_EDGE_SETS = { + Regime.FOOTPRINT: "corner-contact-edge-to-edge/1", + Regime.RELIEF: "corner-contact-relief-edge-to-edge/1", +} + +# Rules that follow from the edge-to-edge assumption. They are options only with it. +EDGE_TO_EDGE_RULES = ("equal_edges", "wall_edges") + ORDERS = ("matched-edges", "generated", "random") TRAY_ROTATIONS = ("once", "all") @@ -58,18 +75,26 @@ "closure_pruning": True, "lookahead": False, "order": "matched-edges", + "equal_edges": True, + "wall_edges": True, } -def _options(given: Mapping[str, Any]) -> dict[str, Any]: +def _options(given: Mapping[str, Any], edge_to_edge: bool) -> dict[str, Any]: unknown = sorted(set(given) - set(DEFAULTS)) if unknown: raise ValueError(f"{NAME}: unknown options {', '.join(unknown)}") + stray = sorted(set(given) & set(EDGE_TO_EDGE_RULES)) + if stray and not edge_to_edge: + raise ValueError( + f"{NAME}: {', '.join(stray)} only mean something under the " + f"{Assumption.EDGE_TO_EDGE.value} assumption" + ) options = {**DEFAULTS, **given} limit = options["node_limit"] if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or limit < 1): raise ValueError(f"{NAME}: node_limit must be a positive integer") - for switch in ("anchor", "cavity_pruning", "closure_pruning", "lookahead"): + for switch in ("anchor", "cavity_pruning", "closure_pruning", "lookahead", *EDGE_TO_EDGE_RULES): if not isinstance(options[switch], bool): raise ValueError(f"{NAME}: {switch} must be true or false") if options["order"] not in ORDERS: @@ -87,7 +112,8 @@ def _options(given: Mapping[str, Any]) -> dict[str, Any]: def solve(instance: PuzzleInstance, config: SolverConfig) -> SolveResult: if instance.regime not in CANDIDATE_SETS: raise ValueError(f"{NAME} does not work in the {instance.regime} regime") - options = _options(config.options) + edge_to_edge = Assumption.EDGE_TO_EDGE in config.assumptions + options = _options(config.options, edge_to_edge) if config.seed < 0: raise ValueError(f"{NAME}: the seed must not be negative") @@ -129,6 +155,9 @@ def solve(instance: PuzzleInstance, config: SolverConfig) -> SolveResult: lookahead=options["lookahead"], order=options["order"], seed=config.seed, + edge_to_edge=edge_to_edge, + equal_edges=options["equal_edges"], + wall_edges=options["wall_edges"], ) cpu_time_s = time.process_time() - cpu_started @@ -147,6 +176,8 @@ def solve(instance: PuzzleInstance, config: SolverConfig) -> SolveResult: rejected_outside=outcome.rejected_outside, rejected_overlap=outcome.rejected_overlap, rejected_roof=outcome.rejected_roof, + rejected_junction=outcome.rejected_junction if edge_to_edge else None, + rejected_wall=outcome.rejected_wall if edge_to_edge else None, pruned_cavity=outcome.pruned_cavity, pruned_closure=outcome.pruned_closure, pruned_anchor=outcome.pruned_anchor, @@ -175,9 +206,10 @@ def solve(instance: PuzzleInstance, config: SolverConfig) -> SolveResult: # assemblies in exact arithmetic; this is f64 with tolerances. candidates_proven_complete=False, metrics=metrics.to_dict(), - candidate_set=CANDIDATE_SETS[instance.regime], + candidate_set=(EDGE_TO_EDGE_SETS if edge_to_edge else CANDIDATE_SETS)[instance.regime], config=config, solver_version=_native.version(), + assumptions=config.assumptions, ) @@ -186,4 +218,5 @@ def solve(instance: PuzzleInstance, config: SolverConfig) -> SolveResult: run=solve, candidate_sets=CANDIDATE_SETS, description="Rust: depth-first search over corner contacts, with roofs and pruning", + assumptions=frozenset({Assumption.EDGE_TO_EDGE}), ) diff --git a/tests/architecture/test_layering.py b/tests/architecture/test_layering.py index ff4c6ea..c30d003 100644 --- a/tests/architecture/test_layering.py +++ b/tests/architecture/test_layering.py @@ -8,7 +8,7 @@ import pytest -from maxplus_solvers import _native +from maxplus_solvers import _native, solvers from support import corpus ROOT = corpus.ROOT @@ -195,7 +195,14 @@ def test_every_search_rule_is_a_documented_switch() -> None: contract = (ROOT / "docs" / "solver-contract.md").read_text(encoding="utf-8") algorithms = (ROOT / "docs" / "algorithms.md").read_text(encoding="utf-8") expected = { - contact_dfs: {"anchor", "cavity_pruning", "closure_pruning", "lookahead"}, + contact_dfs: { + "anchor", + "cavity_pruning", + "closure_pruning", + "lookahead", + "equal_edges", + "wall_edges", + }, cp_sat: {"anchor", "cavity_pruning", "closure_pruning", "coverage"}, } for solver, rules in expected.items(): @@ -212,6 +219,31 @@ def test_every_search_rule_is_a_documented_switch() -> None: assert f"`{switch}`" in algorithms, f"{switch} has no place in algorithms.md" +def test_an_assumption_is_declared_documented_and_named_in_the_candidate_set() -> None: + """An assumption narrows what a search finds, so it is never an option. + + Every solver declares what it can assume; each assumption has a row in the + contract; a solver that can make one has a candidate set for it in every + regime it works in, distinct from the set it uses assuming nothing. + """ + from maxplus_solvers.models import Assumption + from maxplus_solvers.solvers import contact_dfs + + contract = (ROOT / "docs" / "solver-contract.md").read_text(encoding="utf-8") + _, _, section = contract.partition("## Assumptions") + for assumption in Assumption: + assert f"| `{assumption.value}` |" in section, assumption + assert assumption.value not in contact_dfs.DEFAULTS, "an assumption is not an option" + for name in solvers.available(): + spec = solvers.get(name) + assert spec.assumptions <= set(Assumption), name + assert contact_dfs.SPEC.assumptions == {Assumption.EDGE_TO_EDGE} + assert set(contact_dfs.EDGE_TO_EDGE_SETS) == set(contact_dfs.CANDIDATE_SETS) + for regime, name in contact_dfs.EDGE_TO_EDGE_SETS.items(): + assert name != contact_dfs.CANDIDATE_SETS[regime] + assert f"| `{name}` |" in contract, name + + def test_cp_sat_is_given_one_worker_and_no_objective() -> None: """A run that can be repeated, and counts that mean something. diff --git a/tests/corpus/test_benchmark.py b/tests/corpus/test_benchmark.py index 319360b..50e04ad 100644 --- a/tests/corpus/test_benchmark.py +++ b/tests/corpus/test_benchmark.py @@ -30,6 +30,8 @@ FLAT = corpus.fixture_ids(kind="corpus", regime="footprint") RELIEF = corpus.fixture_ids(kind="corpus", regime="relief") HASHES = {entry["id"]: entry["instanceHash"] for entry in corpus.index()["fixtures"]} +# Where the corpus manifest stops a search that would not end. +NODE_LIMIT = 1_500_000 def by(records: list[dict[str, Any]], solver: str) -> dict[str, dict[str, Any]]: @@ -56,7 +58,8 @@ def test_one_command_reproduces_the_corpus_table( assert {record["solver"] for record in records} == set(solvers.available()) assert sorted(by(records, "rust.contact_dfs")) == sorted(CORPUS) assert sorted(by(records, "cp_sat.placements")) == sorted(CORPUS) - assert sorted(by(records, "python.contact_dfs")) == sorted(FLAT) + # The prototype's list was fixed before cor1 joined the corpus; it would stop there too. + assert sorted(by(records, "python.contact_dfs")) == sorted(set(FLAT) - corpus.UNFINISHED) for record in records: # Whatever was returned passes the validator. assert record["status"] in ("solved", "interrupted"), record["fixture"] @@ -66,9 +69,18 @@ def test_one_command_reproduces_the_corpus_table( assert record["config"]["tolerances"]["contactNoiseMm"] > 0 assert record["config"]["seed"] == 0 assert record["instanceHash"] == HASHES[record["fixture"]] - # The two production solvers finish everything; the prototype is stopped on the largest. + # The two production solvers finish everything but cor1-flat, stopped at the node + # limit before it found anything; the prototype is stopped on the largest. for solver in ("rust.contact_dfs", "cp_sat.placements"): - assert all(record["exhaustive"] for record in by(records, solver).values()) + results = by(records, solver) + unfinished = sorted(f for f, record in results.items() if not record["exhaustive"]) + assert unfinished == sorted(corpus.UNFINISHED), solver + for fixture in unfinished: + assert results[fixture]["status"] == "interrupted" + assert results[fixture]["metrics"]["nodes"] == NODE_LIMIT + # The limit is far above what any finished search needed. + finished = [r["metrics"]["nodes"] for f, r in results.items() if f not in unfinished] + assert max(finished) < NODE_LIMIT / 1.4 prototype = by(records, "python.contact_dfs") stopped = [fixture for fixture, record in prototype.items() if not record["exhaustive"]] assert sorted(stopped) == ["new1-flat", "new2-flat", "rat2-flat"] @@ -80,8 +92,8 @@ def test_the_committed_table_is_the_reproducible_kind() -> None: header = [cell.strip() for cell in lines[0].strip("|").split("|")] assert header[:4] == ["Fixture", "Pieces", "Solver", "Mode"] assert not [title for title in header if title.endswith(", s") or "SAT" in title] - # 16 + 16 + 8 runs, a header and a rule. - assert len(lines) == 40 + 2 + # 18 + 18 + 8 runs, a header and a rule. + assert len(lines) == 44 + 2 # --- the committed manifests -------------------------------------------------------------- @@ -108,6 +120,7 @@ def test_every_committed_manifest_can_be_run(path: Path) -> None: def test_the_manifests_the_documents_name_exist() -> None: assert {path.stem for path in MANIFESTS.glob("*.toml")} == { "corpus", + "edge_to_edge", "factorial", "smoke", "tolerance", diff --git a/tests/corpus/test_cp_sat.py b/tests/corpus/test_cp_sat.py index 9f4be04..f072bb5 100644 --- a/tests/corpus/test_cp_sat.py +++ b/tests/corpus/test_cp_sat.py @@ -3,7 +3,9 @@ On every fixture, in its own regime, ``cp_sat.placements`` and ``rust.contact_dfs`` are both run to the end, and the two sets of assemblies are compared polygon by polygon with the test oracle. Both exhaust on every -fixture, so the comparison leaves none out. +fixture but ``cor1-flat``, added after the phase closed, whose search has not +been seen to end; CP-SAT lists its placements with that search, so it is left +out by name. The agreement is less than it sounds and more than nothing. CP-SAT chooses among the placements a run of the same search listed, so it cannot find an @@ -27,8 +29,9 @@ DFS = "rust.contact_dfs" PIECES = {entry["id"]: entry["pieceCount"] for entry in corpus.index()["fixtures"]} -CORPUS = corpus.fixture_ids(kind="corpus") -FLAT = corpus.fixture_ids(kind="corpus", regime="footprint") +EVERY = corpus.fixture_ids(kind="corpus") +CORPUS = [f for f in EVERY if f not in corpus.UNFINISHED] +FLAT = [f for f in corpus.fixture_ids(kind="corpus", regime="footprint") if f in CORPUS] RELIEF = corpus.fixture_ids(kind="corpus", regime="relief") SYNTHETIC = corpus.fixture_ids(kind="synthetic") SMALL = [f for f in FLAT if PIECES[f] <= 11] @@ -81,7 +84,8 @@ def alike(x: Any, y: Any) -> bool: def test_the_exit_criterion_covers_every_fixture() -> None: - assert len(CORPUS) == 16 and len(SYNTHETIC) == 4 + assert len(EVERY) == 18 and len(CORPUS) == 17 and len(SYNTHETIC) == 4 + assert sorted(set(EVERY) - set(CORPUS)) == ["cor1-flat"] assert set(FLAT) >= SLOW | set(ASSEMBLIES) diff --git a/tests/corpus/test_edge_to_edge.py b/tests/corpus/test_edge_to_edge.py new file mode 100644 index 0000000..ece34db --- /dev/null +++ b/tests/corpus/test_edge_to_edge.py @@ -0,0 +1,201 @@ +"""Phase 8 exit criterion: assuming edge to edge finds exactly the edge-to-edge assemblies. + +Every tropical puzzle is cut from a polyhedral complex, so its pieces meet edge +to edge: no vertex of a piece lies inside another piece's edge. Told to assume +this, ``rust.contact_dfs`` refuses placements that make a T, and uses two rules +that follow: a piece edge lies only against an equally long edge of another +piece, and an edge with no such partner stays on the tray. + +For every corpus fixture the search is run to its end without the assumption +and with it, the two rules on and off. What the assumed searches find is +exactly what the plain search finds that the independent oracle +(``support.geometry.is_edge_to_edge``, by twin edges) calls edge to edge; the +answer key is among it and the validator passes all of it. ``cor1-flat``, whose +plain search has not been seen to end, is tested apart: everything the assumed +search returns is valid and edge to edge by the oracle, and the key is among it. The counts are +relative to the candidates the search generates, in ``f64`` with tolerances. +""" + +from pathlib import Path +from typing import Any + +import pytest + +from maxplus_solvers import ( + Assumption, + PuzzleInstance, + Regime, + SolverConfig, + SolveResult, + SolveStatus, + solve, +) +from maxplus_solvers.experiments import benchmark, proxies +from maxplus_solvers.experiments.cli import main +from support import assemblies, corpus, geometry + +DFS = "rust.contact_dfs" +E2E = (Assumption.EDGE_TO_EDGE,) +# Twin edges are found to this, in mm: far above rounding, far below any feature. +TWIN_MM = 1e-6 + +ROOT = Path(__file__).resolve().parents[2] +MANIFESTS = ROOT / "benchmarks" / "manifests" +RESULTS = ROOT / "benchmarks" / "results" +EVERY = corpus.fixture_ids(kind="corpus") +CORPUS = [f for f in EVERY if f not in corpus.UNFINISHED] +# Assemblies found assuming nothing, up to turning the tray, where not one (phase 5). +ASSEMBLIES = {"rat1-flat": 101, "rat2-flat": 2} +# Assemblies found assuming edge to edge, where not one. +EDGE_TO_EDGE_ASSEMBLIES = {"cor1-flat": 48} +# Where a search assuming nothing stops in the committed table (benchmarks/manifests). +NODE_LIMIT = 1_500_000 +# Whole plain searches of these take tens of seconds. +SLOW = {"new1-flat", "new2-flat"} +RULES = [ + {"equal_edges": True, "wall_edges": True}, + {"equal_edges": True, "wall_edges": False}, + {"equal_edges": False, "wall_edges": True}, + {"equal_edges": False, "wall_edges": False}, +] + + +def marked(fixture_ids: list[str]) -> list[Any]: + return [ + pytest.param(f, marks=pytest.mark.slow) if f in SLOW else pytest.param(f) + for f in fixture_ids + ] + + +def instance_of(fixture_id: str) -> PuzzleInstance: + return PuzzleInstance.from_dict(corpus.fixture(fixture_id)) + + +def placed(instance: PuzzleInstance, result: SolveResult) -> list[Any]: + return [ + [piece.world_polygon(solution.poses[piece.id]) for piece in instance.pieces] + for solution in result.solutions + ] + + +def same_set(a: list[Any], b: list[Any]) -> bool: + return len(a) == len(b) and all(sum(assemblies.same(x, y) for y in b) == 1 for x in a) + + +def test_every_answer_key_meets_edge_to_edge() -> None: + """The premise, on what the generator made: no corpus puzzle has a T.""" + for fixture_id in EVERY: + instance = corpus.fixture(fixture_id) + target = instance["target"]["vertices"] + world = assemblies.world(instance, corpus.key(fixture_id)["poses"]) + assert geometry.is_edge_to_edge(world, target, TWIN_MM), fixture_id + + +@pytest.mark.parametrize("fixture_id", marked(CORPUS)) +def test_the_assumption_finds_exactly_the_edge_to_edge_assemblies(fixture_id: str) -> None: + instance = instance_of(fixture_id) + plain = solve(instance, SolverConfig(DFS, mode=instance.regime, max_solutions=None)) + assert plain.exhaustive + edge_to_edge = [ + assembly + for assembly in placed(instance, plain) + if geometry.is_edge_to_edge(assembly, instance.target, TWIN_MM) + ] + key = assemblies.world(corpus.fixture(fixture_id), corpus.key(fixture_id)["poses"]) + turns = [ + assemblies.turned(key, turn, geometry.centroid(instance.target)) + for turn in assemblies.tray_turns(instance.target) + ] + + for rules in RULES: + config = SolverConfig( + DFS, mode=instance.regime, max_solutions=None, assumptions=E2E, options=rules + ) + result = solve(instance, config, validate=True) + assert result.status is SolveStatus.SOLVED, rules + assert result.exhaustive, rules + assert result.assumptions == E2E + assert result.candidate_set.endswith("-edge-to-edge/1") + found = placed(instance, result) + assert same_set(found, edge_to_edge), (rules, len(found), len(edge_to_edge)) + assert all(solution.valid is True for solution in result.solutions), rules + assert sum(any(assemblies.same(k, a) for k in turns) for a in found) == 1, rules + # The assumption only takes work away. + assert result.metrics["nodes"] <= plain.metrics["nodes"], rules + + +def test_where_the_plain_search_does_not_end_the_assumed_one_does() -> None: + """``cor1-flat``: 48 edge-to-edge assemblies, the answer key among them. + + Its plain search was stopped at 3 000 000 nodes, so there is nothing to + compare against; what is checked is what can be checked one assembly at a + time. The count is relative to the candidates, like every count here: the + corrugated columns change places without making a T. + """ + instance = instance_of("cor1-flat") + target = instance.target + for rules in RULES: + config = SolverConfig(DFS, max_solutions=None, assumptions=E2E, options=rules) + result = solve(instance, config, validate=True) + assert result.status is SolveStatus.SOLVED and result.exhaustive, rules + found = placed(instance, result) + assert len(found) == EDGE_TO_EDGE_ASSEMBLIES["cor1-flat"], rules + assert all(solution.valid is True for solution in result.solutions), rules + assert all(geometry.is_edge_to_edge(a, target, TWIN_MM) for a in found), rules + assert all(len(orbit) == 1 for orbit in assemblies.orbits(target, found)), rules + key = assemblies.world(corpus.fixture("cor1-flat"), corpus.key("cor1-flat")["poses"]) + centre = geometry.centroid(target) + turns = [assemblies.turned(key, t, centre) for t in assemblies.tray_turns(target)] + assert sum(any(assemblies.same(k, a) for k in turns) for a in found) == 1, rules + + +@pytest.mark.parametrize("fixture_id", ["rat1-flat", "rat2-flat"]) +def test_the_footprints_with_several_assemblies_have_one_that_meets_edge_to_edge( + fixture_id: str, +) -> None: + """rat1-flat has 101 assemblies and rat2-flat 2 (phase 5); only the answer has no T.""" + instance = instance_of(fixture_id) + config = SolverConfig(DFS, max_solutions=None, assumptions=E2E) + assert len(solve(instance, config).solutions) == 1 + + +# --- the committed table and the edge graph ----------------------------------------------- + + +@pytest.mark.slow +def test_one_command_reproduces_the_edge_to_edge_table( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + out, table = tmp_path / "edge_to_edge.jsonl", tmp_path / "edge_to_edge.md" + arguments = ["run", str(MANIFESTS / "edge_to_edge.toml"), "--fixtures", str(corpus.FIXTURES)] + code = main([*arguments, "--out", str(out), "--table", str(table), "--no-times", "--quiet"]) + assert code == 0, "some run could not be made" + produced = table.read_text(encoding="utf-8") + assert capsys.readouterr().out == produced + assert produced == (RESULTS / "edge_to_edge.md").read_text(encoding="utf-8") + records = benchmark.read(out) + # Each corpus puzzle once assuming nothing, and four times assuming edge to edge. + assert len(records) == 5 * len(EVERY) + for record in records: + fixture, assumed = record["fixture"], bool(record["config"]["assumptions"]) + if fixture in corpus.UNFINISHED and not assumed: + assert record["status"] == "interrupted" and not record["exhaustive"], fixture + assert record["metrics"]["nodes"] == NODE_LIMIT + continue + assert record["status"] == "solved" and record["exhaustive"], fixture + expected = (EDGE_TO_EDGE_ASSEMBLIES if assumed else ASSEMBLIES).get(fixture, 1) + assert record["validSolutions"] == record["solutions"] == expected, fixture + + +@pytest.mark.parametrize("fixture_id", EVERY) +def test_the_assumption_thins_the_edge_graph(fixture_id: str) -> None: + """Without roofs an edge could lie against dozens of others; assuming edge to + edge, against a few at most. That no contact of the answer key is lost is + shown above, by the search finding the key with ``equal_edges`` on.""" + instance = instance_of(fixture_id) + plain = proxies.static(instance) + assumed = proxies.static(instance, edge_to_edge=True) + assert assumed.edges == plain.edges + assert assumed.mean_degree < plain.mean_degree + if instance.regime is Regime.FOOTPRINT: + assert assumed.mean_degree < plain.mean_degree / 10 diff --git a/tests/corpus/test_fixtures.py b/tests/corpus/test_fixtures.py index a01e701..6225523 100644 --- a/tests/corpus/test_fixtures.py +++ b/tests/corpus/test_fixtures.py @@ -53,16 +53,19 @@ def placed(fixture: dict[str, Any], key: dict[str, Any]) -> dict[str, list[tuple def test_the_corpus_is_complete() -> None: - """Eight constructions in two variants, and the four synthetics.""" - constructions = ["new1", "new2", "new3", "new4", "new5", "rat1", "rat2", "rev2"] + """Nine constructions in two variants, and the four synthetics.""" + constructions = ["cor1", "new1", "new2", "new3", "new4", "new5", "rat1", "rat2", "rev2"] assert sorted(CORPUS) == sorted(constructions + [f"{c}-flat" for c in constructions]) assert sorted(SYNTHETIC) == [ "syn-four-squares", "syn-four-triangles", "syn-two-rectangles", "syn-two-rectangles-ridge", ] # fmt: skip counts = {entry["id"]: entry["pieceCount"] for entry in corpus.index()["fixtures"]} assert {c: counts[c] for c in constructions} == { - "new1": 16, "new2": 16, "new3": 9, "new4": 9, "new5": 6, "rat1": 11, "rat2": 20, "rev2": 9, + "cor1": 27, "new1": 16, "new2": 16, "new3": 9, "new4": 9, "new5": 6, "rat1": 11, "rat2": 20, + "rev2": 9, } # fmt: skip + # Every flat twin has its relief puzzle's pieces. + assert all(counts[f"{c}-flat"] == counts[c] for c in constructions) def test_files_and_manifest_agree() -> None: diff --git a/tests/corpus/test_rust_contact_dfs.py b/tests/corpus/test_rust_contact_dfs.py index 6f4efe6..6939bde 100644 --- a/tests/corpus/test_rust_contact_dfs.py +++ b/tests/corpus/test_rust_contact_dfs.py @@ -1,6 +1,9 @@ -"""Phase 5 exit criterion: ``rust.contact_dfs`` solves and validates all 16 corpus fixtures. +"""Phase 5 exit criterion: ``rust.contact_dfs`` solves and validates the corpus fixtures. -Each fixture is searched to the end in its own regime. Every assembly returned +Each fixture is searched to the end in its own regime. That was all 16 when the +phase closed; ``cor1``, added since, is searched to the end with its roofs and +not without them, and ``cor1-flat`` is tested for what an unfinished search can +say. Every assembly returned passes the independent validator, the answer key is among them, and the times to the first solution and to the end of the search are reported separately. On the fixtures the Python prototype can finish, the two solvers find the same @@ -34,14 +37,17 @@ } PIECES = {entry["id"]: entry["pieceCount"] for entry in corpus.index()["fixtures"]} -CORPUS = corpus.fixture_ids(kind="corpus") -FLAT = corpus.fixture_ids(kind="corpus", regime="footprint") +EVERY = corpus.fixture_ids(kind="corpus") +CORPUS = [f for f in EVERY if f not in corpus.UNFINISHED] +FLAT = [f for f in corpus.fixture_ids(kind="corpus", regime="footprint") if f in CORPUS] RELIEF = corpus.fixture_ids(kind="corpus", regime="relief") SYNTHETIC = corpus.fixture_ids(kind="synthetic") # What the prototype finishes in seconds: the footprints of up to 11 pieces. SMALL = [f for f in FLAT if PIECES[f] <= 11] # Whole searches of these take tens of seconds. SLOW = {"new1-flat", "new2-flat"} +# Relief puzzles built to be hard for this search (cor1: level creases at shared heights). +HARD_RELIEF = {"cor1"} # Assemblies found by the whole search, up to turning the tray. Not in this table: one. # rat1-flat's 101 is the prototype's 404 in four orientations each (phase 4). @@ -90,8 +96,11 @@ def same_set(a: list[Any], b: list[Any]) -> bool: def test_the_exit_criterion_covers_the_whole_corpus() -> None: - assert len(CORPUS) == 16 and len(FLAT) == 8 and len(RELIEF) == 8 + assert len(EVERY) == 18 and len(FLAT) == 8 and len(RELIEF) == 9 assert sorted(CORPUS) == sorted(FLAT + RELIEF) + # Only footprints are left out, and only those named. + assert sorted(set(EVERY) - set(CORPUS)) == sorted(corpus.UNFINISHED) == ["cor1-flat"] + assert set(RELIEF) >= HARD_RELIEF assert sorted(SMALL) == ["new3-flat", "new4-flat", "new5-flat", "rat1-flat", "rev2-flat"] assert set(FLAT) >= SLOW | set(ASSEMBLIES) @@ -149,6 +158,23 @@ def test_the_first_solution_is_reported_before_the_search_is_finished(fixture_id assert "exhausted_s" not in result.metrics +def test_a_search_that_is_stopped_claims_nothing_about_the_rest() -> None: + """``cor1-flat``: 27 footprints, stopped at a node limit before any assembly. + + What it found by then is pinned (a regression value: no oracle knows where + the search is after 200 000 nodes). The finding is that it found nothing: + without roofs and without the edge-to-edge assumption, the corrugated + columns leave the search wandering for a long way. + """ + instance = instance_of("cor1-flat") + result = solve(instance, whole(instance.regime, node_limit=200_000), validate=True) + assert result.status is SolveStatus.INTERRUPTED + assert not result.exhaustive + assert "exhausted_s" not in result.metrics + assert result.metrics["nodes"] == 200_000 + assert result.solutions == () + + # --- against the prototype ---------------------------------------------------------------- @@ -242,7 +268,7 @@ def run(seed: int) -> SolveResult: # --- what the roofs do -------------------------------------------------------------------- -@pytest.mark.parametrize("fixture_id", RELIEF) +@pytest.mark.parametrize("fixture_id", [f for f in RELIEF if f not in HARD_RELIEF]) def test_the_roofs_leave_one_assembly_and_a_short_search(fixture_id: str) -> None: """A finding: in relief every corpus puzzle has one assembly, found almost directly. @@ -259,6 +285,20 @@ def test_the_roofs_leave_one_assembly_and_a_short_search(fixture_id: str) -> Non assert result.metrics["rejected_roof"] > 0 +def test_level_creases_make_a_relief_puzzle_hard() -> None: + """``cor1``, made to be hard with its roofs on: one assembly, at ten times the cost. + + Its ridges and valleys each stand at one height across a row, so the walls + along them look alike. Every other relief puzzle in the corpus takes at + most 200 nodes with every rule off; this one, of 27 pieces, more than 1 000. + """ + instance = instance_of("cor1") + result = solve(instance, whole(instance.regime, **dict.fromkeys(SWITCHES, False))) + assert result.exhaustive + assert len(result.solutions) == 1 + assert result.metrics["nodes"] > 1_000 + + def test_a_relief_puzzle_seen_as_a_footprint_has_its_twins_assemblies() -> None: """``rat1`` with its roofs hidden: 101 assemblies again, from other stored rotations.""" relief = instance_of("rat1") diff --git a/tests/corpus/test_search_geometry_agrees_with_shapely.py b/tests/corpus/test_search_geometry_agrees_with_shapely.py index f3eeea4..e54465a 100644 --- a/tests/corpus/test_search_geometry_agrees_with_shapely.py +++ b/tests/corpus/test_search_geometry_agrees_with_shapely.py @@ -71,7 +71,12 @@ def roofs_of(instance: PuzzleInstance) -> list[tuple[float, float, float]] | Non def assembly(instance: PuzzleInstance) -> Any: return _native.Assembly( - instance.target, [piece.polygon for piece in instance.pieces], roofs_of(instance), **TOL + instance.target, + [piece.polygon for piece in instance.pieces], + roofs_of(instance), + length_tol=TOL["length_tol"], + angle_tol=TOL["angle_tol"], + slope_tol=TOL["slope_tol"], ) diff --git a/tests/keys/cor1-flat.json b/tests/keys/cor1-flat.json new file mode 100644 index 0000000..4d81d04 --- /dev/null +++ b/tests/keys/cor1-flat.json @@ -0,0 +1,174 @@ +{ + "instanceId": "cor1-flat", + "instanceHash": "f6faf9abc88d94dedb1b5a5ea5bcf1a66c75e56095785034c623db24e1aeceb0", + "sanitizer": { + "version": 1, + "seed": 20261109 + }, + "poses": { + "p00": { + "x": 42.19607843137255, + "y": 59.4, + "theta": 0.5240740876621883 + }, + "p01": { + "x": -11.607843137254902, + "y": 59.4, + "theta": 2.736540362053726 + }, + "p02": { + "x": -11.607843137254902, + "y": -55.8, + "theta": -1.7856559689387153 + }, + "p03": { + "x": 42.19607843137255, + "y": 5.4, + "theta": 0.8719676744639182 + }, + "p04": { + "x": 17.60779397623009, + "y": -55.32446373713501, + "theta": 1.5864298561371513 + }, + "p05": { + "x": 42.19607843137255, + "y": 33.3, + "theta": 1.0442998116463311 + }, + "p06": { + "x": -50.03921568627451, + "y": 59.4, + "theta": 1.1917302520811228 + }, + "p07": { + "x": -11.607843137254902, + "y": 5.4, + "theta": 0.1519005294758804 + }, + "p08": { + "x": 62.588235294117645, + "y": 59.4, + "theta": -1.5225778618015862 + }, + "p09": { + "x": -50.03921568627451, + "y": -24.3, + "theta": -2.7910927095956204 + }, + "p10": { + "x": -50.03921568627451, + "y": 33.3, + "theta": -2.134557491454423 + }, + "p11": { + "x": 42.19607843137255, + "y": -24.3, + "theta": -1.8471251150421137 + }, + "p12": { + "x": 18.03921568627451, + "y": 59.4, + "theta": 2.8362074392761305 + }, + "p13": { + "x": 62.588235294117645, + "y": 5.4, + "theta": -0.9261962522651964 + }, + "p14": { + "x": 18.03921568627451, + "y": 5.4, + "theta": 0.5791177381627817 + }, + "p15": { + "x": 41.85022374680614, + "y": -49.31248135443282, + "theta": 2.8301033478583535 + }, + "p16": { + "x": 62.588235294117645, + "y": -24.3, + "theta": -0.8313386792190458 + }, + "p17": { + "x": -50.03921568627451, + "y": -55.8, + "theta": 1.6337955469383756 + }, + "p18": { + "x": -11.607843137254902, + "y": -24.3, + "theta": 0.7502328689179265 + }, + "p19": { + "x": 41.3900324803958, + "y": -65.71991434094036, + "theta": -3.132190460174404 + }, + "p20": { + "x": 62.28005701298201, + "y": -47.60999524891817, + "theta": -1.0764025814864966 + }, + "p21": { + "x": 18.03921568627451, + "y": -24.3, + "theta": 0.5168607496035493 + }, + "p22": { + "x": 18.03921568627451, + "y": 33.3, + "theta": 2.9614363816728058 + }, + "p23": { + "x": 62.88773456876784, + "y": -63.75935545260268, + "theta": -2.3459440987406395 + }, + "p24": { + "x": -50.03921568627451, + "y": 5.4, + "theta": -2.3809263076393035 + }, + "p25": { + "x": -11.607843137254902, + "y": 33.3, + "theta": 2.5309967331655816 + }, + "p26": { + "x": 62.588235294117645, + "y": 33.3, + "theta": 0.27462682941501093 + } + }, + "sourceIds": { + "p00": "Jc", + "p01": "Eb", + "p02": "Ab", + "p03": "Hc", + "p04": "Fb", + "p05": "Ic", + "p06": "Ea", + "p07": "Cb", + "p08": "Oc", + "p09": "Ba", + "p10": "Da", + "p11": "Gc", + "p12": "Jb", + "p13": "Mc", + "p14": "Hb", + "p15": "Fc", + "p16": "Lc", + "p17": "Aa", + "p18": "Bb", + "p19": "Fd", + "p20": "Kc", + "p21": "Gb", + "p22": "Ib", + "p23": "Kd", + "p24": "Ca", + "p25": "Db", + "p26": "Nc" + } +} diff --git a/tests/keys/cor1.json b/tests/keys/cor1.json new file mode 100644 index 0000000..d6d9b3d --- /dev/null +++ b/tests/keys/cor1.json @@ -0,0 +1,174 @@ +{ + "instanceId": "cor1", + "instanceHash": "026f6a52f04e26483d652f366c471c142c75244b7e203dedefdd281098beadff", + "sanitizer": { + "version": 1, + "seed": 20261109 + }, + "poses": { + "p00": { + "x": 42.19607843137255, + "y": -24.3, + "theta": 1.0638873832429923 + }, + "p01": { + "x": 62.88773456876784, + "y": -63.75935545260268, + "theta": -1.1231561867764175 + }, + "p02": { + "x": 41.85022374680614, + "y": -49.31248135443282, + "theta": -1.4930210710059275 + }, + "p03": { + "x": 62.588235294117645, + "y": 5.4, + "theta": -2.220773848728805 + }, + "p04": { + "x": 62.588235294117645, + "y": 33.3, + "theta": 2.3454030091047127 + }, + "p05": { + "x": 42.19607843137255, + "y": 33.3, + "theta": 0.8973814285486794 + }, + "p06": { + "x": -11.607843137254902, + "y": 5.4, + "theta": -1.0849582064301357 + }, + "p07": { + "x": -11.607843137254902, + "y": 59.4, + "theta": 1.881722680458913 + }, + "p08": { + "x": 62.588235294117645, + "y": -24.3, + "theta": 1.1160502143208202 + }, + "p09": { + "x": 62.588235294117645, + "y": 59.4, + "theta": 2.5954002605556523 + }, + "p10": { + "x": 62.28005701298201, + "y": -47.60999524891817, + "theta": -1.34655532762477 + }, + "p11": { + "x": -11.607843137254902, + "y": -24.3, + "theta": -1.074095822560223 + }, + "p12": { + "x": 18.03921568627451, + "y": -24.3, + "theta": -2.148361405598077 + }, + "p13": { + "x": -50.03921568627451, + "y": -55.8, + "theta": 2.852962242166671 + }, + "p14": { + "x": -11.607843137254902, + "y": 33.3, + "theta": 2.203001069849427 + }, + "p15": { + "x": -50.03921568627451, + "y": -24.3, + "theta": -0.9513597195843406 + }, + "p16": { + "x": 17.60779397623009, + "y": -55.32446373713501, + "theta": -0.28355365945443484 + }, + "p17": { + "x": 18.03921568627451, + "y": 5.4, + "theta": -1.3830369254102453 + }, + "p18": { + "x": 42.19607843137255, + "y": 59.4, + "theta": -2.559615807921442 + }, + "p19": { + "x": -50.03921568627451, + "y": 59.4, + "theta": 1.8643149934550438 + }, + "p20": { + "x": 42.19607843137255, + "y": 5.4, + "theta": -2.0147214992282154 + }, + "p21": { + "x": -50.03921568627451, + "y": 33.3, + "theta": 0.7215572726903883 + }, + "p22": { + "x": 18.03921568627451, + "y": 59.4, + "theta": 2.900979355795021 + }, + "p23": { + "x": 41.3900324803958, + "y": -65.71991434094036, + "theta": 1.2523187818372126 + }, + "p24": { + "x": -50.03921568627451, + "y": 5.4, + "theta": 0.686708442697153 + }, + "p25": { + "x": -11.607843137254902, + "y": -55.8, + "theta": 1.2772017387388823 + }, + "p26": { + "x": 18.03921568627451, + "y": 33.3, + "theta": 1.7965535380059032 + } + }, + "sourceIds": { + "p00": "Gc", + "p01": "Kd", + "p02": "Fc", + "p03": "Mc", + "p04": "Nc", + "p05": "Ic", + "p06": "Cb", + "p07": "Eb", + "p08": "Lc", + "p09": "Oc", + "p10": "Kc", + "p11": "Bb", + "p12": "Gb", + "p13": "Aa", + "p14": "Db", + "p15": "Ba", + "p16": "Fb", + "p17": "Hb", + "p18": "Jc", + "p19": "Ea", + "p20": "Hc", + "p21": "Da", + "p22": "Jb", + "p23": "Fd", + "p24": "Ca", + "p25": "Ab", + "p26": "Ib" + } +} diff --git a/tests/keys/new1-flat.json b/tests/keys/new1-flat.json index 996ff33..589fe2b 100644 --- a/tests/keys/new1-flat.json +++ b/tests/keys/new1-flat.json @@ -1,6 +1,6 @@ { "instanceId": "new1-flat", - "instanceHash": "5cea41e18add833a84afe209351b407bea5c41f3b998c9c76f41b567b6cb66a1", + "instanceHash": "e2c6b3360c87150ede3e059afbdf07e2c690e06b60d17c15374363fb4d38915f", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new1.json b/tests/keys/new1.json index 4aea0a2..aa5420d 100644 --- a/tests/keys/new1.json +++ b/tests/keys/new1.json @@ -1,6 +1,6 @@ { "instanceId": "new1", - "instanceHash": "316f47096c88b5d96a5ebd517f536a39fea14f5b8991126f11abf05a63af91f7", + "instanceHash": "8f77d45bb31789eaabbb58b51acc1a82686961655370bd64235d27b674c88694", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new2-flat.json b/tests/keys/new2-flat.json index c00e303..b70b387 100644 --- a/tests/keys/new2-flat.json +++ b/tests/keys/new2-flat.json @@ -1,6 +1,6 @@ { "instanceId": "new2-flat", - "instanceHash": "59a938c00227006b4c39007dbf87b40dde7fb11b50eb546cd065b9cc4df03785", + "instanceHash": "806c33e986132b3e09b3d08dcd455e5dbc79dd57caa73c7056363329a5552569", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new2.json b/tests/keys/new2.json index f1b1c49..d9685b0 100644 --- a/tests/keys/new2.json +++ b/tests/keys/new2.json @@ -1,6 +1,6 @@ { "instanceId": "new2", - "instanceHash": "182cebb40e07f854b46e39d819b3b45a54838ff0345e998915a6f3ade2d1ef70", + "instanceHash": "3e241af54d54f34251097f97c88d4c048dac2f4aa92636995f1e58e96fb831c6", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new3-flat.json b/tests/keys/new3-flat.json index 0ccc10d..0199c12 100644 --- a/tests/keys/new3-flat.json +++ b/tests/keys/new3-flat.json @@ -1,6 +1,6 @@ { "instanceId": "new3-flat", - "instanceHash": "3bef95861401962974a94cc7bd3af623140579de81ce8c4a1752d3e88cb8a19b", + "instanceHash": "0375980860cc4864066b5705a43b295deadecf188ddcb900a867f2204c98d9b2", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new3.json b/tests/keys/new3.json index f850555..26f8649 100644 --- a/tests/keys/new3.json +++ b/tests/keys/new3.json @@ -1,6 +1,6 @@ { "instanceId": "new3", - "instanceHash": "f323c0f36ee5c67a4ed9909df8647c76b7a8b5daaf1185d58b0cb599d73d4077", + "instanceHash": "ffa7dd51d43a0bd68ac3842eecef7b0b3444479c5e1e6f1eded8b8124c79358c", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new4-flat.json b/tests/keys/new4-flat.json index 2da1141..2d33d9e 100644 --- a/tests/keys/new4-flat.json +++ b/tests/keys/new4-flat.json @@ -1,6 +1,6 @@ { "instanceId": "new4-flat", - "instanceHash": "e9b5924cff70660da1d21edfbbfc0afc4379f2c2b70b27c446b9589e8aef3e0b", + "instanceHash": "b760c7313023cc5096b8445bf49e0c70863cdc697e4cef6ea8c875786e038952", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new4.json b/tests/keys/new4.json index 21403ae..276dcd3 100644 --- a/tests/keys/new4.json +++ b/tests/keys/new4.json @@ -1,6 +1,6 @@ { "instanceId": "new4", - "instanceHash": "72113b0654c26918d6d5245a37490c80a627a30303190223603de35003c32498", + "instanceHash": "262293f93491b1cd363f52d0957d362edf45f76e0a18463594034f0051d0354b", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new5-flat.json b/tests/keys/new5-flat.json index c28c062..3069ed6 100644 --- a/tests/keys/new5-flat.json +++ b/tests/keys/new5-flat.json @@ -1,6 +1,6 @@ { "instanceId": "new5-flat", - "instanceHash": "2b719a8e0e9e1b04e870a73388b596e5c7b21ed2a983a7363d5deddd31fdf692", + "instanceHash": "08a9a7d6f35079f33abc0b6bf205b800330ea87f76d9b50536be3568080d3bf3", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/new5.json b/tests/keys/new5.json index 997d189..54e1872 100644 --- a/tests/keys/new5.json +++ b/tests/keys/new5.json @@ -1,6 +1,6 @@ { "instanceId": "new5", - "instanceHash": "dadb5297b3ba835bc2da28201a5430cc796afbe59dac4474a0f90f2c0fe597ac", + "instanceHash": "d972897b43f6db974556e2d37ab9ae9c7cd850ceda56fdba9cdb741083d7dc6a", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/rat1-flat.json b/tests/keys/rat1-flat.json index 546defa..e2ce35f 100644 --- a/tests/keys/rat1-flat.json +++ b/tests/keys/rat1-flat.json @@ -1,6 +1,6 @@ { "instanceId": "rat1-flat", - "instanceHash": "ce4e5d5431c8a8daa8bd2ff3dce519e0ba669b9507868ace5376295a495c7577", + "instanceHash": "9b7eeef268cd4e79418c51a2853bc7359aae7346308ebd847c6cfd77a6a6ab26", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/rat1.json b/tests/keys/rat1.json index 8352ee4..941631c 100644 --- a/tests/keys/rat1.json +++ b/tests/keys/rat1.json @@ -1,6 +1,6 @@ { "instanceId": "rat1", - "instanceHash": "3b8ac23d1a3395c8b30313ea53253973ec1e515a9dfae59b1eb7702f5546b41d", + "instanceHash": "f895d290552212be413b5e187759a8ec76161cc46bba7fa6cf4ab8b4cb242664", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/rat2-flat.json b/tests/keys/rat2-flat.json index 6a39e72..87429b8 100644 --- a/tests/keys/rat2-flat.json +++ b/tests/keys/rat2-flat.json @@ -1,6 +1,6 @@ { "instanceId": "rat2-flat", - "instanceHash": "dbac49368deabed47b3a50c6ed255c12dec8fe5f6442c36d25794a49114033d0", + "instanceHash": "76df43b7888c5aa0c009afa24e8e9f974e6382bedc282802346f1cd8cd664c73", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/rat2.json b/tests/keys/rat2.json index d185a6f..b9a2694 100644 --- a/tests/keys/rat2.json +++ b/tests/keys/rat2.json @@ -1,6 +1,6 @@ { "instanceId": "rat2", - "instanceHash": "ea656bb60309a5582eecf701870916707c8ee154182fb232845c4242e08e0ddb", + "instanceHash": "b4a9cbd44edc4f9425df0cc11069679078abd8d1b487163d7ba5fbbab8a13741", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/rev2-flat.json b/tests/keys/rev2-flat.json index 022f07e..07fe2b9 100644 --- a/tests/keys/rev2-flat.json +++ b/tests/keys/rev2-flat.json @@ -1,6 +1,6 @@ { "instanceId": "rev2-flat", - "instanceHash": "2acb913456ef45663e8622a80085cd69b1d99b12bf3d4f5cd530881350576608", + "instanceHash": "4d35562a36ca9ad667d3afbf464c37a0e123fdcd2639175e7ecfeaf8fab7a272", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/keys/rev2.json b/tests/keys/rev2.json index 29d1bb1..bc15230 100644 --- a/tests/keys/rev2.json +++ b/tests/keys/rev2.json @@ -1,6 +1,6 @@ { "instanceId": "rev2", - "instanceHash": "bcd0168ea567cf80cdda0ffeef4fbae9a35e7db78336a6cdebe69edaadb486c5", + "instanceHash": "d45bf8b85e80fb55123833cc59745b7545334614476d7c30c62f2c1d26e97218", "sanitizer": { "version": 1, "seed": 20261109 diff --git a/tests/support/corpus.py b/tests/support/corpus.py index 2eb9b4d..d64ca12 100644 --- a/tests/support/corpus.py +++ b/tests/support/corpus.py @@ -17,6 +17,11 @@ SOURCE_ENV = "TROPICAL_PUZZLE_LAB" +# Corpus fixtures whose whole search, assuming nothing, has not been seen to end: +# cor1-flat was stopped at 3 000 000 nodes. Tests that compare against the end of +# that search leave these out by name, and test them separately for what can be said. +UNFINISHED = frozenset({"cor1-flat"}) + def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8")) diff --git a/tests/support/documents.py b/tests/support/documents.py index ec51b18..eacb6cd 100644 --- a/tests/support/documents.py +++ b/tests/support/documents.py @@ -109,3 +109,23 @@ def three_strips_relief() -> dict[str, Any]: for piece, centre in zip(doc["pieces"], THREE_STRIP_CENTRES, strict=True): piece["roof"] = {"z0": 20.0 + (centre + 60.0) / 4, "gx": 0.25, "gy": 0.0} return doc + + +def block_and_squares() -> dict[str, Any]: + """A 144 by 72 mm block and two 72 mm squares in the 144 mm tray. + + They fit one way, up to turning the tray and exchanging the squares: the + block along one wall, the squares side by side along it. Their shared + corner then stands at the middle of the block's long edge, a T, so no + assembly of these pieces meets edge to edge. + """ + doc = footprint() + block = [[-72.0, -36.0], [72.0, -36.0], [72.0, 36.0], [-72.0, 36.0]] + square = [[-36.0, -36.0], [36.0, -36.0], [36.0, 36.0], [-36.0, 36.0]] + doc["id"] = "block-and-squares" + doc["pieces"] = [ + {"id": "p00", "polygon": block}, + {"id": "p01", "polygon": [list(v) for v in square]}, + {"id": "p02", "polygon": [list(v) for v in square]}, + ] + return doc diff --git a/tests/support/geometry.py b/tests/support/geometry.py index 4ea1e69..6eea4c6 100644 --- a/tests/support/geometry.py +++ b/tests/support/geometry.py @@ -101,3 +101,48 @@ def same_polygon(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]], tol return any( all(math.dist(a[i], b[(i + shift) % n]) <= tol for i in range(n)) for shift in range(n) ) + + +def segment_distance(p: Sequence[float], a: Sequence[float], b: Sequence[float]) -> float: + """Distance from ``p`` to the segment from ``a`` to ``b``: to the nearest point of it.""" + dx, dy = b[0] - a[0], b[1] - a[1] + t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / (dx * dx + dy * dy) + t = min(1.0, max(0.0, t)) + return math.dist(p, (a[0] + t * dx, a[1] + t * dy)) + + +def is_edge_to_edge( + polygons: Sequence[Sequence[Sequence[float]]], + target: Sequence[Sequence[float]], + tol: float, +) -> bool: + """Whether placed pieces that cover ``target`` meet edge to edge, by twin edges. + + Every edge of every piece either lies on the target's boundary (both ends + within ``tol`` of one side of it) or is, run backwards, an edge of exactly + one other piece (both ends within ``tol``). For pieces that cover the + target this is the same as no vertex lying strictly inside another piece's + edge, the form the search uses: if an interior edge has one twin, the twin's + piece lines the whole edge, and a vertex of a third piece inside it would + overlap one of them. + """ + m = len(target) + sides = [(target[j], target[(j + 1) % m]) for j in range(m)] + for p, piece in enumerate(polygons): + n = len(piece) + for i in range(n): + a, b = piece[i], piece[(i + 1) % n] + if any( + segment_distance(a, s, e) <= tol and segment_distance(b, s, e) <= tol + for s, e in sides + ): + continue + twins = sum( + math.dist(a, other[(j + 1) % len(other)]) <= tol and math.dist(b, other[j]) <= tol + for q, other in enumerate(polygons) + if q != p + for j in range(len(other)) + ) + if twins != 1: + return False + return True diff --git a/tests/unit/test_edge_to_edge.py b/tests/unit/test_edge_to_edge.py new file mode 100644 index 0000000..dd6ead2 --- /dev/null +++ b/tests/unit/test_edge_to_edge.py @@ -0,0 +1,221 @@ +"""The edge-to-edge assumption, on puzzles whose assemblies can be listed by hand. + +Two 72 by 144 mm strips fill the 144 mm tray in one way, side by side, meeting +along a whole edge. A 144 by 72 mm block and two 72 mm squares also fill it in +one way, and in that one the squares' shared corner is in the middle of the +block's edge (``support.documents.block_and_squares``). The assumption keeps +the first and has nothing to return for the second. +""" + +import json +from pathlib import Path +from typing import Any + +import pytest + +from maxplus_solvers import ( + Assumption, + PuzzleInstance, + Regime, + SolverConfig, + SolveResult, + SolveStatus, + cli, + solve, +) +from maxplus_solvers.experiments import report +from maxplus_solvers.experiments.manifest import ManifestError, expand, parse +from support import documents, geometry + +DFS = "rust.contact_dfs" +E2E = (Assumption.EDGE_TO_EDGE,) +TRAY = [(-72.0, -72.0), (72.0, -72.0), (72.0, 72.0), (-72.0, 72.0)] + + +def strips() -> PuzzleInstance: + return PuzzleInstance.from_dict(documents.footprint()) + + +def block_and_squares() -> PuzzleInstance: + return PuzzleInstance.from_dict(documents.block_and_squares()) + + +def everything(assumptions: tuple[Assumption, ...] = (), **options: Any) -> SolverConfig: + return SolverConfig(DFS, max_solutions=None, assumptions=assumptions, options=options) + + +def placed(instance: PuzzleInstance, result: SolveResult) -> list[Any]: + return [ + [piece.world_polygon(solution.poses[piece.id]) for piece in instance.pieces] + for solution in result.solutions + ] + + +# --- the oracle --------------------------------------------------------------------------- + + +def test_the_oracle_tells_a_t_from_a_shared_edge() -> None: + left = [(-72.0, -72.0), (0.0, -72.0), (0.0, 72.0), (-72.0, 72.0)] + right = [(0.0, -72.0), (72.0, -72.0), (72.0, 72.0), (0.0, 72.0)] + assert geometry.is_edge_to_edge([left, right], TRAY, 1e-6) + # The right half cut across: its two parts' shared corner (0, 0) is inside left's edge. + lower = [(0.0, -72.0), (72.0, -72.0), (72.0, 0.0), (0.0, 0.0)] + upper = [(0.0, 0.0), (72.0, 0.0), (72.0, 72.0), (0.0, 72.0)] + assert not geometry.is_edge_to_edge([left, lower, upper], TRAY, 1e-6) + # An edge with no twin at all, in the open: a piece missing. + assert not geometry.is_edge_to_edge([left], TRAY, 1e-6) + + +# --- what the search finds ---------------------------------------------------------------- + + +def test_two_strips_are_found_with_the_assumption_and_without() -> None: + instance = strips() + plain = solve(instance, everything()) + assumed = solve(instance, everything(E2E)) + assert placed(instance, plain) == placed(instance, assumed) + assert len(assumed.solutions) == 1 + assert geometry.is_edge_to_edge(placed(instance, assumed)[0], TRAY, 1e-6) + + +def test_a_block_and_two_squares_fit_only_in_a_t() -> None: + instance = block_and_squares() + plain = solve(instance, everything(), validate=True) + assert plain.status is SolveStatus.SOLVED and len(plain.solutions) == 1 + assert plain.solutions[0].valid is True + assert not geometry.is_edge_to_edge(placed(instance, plain)[0], TRAY, 1e-6) + for equal_edges in (True, False): + for wall_edges in (True, False): + options = {"equal_edges": equal_edges, "wall_edges": wall_edges} + assumed = solve(instance, everything(E2E, **options)) + assert assumed.status is SolveStatus.NO_SOLUTION_FOUND, options + assert assumed.exhaustive, options + + +def test_the_rules_that_follow_from_the_assumption_are_counted() -> None: + assumed = solve(block_and_squares(), everything(E2E)) + # The block has no partner for its long edges, so it never leaves the wall; + # along the wall the squares can only stand where they make a T with it. + assert assumed.metrics["rejected_wall"] > 0 + without_rules = solve(block_and_squares(), everything(E2E, wall_edges=False)) + assert without_rules.metrics["rejected_wall"] == 0 + assert without_rules.metrics["rejected_junction"] > 0 + # Without the assumption the counts are not there at all, rather than zero. + plain = solve(block_and_squares(), everything()) + assert "rejected_junction" not in plain.metrics and "rejected_wall" not in plain.metrics + + +# --- what a result records ---------------------------------------------------------------- + + +def test_a_result_names_its_assumption_and_its_own_candidate_set() -> None: + plain = solve(strips(), everything()) + assumed = solve(strips(), everything(E2E)) + assert plain.assumptions == () and plain.candidate_set == "corner-contact/1" + assert assumed.assumptions == E2E + assert assumed.candidate_set == "corner-contact-edge-to-edge/1" + relief = solve( + PuzzleInstance.from_dict(documents.relief()), + SolverConfig(DFS, mode=Regime.RELIEF, max_solutions=None, assumptions=E2E), + ) + assert relief.candidate_set == "corner-contact-relief-edge-to-edge/1" + again = SolveResult.from_dict(json.loads(json.dumps(assumed.to_dict()))) + assert again == assumed + assert again.config is not None and again.config.assumptions == E2E + + +def test_a_record_from_before_assumptions_reads_as_making_none() -> None: + document = solve(strips(), everything()).to_dict() + del document["assumptions"] + assert document["config"] is not None + del document["config"]["assumptions"] + old = SolveResult.from_dict(document) + assert old.assumptions == () and old.config is not None and old.config.assumptions == () + + +def test_assumptions_are_kept_in_one_order_and_once() -> None: + config = SolverConfig(DFS, assumptions=("edge-to-edge", Assumption.EDGE_TO_EDGE)) # type: ignore[arg-type] + assert config.assumptions == E2E + + +@pytest.mark.parametrize( + ("make", "message"), + [ + (lambda: SolverConfig(DFS, assumptions=("convex",)), "convex"), # type: ignore[arg-type] + (lambda: SolverConfig(DFS, assumptions="edge-to-edge"), "not one string"), # type: ignore[arg-type] + ], +) +def test_an_assumption_that_is_not_one_is_refused(make: Any, message: str) -> None: + with pytest.raises(ValueError, match=message): + make() + + +def test_its_rules_mean_nothing_without_the_assumption() -> None: + with pytest.raises(ValueError, match="only mean something under the edge-to-edge"): + solve(strips(), everything(equal_edges=False)) + with pytest.raises(ValueError, match="wall_edges must be true or false"): + solve(strips(), everything(E2E, wall_edges="yes")) + + +@pytest.mark.parametrize("solver", ["python.contact_dfs", "cp_sat.placements"]) +def test_a_solver_that_cannot_make_the_assumption_refuses_it(solver: str) -> None: + with pytest.raises(ValueError, match="cannot assume edge-to-edge"): + solve(strips(), SolverConfig(solver, assumptions=E2E)) + + +# --- the command line and the experiments ------------------------------------------------- + + +def test_the_command_line_takes_the_assumption_and_says_so( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + path = tmp_path / "block.json" + path.write_text(json.dumps(documents.block_and_squares()), encoding="utf-8") + assert cli.main([str(path), "--max-solutions", "all"]) == cli.SOLVED + capsys.readouterr() + code = cli.main([str(path), "--max-solutions", "all", "--assume", "edge-to-edge"]) + assert code == cli.NOT_SOLVED + out = capsys.readouterr().out + assert "corner-contact-edge-to-edge/1" in out + assert "assuming edge-to-edge" in out + + +def test_a_manifest_crosses_the_assumption_with_its_other_factors() -> None: + data = { + "name": "hand", + "fixtures": ["corpus"], + "runs": [{"solver": DFS, "assume": ["none", "edge-to-edge"], "seeds": [0, 1]}], + } + runs = list(expand(parse(data), ["toy"])) + assert [(r.assume, r.seed) for r in runs] == [ + ("none", 0), + ("none", 1), + ("edge-to-edge", 0), + ("edge-to-edge", 1), + ] + data["runs"][0]["assume"] = "convex" + with pytest.raises(ManifestError, match="neither 'none' nor an assumption"): + parse(data) + + +def test_a_table_always_shows_the_assumption_when_one_is_made() -> None: + def record(assumptions: list[str]) -> dict[str, Any]: + return { + "fixture": "toy", + "pieces": 2, + "solver": DFS, + "mode": "footprint", + "contactScale": 1.0, + "config": {"seed": 0, "options": {}, "assumptions": assumptions}, + "status": "solved", + "exhaustive": True, + "solutions": 1, + "metrics": {"nodes": 3}, + } + + assert "assumes" not in report.rows([record([])])[0] + # Shown even when every row makes the same one: those rows say something narrower. + header, row = report.rows([record(["edge-to-edge"])]) + assert row[header.index("assumes")] == "edge-to-edge" + header, *rows = report.rows([record([]), record(["edge-to-edge"])]) + assert [r[header.index("assumes")] for r in rows] == ["nothing", "edge-to-edge"] From 3d1a1d8cf02bdcb634c58565013fe786658f257a Mon Sep 17 00:00:00 2001 From: Igor Kuvychko Date: Thu, 12 Nov 2026 11:17:13 -0800 Subject: [PATCH 2/2] Mark phase 8 done: exit tests pass in CI on Linux and Windows Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Jfg9fgTR9LYn4D2rTtfifs --- docs/roadmap.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 4a2cf85..3836e5c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -12,9 +12,9 @@ Each phase is sized for one working session and ends with an exit criterion that | 5 | Rust contact DFS | Done | | 6 | CP-SAT backend | Done | | 7 | Benchmark and research platform | Done | -| 8 | The edge-to-edge assumption | In progress | +| 8 | The edge-to-edge assumption | Done | -The source corpus is 8 constructions in two variants each (relief and flat), 16 puzzles of 6 to 20 convex pieces with 3 to 8 vertices, in a 144 mm square tray. +The source corpus is 9 constructions in two variants each (relief and flat), 18 puzzles of 6 to 27 convex pieces with 3 to 8 vertices, in a 144 mm square tray. ## Phase 0: repository skeleton @@ -196,7 +196,7 @@ Tropical puzzles are cut from a polyhedral complex, so their pieces meet edge to **Exit:** on every corpus fixture, the search under the assumption finds exactly the assemblies of the plain search that an independent check calls edge to edge, with the two rules on and off, and the answer key among them. On `cor1-flat`, whose plain search does not end, everything the assumed search finds is edge to edge by that check and valid, and the answer key is among it. -Decisions so far: +Done, with these decisions: - The exit criterion is `tests/corpus/test_edge_to_edge.py::test_the_assumption_finds_exactly_the_edge_to_edge_assemblies`. The independent check is `support.geometry.is_edge_to_edge`, by twin edges, where the search decides by vertices inside edges. - An assumption is not a pruning rule, because it changes what a whole search finds. The two rules that follow from it are pruning rules within it, tested as such.