From c58d1fe02b6d4000e5acb569894be04cdd01dac6 Mon Sep 17 00:00:00 2001 From: Igor Kuvychko Date: Tue, 17 Nov 2026 11:38:55 -0800 Subject: [PATCH 1/3] Prepare the public release: README orientation, traceable claims, a results figure README: an "At a glance" section (the three solvers, the regimes, how to reproduce the tables), the four findings with each number's puzzle, regime, solver and metric, a section on what the numbers do and do not claim (exact counts against lower bounds, candidates, f64), and the app's puzzle names beside the fixture ids. Corrections: "1 to 7 partners with roofs" excluded Pleat (16 to 24); the Pleat footprint counts are lower bounds from stopped searches; plt1's 749 nodes are with roofs; cor1-flat finishes assuming edge to edge. experiments.md: the expensive rows now include Pleat; construction families include cor and plt; the "Source rating" column predates the source's switch to a rating computed from this repository's node counts (tropical-puzzle-lab cfe2c8b), so it is marked as the earlier, diversity-based rating. A figure, docs/figures/at-a-glance.svg, drawn by `maxplus-bench figure` from the two committed tables (report.parse_markdown reads them back), and held to them by tests/corpus/test_figure.py. tests/architecture/test_doc_links.py checks that relative links, anchors and quoted paths in the documents exist. LICENSE: copyright Igor Kuvychko and Madeline V. Brandt, as in tropical-puzzle-lab. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +- LICENSE | 2 +- README.md | 137 +- docs/experiments.md | 16 +- docs/figures/at-a-glance.svg | 2143 +++++++++++++++++ python/maxplus_solvers/experiments/cli.py | 32 +- .../maxplus_solvers/experiments/plotting.py | 115 +- python/maxplus_solvers/experiments/report.py | 28 + tests/architecture/test_doc_links.py | 111 + tests/corpus/test_figure.py | 66 + tests/unit/test_plotting.py | 76 + tests/unit/test_report_tables.py | 40 + 12 files changed, 2716 insertions(+), 54 deletions(-) create mode 100644 docs/figures/at-a-glance.svg create mode 100644 tests/architecture/test_doc_links.py create mode 100644 tests/corpus/test_figure.py create mode 100644 tests/unit/test_report_tables.py diff --git a/CLAUDE.md b/CLAUDE.md index e27f500..fb61c0d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,6 +35,7 @@ uv run maxplus-bench run benchmarks/manifests/corpus.toml --no-times 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 maxplus-bench figure # redraw docs/figures/at-a-glance.svg from the two committed tables uv run python scripts/import_fixtures.py --source ../tropical-puzzle-lab # regenerate fixtures and keys uv run python scripts/import_fixtures.py --source ../tropical-puzzle-lab --check # compare, write nothing ``` @@ -85,6 +86,7 @@ Rules: ## Invariants that are easy to break +- **A public number can be traced.** Every figure the README or `docs/` quotes names its puzzle, regime, solver, assumption and metric, and comes from a committed table or a stated run. Relative links and quoted repository paths in them resolve (`tests/architecture/test_doc_links.py`). - **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. @@ -92,7 +94,7 @@ Rules: - **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. - **Search rules are switches, and the measurement is the product.** The question is what makes a puzzle hard and what helps, not how fast a solver is. A pruning rule, an ordering or a symmetry reduction added to a solver is an option that can be turned off, is tested not to change what the whole search finds, and gets its row in the ablation table of `docs/algorithms.md`. A rule that costs more than it saves stays, switched off, with its numbers. - **Experiments are callers.** `experiments/` goes through `api.solve` like any user, and nothing outside it imports it. Only `experiments/plotting.py` imports matplotlib; running a manifest needs no plotting stack. -- **A committed table has no times.** `benchmarks/results/*.md` are written with `--no-times`: statuses and counts, which a deterministic solver reproduces exactly and a test compares. Times, CP-SAT's own counts and the `.jsonl` records belong to a machine and are not committed. When a solver change moves a count, regenerate the table with the command and say why in the commit. +- **A committed table has no times.** `benchmarks/results/*.md` are written with `--no-times`: statuses and counts, which a deterministic solver reproduces exactly and a test compares. Times, CP-SAT's own counts and the `.jsonl` records belong to a machine and are not committed. When a solver change moves a count, regenerate the table with the command, then the README's figure with `maxplus-bench figure`, and say why in the commit. - **The suite does not run million-node searches.** The fixtures in `corpus.EXPENSIVE` (`tests/support/corpus.py`: `cor1-flat`, `new1-flat`, `new2-flat`, and all ten Pleat fixtures, `plt1` to `plt5` with their footprints) are left out of the per-fixture tests, and the table tests reproduce every other row with `maxplus-bench run --only`. Their rows are checked against a search only by running the full command, so a solver change that could move them means running it by hand. There is no `slow` marker; a test that needs one is a test to make smaller. - **Completeness and uniqueness are explicit claims.** A result says whether the search was exhaustive and over which candidate set. "No solution found" and CP-SAT `INFEASIBLE` are relative to the candidates generated unless completeness is proven. - **Layering is one-way:** core ← geometry ← search ← py. Python reaches Rust only through `_native`. diff --git a/LICENSE b/LICENSE index 9218202..37f2546 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 Igor Kuvychko +Copyright (c) 2026 Igor Kuvychko and Madeline V. Brandt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index e928af6..7767841 100644 --- a/README.md +++ b/README.md @@ -1,59 +1,117 @@ # tiling-solvers -A solver laboratory for geometric tiling puzzles, starting with the tropical puzzles published by [Tropical Puzzle Lab](https://github.com/maxpluslab/tropical-puzzle-lab). +A solver laboratory for geometric tiling puzzles, starting with the tropical puzzles published by [Tropical Puzzle Lab](https://github.com/maxpluslab/tropical-puzzle-lab). It is a research platform, not a single solver. Several search methods run on the same puzzles, behind one contract, with an independent validator and reproducible benchmarks. The question it asks is what makes a puzzle hard for a search, and what helps. -The aim is a research platform, not a single solver: +![Search-tree nodes of a whole search for each of the 14 constructions, flat, with roofs, and flat assuming edge to edge](docs/figures/at-a-glance.svg) -- several custom Rust algorithms that can be developed and compared side by side; -- established engines such as OR-Tools CP-SAT, as alternative formulations over the same generated placements; -- Python prototypes that migrate to Rust once the idea is settled; -- geometry, candidate generation, input formats, validation and benchmarking shared by all of them; -- experiments on puzzle difficulty, ambiguity, uniqueness and geometric tolerances. +*Search effort for each construction (pieces in brackets), as nodes in the search tree of `rust.contact_dfs` with default options and tolerances, node limit 1 500 000. Each point is a whole search, with every assembly found, unless it is an open arrow: those flat searches were stopped at the limit, so their true cost is larger. Nodes are not running times and not a measure of how hard a puzzle is for a person. Data: [corpus.md](benchmarks/results/corpus.md) and [edge_to_edge.md](benchmarks/results/edge_to_edge.md); drawn by `uv run maxplus-bench figure`.* -Python owns orchestration and analysis. Rust owns the geometry and the search. +## At a glance + +**Three solvers, one contract.** Each takes a sanitized puzzle and returns assemblies, with a statement of what it searched and whether it searched all of it ([solver contract](docs/solver-contract.md)). + +- `rust.contact_dfs` is the main solver. It is a depth-first search that places one piece at a time against the pieces already down, in contact along edges and corners. Every pruning rule, ordering and symmetry reduction can be switched off, and it can be told to assume that pieces meet edge to edge. +- `cp_sat.placements` hands the placements that search generates to OR-Tools CP-SAT as a choice problem. It is a second formulation over the same candidates, which checks the search's bookkeeping. It is not an independent enumeration of every possible placement. +- `python.contact_dfs` is the Python prototype the Rust search was built from. It has no pruning and no tray symmetry, and is kept as a reference. + +**Three information regimes,** never compared with each other: **footprint**, the polygons only (the app's *Flat* mode); **relief**, the polygons and the planes of their roofs (*Relief* mode); and *tropical-aware*, which would add the construction data and which no solver uses yet. On top of a regime, a solver may make an **assumption**. Today the only one is `edge-to-edge`: it narrows which assemblies count, so results under it are reported separately. + +**Reproduce the tables:** + +```sh +uv run maxplus-bench run benchmarks/manifests/corpus.toml --no-times # benchmarks/results/corpus.md +uv run maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times # benchmarks/results/edge_to_edge.md +``` + +Each takes several minutes, most of it on the footprints that run to the node limit. The committed tables hold statuses and counts only, which a deterministic solver reproduces exactly, and the test suite compares every row it can afford to rerun. [docs/experiments.md](docs/experiments.md) has the other experiments (tolerance, heuristics, difficulty proxies) and what they found. ## What we've learned so far -Three findings from the corpus so far, in plain terms. The details and the caveats are in the linked documents. +Four findings, in plain terms. Unless a finding says otherwise, every number is a count of search-tree nodes from `rust.contact_dfs` with default options and tolerances, in a search that ran to its end and assumed nothing. Puzzles are named by fixture id, with the app's name on first use (see [the table below](#names-in-the-puzzle-app)). -- **The third dimension changes the search problem.** `new1` has 16 pieces. Laid flat, the search needs 1 064 878 nodes to find its assembly and show there is no other. With the roofs on, the same pieces need 68 nodes, a difference of more than four orders of magnitude. The roofs work by saying which edges can meet: on average a piece edge has between 1 and 7 possible partners with roofs, and about 77 of 82 on flat `new1`. These counts are nodes in this solver's search tree. They are not running times and not a measure of how hard the puzzle is for a person. ([experiments](docs/experiments.md#flat-against-relief-tolerance-heuristic-puzzle)) -- **Knowing the structure can matter more than a better search.** Tropical cuts never leave a T-junction between pieces. Searching only for assemblies whose pieces meet edge to edge takes flat `new1` from 1 064 878 nodes to 49, which is fewer than the roofs alone need. Finding the right structure did more here than any improvement to the search algorithm. This is an assumption, though, and not a shortcut: it narrows which assemblies count. For example, `rat1` laid flat has 101 assemblies, and only the intended one has no T. ([algorithms](docs/algorithms.md#assuming-the-pieces-meet-edge-to-edge)) -- **Difficulty has more than one dimension.** The number of pieces is not a reliable guide. Two nine-piece flat puzzles cost 45 and 6 104 nodes, more than two orders of magnitude apart. Ambiguity varies as well: the 11-piece `rat1` has 101 assemblies without its roofs and one with them. ([difficulty proxies](docs/experiments.md#difficulty-proxies)) +- **The third dimension changes the search problem.** `new1` (Hill 16a) has 16 pieces. In the footprint regime the search needs 1 064 878 nodes to find its assembly and show there is no other. With its roofs, the same pieces need 68 nodes, more than four orders of magnitude fewer. The roofs work by saying which edges can meet. A piece edge of flat `new1` could lie against about 77 of the 82 edges on average. With roofs, the average is 1.2 to 6.7 possible partners on every relief puzzle except Pleat (below). ([experiments](docs/experiments.md#flat-against-relief-tolerance-heuristic-puzzle)) +- **Knowing the structure can matter more than a better search.** Tropical cuts never leave a T-junction between pieces. Assuming the pieces meet edge to edge takes flat `new1` from 1 064 878 nodes to 49, fewer than its roofs alone need. Finding that structure helped more here than any improvement to the search. It is an assumption, though, not a shortcut, because it narrows which assemblies count. For example, `rat1-flat` (Terrain 11a, flat) has 101 assemblies, and only the intended one has no T. ([algorithms](docs/algorithms.md#assuming-the-pieces-meet-edge-to-edge)) +- **Difficulty has more than one dimension.** The number of pieces is not a reliable guide. Two nine-piece footprints, `rev2-flat` (Bowl 9a) and `new3-flat` (Hill 9a), cost 45 and 6 104 nodes. Ambiguity varies as well: the 11-piece `rat1` has 101 assemblies without its roofs and one with them. ([difficulty proxies](docs/experiments.md#difficulty-proxies)) +- **Roofs can be made to help less.** The Pleat puzzles were built for this in Tropical Puzzle Lab. They stand every corner of a grid of triangles at one of just two heights, so even with roofs an edge has 16 to 24 possible partners on average. With its roofs, the hardest, `plt1` (Pleat 32a, 32 pieces), takes 21 973 nodes and has one assembly. That compares with 1 529 for `cor1` (Corrugated 27a) and at most 94 for the other relief puzzles. Without roofs, every Pleat search was stopped at the node limit, having found at least 26 998 to 95 344 assemblies and still finding more. With roofs and assuming edge to edge, `plt1` takes 749 nodes. CP-SAT, given the same placements, settles every Pleat relief puzzle without a single conflict (its own count, from a run by hand). So the Pleat puzzles are hard for this search, not for every method. ([experiments](docs/experiments.md#the-corpus-table)) -- **Roofs can be made to help less.** The Pleat puzzles, built for this in Tropical Puzzle Lab, stand every corner of a grid of triangles at one of just two heights, so many edges look alike even with their roofs. The hardest, `plt1` with 32 pieces, takes 21 973 nodes with its roofs on and still has one assembly, against 1 529 for `cor1` and at most 94 for the rest. Without roofs the same triangles fit together in tens of thousands of ways. Assuming edge to edge brings it down to 749 nodes, and CP-SAT settles it without a single conflict, so it is hard for this search, not for every method. ([experiments](docs/experiments.md#the-corpus-table)) +One question is still open. `cor1`, with 27 pieces, was built to be hard, and its footprint search has not been seen to finish: it was stopped without an assembly at 1 500 000 nodes in the table and at 3 000 000 by hand. Assuming edge to edge, it does finish, with 48 assemblies in 44 539 nodes. -One question is still open. `cor1`, with 27 pieces, was built to be hard, and its flat search has not been seen to finish. Everything above is computational evidence, not proof. It is relative to the placements the solvers generate and to floating-point arithmetic with stated tolerances. [docs/solver-contract.md](docs/solver-contract.md) says exactly what a result claims. +## What the numbers are, and are not -## Status +- **Relative to the candidates.** A solver searches the placements it generates: pieces in contact along edges and corners, within a contact tolerance. "One assembly" means a search that ran to its end over that candidate set found exactly one. It is not a proof that no other assembly exists. Every result names its candidate set and says whether that set is proven complete (so far, it never is). +- **Floating point.** The geometry is `f64` with explicit, stated tolerances, not exact arithmetic. Nothing here is a mathematical proof. +- **Exact counts and lower bounds.** In the tables, "Whole search: yes" means the count is every assembly over the candidate set. "no" means the search hit its node limit, so the assemblies and nodes it reports are lower bounds. +- **Checked independently.** Every assembly in the committed tables passes an independent validator (`python/maxplus_solvers/validation.py`, on Shapely). It shares no code with the search and follows the browser player's completion rules, departing from them only on the stricter side. +- **Search effort, not human difficulty.** Nodes count what this search tried, and depend on its rules. They are not running times, and nothing here has measured a person. -**Contracts and fixtures.** The instance format, the sanitizing importer and the benchmark corpus exist: 28 puzzles from Tropical Puzzle Lab (fourteen 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 22 of the 28 corpus puzzles, and every assembly it returns passes the validator. The other six are footprints it stops at 1 500 000 nodes: `cor1-flat`, built to be hard, and the five Pleat footprints, which have tens of thousands of assemblies each. `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. It is a second formulation over the same candidate set, not an independent enumeration of every possible placement. It checks the search's bookkeeping and pruning, but it cannot find an assembly that uses a placement the search never generated. `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). +[docs/solver-contract.md](docs/solver-contract.md) says exactly what a result claims. -```python -from maxplus_solvers import load_puzzle +## Names in the puzzle app -puzzle = load_puzzle("benchmarks/fixtures/new2.json") -flat = load_puzzle( - "benchmarks/fixtures/new2.json", regime="footprint" -) # the same pieces without roofs +The app shows puzzles by name, with a **Relief | Flat** switch. Here they are fixture ids: the id is the relief puzzle, and `-flat` the same footprints without roofs (the footprint regime). An assembly here is what the app calls a solution: a placement of every piece that passes the completion rules. + +| Id | App name | Pieces | | Id | App name | Pieces | +| --- | --- | --- | --- | --- | --- | --- | +| `new5` | Hill 6a | 6 | | `rat2` | Terrain 20a | 20 | +| `new3` | Hill 9a | 9 | | `cor1` | Corrugated 27a | 27 | +| `new4` | Hill 9b | 9 | | `plt1` | Pleat 32a | 32 | +| `rev2` | Bowl 9a | 9 | | `plt2` | Pleat 32b | 32 | +| `rat1` | Terrain 11a | 11 | | `plt3` | Pleat 32c | 32 | +| `new1` | Hill 16a | 16 | | `plt4` | Pleat 32d | 32 | +| `new2` | Hill 16b | 16 | | `plt5` | Pleat 24e | 24 | + +The app's 1–5 difficulty rating is derived from this repository's node counts. It describes this search, not a person's experience. + +## Quick start + +You need [uv](https://docs.astral.sh/uv/) and a stable [Rust toolchain](https://rustup.rs/). + +```sh +uv sync # creates .venv, builds the Rust extension, installs the dev tools +uv run pytest # Python tests +cargo test --workspace --exclude tiling-py # Rust tests ``` -Solving, from Python or from the command line: +`uv sync` installs the development group, which includes Shapely (the validator), OR-Tools (CP-SAT) and matplotlib, so everything below works from a fresh checkout. A user installing the package picks these as the extras `validate`, `cp-sat` and `analysis`; the Rust solvers need none of them. `uv sync` and `uv run` rebuild the extension when Rust sources change. -```python -from maxplus_solvers import SolverConfig, solve +Solve a puzzle from the command line: -result = solve(puzzle, SolverConfig("rust.contact_dfs", mode="relief", max_solutions=None)) -print(result.status, len(result.solutions), result.exhaustive, result.metrics["nodes"]) +```sh +uv run maxplus-solve new5-flat --max-solutions all --validate ``` +```text +rust.contact_dfs on 9352aafe3966 (footprint): solved + the search ran to its end; candidates corner-contact/1, not proven complete + solution 1: 6 pieces, valid + nodes=90, backtracks=70, placements=89, candidates_generated=968 + ... +``` + +More examples: + ```sh uv run maxplus-solve new2 --mode relief --max-solutions all --validate -uv run maxplus-solve rat1-flat --max-solutions all --option closure_pruning=false +uv run maxplus-solve new1-flat --assume edge-to-edge --max-solutions all --validate # 49 nodes +uv run maxplus-solve rat1-flat --max-solutions all --option closure_pruning=false # a rule switched off +uv run maxplus-solve rat1-flat --solver cp_sat.placements --max-solutions all ``` -What a result claims, and what it does not, is in [docs/solver-contract.md](docs/solver-contract.md). +Or from Python: -With the `validate` extra (Shapely), poses can be checked against the completion rules: +```python +from maxplus_solvers import SolverConfig, load_puzzle, solve + +puzzle = load_puzzle("benchmarks/fixtures/new2.json") +# The same pieces without roofs: +flat = load_puzzle("benchmarks/fixtures/new2.json", regime="footprint") + +config = SolverConfig("rust.contact_dfs", mode="relief", max_solutions=None) +result = solve(puzzle, config, validate=True) +print(result.status, len(result.solutions), result.exhaustive, result.metrics["nodes"]) +``` + +The validator can also be called on its own, on any poses: ```python from maxplus_solvers.validation import validate_solution @@ -62,17 +120,15 @@ report = validate_solution(puzzle, poses) # poses: {piece id: Pose} print(report.solved, report.failed, report.residuals()) ``` -## Quick start - -You need [uv](https://docs.astral.sh/uv/) and a stable [Rust toolchain](https://rustup.rs/). +## Status -```sh -uv sync # creates .venv and builds the Rust extension -uv run pytest # Python tests -cargo test --workspace --exclude tiling-py # Rust tests -``` +- **Contracts and fixtures.** The corpus is 28 puzzles from Tropical Puzzle Lab: fourteen constructions, each with its roofs and without. There are also 4 synthetic puzzles with known solution counts. Each has an answer key that only tests read. The sanitizing importer strips everything that hints at the answer. +- **Validator.** An independent check of an assembly against the browser player's completion rules. +- **Geometry.** A Rust kernel (separating-axis depth, convex clipping, containment, edge signatures, roof continuity), tested against the validator on random poses of every fixture's pieces. +- **Solvers.** `rust.contact_dfs` runs the search to its end on 22 of the 28 corpus puzzles, and every assembly it returns passes the validator. The other six are footprints it stops at 1 500 000 nodes: `cor1-flat`, and the five Pleat footprints, of which each still has more assemblies to find at the limit. Assuming edge to edge, it finishes all 28. `cp_sat.placements` returns the same assemblies on every puzzle it is given. +- **Experiments.** `maxplus-bench` runs TOML manifests over the corpus and writes the result tables. The findings so far are in [docs/experiments.md](docs/experiments.md), and the measurement behind each search rule is in [docs/algorithms.md](docs/algorithms.md). -`uv sync` and `uv run` rebuild the extension when Rust sources change. +The work is laid out phase by phase in [docs/roadmap.md](docs/roadmap.md), and the design in [docs/architecture.md](docs/architecture.md). ## Layout @@ -91,11 +147,12 @@ notebooks/ a first look at results, with figures scripts/ `import_fixtures.py` regenerates fixtures and answer keys tests/ pytest suites: unit, property, corpus, architecture; answer keys in `tests/keys/` docs/ architecture, roadmap, the solver contract, the algorithms and the experiments +docs/figures/ the figure above, drawn from the committed tables ``` ## Relation to Tropical Puzzle Lab -Tropical Puzzle Lab remains the authority for constructing puzzles. This repository consumes its published `puzzle.json` format and turns it into sanitized solver instances: no reference poses, no construction metadata, pieces rotated and shuffled so that nothing about the stored form hints at the answer. +Tropical Puzzle Lab remains the authority for constructing puzzles and for the rules of completion. This repository reads its published `puzzle.json` format and turns each puzzle into a sanitized solver instance: no reference poses, no construction metadata, and pieces rotated and shuffled so that nothing about the stored form hints at the answer. The fixtures record the source commit they were imported from. ## License diff --git a/docs/experiments.md b/docs/experiments.md index f29c289..72ba9f3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16,7 +16,7 @@ uv run maxplus-bench proxies --results benchmarks/results/corpus.jsonl # difficu `run` writes one JSON line per run to `benchmarks/results/.jsonl` (`--out` to choose), prints the table, and with `--table FILE` writes it too. It exits with 1 if any run could not be made. `--no-times` leaves out times and CP-SAT's own counts, which depend on the machine and the OR-Tools build; what is left is reproduced exactly by a deterministic solver. `--only FIXTURE...` runs a manifest on some of its fixtures, every run on them unchanged: its table is the full table's rows for those fixtures. -`benchmarks/results/corpus.md` is the committed table of the corpus manifest: every registered solver on every corpus puzzle it can run. The command above reproduces it. `tests/corpus/test_benchmark.py` reproduces all of it but the rows of the footprints that take a million nodes or more (`cor1-flat`, `new1-flat`, `new2-flat`) and of `rat2-flat`, where CP-SAT takes over a minute: it runs the command `--only` on the rest and compares those rows exactly. The rows it leaves out are checked only by running the full command, about six minutes; the test reads them to hold them to what the documents say of them. The `.jsonl` files are not committed. +`benchmarks/results/corpus.md` is the committed table of the corpus manifest: every registered solver on every corpus puzzle it can run. The command above reproduces it. `tests/corpus/test_benchmark.py` reproduces all of it but the rows of the expensive fixtures (`support.corpus.EXPENSIVE`: the footprints that take a million nodes or more, `cor1-flat`, `new1-flat` and `new2-flat`, and all ten Pleat fixtures) and of `rat2-flat`, where CP-SAT takes over a minute: it runs the command `--only` on the rest and compares those rows exactly. The rows it leaves out are checked only by running the full command by hand; the test reads them to hold them to what the documents say of them. The `.jsonl` files are not committed. Needs the `validate` extra for the validity columns and the `cp-sat` extra for `cp_sat.placements`. A run whose solver cannot be loaded is recorded as an error and the rest go on. @@ -63,7 +63,7 @@ One JSON object per line: | Field | Meaning | | --- | --- | -| `manifest`, `fixture`, `kind`, `construction`, `pieces`, `fixtureRegime` | What was run on. `construction` is the source's family (`new`, `rat`, `rev`). | +| `manifest`, `fixture`, `kind`, `construction`, `pieces`, `fixtureRegime` | What was run on. `construction` is the source's family (`new`, `rat`, `rev`, `cor`, `plt`). | | `solver`, `solverVersion`, `mode`, `contactScale` | Who ran it and in which regime. | | `config` | The whole `SolverConfig` as run: options, seed, limits and the tolerances after scaling. | | `instanceHash` | The hash of the instance, as in `SolveResult`. | @@ -83,8 +83,8 @@ One metric was added for this. `backtrack_depth` is the sum, over dead ends, of - Both production solvers finish every corpus puzzle but `cor1-flat` and the five Pleat footprints, 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 the puzzles built to be hard with their roofs on: `cor1`, 1 529, and the five Pleat puzzles, 7 488 to 21 973 (below). Without roofs, 45 to 1 064 878 where it ends. -- The footprints have one assembly each, except `rat1-flat` (101), `rat2-flat` (2) and the Pleat footprints, stopped at the limit with 26 998 to 95 344 assemblies found and still finding more. -- **Pleat**, the hardest relief puzzles. Tropical Puzzle Lab's `plt1` to `plt5` are a grid of rectangles, each cut along a diagonal, with every grid corner at one of two heights. An edge then has one of four height profiles, so the roofs leave it many possible mates: a mean degree of 16 to 24 in the edge graph, against at most 6.7 for every other relief puzzle (`test_benchmark.py`). The roofs still single out one assembly, but only late: the four 4 x 4 puzzles (32 pieces) take 10 787 to 21 973 nodes, the 4 x 3 one 7 488. What makes them hard is specific to this search. Assuming edge to edge, they take 436 to 749 nodes, fewer than `cor1`'s 967, because most wrong matches are a short edge part way along a long one. Without roofs, under the same assumption, the search ends: 288 assemblies on each 4 x 4 grid and 72 on the 4 x 3 one, in 5 566 to 41 068 nodes ([edge_to_edge.md](../benchmarks/results/edge_to_edge.md)). CP-SAT, choosing among the same placements, settles each without a conflict: propagation alone decides it once the placements are listed. Designs that failed on the way (breaking a symmetric roof at one place, fans of triangles, three heights) are in each puzzle's `provenance.md` in Tropical Puzzle Lab. +- The footprints have one assembly each, except `rat1-flat` (101), `rat2-flat` (2) and the Pleat footprints, stopped at the limit with 26 998 to 95 344 assemblies found and still finding more: lower bounds, not counts. +- **Pleat**, the hardest relief puzzles. Tropical Puzzle Lab's `plt1` to `plt5` are a grid of rectangles, each cut along a diagonal, with every grid corner at one of two heights. An edge then has one of four height profiles, so the roofs leave it many possible mates: a mean degree of 16 to 24 in the edge graph, against at most 6.7 for every other relief puzzle (`test_benchmark.py`). The roofs still single out one assembly, but only late: the four 4 x 4 puzzles (32 pieces) take 10 787 to 21 973 nodes, the 4 x 3 one 7 488. What makes them hard is specific to this search. Assuming edge to edge, they take 436 to 749 nodes, fewer than `cor1`'s 967, because most wrong matches are a short edge part way along a long one. Without roofs, under the same assumption, the search ends: 288 assemblies on each 4 x 4 grid and 72 on the 4 x 3 one, in 5 566 to 41 068 nodes ([edge_to_edge.md](../benchmarks/results/edge_to_edge.md)). CP-SAT, choosing among the same placements, settles each without a conflict: propagation alone decides it once the placements are listed. (CP-SAT's own counts belong to a machine and are not in the committed table; `tests/corpus/test_cp_sat.py` holds the other relief puzzles to zero conflicts, and the Pleat ones were run by hand.) Designs that failed on the way (breaking a symmetric roof at one place, fans of triangles, three heights) are in each puzzle's `provenance.md` in Tropical Puzzle Lab. - Listing tens of thousands of assemblies exposed a cost in the search itself: each new assembly was compared with every earlier one, so the cost grew with the square of the number found, about nine hours for one Pleat footprint. It now bisects a sorted list of canonical forms (`canonical::Form`), with the same assemblies found and counted. - 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`. @@ -226,7 +226,7 @@ The stopped searches make these tables machine-dependent at the 16-piece footpri | `new2-flat` | 16 | 82 | 76.7 | 0 | 128 | 4.78 | 4 | 909 750 | 5.72 | 22.0 | | `new1-flat` | 16 | 82 | 76.7 | 0 | 256 | 6.43 | 3 | 1 064 878 | 6.03 | 32.5 | -The source's numbers are the Leinster–Cobbold diversity of the pieces' intrinsic volumes and the one-to-five rating it derives from it, copied into `benchmarks/fixtures/index.json` by the importer. The source reads lower diversity as harder. +The source's numbers are the Leinster–Cobbold diversity of the pieces' intrinsic volumes and the one-to-five rating, copied into `benchmarks/fixtures/index.json` by the importer. The source reads lower diversity as harder. The ratings in this table are the ones the source derived from diversity when the table was made. Since Tropical Puzzle Lab `cfe2c8b` (2026-11-15) the source's rating is computed from this repository's node counts instead, so `maxplus-bench proxies` on today's fixtures shows other ratings, and correlating them with nodes would only measure the search against itself. The "Source rating" column and its correlations below are a record of the earlier, diversity-based rating. Spearman rank correlation with the nodes of the whole search, within each regime, eight puzzles in each: @@ -247,7 +247,7 @@ What it shows, with eight points behind each coefficient: - **Degree is the regime.** Without roofs a piece edge can lie against nearly every other edge (mean degree 77 of 82 on `new1-flat`) and no edge has a unique mate. With roofs the mean degree is 1.2 to 6.7. That one number separates the two regimes completely, and within relief it ranks the puzzles almost exactly. Roofs make a puzzle easy by saying which edges can meet. - **Without roofs, size and depth.** The number of pieces ranks the footprints as well as anything static does, and what tracks the cost best is how deep the dead ends are, which is known only after searching. The static proxies do not see why `new3-flat` costs twelve times `new4-flat` with the same number of pieces and edges and the same mean degree. Its symmetry count is twice as large; that is one data point. -- **The source's rating is about people.** It ranks the relief puzzles much as the search does (+0.85) and the footprints less well (+0.54). Its diversity runs the wrong way for a search: the source reads lower diversity as harder, and here higher diversity goes with more nodes, weakly. The rating is designed for a person matching walls, not for this search, and the corpus is too small to say more. +- **The source's earlier rating was about people.** The diversity-based rating ranks the relief puzzles much as the search does (+0.85) and the footprints less well (+0.54). Its diversity runs the wrong way for a search: the source reads lower diversity as harder, and here higher diversity goes with more nodes, weakly. The rating is designed for a person matching walls, not for this search, and the corpus is too small to say more. - **`rev2` is the outlier that explains the rest.** Three quarters of its edges have exactly one mate, its mean degree is 1.19, and it is the cheapest puzzle in both regimes although it has nine pieces. 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. @@ -260,7 +260,9 @@ Correlations are taken within a regime only. Across both, any number that differ ## 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. +`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. `regimes_at_a_glance` draws the README's figure, [`docs/figures/at-a-glance.svg`](figures/at-a-glance.svg): for each construction, the whole-search nodes of `rust.contact_dfs` without roofs, with roofs, and without roofs assuming edge to edge (both of the assumption's rules on), on a log scale. It reads the committed tables, not records, so `uv run maxplus-bench figure` redraws it without searching; a footprint search stopped at the node limit is an open arrow at 1 500 000, a lower bound. `tests/corpus/test_figure.py` holds the committed file to the tables. When a solver change moves a count, regenerate the tables, then the figure. + +`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 diff --git a/docs/figures/at-a-glance.svg b/docs/figures/at-a-glance.svg new file mode 100644 index 0000000..a08f011 --- /dev/null +++ b/docs/figures/at-a-glance.svg @@ -0,0 +1,2143 @@ + + + + + + + + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/python/maxplus_solvers/experiments/cli.py b/python/maxplus_solvers/experiments/cli.py index be27d33..c598464 100644 --- a/python/maxplus_solvers/experiments/cli.py +++ b/python/maxplus_solvers/experiments/cli.py @@ -3,7 +3,8 @@ ``maxplus-bench run MANIFEST`` runs every run the manifest names, writes one JSON line per run and prints the results table. ``maxplus-bench table FILE`` prints the table of a results file again. ``maxplus-bench proxies`` prints the -difficulty proxies of the corpus beside the source's rating. +difficulty proxies of the corpus beside the source's rating. ``maxplus-bench +figure`` draws the committed tables as one figure (the ``analysis`` extra). """ import argparse @@ -18,6 +19,7 @@ DEFAULT_FIXTURES = Path("benchmarks") / "fixtures" DEFAULT_RESULTS = Path("benchmarks") / "results" +DEFAULT_FIGURE = Path("docs") / "figures" / "at-a-glance.svg" def _parser() -> argparse.ArgumentParser: @@ -60,9 +62,30 @@ def _parser() -> argparse.ArgumentParser: prox.add_argument( "--solver", default="rust.contact_dfs", help="whose records to read from --results" ) + + fig = commands.add_parser( + "figure", help="draw the committed corpus and edge-to-edge tables as one figure" + ) + fig.add_argument( + "--results", + type=Path, + default=DEFAULT_RESULTS, + help="where corpus.md and edge_to_edge.md are", + ) + fig.add_argument("--out", type=Path, default=DEFAULT_FIGURE, help="the file to write") return parser +def glance_figure(results: Path, out: Path) -> None: + """Draw ``corpus.md`` and ``edge_to_edge.md`` from ``results`` into ``out``.""" + # Imported here: every other command runs without the plotting stack. + from maxplus_solvers.experiments import plotting + + corpus = report.parse_markdown((results / "corpus.md").read_text(encoding="utf-8")) + e2e = report.parse_markdown((results / "edge_to_edge.md").read_text(encoding="utf-8")) + plotting.save(plotting.regimes_at_a_glance(corpus, e2e), out) + + def _progress(record: Mapping[str, Any]) -> None: options = record["config"]["options"] setting = " ".join(f"{name}={value}" for name, value in sorted(options.items())) @@ -178,6 +201,13 @@ def main(argv: Sequence[str] | None = None) -> int: args.table.write_text(text, encoding="utf-8", newline="\n") print(text, end="") return 1 if any(record["status"] == "error" for record in records) else 0 + if args.command == "figure": + try: + glance_figure(args.results, args.out) + except ValueError as error: # a committed table that cannot be read + parser.error(str(error)) + print(args.out) + return 0 if args.command == "table": print(report.table(benchmark.read(args.results), times=not args.no_times), end="") return 0 diff --git a/python/maxplus_solvers/experiments/plotting.py b/python/maxplus_solvers/experiments/plotting.py index d0377cd..9dd92f9 100644 --- a/python/maxplus_solvers/experiments/plotting.py +++ b/python/maxplus_solvers/experiments/plotting.py @@ -1,7 +1,8 @@ """Figures from benchmark records. Needs matplotlib, the ``analysis`` extra. -Each function takes records as :func:`benchmark.read` returns them and gives -back a matplotlib figure; nothing is shown or saved unless asked. The figures +Each function takes records as :func:`benchmark.read` returns them, or for +:func:`regimes_at_a_glance` the rows of committed tables, and gives back a +matplotlib figure; nothing is shown or saved unless asked. The figures are drawn off-screen, so they can be made on a machine without a display. """ @@ -9,6 +10,7 @@ from pathlib import Path from typing import Any +from matplotlib import rc_context from matplotlib.figure import Figure @@ -76,7 +78,112 @@ def proxy_against_cost( return figure +GLANCE_SOLVER = "rust.contact_dfs" + +# The series of the figure below, in drawing order: label, marker, filled. +GLANCE_SERIES = ( + ("flat, assuming nothing", "o", True), + ("flat, stopped at the node limit (a lower bound)", ">", False), + ("relief, assuming nothing", "s", True), + ("flat, assuming edge to edge", "D", True), +) + + +def _glance_points( + corpus_rows: Sequence[Mapping[str, str]], e2e_rows: Sequence[Mapping[str, str]] +) -> tuple[list[tuple[str, int]], dict[str, dict[str, int]]]: + """Constructions with their piece counts, and nodes by series and construction.""" + + def need(row: Mapping[str, str], *columns: str) -> None: + missing = [c for c in columns if c not in row] + if missing: + raise ValueError(f"table row lacks the columns {missing}") + + def nodes(text: str) -> int: + return int(text.replace(" ", "")) + + solver = f"`{GLANCE_SOLVER}`" + pieces: dict[str, int] = {} + series: dict[str, dict[str, int]] = {label: {} for label, _, _ in GLANCE_SERIES} + for row in corpus_rows: + need(row, "Fixture", "Pieces", "Solver", "Mode", "Whole search", "Nodes") + if row["Solver"] != solver: + continue + construction = row["Fixture"].strip("`").removesuffix("-flat") + pieces[construction] = int(row["Pieces"]) + if row["Mode"] == "relief": + label = GLANCE_SERIES[2][0] + elif row["Whole search"] == "yes": + label = GLANCE_SERIES[0][0] + else: + label = GLANCE_SERIES[1][0] + series[label][construction] = nodes(row["Nodes"]) + for row in e2e_rows: + need(row, "Fixture", "Solver", "Mode", "assumes", "equal_edges", "wall_edges", "Nodes") + chosen = (row["Solver"], row["Mode"], row["assumes"], row["equal_edges"], row["wall_edges"]) + if chosen == (solver, "footprint", "edge-to-edge", "true", "true"): + construction = row["Fixture"].strip("`").removesuffix("-flat") + series[GLANCE_SERIES[3][0]][construction] = nodes(row["Nodes"]) + order = sorted(pieces.items(), key=lambda item: (item[1], item[0])) + return order, series + + +def regimes_at_a_glance( + corpus_rows: Sequence[Mapping[str, str]], e2e_rows: Sequence[Mapping[str, str]] +) -> Figure: + """Whole-search nodes of each construction, flat, with roofs, and flat assuming edge to edge. + + Takes the rows of the committed tables ``benchmarks/results/corpus.md`` and + ``edge_to_edge.md`` as :func:`report.parse_markdown` reads them, so it needs no + search. Only ``rust.contact_dfs`` is drawn, with both edge-to-edge rules on. + A flat search stopped at the node limit is drawn as an open arrow at the limit: + the true count is larger. + """ + order, series = _glance_points(corpus_rows, e2e_rows) + figure = Figure(figsize=(7.0, 0.32 * len(order) + 1.6), layout="constrained") + axes = figure.add_subplot() + axes.set_title("Search effort: roofs, and the edge-to-edge assumption", fontsize="medium") + axes.set_xlabel(f"search-tree nodes of the whole search ({GLANCE_SOLVER}), log scale") + rows = {construction: index for index, (construction, _) in enumerate(order)} + axes.set_yticks( + range(len(order)), [f"{construction} ({count})" for construction, count in order] + ) + for construction, index in rows.items(): + values = [points[construction] for points in series.values() if construction in points] + if values: + axes.plot([min(values), max(values)], [index, index], color="0.85", zorder=1) + for (label, marker, filled), color in zip( + GLANCE_SERIES, ("tab:red", "tab:red", "tab:blue", "tab:green"), strict=True + ): + points = series[label] + if not points: + continue + axes.scatter( + [points[c] for c in points], + [rows[c] for c in points], + marker=marker, + s=36, + label=label, + facecolors=color if filled else "none", + edgecolors=color, + zorder=2, + ) + axes.set_xscale("log") + axes.invert_yaxis() + axes.set_ylabel("construction (pieces)") + axes.grid(axis="x", color="0.92") + axes.legend(fontsize="x-small", loc="upper right") + return figure + + def save(figure: Figure, path: Path) -> None: - """Write a figure to a file; the suffix chooses the format.""" + """Write a figure to a file; the suffix chooses the format. + + An SVG carries no date and a fixed id salt, so the same figure is the same file. + """ path.parent.mkdir(parents=True, exist_ok=True) - figure.savefig(path, dpi=150) + if path.suffix == ".svg": + with rc_context({"svg.hashsalt": "maxplus-solvers"}): + figure.savefig(path, metadata={"Date": None}) + else: + figure.savefig(path, dpi=150) diff --git a/python/maxplus_solvers/experiments/report.py b/python/maxplus_solvers/experiments/report.py index 8a2d002..48515e1 100644 --- a/python/maxplus_solvers/experiments/report.py +++ b/python/maxplus_solvers/experiments/report.py @@ -112,6 +112,34 @@ def markdown(cells: Sequence[Sequence[str]]) -> str: return "\n".join(lines) + "\n" +def parse_markdown(text: str) -> list[dict[str, str]]: + """A table written by :func:`markdown`, read back: one dict per body row, by header. + + Cells are stripped and otherwise kept as written (backticks, spaced + thousands). A table without its rule, or with a row of the wrong width, + is refused, so that a damaged file is not read as a shorter table. + """ + + def cells(line: str) -> list[str]: + line = line.strip() + if not (line.startswith("|") and line.endswith("|")): + raise ValueError(f"not a table row: {line!r}") + return [cell.strip() for cell in line[1:-1].split("|")] + + lines = [line for line in text.splitlines() if line.strip()] + if len(lines) < 2: + raise ValueError("a table needs a header and a rule") + header, rule, *body = (cells(line) for line in lines) + if len(rule) != len(header) or any(set(cell) - {"-", ":"} or not cell for cell in rule): + raise ValueError("the second line of a table must be its rule") + rows: list[dict[str, str]] = [] + for number, row in enumerate(body, start=3): + if len(row) != len(header): + raise ValueError(f"line {number} has {len(row)} cells, the header {len(header)}") + rows.append(dict(zip(header, row, strict=True))) + return rows + + def table(records: Sequence[Mapping[str, Any]], *, times: bool = True) -> str: """The results table of an experiment, as Markdown.""" return markdown(rows(records, times=times)) diff --git a/tests/architecture/test_doc_links.py b/tests/architecture/test_doc_links.py new file mode 100644 index 0000000..4c9a046 --- /dev/null +++ b/tests/architecture/test_doc_links.py @@ -0,0 +1,111 @@ +"""What the documents point at exists: relative links, their anchors, and quoted repository paths. + +A public reader follows the README and ``docs/`` to tables, fixtures, the validator +and the figure. A renamed file or heading must break this test, not the reader's click. +""" + +import re +import subprocess +from pathlib import Path + +import pytest + +from support import corpus + +ROOT = corpus.ROOT +DOCUMENTS = [ROOT / "README.md", ROOT / "CLAUDE.md", *sorted((ROOT / "docs").glob("*.md"))] + +LINK = re.compile(r"\]\(([^)\s]+)\)") +CODE_SPAN = re.compile(r"`([^`\s]+)`") +# A code span is taken for a path when it starts at one of these and names no pattern. +TOP_LEVEL = ("benchmarks/", "crates/", "docs/", "notebooks/", "python/", "schemas/", "scripts/", + "tests/", ".github/") # fmt: skip +SIBLING = re.compile(r"tropical.puzzle.lab", re.IGNORECASE) +# Generated on a machine and never committed (CLAUDE.md: a committed table has no times). +NOT_COMMITTED = (".jsonl",) + + +def slug(heading: str) -> str: + """GitHub's anchor for a heading: lower case, punctuation dropped, spaces to hyphens.""" + text = re.sub(r"[`*]", "", heading.strip().lower()) + text = re.sub(r"[^\w\- ]", "", text) + return text.replace(" ", "-") + + +def anchors(path: Path) -> set[str]: + text = path.read_text(encoding="utf-8") + text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) # no headings inside code blocks + return {slug(line.lstrip("#")) for line in text.splitlines() if re.match(r"#{1,6} ", line)} + + +def broken_links(document: Path) -> list[str]: + text = document.read_text(encoding="utf-8") + broken: list[str] = [] + for target in LINK.findall(text): + if re.match(r"[a-z]+:", target): # https:, mailto: + continue + file_part, _, anchor = target.partition("#") + path = (document.parent / file_part).resolve() if file_part else document + if not path.exists() or (anchor and path.suffix == ".md" and anchor not in anchors(path)): + broken.append(target) + return broken + + +def missing_paths(document: Path) -> list[str]: + text = document.read_text(encoding="utf-8") + missing: list[str] = [] + # A line about Tropical Puzzle Lab quotes that repository's paths, not this one's. + own = "\n".join(line for line in text.splitlines() if not SIBLING.search(line)) + for span in CODE_SPAN.findall(own): + path = span.split("::")[0].rstrip(".,:") + if not path.startswith(TOP_LEVEL) or any(c in path for c in "*<>{}"): + continue + if path.endswith(NOT_COMMITTED): + continue + if not (ROOT / path).exists(): + missing.append(span) + return missing + + +@pytest.mark.parametrize("document", DOCUMENTS, ids=lambda p: p.relative_to(ROOT).as_posix()) +def test_every_relative_link_resolves(document: Path) -> None: + assert broken_links(document) == [] + + +@pytest.mark.parametrize("document", DOCUMENTS, ids=lambda p: p.relative_to(ROOT).as_posix()) +def test_every_quoted_repository_path_exists(document: Path) -> None: + assert missing_paths(document) == [] + + +def test_a_broken_link_and_a_missing_path_are_caught(tmp_path: Path) -> None: + # The guard itself, on a document written to fail: a missing file, a missing anchor, + # and a quoted path that does not exist. The good link and path must pass. + (tmp_path / "other.md").write_text("# A heading, with `code`\n", encoding="utf-8") + document = tmp_path / "doc.md" + document.write_text( + "[ok](other.md#a-heading-with-code) [gone](nowhere.md) [bad](other.md#no-such)\n" + "`docs/roadmap.md` `docs/no-such-file.md`\n", + encoding="utf-8", + ) + assert broken_links(document) == ["nowhere.md", "other.md#no-such"] + assert missing_paths(document) == ["docs/no-such-file.md"] + + +def test_every_linked_file_is_committed() -> None: + """A link to a file that exists only on this machine is as broken as a missing one.""" + tracked = set( + subprocess.run( + ["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True + ).stdout.splitlines() + ) + untracked: list[str] = [] + for document in DOCUMENTS: + for target in LINK.findall(document.read_text(encoding="utf-8")): + file_part = target.partition("#")[0] + if not file_part or re.match(r"[a-z]+:", target): + continue + path = (document.parent / file_part).resolve() + relative = path.relative_to(ROOT).as_posix() + if path.is_file() and relative not in tracked: + untracked.append(relative) + assert untracked == [] diff --git a/tests/corpus/test_figure.py b/tests/corpus/test_figure.py new file mode 100644 index 0000000..41d3f91 --- /dev/null +++ b/tests/corpus/test_figure.py @@ -0,0 +1,66 @@ +"""The committed figure, ``docs/figures/at-a-glance.svg``, is drawn from the committed tables. + +``maxplus-bench figure`` writes it from ``benchmarks/results/corpus.md`` and +``edge_to_edge.md``. The bytes are not compared, since the glyphs depend on the +matplotlib build. What is compared are the labels matplotlib writes into the SVG as +comments, and the points of a fresh drawing against values read off the tables by hand. +""" + +import re +from pathlib import Path + +import numpy as np +import pytest + +from maxplus_solvers.experiments import plotting, report +from maxplus_solvers.experiments.cli import main +from support import corpus + +RESULTS = corpus.ROOT / "benchmarks" / "results" +FIGURE = corpus.ROOT / "docs" / "figures" / "at-a-glance.svg" +CONSTRUCTIONS = sorted({f.removesuffix("-flat") for f in corpus.fixture_ids(kind="corpus")}) + + +def read(name: str) -> list[dict[str, str]]: + return report.parse_markdown((RESULTS / name).read_text(encoding="utf-8")) + + +def labels_in(svg: str) -> set[str]: + return set(re.findall(r"", svg)) + + +def test_the_committed_figure_names_every_construction_and_series() -> None: + labels = labels_in(FIGURE.read_text(encoding="utf-8")) + pieces = {row["Fixture"].strip("`"): row["Pieces"] for row in read("corpus.md")} + assert {f"{c} ({pieces[c]})" for c in CONSTRUCTIONS} <= labels + assert {label for label, _, _ in plotting.GLANCE_SERIES} <= labels + + +def test_the_committed_figure_is_what_the_command_draws_now(tmp_path: Path) -> None: + out = tmp_path / "glance.svg" + assert main(["figure", "--results", str(RESULTS), "--out", str(out)]) == 0 + assert labels_in(out.read_text(encoding="utf-8")) == labels_in( + FIGURE.read_text(encoding="utf-8") + ) + + +@pytest.mark.parametrize( + ("series", "construction", "nodes"), + [ + # Read off benchmarks/results/corpus.md and edge_to_edge.md by hand. + ("flat, assuming nothing", "new1", 1_064_878), + ("relief, assuming nothing", "new1", 68), + ("flat, assuming edge to edge", "new1", 49), + ("relief, assuming nothing", "plt1", 21_973), + ("flat, stopped at the node limit (a lower bound)", "cor1", 1_500_000), + ("flat, assuming edge to edge", "cor1", 44_539), + ], +) +def test_the_figure_places_points_from_the_tables( + series: str, construction: str, nodes: int +) -> None: + (axes,) = plotting.regimes_at_a_glance(read("corpus.md"), read("edge_to_edge.md")).axes + ticks = [label.get_text().split(" ")[0] for label in axes.get_yticklabels()] + collection = next(c for c in axes.collections if c.get_label() == series) + points = {ticks[int(y)]: x for x, y in np.asarray(collection.get_offsets(), dtype=float)} + assert points[construction] == pytest.approx(nodes, abs=1e-9) diff --git a/tests/unit/test_plotting.py b/tests/unit/test_plotting.py index 82f7bd2..4a09e65 100644 --- a/tests/unit/test_plotting.py +++ b/tests/unit/test_plotting.py @@ -80,6 +80,82 @@ def test_a_proxy_is_drawn_against_a_cost_for_the_fixtures_that_have_both() -> No assert (axes.get_xlabel(), axes.get_ylabel()) == ("mean_degree", "nodes") +# --- the figure at a glance, from rows of the committed tables ---------------------------- + + +def corpus_row(fixture: str, pieces: int, mode: str, whole: str, nodes: str) -> dict[str, str]: + return { + "Fixture": f"`{fixture}`", + "Pieces": str(pieces), + "Solver": "`rust.contact_dfs`", + "Mode": mode, + "Whole search": whole, + "Nodes": nodes, + } + + +def e2e_row(fixture: str, mode: str, equal: str, wall: str, nodes: str) -> dict[str, str]: + return { + "Fixture": f"`{fixture}`", + "Solver": "`rust.contact_dfs`", + "Mode": mode, + "assumes": "edge-to-edge", + "equal_edges": equal, + "wall_edges": wall, + "Nodes": nodes, + } + + +# Rows in the shape report.parse_markdown gives: one construction whose flat search +# ended, one stopped at the limit, and rows the figure must ignore. +CORPUS_ROWS = [ + corpus_row("a", 4, "relief", "yes", "12"), + corpus_row("a-flat", 4, "footprint", "yes", "1 234"), + corpus_row("b", 9, "relief", "yes", "300"), + corpus_row("b-flat", 9, "footprint", "no", "1 500 000"), + {**corpus_row("a-flat", 4, "footprint", "yes", "7"), "Solver": "`cp_sat.placements`"}, +] +E2E_ROWS = [ + e2e_row("a-flat", "footprint", "true", "true", "20"), + e2e_row("a-flat", "footprint", "false", "true", "99"), # one rule off: not drawn + e2e_row("b-flat", "footprint", "true", "true", "5 000"), + e2e_row("b", "relief", "true", "true", "77"), # relief under the assumption: not drawn +] + + +def test_the_glance_draws_each_construction_in_its_three_regimes() -> None: + (axes,) = plotting.regimes_at_a_glance(CORPUS_ROWS, E2E_ROWS).axes + series = {str(c.get_label()): values(c.get_offsets()) for c in axes.collections} + # Rows go by pieces: a (4 pieces) at y 0, b (9) at y 1. Values from the rows above. + assert series["flat, assuming nothing"] == [[1234, 0]] + assert series["flat, stopped at the node limit (a lower bound)"] == [[1_500_000, 1]] + assert series["relief, assuming nothing"] == [[12, 0], [300, 1]] + assert series["flat, assuming edge to edge"] == [[20, 0], [5000, 1]] + assert [label.get_text() for label in axes.get_yticklabels()] == ["a (4)", "b (9)"] + assert axes.get_xscale() == "log" + + +def test_a_stopped_search_is_an_open_marker() -> None: + (axes,) = plotting.regimes_at_a_glance(CORPUS_ROWS, E2E_ROWS).axes + stopped = next(c for c in axes.collections if "lower bound" in str(c.get_label())) + assert len(stopped.get_facecolor()) == 0 # facecolors "none" + assert len(stopped.get_edgecolor()) == 1 + + +def test_the_glance_refuses_a_table_without_its_columns() -> None: + broken = [{k: v for k, v in CORPUS_ROWS[0].items() if k != "Whole search"}] + with pytest.raises(ValueError, match="Whole search"): + plotting.regimes_at_a_glance(broken, E2E_ROWS) + + +def test_an_svg_is_the_same_file_when_drawn_twice(tmp_path: Path) -> None: + first, second = tmp_path / "1.svg", tmp_path / "2.svg" + plotting.save(plotting.regimes_at_a_glance(CORPUS_ROWS, E2E_ROWS), first) + plotting.save(plotting.regimes_at_a_glance(CORPUS_ROWS, E2E_ROWS), second) + assert first.read_bytes() == second.read_bytes() + assert b"" not in first.read_bytes() + + @pytest.mark.parametrize("suffix", [".png", ".svg"]) def test_a_figure_is_saved_where_asked(tmp_path: Path, suffix: str) -> None: path = tmp_path / "figures" / f"nodes{suffix}" diff --git a/tests/unit/test_report_tables.py b/tests/unit/test_report_tables.py new file mode 100644 index 0000000..e560201 --- /dev/null +++ b/tests/unit/test_report_tables.py @@ -0,0 +1,40 @@ +"""Committed tables read back: ``report.parse_markdown`` is the inverse of ``report.markdown``.""" + +import pytest + +from maxplus_solvers.experiments import report + +# Written by hand in the shape of benchmarks/results/*.md. +TABLE = """\ +| Fixture | Nodes | Whole search | +| --- | --- | --- | +| `a-flat` | 1 064 878 | yes | +| `b` | 26 | | +""" + + +def test_a_table_is_read_by_its_header() -> None: + assert report.parse_markdown(TABLE) == [ + {"Fixture": "`a-flat`", "Nodes": "1 064 878", "Whole search": "yes"}, + {"Fixture": "`b`", "Nodes": "26", "Whole search": ""}, + ] + + +def test_what_markdown_writes_is_read_back_unchanged() -> None: + cells = [["x", "y"], ["1", "`two`"], ["", "3 000"]] + rows = report.parse_markdown(report.markdown(cells)) + assert [[row["x"], row["y"]] for row in rows] == cells[1:] + + +@pytest.mark.parametrize( + ("text", "message"), + [ + ("| a | b |\n| 1 | 2 |\n", "rule"), # the rule is missing + ("| a | b |\n| --- | --- |\n| 1 |\n", "line 3 has 1 cells"), # a short row + ("| a |\n| --- |\n1\n", "not a table row"), # a line that is not a row + ("| a |\n", "header and a rule"), + ], +) +def test_a_damaged_table_is_refused(text: str, message: str) -> None: + with pytest.raises(ValueError, match=message): + report.parse_markdown(text) From 7f690ebe33a9f3bd7d6aac3b4e2d71c04da359ed Mon Sep 17 00:00:00 2001 From: Igor Kuvychko Date: Tue, 17 Nov 2026 12:36:47 -0800 Subject: [PATCH 2/3] README: the full table runs take about half an hour each, not minutes Measured while reproducing both committed tables exactly. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7767841..943a8a1 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ uv run maxplus-bench run benchmarks/manifests/corpus.toml --no-times # be uv run maxplus-bench run benchmarks/manifests/edge_to_edge.toml --no-times # benchmarks/results/edge_to_edge.md ``` -Each takes several minutes, most of it on the footprints that run to the node limit. The committed tables hold statuses and counts only, which a deterministic solver reproduces exactly, and the test suite compares every row it can afford to rerun. [docs/experiments.md](docs/experiments.md) has the other experiments (tolerance, heuristics, difficulty proxies) and what they found. +Each took about half an hour on a laptop, most of it on the footprints that run to the node limit. The committed tables hold statuses and counts only, which a deterministic solver reproduces exactly, and the test suite compares every row it can afford to rerun. [docs/experiments.md](docs/experiments.md) has the other experiments (tolerance, heuristics, difficulty proxies) and what they found. ## What we've learned so far From 3fd23758f2fc0538747b3deb57790dcfa283e1fb Mon Sep 17 00:00:00 2001 From: Igor Kuvychko Date: Tue, 17 Nov 2026 12:50:13 -0800 Subject: [PATCH 3/3] Figure: add relief assuming edge to edge The figure showed the assumption only without roofs. It now draws all four combinations: colour is the regime (red flat, blue relief), a diamond is the edge-to-edge assumption. Flat and relief points sit just below and above each row's line, since equal counts (new5, new3, new1 assuming edge to edge) hid one another. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- docs/experiments.md | 2 +- docs/figures/at-a-glance.svg | 385 ++++++++++-------- .../maxplus_solvers/experiments/plotting.py | 48 ++- tests/corpus/test_figure.py | 6 +- tests/unit/test_plotting.py | 20 +- 6 files changed, 275 insertions(+), 190 deletions(-) diff --git a/README.md b/README.md index 943a8a1..dec2b06 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ A solver laboratory for geometric tiling puzzles, starting with the tropical puzzles published by [Tropical Puzzle Lab](https://github.com/maxpluslab/tropical-puzzle-lab). It is a research platform, not a single solver. Several search methods run on the same puzzles, behind one contract, with an independent validator and reproducible benchmarks. The question it asks is what makes a puzzle hard for a search, and what helps. -![Search-tree nodes of a whole search for each of the 14 constructions, flat, with roofs, and flat assuming edge to edge](docs/figures/at-a-glance.svg) +![Search-tree nodes of a whole search for each of the 14 constructions, flat and with roofs, assuming nothing and assuming edge to edge](docs/figures/at-a-glance.svg) -*Search effort for each construction (pieces in brackets), as nodes in the search tree of `rust.contact_dfs` with default options and tolerances, node limit 1 500 000. Each point is a whole search, with every assembly found, unless it is an open arrow: those flat searches were stopped at the limit, so their true cost is larger. Nodes are not running times and not a measure of how hard a puzzle is for a person. Data: [corpus.md](benchmarks/results/corpus.md) and [edge_to_edge.md](benchmarks/results/edge_to_edge.md); drawn by `uv run maxplus-bench figure`.* +*Search effort for each construction (pieces in brackets): red without roofs, just below the line, and blue with them, just above it; diamonds assume the pieces meet edge to edge. Effort is counted in nodes in the search tree of `rust.contact_dfs` with default options and tolerances, node limit 1 500 000. Each point is a whole search, with every assembly found, unless it is an open arrow: those flat searches were stopped at the limit, so their true cost is larger. Nodes are not running times and not a measure of how hard a puzzle is for a person. Data: [corpus.md](benchmarks/results/corpus.md) and [edge_to_edge.md](benchmarks/results/edge_to_edge.md); drawn by `uv run maxplus-bench figure`.* ## At a glance diff --git a/docs/experiments.md b/docs/experiments.md index 72ba9f3..caec888 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -260,7 +260,7 @@ Correlations are taken within a regime only. Across both, any number that differ ## 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. `regimes_at_a_glance` draws the README's figure, [`docs/figures/at-a-glance.svg`](figures/at-a-glance.svg): for each construction, the whole-search nodes of `rust.contact_dfs` without roofs, with roofs, and without roofs assuming edge to edge (both of the assumption's rules on), on a log scale. It reads the committed tables, not records, so `uv run maxplus-bench figure` redraws it without searching; a footprint search stopped at the node limit is an open arrow at 1 500 000, a lower bound. `tests/corpus/test_figure.py` holds the committed file to the tables. When a solver change moves a count, regenerate the tables, then the figure. +`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. `regimes_at_a_glance` draws the README's figure, [`docs/figures/at-a-glance.svg`](figures/at-a-glance.svg): for each construction, the whole-search nodes of `rust.contact_dfs` without roofs and with them (colour), assuming nothing or assuming edge to edge with both of the assumption's rules on (marker), on a log scale. It reads the committed tables, not records, so `uv run maxplus-bench figure` redraws it without searching; a footprint search stopped at the node limit is an open arrow at 1 500 000, a lower bound. `tests/corpus/test_figure.py` holds the committed file to the tables. When a solver change moves a count, regenerate the tables, then the figure. `notebooks/first-look.ipynb` runs a manifest, prints its table and the proxies and draws both; a test runs it from top to bottom. diff --git a/docs/figures/at-a-glance.svg b/docs/figures/at-a-glance.svg index a08f011..570a07f 100644 --- a/docs/figures/at-a-glance.svg +++ b/docs/figures/at-a-glance.svg @@ -37,73 +37,73 @@ z " style="fill: #ffffff"/> - - - - - - - - - - - - - - @@ -1189,12 +1189,12 @@ L -3.5 0 " style="stroke: #000000; stroke-width: 0.8"/> - + - + @@ -1209,12 +1209,12 @@ L -3.5 0 - + - + - + - + @@ -1281,12 +1281,12 @@ z - + - + - + - + @@ -1334,12 +1334,12 @@ z - + - + @@ -1355,12 +1355,12 @@ z - + - + @@ -1376,12 +1376,12 @@ z - + - + @@ -1397,12 +1397,12 @@ z - + - + - + - + - + - + @@ -1500,12 +1500,12 @@ z - + - + @@ -1521,12 +1521,12 @@ z - + - + @@ -1542,12 +1542,12 @@ z - + - + @@ -1617,39 +1617,39 @@ z " style="stroke: #d62728"/> - - - - - - - - + + + + + + + + - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + - - - - - - - - + + + + + + + + - + - +" style="stroke: #1f77b4"/> - - - - - - - - - - - - - - + + + + + + + + + + + + + + @@ -1907,19 +1933,19 @@ z - - + @@ -1975,7 +2001,7 @@ z - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2096,40 +2158,43 @@ z - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/python/maxplus_solvers/experiments/plotting.py b/python/maxplus_solvers/experiments/plotting.py index 9dd92f9..117c2c7 100644 --- a/python/maxplus_solvers/experiments/plotting.py +++ b/python/maxplus_solvers/experiments/plotting.py @@ -80,12 +80,21 @@ def proxy_against_cost( GLANCE_SOLVER = "rust.contact_dfs" -# The series of the figure below, in drawing order: label, marker, filled. +# The series of the figure below, in drawing order: label, marker, filled, colour. +# The colour is the regime, the marker the assumption. +FLAT, RELIEF = "tab:red", "tab:blue" +# Within a construction's row, flat points sit a little below the line and relief points +# a little above it, so that equal counts in the two regimes do not hide each other. +ROW_OFFSET = {FLAT: 0.15, RELIEF: -0.15} GLANCE_SERIES = ( - ("flat, assuming nothing", "o", True), - ("flat, stopped at the node limit (a lower bound)", ">", False), - ("relief, assuming nothing", "s", True), - ("flat, assuming edge to edge", "D", True), + ("flat, assuming nothing", "o", True, FLAT), + ("flat, stopped at the node limit (a lower bound)", ">", False, FLAT), + ("flat, assuming edge to edge", "D", True, FLAT), + ("relief, assuming nothing", "s", True, RELIEF), + ("relief, assuming edge to edge", "D", True, RELIEF), +) +FLAT_NOTHING, FLAT_STOPPED, FLAT_E2E, RELIEF_NOTHING, RELIEF_E2E = ( + label for label, *_ in GLANCE_SERIES ) @@ -104,7 +113,7 @@ def nodes(text: str) -> int: solver = f"`{GLANCE_SOLVER}`" pieces: dict[str, int] = {} - series: dict[str, dict[str, int]] = {label: {} for label, _, _ in GLANCE_SERIES} + series: dict[str, dict[str, int]] = {label: {} for label, *_ in GLANCE_SERIES} for row in corpus_rows: need(row, "Fixture", "Pieces", "Solver", "Mode", "Whole search", "Nodes") if row["Solver"] != solver: @@ -112,18 +121,20 @@ def nodes(text: str) -> int: construction = row["Fixture"].strip("`").removesuffix("-flat") pieces[construction] = int(row["Pieces"]) if row["Mode"] == "relief": - label = GLANCE_SERIES[2][0] + label = RELIEF_NOTHING elif row["Whole search"] == "yes": - label = GLANCE_SERIES[0][0] + label = FLAT_NOTHING else: - label = GLANCE_SERIES[1][0] + label = FLAT_STOPPED series[label][construction] = nodes(row["Nodes"]) for row in e2e_rows: need(row, "Fixture", "Solver", "Mode", "assumes", "equal_edges", "wall_edges", "Nodes") chosen = (row["Solver"], row["Mode"], row["assumes"], row["equal_edges"], row["wall_edges"]) - if chosen == (solver, "footprint", "edge-to-edge", "true", "true"): - construction = row["Fixture"].strip("`").removesuffix("-flat") - series[GLANCE_SERIES[3][0]][construction] = nodes(row["Nodes"]) + if chosen[0] != solver or chosen[2:] != ("edge-to-edge", "true", "true"): + continue + construction = row["Fixture"].strip("`").removesuffix("-flat") + label = RELIEF_E2E if row["Mode"] == "relief" else FLAT_E2E + series[label][construction] = nodes(row["Nodes"]) order = sorted(pieces.items(), key=lambda item: (item[1], item[0])) return order, series @@ -131,11 +142,12 @@ def nodes(text: str) -> int: def regimes_at_a_glance( corpus_rows: Sequence[Mapping[str, str]], e2e_rows: Sequence[Mapping[str, str]] ) -> Figure: - """Whole-search nodes of each construction, flat, with roofs, and flat assuming edge to edge. + """Whole-search nodes per construction, flat and with roofs, assuming nothing or edge to edge. Takes the rows of the committed tables ``benchmarks/results/corpus.md`` and ``edge_to_edge.md`` as :func:`report.parse_markdown` reads them, so it needs no - search. Only ``rust.contact_dfs`` is drawn, with both edge-to-edge rules on. + search. Only ``rust.contact_dfs`` is drawn, and under the assumption only with both + of its rules on. Colour is the regime, a diamond the assumption. A flat search stopped at the node limit is drawn as an open arrow at the limit: the true count is larger. """ @@ -152,17 +164,15 @@ def regimes_at_a_glance( values = [points[construction] for points in series.values() if construction in points] if values: axes.plot([min(values), max(values)], [index, index], color="0.85", zorder=1) - for (label, marker, filled), color in zip( - GLANCE_SERIES, ("tab:red", "tab:red", "tab:blue", "tab:green"), strict=True - ): + for label, marker, filled, color in GLANCE_SERIES: points = series[label] if not points: continue axes.scatter( [points[c] for c in points], - [rows[c] for c in points], + [rows[c] + ROW_OFFSET[color] for c in points], marker=marker, - s=36, + s=30 if marker == "D" else 36, label=label, facecolors=color if filled else "none", edgecolors=color, diff --git a/tests/corpus/test_figure.py b/tests/corpus/test_figure.py index 41d3f91..f87e974 100644 --- a/tests/corpus/test_figure.py +++ b/tests/corpus/test_figure.py @@ -33,7 +33,7 @@ def test_the_committed_figure_names_every_construction_and_series() -> None: labels = labels_in(FIGURE.read_text(encoding="utf-8")) pieces = {row["Fixture"].strip("`"): row["Pieces"] for row in read("corpus.md")} assert {f"{c} ({pieces[c]})" for c in CONSTRUCTIONS} <= labels - assert {label for label, _, _ in plotting.GLANCE_SERIES} <= labels + assert {label for label, *_ in plotting.GLANCE_SERIES} <= labels def test_the_committed_figure_is_what_the_command_draws_now(tmp_path: Path) -> None: @@ -52,6 +52,8 @@ def test_the_committed_figure_is_what_the_command_draws_now(tmp_path: Path) -> N ("relief, assuming nothing", "new1", 68), ("flat, assuming edge to edge", "new1", 49), ("relief, assuming nothing", "plt1", 21_973), + ("relief, assuming edge to edge", "plt1", 749), + ("relief, assuming edge to edge", "new1", 49), ("flat, stopped at the node limit (a lower bound)", "cor1", 1_500_000), ("flat, assuming edge to edge", "cor1", 44_539), ], @@ -62,5 +64,5 @@ def test_the_figure_places_points_from_the_tables( (axes,) = plotting.regimes_at_a_glance(read("corpus.md"), read("edge_to_edge.md")).axes ticks = [label.get_text().split(" ")[0] for label in axes.get_yticklabels()] collection = next(c for c in axes.collections if c.get_label() == series) - points = {ticks[int(y)]: x for x, y in np.asarray(collection.get_offsets(), dtype=float)} + points = {ticks[round(y)]: x for x, y in np.asarray(collection.get_offsets(), dtype=float)} assert points[construction] == pytest.approx(nodes, abs=1e-9) diff --git a/tests/unit/test_plotting.py b/tests/unit/test_plotting.py index 4a09e65..2d601eb 100644 --- a/tests/unit/test_plotting.py +++ b/tests/unit/test_plotting.py @@ -119,18 +119,26 @@ def e2e_row(fixture: str, mode: str, equal: str, wall: str, nodes: str) -> dict[ e2e_row("a-flat", "footprint", "true", "true", "20"), e2e_row("a-flat", "footprint", "false", "true", "99"), # one rule off: not drawn e2e_row("b-flat", "footprint", "true", "true", "5 000"), - e2e_row("b", "relief", "true", "true", "77"), # relief under the assumption: not drawn + e2e_row("b", "relief", "true", "true", "77"), + e2e_row("b", "relief", "true", "false", "88"), # one rule off: not drawn ] def test_the_glance_draws_each_construction_in_its_three_regimes() -> None: (axes,) = plotting.regimes_at_a_glance(CORPUS_ROWS, E2E_ROWS).axes series = {str(c.get_label()): values(c.get_offsets()) for c in axes.collections} - # Rows go by pieces: a (4 pieces) at y 0, b (9) at y 1. Values from the rows above. - assert series["flat, assuming nothing"] == [[1234, 0]] - assert series["flat, stopped at the node limit (a lower bound)"] == [[1_500_000, 1]] - assert series["relief, assuming nothing"] == [[12, 0], [300, 1]] - assert series["flat, assuming edge to edge"] == [[20, 0], [5000, 1]] + # Rows go by pieces: a (4 pieces) at y 0, b (9) at y 1. Flat points sit 0.15 below + # the row (larger y, the axis is inverted), relief 0.15 above. Values from the rows above. + expected = { + "flat, assuming nothing": [[1234, 0.15]], + "flat, stopped at the node limit (a lower bound)": [[1_500_000, 1.15]], + "flat, assuming edge to edge": [[20, 0.15], [5000, 1.15]], + "relief, assuming nothing": [[12, -0.15], [300, 0.85]], + "relief, assuming edge to edge": [[77, 0.85]], + } + assert sorted(series) == sorted(expected) + for label, points in expected.items(): + assert series[label] == [pytest.approx(p, abs=1e-12) for p in points], label assert [label.get_text() for label in axes.get_yticklabels()] == ["a (4)", "b (9)"] assert axes.get_xscale() == "log"