diff --git a/CLAUDE.md b/CLAUDE.md index b2948cc..2a50303 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,6 +16,7 @@ uv run pytest # all Python tests uv run pytest tests/unit/test_native.py::test_version_matches_the_package uv run pytest tests/corpus # every committed fixture and its answer key uv run pytest tests/corpus/test_native_agrees_with_validator.py # Rust geometry against the validator +uv run pytest -m "not slow" # without the whole searches that take tens of seconds uv run pytest -m "not source" # without the tropical-puzzle-lab checkout HYPOTHESIS_PROFILE=ci uv run pytest # the derandomized, larger property runs CI uses uv run ruff check && uv run ruff format --check @@ -25,8 +26,10 @@ cargo fmt --all cargo clippy --workspace --all-targets -- -D warnings cargo test --workspace --exclude tiling-py # tiling-py is a cdylib, tested through pytest cargo test -p tiling-geometry signed_area +cargo test -p tiling-search # the search, on random tilings from tiling-geometry's `testing` feature 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 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 ``` @@ -36,8 +39,8 @@ uv run python scripts/import_fixtures.py --source ../tropical-puzzle-lab --check ## Architecture - `crates/tiling-core`: domain types. No dependencies on the other crates. -- `crates/tiling-geometry`: convex geometry, contact matching, candidate generation. Depends on core. Primitives take `&[Vec2]`; proptest strategies shared by its tests are in `src/testing.rs`. -- `crates/tiling-search`: custom solvers, one module each. Depends on core and geometry. +- `crates/tiling-geometry`: convex geometry, contact matching, candidate generation, cavities. Depends on core. Primitives take `&[Vec2]`; proptest strategies are in `src/testing.rs`, public behind the `testing` feature so that `tiling-search` can test on the same random tilings. +- `crates/tiling-search`: custom solvers, one module each (`contact_dfs`), and `canonical`, which decides when two assemblies are the same. Depends on core and geometry. - `crates/tiling-py`: PyO3 bindings, built by maturin as `maxplus_solvers._native`. Converts types and forwards calls; no algorithms. - `python/maxplus_solvers`: the user-facing package: models, importers, solver adapters, validation, experiments. When a function is added to `_native`, add it to `_native.pyi` too. `_native` takes a polygon as a sequence of pairs, a pose as `(x, y, theta)` and a roof as `(z0, gx, gy)`. - `models.py` holds the contracts; `schemas/instance-v1.json` is their JSON form and `tiling-core` mirrors the instance types. Change all three together. @@ -80,6 +83,8 @@ Rules: - **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. +- **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. +- **Slow tests still run.** The `slow` marker is for deselecting locally (`-m "not slow"`); CI runs everything. - **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`. - **Production solvers cross the Python/Rust boundary once per solve.** Prototypes may call individual geometry primitives; a Rust solver receives the instance and runs to completion. diff --git a/Cargo.lock b/Cargo.lock index f0aa5d2..13a89c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -379,6 +379,7 @@ dependencies = [ name = "tiling-search" version = "0.1.0" dependencies = [ + "proptest", "tiling-core", "tiling-geometry", ] diff --git a/README.md b/README.md index 18097d5..0f1c11e 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. A first solver exists: `python.contact_dfs`, a Python prototype of the contact search, which solves the 6-, 9- and 11-piece footprint puzzles and returns assemblies that pass the validator. 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: 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. Two 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. Each of its rules 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). ```python from maxplus_solvers import load_puzzle @@ -25,6 +25,22 @@ flat = load_puzzle( ) # the same pieces without roofs ``` +Solving, from Python or from the command line: + +```python +from maxplus_solvers import SolverConfig, solve + +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 new2 --mode relief --max-solutions all --validate +uv run maxplus-solve rat1-flat --max-solutions all --option closure_pruning=false +``` + +What a result claims, and what it does not, is in [docs/solver-contract.md](docs/solver-contract.md). + With the `validate` extra (Shapely), poses can be checked against the completion rules: ```python @@ -59,7 +75,7 @@ schemas/ versioned exchange formats (`instance-v1.json`) benchmarks/fixtures/ sanitized puzzle instances, generated scripts/ `import_fixtures.py` regenerates fixtures and answer keys tests/ pytest suites: unit, property, corpus, architecture; answer keys in `tests/keys/` -docs/ architecture and roadmap +docs/ architecture, roadmap, the solver contract and the algorithms ``` Planned, added by the roadmap phase that needs them: benchmark manifests, `notebooks/`. diff --git a/crates/tiling-geometry/Cargo.toml b/crates/tiling-geometry/Cargo.toml index 3465765..d932c37 100644 --- a/crates/tiling-geometry/Cargo.toml +++ b/crates/tiling-geometry/Cargo.toml @@ -7,8 +7,13 @@ rust-version.workspace = true license.workspace = true repository.workspace = true +[features] +# Proptest strategies for other crates' tests: random convex polygons and tilings. +testing = ["dep:proptest"] + [dependencies] tiling-core.workspace = true +proptest = { workspace = true, optional = true } [dev-dependencies] proptest.workspace = true diff --git a/crates/tiling-geometry/src/assembly.rs b/crates/tiling-geometry/src/assembly.rs index 745e809..2d8d2d1 100644 --- a/crates/tiling-geometry/src/assembly.rs +++ b/crates/tiling-geometry/src/assembly.rs @@ -34,9 +34,11 @@ use std::fmt; 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::polygon::{is_convex_ccw, outside_depth, transform}; +use crate::relief::{roof_height, seam_mismatch}; use crate::sat::penetration_depth; /// One way to put a piece down, and the contact that produced it. @@ -76,6 +78,32 @@ pub struct CandidateStats { pub rejected_outside: u64, /// Of the rest, rejected for entering a placed piece. pub rejected_overlap: u64, + /// Rejected because the roof would not meet a neighbour's: at the corner + /// before the other checks, or along a shared edge after them. Always zero + /// for pieces without roofs. + pub rejected_roof: u64, +} + +/// Smallest axis-aligned box around a polygon, as `[min x, min y, max x, max y]`. +fn bounds(polygon: &[Vec2]) -> [f64; 4] { + let mut b = [ + f64::INFINITY, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NEG_INFINITY, + ]; + for p in polygon { + b[0] = b[0].min(p[0]); + b[1] = b[1].min(p[1]); + b[2] = b[2].max(p[0]); + b[3] = b[3].max(p[1]); + } + b +} + +/// 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] } #[derive(Debug, Clone, PartialEq, Eq)] @@ -117,6 +145,7 @@ pub struct Assembly { tolerance: ContactTolerance, poses: Vec>, world: Vec>>, + boxes: Vec<[f64; 4]>, /// Placed pieces, oldest first. stack: Vec, stats: CandidateStats, @@ -129,7 +158,15 @@ impl Assembly { tolerance: ContactTolerance, ) -> Result { let positive = |v: f64| v.is_finite() && v > 0.0; - if !(positive(tolerance.length) && positive(tolerance.angle) && positive(tolerance.slope)) { + if ![ + tolerance.length, + tolerance.angle, + tolerance.slope, + tolerance.height, + ] + .into_iter() + .all(positive) + { return Err(AssemblyError::BadTolerance); } if !is_convex_ccw(&target) { @@ -147,6 +184,7 @@ impl Assembly { tolerance, poses: vec![None; count], world: vec![None; count], + boxes: vec![[0.0; 4]; count], stack: Vec::with_capacity(count), stats: CandidateStats::default(), }) @@ -185,6 +223,11 @@ impl Assembly { self.poses.get(piece).copied().flatten() } + /// A placed piece's polygon in the world. + pub fn world(&self, piece: usize) -> Option<&[Vec2]> { + self.world.get(piece)?.as_deref() + } + pub fn all_placed(&self) -> bool { self.stack.len() == self.shapes.len() } @@ -198,7 +241,9 @@ impl Assembly { if self.poses[piece].is_some() { return Err(AssemblyError::AlreadyPlaced(piece)); } - self.world[piece] = Some(transform(&self.shapes[piece].polygon, &pose)); + let world = transform(&self.shapes[piece].polygon, &pose); + self.boxes[piece] = bounds(&world); + self.world[piece] = Some(world); self.poses[piece] = Some(pose); self.stack.push(piece); Ok(()) @@ -227,6 +272,93 @@ impl Assembly { free_corners(&self.target, &self.placed_polygons(), &self.tolerance) } + /// The separate parts of the uncovered region whose corners are `corners`, + /// which must be this state's [`Assembly::frontier`]. `None` if they do not + /// link up; see [`cavities`]. + pub fn cavities(&self, corners: &[Corner]) -> Option> { + cavities(corners, &self.tolerance) + } + + /// The largest step between the roof of `piece`, placed at `pose`, and the + /// roofs of the placed pieces, along the stretches of edge it shares with + /// them. Zero for a piece without a roof, or one that shares no edge. + /// + /// Two roofs are planes, so the step along a shared stretch is largest at + /// one of its ends, and those are the only points measured. + pub fn roof_step(&self, piece: usize, pose: &Pose) -> Result { + let shape = self + .shapes + .get(piece) + .ok_or(AssemblyError::NoSuchPiece(piece))?; + Ok(self.roof_step_of(piece, pose, &transform(&shape.polygon, pose))) + } + + fn roof_step_of(&self, piece: usize, pose: &Pose, world: &[Vec2]) -> f64 { + let Some(roof) = &self.shapes[piece].roof else { + return 0.0; + }; + let reach = bounds(world); + let n = world.len(); + let mut worst: f64 = 0.0; + for &other in &self.stack { + let Some(other_roof) = &self.shapes[other].roof else { + continue; + }; + if other == piece || apart(&reach, &self.boxes[other], self.tolerance.length) { + continue; + } + let (Some(other_world), Some(other_pose)) = (&self.world[other], &self.poses[other]) + else { + continue; + }; + let m = other_world.len(); + for i in 0..n { + let (a0, a1) = (world[i], world[(i + 1) % n]); + let length = (a1[0] - a0[0]).hypot(a1[1] - a0[1]); + let u = [(a1[0] - a0[0]) / length, (a1[1] - a0[1]) / length]; + for j in 0..m { + let (b0, b1) = (other_world[j], other_world[(j + 1) % m]); + // Position of a point along this edge, and its distance off the edge's line. + let along = |p: Vec2| u[0] * (p[0] - a0[0]) + u[1] * (p[1] - a0[1]); + let off = |p: Vec2| (u[0] * (p[1] - a0[1]) - u[1] * (p[0] - a0[0])).abs(); + // A neighbour's edge on the same line runs the other way. + let (start, end) = (along(b1), along(b0)); + if end <= start + || off(b0) > self.tolerance.length + || off(b1) > self.tolerance.length + { + continue; + } + let (from, to) = (start.max(0.0), end.min(length)); + if to - from <= self.tolerance.length { + continue; + } + let at = |t: f64| [a0[0] + t * u[0], a0[1] + t * u[1]]; + worst = worst.max(seam_mismatch( + roof, + pose, + other_roof, + other_pose, + at(from), + at(to), + )); + } + } + } + worst + } + + /// Whether `world` enters a placed piece by more than the length tolerance. + fn enters_a_placed_piece(&self, world: &[Vec2]) -> bool { + let reach = bounds(world); + self.stack.iter().any(|&other| { + !apart(&reach, &self.boxes[other], 0.0) + && self.world[other].as_ref().is_some_and(|polygon| { + penetration_depth(world, polygon) > self.tolerance.length + }) + }) + } + /// Measure a placement of `piece` against the target and the other placed pieces. pub fn check_placement( &self, @@ -270,6 +402,12 @@ impl Assembly { /// omitted placement would put the same shape, with the same roof, in the /// same place. /// + /// Pieces with roofs must also meet their neighbours' roofs. The slopes + /// along the contact are compared before any pose exists, through the + /// compatibility graph; then the heights at the corner; and, once the + /// placement is known to fit, the heights along every edge it shares with a + /// placed piece. + /// /// 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. @@ -300,12 +438,17 @@ impl Assembly { corner.direction, ); self.stats.generated += 1; - let check = - self.check_polygon(piece, &transform(&self.shapes[piece].polygon, &pose)); - if check.outside > self.tolerance.length { + if !self.roofs_meet_at(corner, piece, vertex) { + self.stats.rejected_roof += 1; + continue; + } + let world = transform(&self.shapes[piece].polygon, &pose); + if outside_depth(&world, &self.target) > self.tolerance.length { self.stats.rejected_outside += 1; - } else if check.overlap > self.tolerance.length { + } else if self.enters_a_placed_piece(&world) { self.stats.rejected_overlap += 1; + } else if self.roof_step_of(piece, &pose, &world) > self.tolerance.height { + self.stats.rejected_roof += 1; } else { candidates.push(CandidatePlacement { piece, @@ -318,6 +461,23 @@ impl Assembly { } candidates } + + /// Whether the roof of `piece` at its vertex `vertex` is as high as the + /// roof of the piece the corner's first side belongs to, at the corner. + /// True when either has no roof, and for a side that belongs to the tray. + fn roofs_meet_at(&self, corner: &Corner, piece: usize, vertex: usize) -> bool { + let EdgeRef::Piece { piece: fixed, .. } = corner.source else { + return true; + }; + let (Some(height), Some(roof), Some(pose)) = ( + self.graph.signatures(piece)[vertex].height_start, + &self.shapes[fixed].roof, + &self.poses[fixed], + ) else { + return true; + }; + (roof_height(roof, pose, corner.vertex) - height).abs() <= self.tolerance.height + } } #[cfg(test)] @@ -327,6 +487,7 @@ mod tests { use crate::testing::{TOL, Tiling, close, tiling}; use proptest::prelude::*; use std::f64::consts::FRAC_PI_2; + use tiling_core::Roof; fn bare(polygon: Vec) -> Shape { Shape { @@ -507,7 +668,8 @@ mod tests { CandidateStats { generated: 5, rejected_outside: 1, - rejected_overlap: 0 + rejected_overlap: 0, + rejected_roof: 0 } ); } @@ -535,6 +697,76 @@ mod tests { assert_eq!(assembly.stats().rejected_outside, 2); } + /// A 2 x 4 strip under a level roof at height 1 against the left wall, a + /// 2 x 2 square at the same height, and a 3 x 2 block one higher. + fn roofed() -> Assembly { + let level = |polygon, z0| Shape { + polygon, + roof: Some(Roof { + z0, + gx: 0.0, + gy: 0.0, + }), + }; + let shapes = vec![ + level(rectangle(2.0, 4.0), 1.0), + level(rectangle(2.0, 2.0), 1.0), + level(rectangle(3.0, 2.0), 2.0), + ]; + let mut assembly = Assembly::new(tray(), shapes, TOL).unwrap(); + assembly.place(0, at(1.0, 2.0, 0.0)).unwrap(); + assembly + } + + fn corner_at(assembly: &Assembly, x: f64, y: f64) -> Corner { + *assembly + .frontier() + .iter() + .find(|c| close(c.vertex[0], x, 1e-9) && close(c.vertex[1], y, 1e-9)) + .unwrap() + } + + #[test] + fn a_roof_step_along_a_seam_refuses_a_placement_that_fits() { + // The corner at (2, 0) starts along the tray's wall, which has no roof: + // nothing can be told at the corner. The block fits standing up, over + // x in [2, 4] and y in [0, 3], and there it lies against the strip one + // millimetre higher. Lying down it reaches x = 5, outside the tray. + let mut assembly = roofed(); + let corner = corner_at(&assembly, 2.0, 0.0); + assert!(matches!(corner.source, EdgeRef::Tray { .. })); + let proposals = assembly.propose(&corner); + assert_eq!(proposals.iter().map(|c| c.piece).collect::>(), [1]); + let stats = assembly.stats(); + assert_eq!( + (stats.generated, stats.rejected_outside, stats.rejected_roof), + (3, 1, 1) + ); + assert!(close( + assembly.roof_step(2, &at(3.0, 1.5, FRAC_PI_2)).unwrap(), + 1.0, + 1e-12 + )); + } + + #[test] + fn a_roof_at_the_wrong_height_is_refused_at_the_corner_before_it_is_placed() { + // The corner at (2, 4) starts down the strip's own edge, so the strip's + // roof is known there. Both ways round the block is a millimetre too + // high at the corner, and it is refused for that, also the way round + // that would stick out of the tray: the roof is asked first. + let mut assembly = roofed(); + let corner = corner_at(&assembly, 2.0, 4.0); + assert!(matches!(corner.source, EdgeRef::Piece { piece: 0, .. })); + let proposals = assembly.propose(&corner); + assert_eq!(proposals.iter().map(|c| c.piece).collect::>(), [1]); + let stats = assembly.stats(); + assert_eq!( + (stats.generated, stats.rejected_outside, stats.rejected_roof), + (3, 0, 2) + ); + } + #[test] fn four_identical_squares_have_one_assembly() { let shapes = (0..4).map(|_| bare(rectangle(2.0, 2.0))).collect(); diff --git a/crates/tiling-geometry/src/cavity.rs b/crates/tiling-geometry/src/cavity.rs new file mode 100644 index 0000000..5a05e17 --- /dev/null +++ b/crates/tiling-geometry/src/cavity.rs @@ -0,0 +1,290 @@ +//! Cavities: the separate parts of the uncovered region, traced from its corners. +//! +//! The uncovered region is still never built by clipping. Its boundary is +//! followed from corner to corner: a corner's first side runs along a fixed +//! edge with the region on its left, and it ends at the next corner on that +//! ray whose own wedge closes looking back along it. Following these links +//! from any corner comes round to it again, and the corners passed are the +//! outline of one cavity, counter-clockwise. +//! +//! A search only ever puts a piece down against the tray or against a placed +//! piece, so what is covered hangs together with the tray wall, and a cavity +//! has no holes: its outline is a single loop. A piece set down in the open, +//! touching nothing, would make a hole, whose outline runs the other way round +//! and has negative area; [`cavities`] declines to answer for such a state. +//! +//! Where the region touches itself at a point, that point carries one corner +//! for each side, and the two sides come out as two cavities. A convex piece +//! cannot reach through such a point, so they are filled separately. +//! +//! A search uses cavities to give up early: the pieces that go into a cavity +//! have exactly its area, and none of them is wider than a convex cavity is. + +use std::f64::consts::{PI, TAU}; + +use tiling_core::Vec2; + +use crate::contact::{ContactTolerance, Corner}; + +/// One connected part of the uncovered region. +#[derive(Debug, Clone, PartialEq)] +pub struct Cavity { + /// Indices into the corner list, counter-clockwise round the cavity. + pub corners: Vec, + /// Square millimetres. + pub area: f64, + /// The cavity's least width, if it is convex: no piece wider than this + /// fits into it. `None` for a cavity with a reflex corner. + pub width: Option, +} + +/// Difference between two directions, in `[0, π]`. +fn turn_between(a: f64, b: f64) -> f64 { + let d = (a - b).rem_euclid(TAU); + d.min(TAU - d) +} + +/// The corner that follows `from` along the boundary: the nearest one on the +/// ray of its first side whose wedge closes looking back down the ray. +fn next_corner(corners: &[Corner], from: usize, tolerance: &ContactTolerance) -> Option { + let corner = &corners[from]; + let (s, c) = corner.direction.sin_cos(); + let back = corner.direction + PI; + let mut best: Option<(f64, usize)> = None; + for (index, other) in corners.iter().enumerate() { + if index == from { + continue; + } + let (dx, dy) = ( + other.vertex[0] - corner.vertex[0], + other.vertex[1] - corner.vertex[1], + ); + let along = dx * c + dy * s; + let off = (dy * c - dx * s).abs(); + if along <= tolerance.length || off > tolerance.length + tolerance.angle * along { + continue; + } + if turn_between(other.direction + other.angle, back) > tolerance.angle { + continue; + } + if best.is_none_or(|(nearest, _)| along < nearest) { + best = Some((along, index)); + } + } + best.map(|(_, index)| index) +} + +/// Least width of a convex counter-clockwise polygon: over its edges, the +/// farthest any vertex lies from the edge's line. A convex polygon fits inside +/// another only if it is no wider than this. +pub fn least_width(outline: &[Vec2]) -> f64 { + let n = outline.len(); + let mut least = f64::INFINITY; + for i in 0..n { + let (p, q) = (outline[i], outline[(i + 1) % n]); + let length = (q[0] - p[0]).hypot(q[1] - p[1]); + let reach = outline + .iter() + .map(|v| ((q[0] - p[0]) * (v[1] - p[1]) - (q[1] - p[1]) * (v[0] - p[0])) / length) + .fold(0.0, f64::max); + least = least.min(reach); + } + least +} + +/// The cavities whose corners are `corners`, as [`crate::free_corners`] lists them. +/// +/// `None` if the corners do not link up into closed loops, or if some loop is +/// the outline of a hole. Neither happens for pieces placed corner to corner, +/// each against the tray or an earlier piece, and a caller that prunes on +/// cavities must treat `None` as "nothing known" rather than as a dead end. +pub fn cavities(corners: &[Corner], tolerance: &ContactTolerance) -> Option> { + let found = outlines(corners, tolerance)?; + found.iter().all(|c| c.area > 0.0).then_some(found) +} + +/// Every closed loop of the boundary. A hole's loop runs clockwise and its +/// area is negative. +fn outlines(corners: &[Corner], tolerance: &ContactTolerance) -> Option> { + let count = corners.len(); + let mut next = Vec::with_capacity(count); + let mut entered = vec![false; count]; + for from in 0..count { + let to = next_corner(corners, from, tolerance)?; + if entered[to] { + return None; + } + entered[to] = true; + next.push(to); + } + + let mut seen = vec![false; count]; + let mut found = Vec::new(); + for start in 0..count { + if seen[start] { + continue; + } + let mut loop_corners = Vec::new(); + let mut at = start; + while !seen[at] { + seen[at] = true; + loop_corners.push(at); + at = next[at]; + } + let outline: Vec = loop_corners.iter().map(|&i| corners[i].vertex).collect(); + let n = outline.len(); + let twice: f64 = (0..n) + .map(|i| { + let (p, q) = (outline[i], outline[(i + 1) % n]); + p[0] * q[1] - q[0] * p[1] + }) + .sum(); + let convex = loop_corners + .iter() + .all(|&i| corners[i].is_convex(tolerance)); + found.push(Cavity { + corners: loop_corners, + area: twice / 2.0, + width: convex.then(|| least_width(&outline)), + }); + } + Some(found) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::contact::free_corners; + use crate::polygon::signed_area; + use crate::testing::{TOL, Tiling, close, tiling}; + use proptest::prelude::*; + + const TRAY: [Vec2; 4] = [[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]]; + + fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec { + vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]] + } + + fn of(placed: &[Vec]) -> Vec { + let listed: Vec<(usize, &[Vec2])> = placed + .iter() + .enumerate() + .map(|(i, p)| (i, p.as_slice())) + .collect(); + let corners = free_corners(&TRAY, &listed, &TOL); + cavities(&corners, &TOL).expect("the corners link up") + } + + #[test] + fn the_empty_tray_is_one_convex_cavity() { + let found = of(&[]); + assert_eq!(found.len(), 1); + assert_eq!(found[0].corners.len(), 4); + assert!(close(found[0].area, 16.0, 1e-12)); + assert!(close(found[0].width.unwrap(), 4.0, 1e-12)); + } + + #[test] + fn a_block_in_a_corner_leaves_an_l() { + // 16 - 2 = 14, with a reflex corner at (2, 1): no width. + let found = of(&[rectangle(0.0, 0.0, 2.0, 1.0)]); + assert_eq!(found.len(), 1); + assert_eq!(found[0].corners.len(), 6); + assert!(close(found[0].area, 14.0, 1e-12)); + assert_eq!(found[0].width, None); + } + + #[test] + fn a_strip_across_the_tray_leaves_two_cavities() { + // The strip 1 <= y <= 2 leaves 4 x 1 below and 4 x 2 above. + let mut found = of(&[rectangle(0.0, 1.0, 4.0, 2.0)]); + found.sort_by(|a, b| a.area.total_cmp(&b.area)); + assert_eq!(found.len(), 2); + assert!(close(found[0].area, 4.0, 1e-12) && close(found[1].area, 8.0, 1e-12)); + assert!(close(found[0].width.unwrap(), 1.0, 1e-12)); + assert!(close(found[1].width.unwrap(), 2.0, 1e-12)); + } + + #[test] + fn cavities_that_touch_at_a_point_are_separate() { + // Two blocks meeting corner to corner at the centre leave two 2 x 2 squares. + let found = of(&[rectangle(0.0, 0.0, 2.0, 2.0), rectangle(2.0, 2.0, 4.0, 4.0)]); + assert_eq!(found.len(), 2); + for cavity in &found { + assert_eq!(cavity.corners.len(), 4); + assert!(close(cavity.area, 4.0, 1e-12)); + assert!(close(cavity.width.unwrap(), 2.0, 1e-12)); + } + } + + #[test] + fn a_piece_in_the_open_makes_a_hole_and_no_answer() { + let block = [rectangle(1.0, 1.0, 2.0, 2.0)]; + let listed: Vec<(usize, &[Vec2])> = vec![(0, block[0].as_slice())]; + let corners = free_corners(&TRAY, &listed, &TOL); + // The tray's outline, 16, and the block's the other way round, -1. + let mut loops = outlines(&corners, &TOL).unwrap(); + loops.sort_by(|a, b| a.area.total_cmp(&b.area)); + assert!(close(loops[0].area, -1.0, 1e-12) && close(loops[1].area, 16.0, 1e-12)); + assert_eq!(cavities(&corners, &TOL), None); + } + + #[test] + fn a_covered_tray_has_no_cavity() { + assert!(of(&[rectangle(0.0, 0.0, 4.0, 4.0)]).is_empty()); + } + + #[test] + fn the_width_of_a_triangle_is_its_least_height() { + // A 3-4-5 triangle: heights 4, 3 and 12/5 onto the hypotenuse. + let outline = [[0.0, 0.0], [3.0, 0.0], [0.0, 4.0]]; + assert!(close(least_width(&outline), 2.4, 1e-12)); + } + + #[test] + fn corners_that_do_not_close_are_refused() { + let listed: Vec<(usize, &[Vec2])> = Vec::new(); + let mut corners = free_corners(&TRAY, &listed, &TOL); + corners.pop(); + assert_eq!(cavities(&corners, &TOL), None); + } + + proptest! { + /// Whatever part of a tiling is down, the cavities have the area of the + /// pieces still missing, and each corner belongs to exactly one. + #[test] + fn cavities_have_the_area_of_the_missing_pieces(tiling in tiling(), mask in any::()) { + let Tiling { target, world, .. } = &tiling; + let placed: Vec<(usize, &[Vec2])> = world + .iter() + .enumerate() + .filter(|(p, _)| mask >> p & 1 == 1) + .map(|(p, polygon)| (p, polygon.as_slice())) + .collect(); + let corners = free_corners(target, &placed, &TOL); + // Any subset may be down here, so a piece can stand in the open and make a + // hole. The loops are then still right, with the hole's area negative. + let found = outlines(&corners, &TOL); + prop_assert!(found.is_some(), "the corners link up"); + let found = found.unwrap(); + let holes = found.iter().filter(|c| c.area <= 0.0).count(); + prop_assert_eq!(cavities(&corners, &TOL).is_some(), holes == 0); + let missing: f64 = world + .iter() + .enumerate() + .filter(|(p, _)| mask >> p & 1 == 0) + .map(|(_, polygon)| signed_area(polygon)) + .sum(); + let total: f64 = found.iter().map(|c| c.area).sum(); + prop_assert!(close(total, missing, 1e-6), "{total} uncovered, {missing} missing"); + let mut uses = vec![0; corners.len()]; + for cavity in &found { + prop_assert!(cavity.area.abs() > 1e-6); + for &corner in &cavity.corners { + uses[corner] += 1; + } + } + prop_assert!(uses.iter().all(|&n| n == 1)); + } + } +} diff --git a/crates/tiling-geometry/src/contact.rs b/crates/tiling-geometry/src/contact.rs index 2b81f32..b3c773d 100644 --- a/crates/tiling-geometry/src/contact.rs +++ b/crates/tiling-geometry/src/contact.rs @@ -28,6 +28,9 @@ pub struct ContactTolerance { pub angle: f64, /// Roof slope, in mm per mm. pub slope: f64, + /// Roof height, in millimetres: how large a step between two roofs still + /// counts as none. + pub height: f64, } /// An edge of the target or of a piece. Edge `i` runs from vertex `i` to vertex `i + 1`. @@ -75,10 +78,16 @@ enum Site { Outside, } +/// Whether two points are within `tolerance` of each other. +fn near(a: Vec2, b: Vec2, tolerance: f64) -> bool { + let (dx, dy) = (a[0] - b[0], a[1] - b[1]); + dx * dx + dy * dy <= tolerance * tolerance +} + fn locate(polygon: &[Vec2], p: Vec2, tolerance: f64) -> Site { let n = polygon.len(); for (i, v) in polygon.iter().enumerate() { - if (v[0] - p[0]).hypot(v[1] - p[1]) <= tolerance { + if near(*v, p, tolerance) { return Site::Vertex(i); } } @@ -182,18 +191,51 @@ pub fn free_corners( placed: &[(usize, &[Vec2])], tolerance: &ContactTolerance, ) -> Vec { - let mut points: Vec = Vec::new(); - for &p in target + // Every vertex once, in the order given: a vertex is dropped if an earlier + // one is within the tolerance. Looking along x keeps this from comparing + // every pair. + let all: Vec = target .iter() .chain(placed.iter().flat_map(|(_, polygon)| polygon.iter())) - { - let known = points - .iter() - .any(|q| (q[0] - p[0]).hypot(q[1] - p[1]) <= tolerance.length); - if !known { - points.push(p); + .copied() + .collect(); + let mut by_x: Vec = (0..all.len()).collect(); + by_x.sort_by(|&a, &b| all[a][0].total_cmp(&all[b][0])); + let mut repeated = vec![false; all.len()]; + for (rank, &i) in by_x.iter().enumerate() { + for &j in &by_x[rank + 1..] { + if all[j][0] - all[i][0] > tolerance.length { + break; + } + if near(all[i], all[j], tolerance.length) { + repeated[i.max(j)] = true; + } } } + let points: Vec = (0..all.len()) + .filter(|&i| !repeated[i]) + .map(|i| all[i]) + .collect(); + + // A point outside a piece's box, grown by the tolerance, is outside the piece. + let boxes: Vec<[f64; 4]> = placed + .iter() + .map(|(_, polygon)| { + let mut b = [ + f64::INFINITY, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NEG_INFINITY, + ]; + for q in polygon.iter() { + b[0] = b[0].min(q[0] - tolerance.length); + b[1] = b[1].min(q[1] - tolerance.length); + b[2] = b[2].max(q[0] + tolerance.length); + b[3] = b[3].max(q[1] + tolerance.length); + } + b + }) + .collect(); let mut corners = Vec::new(); 'points: for &p in &points { @@ -215,7 +257,10 @@ pub fn free_corners( None if matches!(site, Site::Outside) => continue 'points, None => {} } - for &(piece, polygon) in placed { + for (&(piece, polygon), b) in placed.iter().zip(&boxes) { + if p[0] < b[0] || p[0] > b[2] || p[1] < b[1] || p[1] > b[3] { + continue; + } let site = locate(polygon, p, tolerance.length); match interior_range(polygon, &site) { Some((start, width, edge)) => covers.push(Cover { diff --git a/crates/tiling-geometry/src/graph.rs b/crates/tiling-geometry/src/graph.rs index d0de90f..50d467c 100644 --- a/crates/tiling-geometry/src/graph.rs +++ b/crates/tiling-geometry/src/graph.rs @@ -37,6 +37,8 @@ pub struct EdgeGraph { /// `arcs[fixed * edge_count + mover]` over piece edges. Tray edges accept every piece edge. arcs: Vec, classes: Vec, + /// For each piece, the turn that takes its class's first piece onto it. + turns: Vec, symmetry: Vec, } @@ -64,6 +66,15 @@ fn same_cycle( n == b.len() && (0..n).all(|k| same_edge(&a[k], &b[(k + shift) % n], tolerance)) } +/// How many rotations about its centroid map a convex polygon onto itself: +/// 1 for a polygon with no symmetry, 4 for a square. +pub fn rotation_order(polygon: &[Vec2], tolerance: &ContactTolerance) -> usize { + let cycle = edge_signatures(polygon, None); + (0..cycle.len()) + .filter(|&s| same_cycle(&cycle, &cycle, s, tolerance)) + .count() +} + impl EdgeGraph { pub fn build(shapes: &[Shape], tolerance: &ContactTolerance) -> EdgeGraph { let signatures: Vec> = shapes @@ -97,16 +108,27 @@ impl EdgeGraph { } // A piece's class is the first piece with the same cycle of edges. - let classes = (0..shapes.len()) + // With it goes the turn that lays that piece, as stored, onto this one as + // stored: congruent pieces need not be stored the same way round. + let direction = |polygon: &[Vec2], edge: usize| { + let (a, b) = (polygon[edge], polygon[(edge + 1) % polygon.len()]); + (b[1] - a[1]).atan2(b[0] - a[0]) + }; + let (classes, turns): (Vec, Vec) = (0..shapes.len()) .map(|p| { (0..p) - .find(|&q| { + .find_map(|q| { (0..signatures[p].len()) - .any(|s| same_cycle(&signatures[q], &signatures[p], s, tolerance)) + .find(|&s| same_cycle(&signatures[q], &signatures[p], s, tolerance)) + .map(|s| { + let turn = direction(&shapes[p].polygon, s) + - direction(&shapes[q].polygon, 0); + (q, turn) + }) }) - .unwrap_or(p) + .unwrap_or((p, 0.0)) }) - .collect(); + .unzip(); let symmetry = signatures .iter() .map(|cycle| { @@ -122,6 +144,7 @@ impl EdgeGraph { edge_count, arcs, classes, + turns, symmetry, } } @@ -161,6 +184,13 @@ impl EdgeGraph { self.classes[piece] } + /// The turn about its centroid that takes the first piece of this piece's + /// class, as stored, onto this piece as stored. Zero for that first piece. + /// For a piece with a symmetry it is one of several such turns. + pub fn turn_from_class(&self, piece: usize) -> f64 { + self.turns[piece] + } + /// How many rotations map `piece` onto itself, roof included: 1 for a /// piece with no symmetry, 4 for a level square. Vertices `0..n / symmetry` /// then stand for all of them. diff --git a/crates/tiling-geometry/src/lib.rs b/crates/tiling-geometry/src/lib.rs index 28d7add..ca92187 100644 --- a/crates/tiling-geometry/src/lib.rs +++ b/crates/tiling-geometry/src/lib.rs @@ -16,9 +16,11 @@ //! | [`relief`] | roof heights of placed pieces and roof continuity along an edge | //! | [`contact`] | corners of the uncovered region, and the pose that fills one | //! | [`graph`] | which edges may mate, which pieces are interchangeable | +//! | [`cavity`] | the separate parts of the uncovered region, their areas and widths | //! | [`assembly`] | reversible partial assembly: `frontier`, `propose`, `check_placement` | pub mod assembly; +pub mod cavity; pub mod clip; pub mod contact; pub mod edges; @@ -27,14 +29,15 @@ pub mod polygon; pub mod relief; pub mod sat; -#[cfg(test)] -mod testing; +#[cfg(any(test, feature = "testing"))] +pub mod testing; pub use assembly::{Assembly, AssemblyError, CandidatePlacement, CandidateStats, PlacementCheck}; +pub use cavity::{Cavity, cavities, least_width}; pub use clip::{intersection, intersection_area, outside_area}; pub use contact::{ContactTolerance, Corner, EdgeRef, free_corners, pose_at_corner}; pub use edges::{Edge, EdgeSignature, edge_signatures, edges}; -pub use graph::{EdgeGraph, Shape}; +pub use graph::{EdgeGraph, 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 43ba63a..cd787ec 100644 --- a/crates/tiling-geometry/src/testing.rs +++ b/crates/tiling-geometry/src/testing.rs @@ -1,4 +1,5 @@ -//! Proptest strategies and helpers shared by this crate's tests. +//! Proptest strategies and helpers for tests, here and in the crates built on +//! this one, which reach them through the `testing` feature. use std::f64::consts::{PI, TAU}; @@ -13,6 +14,7 @@ pub const TOL: ContactTolerance = ContactTolerance { length: 1e-7, angle: 1e-7, slope: 1e-7, + height: 1e-7, }; pub fn close(a: f64, b: f64, tolerance: f64) -> bool { diff --git a/crates/tiling-py/src/lib.rs b/crates/tiling-py/src/lib.rs index 15667c1..886713f 100644 --- a/crates/tiling-py/src/lib.rs +++ b/crates/tiling-py/src/lib.rs @@ -8,6 +8,8 @@ //! to be convex and counter-clockwise, as everywhere else; only `is_convex_ccw` //! checks it. A polygon with fewer than three vertices is refused. +use std::time::Duration; + use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use tiling_core::{Pose, Roof, Vec2}; @@ -15,6 +17,8 @@ use tiling_core::{Pose, Roof, Vec2}; type Point = (f64, f64); type PoseArg = (f64, f64, f64); type RoofArg = (f64, f64, f64); +/// A cavity as `(area, least width if convex, corner indices)`. +type CavityRow = (f64, Option, Vec); fn checked(polygon: Vec<[f64; 2]>) -> PyResult> { if polygon.len() < 3 { @@ -344,6 +348,48 @@ struct Assembly { inner: tiling_geometry::Assembly, } +/// The shapes and tolerances every assembly-level call takes. +fn puzzle_parts( + pieces: Vec>, + roofs: Option>, + length_tol: f64, + angle_tol: f64, + slope_tol: f64, + height_tol: Option, +) -> PyResult<( + Vec, + tiling_geometry::ContactTolerance, +)> { + if let Some(roofs) = &roofs { + if roofs.len() != pieces.len() { + return Err(PyValueError::new_err(format!( + "{} roofs for {} pieces", + roofs.len(), + pieces.len() + ))); + } + } + let shapes = pieces + .into_iter() + .enumerate() + .map(|(i, polygon)| tiling_geometry::Shape { + polygon, + roof: roofs.as_ref().map(|r| roof_of(r[i])), + }) + .collect(); + let tolerance = tiling_geometry::ContactTolerance { + length: length_tol, + angle: angle_tol, + slope: slope_tol, + height: height_tol.unwrap_or(length_tol), + }; + Ok((shapes, tolerance)) +} + +fn refused(error: tiling_geometry::AssemblyError) -> PyErr { + PyValueError::new_err(error.to_string()) +} + impl Assembly { fn piece_index(&self, piece: usize) -> PyResult { if piece < self.inner.piece_count() { @@ -383,7 +429,7 @@ impl Assembly { #[pymethods] impl Assembly { #[new] - #[pyo3(signature = (target, pieces, roofs=None, *, length_tol, angle_tol, slope_tol))] + #[pyo3(signature = (target, pieces, roofs=None, *, length_tol, angle_tol, slope_tol, height_tol=None))] fn new( target: Vec<[f64; 2]>, pieces: Vec>, @@ -391,32 +437,13 @@ impl Assembly { length_tol: f64, angle_tol: f64, slope_tol: f64, + height_tol: Option, ) -> PyResult { - if let Some(roofs) = &roofs { - if roofs.len() != pieces.len() { - return Err(PyValueError::new_err(format!( - "{} roofs for {} pieces", - roofs.len(), - pieces.len() - ))); - } - } - let shapes = pieces - .into_iter() - .enumerate() - .map(|(i, polygon)| tiling_geometry::Shape { - polygon, - roof: roofs.as_ref().map(|r| roof_of(r[i])), - }) - .collect(); - let tolerance = tiling_geometry::ContactTolerance { - length: length_tol, - angle: angle_tol, - slope: slope_tol, - }; + let (shapes, tolerance) = + puzzle_parts(pieces, roofs, length_tol, angle_tol, slope_tol, height_tol)?; tiling_geometry::Assembly::new(target, shapes, tolerance) .map(|inner| Assembly { inner }) - .map_err(|error| PyValueError::new_err(error.to_string())) + .map_err(refused) } #[getter] @@ -559,17 +586,246 @@ impl Assembly { }) } - /// Candidate work so far as `(generated, rejected_outside, rejected_overlap)`. - fn stats(&self) -> (u64, u64, u64) { + /// The largest step between this piece's roof, placed so, and the roofs of + /// the placed pieces along the edges it shares with them, in mm. + fn roof_step(&self, piece: usize, pose: PoseArg) -> PyResult { + self.inner.roof_step(piece, &pose_of(pose)).map_err(refused) + } + + /// The separate parts of the uncovered region, each as `(area, width, + /// corners)`: its area in mm², its least width if it is convex, and the + /// indices of its corners in `frontier()`, counter-clockwise. `None` if the + /// corners do not link up into closed outlines. + fn cavities(&self) -> Option> { + let corners = self.inner.frontier(); + Some( + self.inner + .cavities(&corners)? + .into_iter() + .map(|c| (c.area, c.width, c.corners)) + .collect(), + ) + } + + /// Candidate work so far as `(generated, rejected_outside, + /// rejected_overlap, rejected_roof)`. + fn stats(&self) -> (u64, u64, u64, u64) { let stats = self.inner.stats(); ( stats.generated, stats.rejected_outside, stats.rejected_overlap, + stats.rejected_roof, ) } } +fn symmetry_of( + target: &[Vec2], + shapes: &[tiling_geometry::Shape], + tolerance: &tiling_geometry::ContactTolerance, + poses: &[&Vec], +) -> PyResult { + // Building an assembly checks the polygons and the tolerances. + let assembly = tiling_geometry::Assembly::new(target.to_vec(), shapes.to_vec(), *tolerance) + .map_err(refused)?; + for given in poses { + if given.len() != shapes.len() { + return Err(PyValueError::new_err(format!( + "{} poses for {} pieces", + given.len(), + shapes.len() + ))); + } + } + Ok(tiling_search::Symmetry::new( + target, + shapes, + assembly.graph(), + tolerance, + )) +} + +/// The canonical form of an assembly: one pose per piece, the same for every +/// assembly that differs only by exchanging congruent pieces, turning a piece +/// onto itself, or turning the tray onto itself. +#[pyfunction] +#[pyo3(signature = (target, pieces, roofs, poses, *, length_tol, angle_tol, slope_tol, height_tol=None))] +#[allow(clippy::too_many_arguments)] +fn canonical_poses( + target: Vec<[f64; 2]>, + pieces: Vec>, + roofs: Option>, + poses: Vec, + length_tol: f64, + angle_tol: f64, + slope_tol: f64, + height_tol: Option, +) -> PyResult> { + let (shapes, tolerance) = + puzzle_parts(pieces, roofs, length_tol, angle_tol, slope_tol, height_tol)?; + let symmetry = symmetry_of(&target, &shapes, &tolerance, &[&poses])?; + let poses: Vec = poses.into_iter().map(pose_of).collect(); + Ok(symmetry + .canonical(&poses) + .into_iter() + .map(|p| (p.x, p.y, p.theta)) + .collect()) +} + +/// Whether two assemblies of one puzzle have the same canonical form. +#[pyfunction] +#[pyo3(signature = (target, pieces, roofs, first, second, *, length_tol, angle_tol, slope_tol, height_tol=None))] +#[allow(clippy::too_many_arguments)] +fn same_assembly( + target: Vec<[f64; 2]>, + pieces: Vec>, + roofs: Option>, + first: Vec, + second: Vec, + length_tol: f64, + angle_tol: f64, + slope_tol: f64, + height_tol: Option, +) -> PyResult { + let (shapes, tolerance) = + puzzle_parts(pieces, roofs, length_tol, angle_tol, slope_tol, height_tol)?; + let symmetry = symmetry_of(&target, &shapes, &tolerance, &[&first, &second])?; + let first: Vec = first.into_iter().map(pose_of).collect(); + let second: Vec = second.into_iter().map(pose_of).collect(); + Ok(symmetry.same(&first, &second)) +} + +/// What `contact_dfs` found, and the work it took. +#[pyclass(frozen, get_all, module = "maxplus_solvers._native")] +struct ContactDfsOutcome { + /// One list of poses per solution, in piece order. + solutions: Vec>, + exhausted: bool, + nodes: u64, + backtracks: u64, + placements: u64, + max_depth: u64, + candidates_generated: u64, + rejected_outside: u64, + rejected_overlap: u64, + rejected_roof: u64, + pruned_cavity: u64, + pruned_closure: u64, + pruned_anchor: u64, + pruned_lookahead: u64, + duplicates: u64, + cavities_unknown: u64, + wall_time_s: f64, + first_solution_s: Option, + tray_order: usize, + anchor: Option, +} + +/// The whole contact search, run to completion in Rust without the interpreter lock. +#[pyfunction] +#[pyo3(signature = ( + target, pieces, roofs=None, *, + length_tol, angle_tol, slope_tol, height_tol=None, + 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, +))] +#[allow(clippy::too_many_arguments)] +fn contact_dfs( + py: Python<'_>, + target: Vec<[f64; 2]>, + pieces: Vec>, + roofs: Option>, + length_tol: f64, + angle_tol: f64, + slope_tol: f64, + height_tol: Option, + max_solutions: Option, + time_limit_s: Option, + node_limit: Option, + all_tray_rotations: bool, + anchor: bool, + cavity_pruning: bool, + closure_pruning: bool, + lookahead: bool, + order: &str, + seed: u64, +) -> PyResult { + use tiling_search::contact_dfs::{Options, Order, TrayRotations, solve}; + + let order = match order { + "generated" => Order::Generated, + "matched-edges" => Order::MatchedEdges, + "random" => Order::Random, + other => { + return Err(PyValueError::new_err(format!( + "order must be generated, matched-edges or random, not {other:?}" + ))); + } + }; + + let (shapes, tolerance) = + puzzle_parts(pieces, roofs, length_tol, angle_tol, slope_tol, height_tol)?; + let time_limit = match time_limit_s { + None => None, + Some(seconds) if seconds.is_finite() && seconds >= 0.0 => { + Some(Duration::from_secs_f64(seconds)) + } + Some(_) => { + return Err(PyValueError::new_err( + "time_limit_s must be finite and not negative", + )); + } + }; + let options = Options { + max_solutions, + time_limit, + node_limit, + tray_rotations: if all_tray_rotations { + TrayRotations::All + } else { + TrayRotations::Once + }, + anchor, + cavity_pruning, + closure_pruning, + lookahead, + order, + seed, + }; + let outcome = py + .detach(|| solve(target, shapes, tolerance, &options)) + .map_err(refused)?; + let stats = outcome.stats; + Ok(ContactDfsOutcome { + solutions: outcome + .solutions + .into_iter() + .map(|poses| poses.into_iter().map(|p| (p.x, p.y, p.theta)).collect()) + .collect(), + exhausted: outcome.exhausted, + nodes: stats.nodes, + backtracks: stats.backtracks, + placements: stats.placements, + max_depth: stats.max_depth, + candidates_generated: stats.candidates.generated, + rejected_outside: stats.candidates.rejected_outside, + rejected_overlap: stats.candidates.rejected_overlap, + rejected_roof: stats.candidates.rejected_roof, + pruned_cavity: stats.pruned_cavity, + pruned_closure: stats.pruned_closure, + pruned_anchor: stats.pruned_anchor, + pruned_lookahead: stats.pruned_lookahead, + duplicates: stats.duplicates, + cavities_unknown: stats.cavities_unknown, + wall_time_s: outcome.elapsed.as_secs_f64(), + first_solution_s: outcome.first_solution.map(|d| d.as_secs_f64()), + tray_order: outcome.tray_order, + anchor: outcome.anchor, + }) +} + #[pymodule] fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(version, m)?)?; @@ -594,5 +850,9 @@ fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_function(wrap_pyfunction!(canonical_poses, m)?)?; + m.add_function(wrap_pyfunction!(same_assembly, m)?)?; + m.add_function(wrap_pyfunction!(contact_dfs, m)?)?; + m.add_class::()?; Ok(()) } diff --git a/crates/tiling-search/Cargo.toml b/crates/tiling-search/Cargo.toml index 1402fa8..5a6370f 100644 --- a/crates/tiling-search/Cargo.toml +++ b/crates/tiling-search/Cargo.toml @@ -11,5 +11,9 @@ repository.workspace = true tiling-core.workspace = true tiling-geometry.workspace = true +[dev-dependencies] +proptest.workspace = true +tiling-geometry = { workspace = true, features = ["testing"] } + [lints] workspace = true diff --git a/crates/tiling-search/src/canonical.rs b/crates/tiling-search/src/canonical.rs new file mode 100644 index 0000000..1817fa4 --- /dev/null +++ b/crates/tiling-search/src/canonical.rs @@ -0,0 +1,407 @@ +//! When two assemblies are the same, and one form to stand for all of them. +//! +//! Three things can differ between assemblies that nobody would call different: +//! +//! - which of several congruent pieces sits where; +//! - a piece turned onto itself, a square by a quarter turn; +//! - the whole assembly turned with the tray, a square tray by a quarter turn. +//! +//! [`Symmetry::canonical`] removes all three. A piece is described by its +//! *seat*: where its centroid is and how it is turned, the turn taken modulo +//! the piece's own symmetry. Congruent pieces need not be stored the same way +//! round, so the turn is measured for the first piece of the class: the turn +//! that piece would need to lie exactly where this one does. Within a class of congruent pieces the seats are +//! put in order and dealt out to the pieces by index. That is done for each +//! rotation of the tray, and the rotation whose list of seats comes first is +//! kept. +//! +//! Comparisons are in `f64` with the search's tolerances: two numbers within +//! the tolerance are equal, and otherwise the smaller comes first. Such an +//! order is only as good as the gap between "equal" and "different". In an +//! assembly, seats that differ do so by millimetres and seats that agree do so +//! to rounding, with the tolerance far from both. + +use std::cmp::Ordering; +use std::f64::consts::{PI, TAU}; + +use tiling_core::{Pose, Vec2}; +use tiling_geometry::{ContactTolerance, EdgeGraph, Shape, centroid, rotation_order}; + +/// Where a piece sits: its centroid in the world, and its turn in `[0, period)`. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Seat { + x: f64, + y: f64, + turn: f64, +} + +/// The symmetries of one puzzle: of its tray, and of and among its pieces. +#[derive(Debug, Clone)] +pub struct Symmetry { + centre: Vec2, + tray_order: usize, + classes: Vec, + /// For each piece, the smallest turn that maps it onto itself. + periods: Vec, + /// For each piece, the turn that takes the first piece of its class onto it. + /// A seat's turn is that of the class's first piece, were it sitting there. + offsets: Vec, + /// Local centroids. A turn about this point is what maps a piece onto itself. + centroids: Vec, + length: f64, + angle: f64, +} + +impl Symmetry { + pub fn new( + target: &[Vec2], + shapes: &[Shape], + graph: &EdgeGraph, + tolerance: &ContactTolerance, + ) -> Symmetry { + Symmetry { + centre: centroid(target), + tray_order: rotation_order(target, tolerance), + classes: (0..shapes.len()).map(|p| graph.class(p)).collect(), + periods: (0..shapes.len()) + .map(|p| TAU / graph.symmetry(p) as f64) + .collect(), + offsets: (0..shapes.len()) + .map(|p| graph.turn_from_class(p)) + .collect(), + centroids: shapes.iter().map(|s| centroid(&s.polygon)).collect(), + length: tolerance.length, + angle: tolerance.angle, + } + } + + /// How many rotations map the tray onto itself. + pub fn tray_order(&self) -> usize { + self.tray_order + } + + /// The point the tray turns about. + pub fn centre(&self) -> Vec2 { + self.centre + } + + /// The class of each piece: the lowest-numbered piece congruent to it. + pub fn classes(&self) -> &[usize] { + &self.classes + } + + /// A turn brought into `[0, period)`, with anything within the tolerance of + /// a whole period counted as none. + fn reduced(&self, turn: f64, period: f64) -> f64 { + let turn = turn.rem_euclid(period); + if period - turn <= self.angle { + 0.0 + } else { + turn + } + } + + fn seat(&self, piece: usize, pose: &Pose) -> Seat { + let [x, y] = pose.apply(self.centroids[piece]); + Seat { + x, + y, + turn: self.reduced(pose.theta + self.offsets[piece], self.periods[piece]), + } + } + + fn pose(&self, piece: usize, seat: &Seat) -> Pose { + // The same range as `pose_at_corner` uses. + let theta = PI - (PI - (seat.turn - self.offsets[piece])).rem_euclid(TAU); + let (s, c) = theta.sin_cos(); + let [lx, ly] = self.centroids[piece]; + Pose { + x: seat.x - (c * lx - s * ly), + y: seat.y - (s * lx + c * ly), + theta, + } + } + + fn compare(&self, a: &Seat, b: &Seat) -> Ordering { + if (a.x - b.x).abs() > self.length { + a.x.total_cmp(&b.x) + } else if (a.y - b.y).abs() > self.length { + a.y.total_cmp(&b.y) + } else if (a.turn - b.turn).abs() > self.angle { + a.turn.total_cmp(&b.turn) + } else { + Ordering::Equal + } + } + + fn compare_all(&self, a: &[Seat], b: &[Seat]) -> Ordering { + a.iter() + .zip(b) + .map(|(x, y)| self.compare(x, y)) + .find(|order| order.is_ne()) + .unwrap_or(Ordering::Equal) + } + + /// The seats of an assembly turned with the tray by `step` of its + /// rotations, congruent pieces put in order. + fn seats(&self, poses: &[Pose], step: usize) -> Vec { + let turn = step as f64 * TAU / self.tray_order as f64; + let (s, c) = turn.sin_cos(); + let mut seats: Vec = poses + .iter() + .enumerate() + .map(|(piece, pose)| { + let seat = self.seat(piece, pose); + let (dx, dy) = (seat.x - self.centre[0], seat.y - self.centre[1]); + Seat { + x: self.centre[0] + c * dx - s * dy, + y: self.centre[1] + s * dx + c * dy, + turn: self.reduced(seat.turn + turn, self.periods[piece]), + } + }) + .collect(); + for class in 0..poses.len() { + let members: Vec = (class..poses.len()) + .filter(|&p| self.classes[p] == class) + .collect(); + // An insertion sort: the tolerant order is not one a library sort may rely on. + for i in 1..members.len() { + let mut j = i; + while j > 0 + && self + .compare(&seats[members[j]], &seats[members[j - 1]]) + .is_lt() + { + seats.swap(members[j], members[j - 1]); + j -= 1; + } + } + } + seats + } + + fn canonical_seats(&self, poses: &[Pose]) -> Vec { + let mut best = self.seats(poses, 0); + for step in 1..self.tray_order { + let seats = self.seats(poses, step); + if self.compare_all(&seats, &best).is_lt() { + best = seats; + } + } + best + } + + /// The canonical form of an assembly: one pose per piece, the same for + /// every assembly that differs from this one only by exchanging congruent + /// pieces, turning pieces onto themselves, or turning the tray. + pub fn canonical(&self, poses: &[Pose]) -> Vec { + self.canonical_seats(poses) + .iter() + .enumerate() + .map(|(piece, seat)| self.pose(piece, seat)) + .collect() + } + + /// Whether two assemblies have the same canonical form. + pub fn same(&self, a: &[Pose], b: &[Pose]) -> bool { + a.len() == b.len() + && self + .compare_all(&self.canonical_seats(a), &self.canonical_seats(b)) + .is_eq() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::f64::consts::FRAC_PI_2; + use tiling_geometry::transform; + + const TOL: ContactTolerance = ContactTolerance { + length: 1e-7, + angle: 1e-7, + slope: 1e-7, + height: 1e-7, + }; + + fn rectangle(w: f64, h: f64) -> Vec { + vec![ + [-w / 2.0, -h / 2.0], + [w / 2.0, -h / 2.0], + [w / 2.0, h / 2.0], + [-w / 2.0, h / 2.0], + ] + } + + fn symmetry_of(target: &[Vec2], polygons: &[Vec]) -> Symmetry { + let shapes: Vec = polygons + .iter() + .map(|polygon| Shape { + polygon: polygon.clone(), + roof: None, + }) + .collect(); + Symmetry::new(target, &shapes, &EdgeGraph::build(&shapes, &TOL), &TOL) + } + + fn at(x: f64, y: f64, theta: f64) -> Pose { + Pose { x, y, theta } + } + + /// A square tray of side 4 about (2, 2); a 1 x 4 strip, a 3 x 4 block. + fn strips() -> (Vec, Vec>) { + ( + vec![[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]], + vec![rectangle(1.0, 4.0), rectangle(3.0, 4.0)], + ) + } + + #[test] + fn the_four_turns_of_an_assembly_have_one_form() { + let (tray, pieces) = strips(); + let symmetry = symmetry_of(&tray, &pieces); + assert_eq!(symmetry.tray_order(), 4); + // The strip against the left wall, then the same turned with the tray by + // quarter turns: against the bottom, the right and the top. + let turns = [ + [at(0.5, 2.0, 0.0), at(2.5, 2.0, 0.0)], + [at(2.0, 0.5, FRAC_PI_2), at(2.0, 2.5, FRAC_PI_2)], + [at(3.5, 2.0, 0.0), at(1.5, 2.0, 0.0)], + [at(2.0, 3.5, FRAC_PI_2), at(2.0, 1.5, FRAC_PI_2)], + ]; + let form = symmetry.canonical(&turns[0]); + for other in &turns { + assert!(symmetry.same(&turns[0], other)); + let again = symmetry.canonical(other); + for (p, q) in form.iter().zip(&again) { + assert!((p.x - q.x).abs() <= 1e-9 && (p.y - q.y).abs() <= 1e-9); + assert!((p.theta - q.theta).abs() <= 1e-9); + } + } + // The form is one of the four: its pieces still tile the tray. + let strip = transform(&pieces[0], &form[0]); + assert!( + strip + .iter() + .all(|p| (-1e-9..=4.0 + 1e-9).contains(&p[0]) + && (-1e-9..=4.0 + 1e-9).contains(&p[1])) + ); + } + + #[test] + fn a_half_turn_of_a_rectangle_is_no_turn() { + let (tray, pieces) = strips(); + let symmetry = symmetry_of(&tray, &pieces); + let plain = [at(0.5, 2.0, 0.0), at(2.5, 2.0, 0.0)]; + let flipped = [at(0.5, 2.0, PI), at(2.5, 2.0, -PI)]; + assert!(symmetry.same(&plain, &flipped)); + } + + #[test] + fn a_different_assembly_has_a_different_form() { + // A tray that is not square, so that nothing can be turned into anything else. + let tray = vec![[0.0, 0.0], [4.0, 0.0], [4.0, 3.0], [0.0, 3.0]]; + let pieces = vec![rectangle(1.0, 3.0), rectangle(3.0, 3.0)]; + let symmetry = symmetry_of(&tray, &pieces); + assert_eq!(symmetry.tray_order(), 2); + let left = [at(0.5, 1.5, 0.0), at(2.5, 1.5, 0.0)]; + let right = [at(3.5, 1.5, 0.0), at(1.5, 1.5, 0.0)]; + // Left and right are each other's half turn about (2, 1.5). + assert!(symmetry.same(&left, &right)); + let shifted = [at(0.5, 1.5, 0.0), at(2.6, 1.5, 0.0)]; + assert!(!symmetry.same(&left, &shifted)); + // So is a piece moved only up, and a piece only turned (by other than its half turn). + let raised = [at(0.5, 1.6, 0.0), at(2.5, 1.5, 0.0)]; + assert!(!symmetry.same(&left, &raised)); + let turned = [at(0.5, 1.5, 0.3), at(2.5, 1.5, 0.0)]; + assert!(!symmetry.same(&left, &turned)); + } + + #[test] + fn congruent_pieces_may_change_places() { + let tray = vec![[0.0, 0.0], [4.0, 0.0], [4.0, 3.0], [0.0, 3.0]]; + let pieces = vec![ + rectangle(1.0, 3.0), + rectangle(1.0, 3.0), + rectangle(2.0, 3.0), + ]; + let symmetry = symmetry_of(&tray, &pieces); + assert_eq!(symmetry.classes(), &[0, 0, 2]); + let one = [at(0.5, 1.5, 0.0), at(1.5, 1.5, 0.0), at(3.0, 1.5, 0.0)]; + let swapped = [at(1.5, 1.5, 0.0), at(0.5, 1.5, 0.0), at(3.0, 1.5, 0.0)]; + assert!(symmetry.same(&one, &swapped)); + // The wide piece between the two narrow ones is another assembly. + let between = [at(0.5, 1.5, 0.0), at(3.5, 1.5, 0.0), at(2.0, 1.5, 0.0)]; + assert!(!symmetry.same(&one, &between)); + // In the form, the lower-numbered twin has the seat that comes first. + let form = symmetry.canonical(&swapped); + assert!(form[0].x < form[1].x); + } + + #[test] + fn twins_stored_at_different_turns_change_places_with_their_turns() { + // The second narrow strip is stored lying down: the same piece, a quarter + // turn round. Standing in the tray it has the pose of a quarter turn. + let tray = vec![[0.0, 0.0], [4.0, 0.0], [4.0, 3.0], [0.0, 3.0]]; + let pieces = vec![ + rectangle(1.0, 3.0), + rectangle(3.0, 1.0), + rectangle(2.0, 3.0), + ]; + let symmetry = symmetry_of(&tray, &pieces); + assert_eq!(symmetry.classes(), &[0, 0, 2]); + let one = [ + at(0.5, 1.5, 0.0), + at(1.5, 1.5, FRAC_PI_2), + at(3.0, 1.5, 0.0), + ]; + let swapped = [ + at(1.5, 1.5, 0.0), + at(0.5, 1.5, FRAC_PI_2), + at(3.0, 1.5, 0.0), + ]; + assert!(symmetry.same(&one, &swapped)); + // The form is still the assembly: by hand, the strips cover x in [0, 1] + // and [1, 2] and the block [2, 4], each over the tray's whole height. + for poses in [&one, &swapped] { + let form = symmetry.canonical(poses); + let mut spans: Vec<[f64; 4]> = pieces + .iter() + .zip(&form) + .map(|(polygon, pose)| { + let world = transform(polygon, pose); + let low = |axis: usize| world.iter().map(|p| p[axis]).fold(f64::MAX, f64::min); + let high = |axis: usize| world.iter().map(|p| p[axis]).fold(f64::MIN, f64::max); + [low(0), high(0), low(1), high(1)] + }) + .collect(); + spans.sort_by(|a, b| a[0].total_cmp(&b[0])); + let expected = [ + [0.0, 1.0, 0.0, 3.0], + [1.0, 2.0, 0.0, 3.0], + [2.0, 4.0, 0.0, 3.0], + ]; + for (span, want) in spans.iter().zip(&expected) { + for (a, b) in span.iter().zip(want) { + assert!((a - b).abs() <= 1e-9, "{spans:?}"); + } + } + } + } + + #[test] + fn a_piece_not_stored_about_its_centroid_is_still_recognised() { + // The strip stored with a corner at its origin: a half turn about the origin + // moves it, a half turn about its centroid does not. + let tray = vec![[0.0, 0.0], [4.0, 0.0], [4.0, 3.0], [0.0, 3.0]]; + let strip = vec![[0.0, 0.0], [1.0, 0.0], [1.0, 3.0], [0.0, 3.0]]; + let symmetry = symmetry_of(&tray, &[strip.clone(), rectangle(3.0, 3.0)]); + let plain = [at(0.0, 0.0, 0.0), at(2.5, 1.5, 0.0)]; + let flipped = [at(1.0, 3.0, PI), at(2.5, 1.5, 0.0)]; + assert!(symmetry.same(&plain, &flipped)); + let form = symmetry.canonical(&flipped); + let world = transform(&strip, &form[0]); + let cx: f64 = world.iter().map(|p| p[0]).sum::() / 4.0; + assert!((cx - 0.5).abs() <= 1e-9 || (cx - 3.5).abs() <= 1e-9); + } +} diff --git a/crates/tiling-search/src/contact_dfs.rs b/crates/tiling-search/src/contact_dfs.rs new file mode 100644 index 0000000..725e0ad --- /dev/null +++ b/crates/tiling-search/src/contact_dfs.rs @@ -0,0 +1,1221 @@ +//! Depth-first search over corner contacts. +//! +//! The rule is the one `tiling_geometry::assembly` argues for: at every node, +//! look at the convex corners of the uncovered region, take the one with the +//! fewest placements that fill it, and try each of those. Nothing else is +//! branched on. +//! +//! On top of the rule this search has what its Python prototype lacks. +//! +//! **Roofs.** When the pieces have roofs, a placement must also continue its +//! neighbours' roofs. That test is part of candidate generation +//! ([`Assembly::propose`]) and so it shapes the choice of corner as well. +//! +//! **Cavity pruning.** The uncovered region falls into cavities. The pieces +//! that end up in a cavity have exactly its area, and none is wider than a +//! convex cavity is. A state is a dead end when some cavity's area is not the +//! sum of the areas of any set of remaining pieces that could go into it, or +//! when some remaining piece could go into no cavity. +//! +//! **Closure pruning.** Take a straight run of the uncovered region's boundary +//! between two convex corners. Neither end lets a piece reach past it, so the +//! pieces that lie along the run each have one whole edge on it, and those +//! edges make up its length exactly. Likewise the pieces that meet in a convex +//! corner each have a vertex there, and their angles make up the corner's. A +//! state is a dead end when a run's length is not a sum of edge lengths of +//! different remaining pieces, or a convex corner's angle not a sum of their +//! angles. +//! +//! **Looking ahead.** Off by default. A placement counts towards a corner only if the state it +//! leads to is not a dead end by the two rules above. The corner branched on +//! is then the one with the fewest placements that survive, which is often one +//! and often none. +//! +//! **The tray's rotations.** A tray that can be turned onto itself gives every +//! assembly once per turn. With [`TrayRotations::Once`] one piece, the +//! *anchor*, is only ever put down with its centroid in one sector of the tray: +//! `[0, 2π/k]` as seen from the tray's centre, for a tray with `k` rotations. +//! Every assembly has a turn that brings the anchor there, so one of each +//! family survives. An anchor whose centroid is on a sector boundary or at the +//! centre survives more than once; those repeats are removed by comparing +//! canonical forms. The anchor is the largest piece that is congruent to no +//! other, so that "the anchor" names one place in an assembly. If there is no +//! such piece, nothing is pruned and the comparison does all of the work. +//! +//! All of this is `f64` with tolerances. The pruning rules are sound for exact +//! assemblies of convex pieces; that they change nothing is tested, here on +//! random tilings and from Python on the corpus. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::f64::consts::TAU; +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, +}; + +use crate::canonical::Symmetry; + +/// What to do about assemblies that are turns of one another. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrayRotations { + /// Return one assembly of each family, in canonical form. + Once, + /// Return every assembly as it is found. + All, +} + +/// How to run the search. Only `max_solutions`, the limits and +/// `tray_rotations` change what is returned; the rest change the work. +#[derive(Debug, Clone, PartialEq)] +pub struct Options { + /// Stop after this many solutions; `None` runs the search to its end. + pub max_solutions: Option, + /// Checked at every node. + pub time_limit: Option, + pub node_limit: Option, + pub tray_rotations: TrayRotations, + /// Hold the anchor piece to one sector of the tray. Only with [`TrayRotations::Once`]. + pub anchor: bool, + /// Give up states with a cavity that cannot be filled. + pub cavity_pruning: bool, + /// Give up states with a run or a corner that the remaining pieces cannot close. + pub closure_pruning: bool, + /// 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. Off by default: it visits + /// fewer nodes but, on most of the corpus, examines more states to do so. + pub lookahead: bool, + pub order: Order, + /// For [`Order::Random`]. + pub seed: u64, +} + +/// The order in which the candidates of a node are tried. It decides how soon +/// the first solution turns up, and nothing about what a whole search finds. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Order { + /// As [`Assembly::propose`] lists them: by piece, then by vertex. + Generated, + /// Placements that share more whole edges with placed pieces first. In a + /// puzzle cut from a subdivision, neighbours share whole edges. + MatchedEdges, + /// A random order drawn from the seed. + Random, +} + +impl Default for Options { + fn default() -> Options { + Options { + max_solutions: Some(1), + time_limit: None, + node_limit: None, + tray_rotations: TrayRotations::Once, + anchor: true, + cavity_pruning: true, + closure_pruning: true, + lookahead: false, + order: Order::MatchedEdges, + seed: 0, + } + } +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Stats { + /// Nodes expanded, the root included. + pub nodes: u64, + /// Nodes abandoned: no candidate for the corner, a dead end by a pruning + /// rule, or every piece down with something left uncovered. + pub backtracks: u64, + /// Pieces put down as a branch of the search, counting every attempt. + /// Placements tried while looking ahead are not counted. + pub placements: u64, + /// The largest number of pieces down at once. + pub max_depth: u64, + pub candidates: CandidateStats, + /// Nodes abandoned because of a cavity. Counted in `backtracks` too. + pub pruned_cavity: u64, + /// Nodes abandoned because of a run or a corner. Counted in `backtracks` too. + pub pruned_closure: u64, + /// Candidates dropped for putting the anchor outside its sector. + pub pruned_anchor: u64, + /// Candidates dropped by looking one placement ahead. + pub pruned_lookahead: u64, + /// Assemblies found that were a turn of one already found. + pub duplicates: u64, + /// States whose corners did not link up into cavities, and so were not pruned. + pub cavities_unknown: u64, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Outcome { + /// One pose per piece, in piece order. + pub solutions: Vec>, + /// The search ran to its end: `solutions` is all it can find. + pub exhausted: bool, + pub stats: Stats, + pub elapsed: Duration, + pub first_solution: Option, + /// How many rotations map the tray onto itself. + pub tray_order: usize, + /// The piece held to one sector, if any was. + pub anchor: Option, +} + +/// Steps a question about areas may take before it is answered "perhaps". +const AREA_BUDGET: u32 = 20_000; +/// The same for the questions asked of every run and corner of every state. +const CLOSURE_BUDGET: u32 = 2_000; + +/// Whether some of `areas[from..]`, largest first, add up to `need`. `rest[i]` +/// is the sum of `areas[i..]`. Running out of budget answers yes, which is the +/// answer that prunes nothing. +fn adds_up( + areas: &[f64], + rest: &[f64], + from: usize, + need: f64, + tolerance: f64, + budget: &mut u32, +) -> bool { + if need.abs() <= tolerance { + return true; + } + if from == areas.len() || rest[from] < need - tolerance { + return false; + } + if *budget == 0 { + return true; + } + *budget -= 1; + (areas[from] <= need + tolerance + && adds_up(areas, rest, from + 1, need - areas[from], tolerance, budget)) + || adds_up(areas, rest, from + 1, need, tolerance, budget) +} + +/// The answer to "can these pieces supply this sum?". +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Supply { + /// Yes, and these pieces do it. + Yes(u64), + No, + /// The budget ran out. Treated as yes, which prunes nothing. + Perhaps, +} + +/// What is known about one sum, from the questions already asked about it. +#[derive(Default)] +struct Known { + /// Sets of pieces that supply it. + supplied_by: Vec, + /// Sets of pieces that cannot. + not_from: Vec, + /// Sets of pieces for which the budget ran out. + undecided: Vec, +} + +/// Answers kept per sum, and sums kept in all, before the oldest are dropped. +const KNOWN_PER_SUM: usize = 8; +const KNOWN_SUMS: usize = 1 << 20; + +/// One kind of number every piece has several of: its edge lengths, or its angles. +/// +/// The same corners and runs are met again and again as a search moves through +/// neighbouring states, with one piece more or less to draw on. So answers are +/// remembered by the sum asked for: a set of pieces that supplied it still +/// does while they are all free, and a set that could not supply it still +/// cannot when pieces are taken away. Sets of pieces are bit masks, which is +/// why the memory is only used for up to 64 pieces. +struct Values { + /// The distinct values of each piece. + each: Vec>, + least: Vec, + most: Vec, + known: RefCell>, +} + +fn remember(list: &mut Vec, set: u64) { + if list.len() == KNOWN_PER_SUM { + list.remove(0); + } + list.push(set); +} + +impl Values { + fn new(all: impl Iterator>, tolerance: f64) -> Values { + // A rectangle has two lengths and one angle. + let each: Vec> = all + .map(|values| { + let mut kept: Vec = Vec::new(); + for value in values { + if !kept.iter().any(|k| (k - value).abs() <= tolerance) { + kept.push(value); + } + } + kept + }) + .collect(); + let fold = |start: f64, pick: fn(f64, f64) -> f64| -> Vec { + each.iter() + .map(|v| v.iter().copied().fold(start, pick)) + .collect() + }; + Values { + least: fold(f64::INFINITY, f64::min), + most: fold(0.0, f64::max), + each, + known: RefCell::new(HashMap::new()), + } + } + + /// Whether taking at most one value from each of the pieces `free[from..]` + /// can add up to `need`. `bounds[i]` holds the smallest value among those + /// pieces and the sum of their largest. + fn one_from_each( + &self, + free: &[usize], + bounds: &[(f64, f64)], + from: usize, + need: f64, + tolerance: f64, + budget: &mut u32, + ) -> Supply { + if need.abs() <= tolerance { + return Supply::Yes(0); + } + if from == free.len() { + return Supply::No; + } + let (least, most) = bounds[from]; + if most < need - tolerance || least > need + tolerance { + return Supply::No; + } + if *budget == 0 { + return Supply::Perhaps; + } + *budget -= 1; + let piece = free[from]; + for &value in &self.each[piece] { + if value > need + tolerance { + continue; + } + match self.one_from_each(free, bounds, from + 1, need - value, tolerance, budget) { + Supply::Yes(set) => return Supply::Yes(set | 1 << (piece % 64)), + Supply::Perhaps => return Supply::Perhaps, + Supply::No => {} + } + } + self.one_from_each(free, bounds, from + 1, need, tolerance, budget) + } + + /// Whether `need` is a sum of one value each from some of the pieces + /// `free`. An undecided question counts as yes. + fn supply(&self, free: &[usize], need: f64, tolerance: f64) -> bool { + if need.abs() <= tolerance { + return true; + } + let remembering = self.each.len() <= 64; + let set = free.iter().fold(0u64, |set, &p| set | 1 << (p % 64)); + let key = need.to_bits(); + if remembering { + if let Some(known) = self.known.borrow().get(&key) { + if known.supplied_by.iter().any(|&s| s & !set == 0) + || known.undecided.contains(&set) + { + return true; + } + if known.not_from.iter().any(|&s| set & !s == 0) { + return false; + } + } + } + let mut bounds = vec![(f64::INFINITY, 0.0); free.len() + 1]; + for i in (0..free.len()).rev() { + let (least, most) = bounds[i + 1]; + bounds[i] = (least.min(self.least[free[i]]), most + self.most[free[i]]); + } + let mut budget = CLOSURE_BUDGET; + let answer = self.one_from_each(free, &bounds, 0, need, tolerance, &mut budget); + if remembering { + let mut known = self.known.borrow_mut(); + if known.len() >= KNOWN_SUMS { + known.clear(); + } + let entry = known.entry(key).or_default(); + match answer { + Supply::Yes(by) => remember(&mut entry.supplied_by, by), + Supply::No => remember(&mut entry.not_from, set), + Supply::Perhaps => remember(&mut entry.undecided, set), + } + } + answer != Supply::No + } +} + +/// SplitMix64: a small generator with a guaranteed stream, so that a seed means +/// the same search everywhere. +struct Random(u64); + +impl Random { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn shuffle(&mut self, items: &mut [T]) { + for i in (1..items.len()).rev() { + let j = (self.next() % (i as u64 + 1)) as usize; + items.swap(i, j); + } + } +} + +enum DeadEnd { + Cavity, + Closure, +} + +fn distance(a: Vec2, b: Vec2) -> f64 { + (b[0] - a[0]).hypot(b[1] - a[1]) +} + +struct Search<'a> { + assembly: Assembly, + options: &'a Options, + symmetry: Symmetry, + anchor: Option, + centroids: Vec, + areas: Vec, + widths: Vec, + lengths: Values, + angles: Values, + area_tolerance: f64, + /// Slack for a sum of up to one length, or one angle, from every piece. + length_slack: f64, + angle_slack: f64, + stats: Stats, + solutions: Vec>, + started: Instant, + first_solution: Option, + stopped: bool, + random: Random, +} + +impl Search<'_> { + fn pruning(&self) -> bool { + self.options.cavity_pruning || self.options.closure_pruning + } + + /// The pieces not yet placed, leaving out `except`. + fn free(&self, except: Option) -> Vec { + (0..self.areas.len()) + .filter(|&p| Some(p) != except && self.assembly.pose(p).is_none()) + .collect() + } + + /// Whether the anchor, placed so, has its centroid in the sector it is held to. + fn in_sector(&self, candidate: &CandidatePlacement) -> bool { + let tolerance = self.assembly.tolerance(); + let centre = self.symmetry.centre(); + let [x, y] = candidate.pose.apply(self.centroids[candidate.piece]); + let (dx, dy) = (x - centre[0], y - centre[1]); + let radius = dx.hypot(dy); + if radius <= tolerance.length { + return true; + } + let bearing = dy.atan2(dx).rem_euclid(TAU); + let slack = tolerance.length / radius + tolerance.angle; + bearing <= TAU / self.symmetry.tray_order() as f64 + slack || bearing >= TAU - slack + } + + /// The cavities of the state as it stands, if pruning wants them and they can be traced. + fn cavities(&mut self, corners: &[Corner]) -> Option> { + if !self.pruning() { + return None; + } + let cavities = self.assembly.cavities(corners); + if cavities.is_none() { + self.stats.cavities_unknown += 1; + } + cavities + } + + /// Why the state as it stands cannot be completed, if the pruning rules can tell. + fn dead_end(&self, corners: &[Corner], cavities: &[Cavity]) -> Option { + let free = self.free(None); + if self.options.cavity_pruning && !self.cavities_can_be_filled(&free, cavities) { + Some(DeadEnd::Cavity) + } else if self.options.closure_pruning + && !self.closures_can_be_met(&free, corners, cavities) + { + Some(DeadEnd::Closure) + } else { + None + } + } + + /// Whether every cavity can still be filled, as far as areas and widths can tell. + fn cavities_can_be_filled(&self, free: &[usize], cavities: &[Cavity]) -> bool { + let length = self.assembly.tolerance().length; + let mut largest_first = free.to_vec(); + largest_first.sort_by(|&a, &b| self.areas[b].total_cmp(&self.areas[a])); + let mut has_a_place = vec![false; largest_first.len()]; + for cavity in cavities { + let mut areas = Vec::with_capacity(largest_first.len()); + for (slot, &piece) in largest_first.iter().enumerate() { + let fits = self.areas[piece] <= cavity.area + self.area_tolerance + && cavity + .width + .is_none_or(|width| self.widths[piece] <= width + length); + if fits { + has_a_place[slot] = true; + areas.push(self.areas[piece]); + } + } + let mut rest = vec![0.0; areas.len() + 1]; + for i in (0..areas.len()).rev() { + rest[i] = rest[i + 1] + areas[i]; + } + let mut budget = AREA_BUDGET; + if !adds_up( + &areas, + &rest, + 0, + cavity.area, + self.area_tolerance, + &mut budget, + ) { + return false; + } + } + has_a_place.iter().all(|&placed| placed) + } + + /// Whether every straight run between two convex corners, and every convex + /// corner, can still be closed by the remaining pieces. + fn closures_can_be_met(&self, free: &[usize], corners: &[Corner], cavities: &[Cavity]) -> bool { + let tolerance = *self.assembly.tolerance(); + for corner in corners.iter().filter(|c| c.is_convex(&tolerance)) { + if !self.angles.supply(free, corner.angle, self.angle_slack) { + return false; + } + } + for cavity in cavities { + let n = cavity.corners.len(); + for i in 0..n { + let (a, b) = ( + &corners[cavity.corners[i]], + &corners[cavity.corners[(i + 1) % n]], + ); + if a.is_convex(&tolerance) + && b.is_convex(&tolerance) + && !self + .lengths + .supply(free, distance(a.vertex, b.vertex), self.length_slack) + { + return false; + } + } + } + true + } + + /// Whether putting the candidate down leaves a state that is not a dead end. + fn survives(&mut self, candidate: &CandidatePlacement) -> bool { + self.assembly + .place(candidate.piece, candidate.pose) + .expect("a proposed piece is free"); + let corners = self.assembly.frontier(); + let alive = if self.assembly.all_placed() { + corners.is_empty() + } else { + match self.cavities(&corners) { + Some(cavities) => self.dead_end(&corners, &cavities).is_none(), + None => true, + } + }; + self.assembly.undo(); + alive + } + + /// The placements for the convex corner that has the fewest. Ties go to the + /// first corner. + /// + /// With `lookahead`, a placement only counts if the state it leads to is + /// not a dead end. The corners are then taken fewest candidates first, so + /// that looking ahead can stop as soon as a corner cannot win. + fn branch(&mut self, corners: &[Corner]) -> Vec { + let tolerance = *self.assembly.tolerance(); + let mut lists: Vec> = Vec::new(); + for corner in corners.iter().filter(|c| c.is_convex(&tolerance)) { + let mut candidates = self.assembly.propose(corner); + if let Some(anchor) = self.anchor { + let before = candidates.len(); + candidates.retain(|c| c.piece != anchor || self.in_sector(c)); + self.stats.pruned_anchor += (before - candidates.len()) as u64; + } + if candidates.is_empty() { + return Vec::new(); + } + lists.push(candidates); + } + // Shortest first; the sort keeps the order of the corners among equals. + lists.sort_by_key(Vec::len); + if !(self.options.lookahead && self.pruning()) { + return lists.into_iter().next().unwrap_or_default(); + } + + let mut best: Option> = None; + for list in lists { + let limit = best.as_ref().map_or(usize::MAX, Vec::len); + let mut alive = Vec::new(); + for candidate in list { + if self.survives(&candidate) { + alive.push(candidate); + if alive.len() >= limit { + break; + } + } else { + self.stats.pruned_lookahead += 1; + } + } + if alive.len() < limit { + let dead = alive.is_empty(); + best = Some(alive); + if dead { + break; + } + } + } + best.unwrap_or_default() + } + + /// How many edges of the candidate, placed, are whole edges of placed pieces. + fn matched_edges(&self, candidate: &CandidatePlacement) -> usize { + let length = self.assembly.tolerance().length; + let near = |a: Vec2, b: Vec2| distance(a, b) <= length; + let world = transform( + &self.assembly.shape(candidate.piece).polygon, + &candidate.pose, + ); + let n = world.len(); + (0..n) + .filter(|&i| { + let (a0, a1) = (world[i], world[(i + 1) % n]); + self.assembly.placed().iter().any(|&other| { + let polygon = self.assembly.world(other).expect("a placed piece"); + let m = polygon.len(); + // A neighbour's edge runs the other way. + (0..m).any(|j| near(a0, polygon[(j + 1) % m]) && near(a1, polygon[j])) + }) + }) + .count() + } + + fn record(&mut self) { + let poses: Vec = (0..self.areas.len()) + .map(|p| self.assembly.pose(p).expect("every piece is placed")) + .collect(); + let poses = match self.options.tray_rotations { + TrayRotations::All => poses, + TrayRotations::Once => { + if self.solutions.iter().any(|s| self.symmetry.same(s, &poses)) { + self.stats.duplicates += 1; + return; + } + self.symmetry.canonical(&poses) + } + }; + self.solutions.push(poses); + if self.first_solution.is_none() { + self.first_solution = Some(self.started.elapsed()); + } + if self + .options + .max_solutions + .is_some_and(|most| self.solutions.len() >= most) + { + self.stopped = true; + } + } + + fn out_of_budget(&self) -> bool { + self.options + .node_limit + .is_some_and(|limit| self.stats.nodes >= limit) + || self + .options + .time_limit + .is_some_and(|limit| self.started.elapsed() >= limit) + } + + fn expand(&mut self) { + if self.out_of_budget() { + self.stopped = true; + return; + } + self.stats.nodes += 1; + let depth = self.assembly.placed().len() as u64; + self.stats.max_depth = self.stats.max_depth.max(depth); + + let corners = self.assembly.frontier(); + if self.assembly.all_placed() { + if corners.is_empty() { + self.record(); + } else { + self.stats.backtracks += 1; + } + return; + } + let cavities = self.cavities(&corners); + if let Some(reason) = cavities + .as_deref() + .and_then(|cavities| self.dead_end(&corners, cavities)) + { + match reason { + DeadEnd::Cavity => self.stats.pruned_cavity += 1, + DeadEnd::Closure => self.stats.pruned_closure += 1, + } + self.stats.backtracks += 1; + return; + } + let mut candidates = self.branch(&corners); + if candidates.is_empty() { + self.stats.backtracks += 1; + return; + } + match self.options.order { + Order::Generated => {} + Order::Random => self.random.shuffle(&mut candidates), + Order::MatchedEdges => { + let mut scored: Vec<(usize, CandidatePlacement)> = candidates + .into_iter() + .map(|c| (self.matched_edges(&c), c)) + .collect(); + // Stable: equal scores keep the order they were generated in. + scored.sort_by_key(|(score, _)| std::cmp::Reverse(*score)); + candidates = scored.into_iter().map(|(_, c)| c).collect(); + } + } + for candidate in candidates { + self.assembly + .place(candidate.piece, candidate.pose) + .expect("a proposed piece is free"); + self.stats.placements += 1; + self.expand(); + self.assembly.undo(); + if self.stopped { + return; + } + } + } +} + +/// Search for assemblies of `shapes` in `target`. +/// +/// The polygons are local, convex and counter-clockwise. If the shapes have +/// roofs, the roofs must be continuous across the assembly, within +/// `tolerance.height`. +pub fn solve( + target: Vec, + shapes: Vec, + tolerance: ContactTolerance, + options: &Options, +) -> Result { + let started = Instant::now(); + let count = shapes.len(); + let areas: Vec = shapes.iter().map(|s| signed_area(&s.polygon)).collect(); + let centroids: Vec = shapes.iter().map(|s| centroid(&s.polygon)).collect(); + let perimeter: f64 = (0..target.len()) + .map(|i| distance(target[i], target[(i + 1) % target.len()])) + .sum(); + let symmetry_shapes = shapes.clone(); + // Refuses anything that is not a convex counter-clockwise polygon. + let assembly = Assembly::new(target, shapes, tolerance)?; + let widths: Vec = symmetry_shapes + .iter() + .map(|s| least_width(&s.polygon)) + .collect(); + let symmetry = Symmetry::new( + assembly.target(), + &symmetry_shapes, + assembly.graph(), + &tolerance, + ); + + let anchored = options.anchor + && options.tray_rotations == TrayRotations::Once + && symmetry.tray_order() > 1; + let anchor = anchored + .then(|| { + let classes = symmetry.classes(); + (0..count) + .filter(|&p| classes.iter().filter(|&&c| c == classes[p]).count() == 1) + .max_by(|&a, &b| areas[a].total_cmp(&areas[b]).then(b.cmp(&a))) + }) + .flatten(); + + let signature = |p: usize| assembly.graph().signatures(p); + let edge_lengths: Vec> = (0..count) + .map(|p| signature(p).iter().map(|e| e.length).collect()) + .collect(); + let vertex_angles: Vec> = (0..count) + .map(|p| signature(p).iter().map(|e| e.angle_start).collect()) + .collect(); + + let mut search = Search { + lengths: Values::new(edge_lengths.into_iter(), tolerance.length), + angles: Values::new(vertex_angles.into_iter(), tolerance.angle), + assembly, + options, + anchor, + centroids, + areas, + widths, + // A boundary off by the length tolerance all the way round the target. + area_tolerance: tolerance.length * perimeter, + length_slack: tolerance.length * (count + 1) as f64, + angle_slack: tolerance.angle * (count + 1) as f64, + stats: Stats::default(), + solutions: Vec::new(), + started, + first_solution: None, + stopped: false, + random: Random(options.seed), + symmetry, + }; + search.expand(); + search.stats.candidates = search.assembly.stats(); + Ok(Outcome { + solutions: search.solutions, + exhausted: !search.stopped, + stats: search.stats, + elapsed: started.elapsed(), + first_solution: search.first_solution, + tray_order: search.symmetry.tray_order(), + anchor, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use proptest::prelude::*; + use tiling_core::Roof; + use tiling_geometry::EdgeGraph; + use tiling_geometry::testing::{TOL, Tiling, tiling}; + + fn rectangle(w: f64, h: f64) -> Vec { + vec![ + [-w / 2.0, -h / 2.0], + [w / 2.0, -h / 2.0], + [w / 2.0, h / 2.0], + [-w / 2.0, h / 2.0], + ] + } + + fn bare(polygons: &[Vec]) -> Vec { + polygons + .iter() + .map(|polygon| Shape { + polygon: polygon.clone(), + roof: None, + }) + .collect() + } + + fn tray(w: f64, h: f64) -> Vec { + vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]] + } + + fn whole() -> Options { + Options { + max_solutions: None, + ..Options::default() + } + } + + fn every_turn() -> Options { + Options { + tray_rotations: TrayRotations::All, + ..whole() + } + } + + /// The search with nothing but the branching rule. + fn plain(options: Options) -> Options { + Options { + anchor: false, + cavity_pruning: false, + closure_pruning: false, + lookahead: false, + order: Order::Generated, + ..options + } + } + + fn run(target: &[Vec2], shapes: &[Shape], options: &Options) -> Outcome { + solve(target.to_vec(), shapes.to_vec(), TOL, options).unwrap() + } + + fn symmetry(target: &[Vec2], shapes: &[Shape]) -> Symmetry { + Symmetry::new(target, shapes, &EdgeGraph::build(shapes, &TOL), &TOL) + } + + /// Whether two lists hold the same assemblies, each once. + fn same_sets(symmetry: &Symmetry, a: &[Vec], b: &[Vec]) -> bool { + a.len() == b.len() + && a.iter() + .all(|x| b.iter().filter(|y| symmetry.same(x, y)).count() == 1) + } + + /// Three strips side by side in a 5 by 3 tray, 1, 1.5 and 2.5 wide. + fn three_strips() -> (Vec, Vec>) { + ( + tray(5.0, 3.0), + vec![ + rectangle(1.0, 3.0), + rectangle(1.5, 3.0), + rectangle(2.5, 3.0), + ], + ) + } + + /// The roof each strip has when the three, in that order from the left, + /// lie under the plane `z = 10 + x / 2`. + fn strips_under_a_slope() -> Vec { + let (_, polygons) = three_strips(); + // Centres at x = 0.5, 1.75 and 3.75. + [0.5, 1.75, 3.75] + .iter() + .zip(polygons) + .map(|(&cx, polygon)| Shape { + polygon, + roof: Some(Roof { + z0: 10.0 + cx / 2.0, + gx: 0.5, + gy: 0.0, + }), + }) + .collect() + } + + #[test] + fn three_strips_can_stand_in_any_order() { + // 3! orders. The tray has a half turn, which pairs each order with its + // reverse: 3 assemblies, 6 with the turns counted. + let (target, polygons) = three_strips(); + let shapes = bare(&polygons); + let all = run(&target, &shapes, &every_turn()); + assert!(all.exhausted); + assert_eq!(all.solutions.len(), 6); + let once = run(&target, &shapes, &whole()); + assert!(once.exhausted); + assert_eq!((once.tray_order, once.solutions.len()), (2, 3)); + // The anchor is the widest strip, and it did some of the work. + assert_eq!(once.anchor, Some(2)); + assert!(once.stats.pruned_anchor > 0); + let symmetry = symmetry(&target, &shapes); + for a in &all.solutions { + let twins = once.solutions.iter().filter(|o| symmetry.same(a, o)); + assert_eq!(twins.count(), 1); + } + } + + #[test] + fn roofs_leave_the_three_strips_one_order() { + // Heights at the left and right edges, in the order the roofs were cut: + // (10, 10.5), (10.5, 11.25), (11.25, 12.5). Two unturned strips meet + // only where a right height equals a left one, which is the original + // order. A strip turned half round shows its other edge, and no two + // right heights or two left heights agree. So: the original, and the + // whole of it turned with the tray. + let (target, _) = three_strips(); + let shapes = strips_under_a_slope(); + let all = run(&target, &shapes, &every_turn()); + assert!(all.exhausted); + assert_eq!(all.solutions.len(), 2); + assert!(all.stats.candidates.rejected_roof > 0); + let once = run(&target, &shapes, &whole()); + assert_eq!(once.solutions.len(), 1); + let at = |x: f64| Pose { + x, + y: 1.5, + theta: 0.0, + }; + let original = [at(0.5), at(1.75), at(3.75)]; + assert!(symmetry(&target, &shapes).same(&once.solutions[0], &original)); + } + + #[test] + fn a_roof_out_of_step_leaves_no_assembly() { + let (target, _) = three_strips(); + let mut shapes = strips_under_a_slope(); + shapes[1].roof.as_mut().unwrap().z0 += 0.25; + let outcome = run(&target, &shapes, &whole()); + assert!(outcome.exhausted); + assert!(outcome.solutions.is_empty()); + } + + #[test] + fn pieces_that_cannot_fill_the_tray_have_no_assembly() { + let shapes = bare(&[rectangle(1.0, 3.0), rectangle(1.5, 3.0)]); + for options in [whole(), plain(whole())] { + let outcome = run(&tray(5.0, 3.0), &shapes, &options); + assert!(outcome.exhausted && outcome.solutions.is_empty()); + assert!(outcome.stats.backtracks > 0); + assert_eq!(outcome.first_solution, None); + } + } + + #[test] + fn a_tray_the_pieces_cannot_add_up_to_is_a_dead_end_at_once() { + // Areas 6, 3 and 3 against a tray of 15: no set of them is 15. With + // pruning the root is the only node; without, pieces are tried first. + let shapes = bare(&[ + rectangle(2.0, 3.0), + rectangle(1.0, 3.0), + rectangle(3.0, 1.0), + ]); + let pruned = run(&tray(5.0, 3.0), &shapes, &whole()); + assert!(pruned.exhausted && pruned.solutions.is_empty()); + assert_eq!(pruned.stats.nodes, 1); + assert_eq!(pruned.stats.pruned_cavity, 1); + let unpruned = run(&tray(5.0, 3.0), &shapes, &plain(whole())); + assert!(unpruned.exhausted && unpruned.solutions.is_empty()); + assert!(unpruned.stats.nodes > 1); + assert_eq!(unpruned.stats.pruned_cavity, 0); + } + + #[test] + fn a_run_no_edges_add_up_to_is_a_dead_end() { + // Areas fit: 2 x 3 and 3 x 3 in a 5 x 3 tray... but as 6 x 1 and 3 x 3 + // they do not: the 6 x 1 bar is longer than any wall. Area pruning + // sees nothing wrong (6 + 9 = 15); the bottom run of 5 is 3 + nothing. + let shapes = bare(&[rectangle(6.0, 1.0), rectangle(3.0, 3.0)]); + let only_closure = Options { + cavity_pruning: false, + lookahead: false, + ..whole() + }; + let outcome = run(&tray(5.0, 3.0), &shapes, &only_closure); + assert!(outcome.exhausted && outcome.solutions.is_empty()); + assert_eq!((outcome.stats.nodes, outcome.stats.pruned_closure), (1, 1)); + let only_cavity = Options { + closure_pruning: false, + lookahead: false, + ..whole() + }; + let outcome = run(&tray(5.0, 3.0), &shapes, &only_cavity); + assert!(outcome.exhausted && outcome.solutions.is_empty()); + assert_eq!(outcome.stats.pruned_closure, 0); + assert!(outcome.stats.nodes > 1); + } + + #[test] + fn limits_stop_the_search_and_say_so() { + let (target, polygons) = three_strips(); + let shapes = bare(&polygons); + let one = run(&target, &shapes, &Options::default()); + assert_eq!(one.solutions.len(), 1); + assert!(!one.exhausted, "stopped at the first solution"); + assert!(one.first_solution.is_some()); + + let limited = Options { + node_limit: Some(2), + ..every_turn() + }; + let stopped = run(&target, &shapes, &limited); + assert!(!stopped.exhausted); + assert_eq!(stopped.stats.nodes, 2); + + let no_time = Options { + time_limit: Some(Duration::ZERO), + ..whole() + }; + let stopped = run(&target, &shapes, &no_time); + assert!(!stopped.exhausted && stopped.solutions.is_empty()); + assert_eq!(stopped.stats.nodes, 0); + } + + #[test] + fn bad_input_is_refused() { + let mut clockwise = rectangle(1.0, 3.0); + clockwise.reverse(); + assert_eq!( + solve(tray(5.0, 3.0), bare(&[clockwise]), TOL, &whole()).unwrap_err(), + AssemblyError::NotConvex(Some(0)) + ); + } + + #[test] + fn a_seed_fixes_a_random_order_and_the_order_changes_nothing_found() { + let (target, polygons) = three_strips(); + let shapes = bare(&polygons); + let symmetry = symmetry(&target, &shapes); + let reference = run(&target, &shapes, &whole()); + let mut orders = Vec::new(); + for seed in 0..8 { + let options = Options { + order: Order::Random, + seed, + ..whole() + }; + let first = run(&target, &shapes, &options); + let again = run(&target, &shapes, &options); + assert_eq!(first.solutions, again.solutions); + assert!(same_sets(&symmetry, &first.solutions, &reference.solutions)); + orders.push(first.solutions); + } + assert!( + orders.iter().any(|o| o != &orders[0]), + "eight seeds, one order" + ); + } + + #[test] + fn sums_are_found_refused_and_remembered() { + // Pieces 0, 1, 2 with values {1, 4}, {2}, {8}. + let values = Values::new( + vec![vec![1.0, 4.0, 1.0], vec![2.0], vec![8.0]].into_iter(), + 1e-9, + ); + assert_eq!(values.each[0], vec![1.0, 4.0], "repeats are dropped"); + let all = [0, 1, 2]; + // 14 = 4 + 2 + 8; 5 is 1 + 4, but both are piece 0's. + assert!(values.supply(&all, 14.0, 1e-9)); + assert!(!values.supply(&all, 5.0, 1e-9)); + assert!(values.supply(&all, 6.0, 1e-9)); + assert!(!values.supply(&[0, 2], 6.0, 1e-9), "6 needs piece 1"); + assert!(!values.supply(&all, 15.0, 1e-9), "more than all of them"); + assert!(values.supply(&[], 0.0, 1e-9)); + assert!(!values.supply(&[], 1.0, 1e-9)); + // What was learnt about 6: pieces 0 and 1 supply it, pieces 0 and 2 cannot. + { + let known = values.known.borrow(); + let six = &known[&6.0f64.to_bits()]; + assert_eq!(six.supplied_by, vec![0b011]); + assert_eq!(six.not_from, vec![0b101]); + } + assert!(values.supply(&all, 6.0, 1e-9)); + assert!( + !values.supply(&[2], 6.0, 1e-9), + "part of a set that could not" + ); + } + + #[test] + fn areas_add_up_or_do_not() { + let areas = [5.0, 3.0, 2.0]; + let rest = [10.0, 5.0, 2.0, 0.0]; + let ask = |need: f64| adds_up(&areas, &rest, 0, need, 1e-9, &mut 1000); + assert!(ask(7.0) && ask(10.0) && ask(0.0) && ask(5.0)); + assert!(!ask(4.0) && !ask(11.0) && !ask(1.0)); + // Out of budget, the answer is the one that prunes nothing. + assert!(adds_up(&areas, &rest, 0, 4.0, 1e-9, &mut 0)); + } + + /// The pieces of a tiling, each with the roof it has under one plane over the whole target. + fn under_a_plane(tiling: &Tiling, a: f64, b: f64) -> Vec { + tiling + .local + .iter() + .zip(&tiling.poses) + .map(|(polygon, pose)| { + let (s, c) = pose.theta.sin_cos(); + Shape { + polygon: polygon.clone(), + roof: Some(Roof { + z0: 20.0 + a * pose.x + b * pose.y, + // The plane's gradient turned back into the piece's frame. + gx: c * a + s * b, + gy: -s * a + c * b, + }), + } + }) + .collect() + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + #[test] + fn the_search_finds_the_tiling_it_was_cut_from(tiling in tiling()) { + let shapes = bare(&tiling.local); + let outcome = run(&tiling.target, &shapes, &whole()); + prop_assert!(outcome.exhausted); + prop_assert_eq!(outcome.stats.cavities_unknown, 0); + let symmetry = symmetry(&tiling.target, &shapes); + let hits = outcome.solutions.iter().filter(|s| symmetry.same(s, &tiling.poses)).count(); + prop_assert_eq!(hits, 1); + } + + /// Pruning, lookahead, the anchor and the order are about work. What is + /// found with all of them is what is found with none. + #[test] + fn the_rules_change_the_work_and_not_what_is_found(tiling in tiling(), seed in any::()) { + let shapes = bare(&tiling.local); + let symmetry = symmetry(&tiling.target, &shapes); + let reference = run(&tiling.target, &shapes, &plain(whole())); + prop_assert!(reference.exhausted); + let variants = [ + whole(), + Options { lookahead: false, ..whole() }, + Options { closure_pruning: false, ..whole() }, + Options { cavity_pruning: false, ..whole() }, + Options { anchor: false, ..whole() }, + Options { order: Order::Random, seed, ..whole() }, + ]; + for options in &variants { + let outcome = run(&tiling.target, &shapes, options); + prop_assert!(outcome.exhausted); + prop_assert!( + same_sets(&symmetry, &outcome.solutions, &reference.solutions), + "{} found against {} with {:?}", + outcome.solutions.len(), reference.solutions.len(), options + ); + } + // With every turn of the tray counted, each assembly is one of those. + let all = run(&tiling.target, &shapes, &every_turn()); + prop_assert!(all.solutions.len() >= reference.solutions.len()); + for found in &all.solutions { + let twins = reference.solutions.iter().filter(|r| symmetry.same(found, r)).count(); + prop_assert_eq!(twins, 1); + } + } + + #[test] + fn roofs_under_one_plane_are_continuous_and_a_lifted_one_is_not( + tiling in tiling(), + a in -0.5f64..0.5, + b in -0.5f64..0.5, + lifted in any::(), + ) { + let shapes = under_a_plane(&tiling, a, b); + let outcome = run(&tiling.target, &shapes, &whole()); + prop_assert!(outcome.exhausted); + let same = symmetry(&tiling.target, &shapes); + let hits = outcome.solutions.iter().filter(|s| same.same(s, &tiling.poses)).count(); + prop_assert_eq!(hits, 1); + // Roofs can only rule assemblies out. + let flat = run(&tiling.target, &bare(&tiling.local), &every_turn()); + let roofed = run(&tiling.target, &shapes, &every_turn()); + prop_assert!(roofed.solutions.len() <= flat.solutions.len()); + + // One roof 1 mm too high: wherever that piece has a neighbour there is a step. + let mut broken = shapes.clone(); + let which = lifted.index(broken.len()); + broken[which].roof.as_mut().unwrap().z0 += 1.0; + let same = symmetry(&tiling.target, &broken); + let outcome = run(&tiling.target, &broken, &whole()); + prop_assert!(outcome.exhausted); + prop_assert!(!outcome.solutions.iter().any(|s| same.same(s, &tiling.poses))); + } + } +} diff --git a/crates/tiling-search/src/lib.rs b/crates/tiling-search/src/lib.rs index b894a52..4fab24a 100644 --- a/crates/tiling-search/src/lib.rs +++ b/crates/tiling-search/src/lib.rs @@ -1,8 +1,15 @@ //! Custom search algorithms. //! -//! Each solver is a module here (`contact_dfs` first, then `branch_bound`) and -//! becomes its own crate only when its size or dependencies justify it. A solver -//! receives the whole instance once and runs entirely in Rust; nothing here -//! calls back into Python. +//! Each solver is a module here and becomes its own crate only when its size +//! or dependencies justify it. A solver receives the whole puzzle once and runs +//! entirely in Rust; nothing here calls back into Python. //! -//! No solver is implemented yet. See `docs/roadmap.md`. +//! | Module | Contents | +//! | --- | --- | +//! | [`contact_dfs`] | depth-first search over corner contacts, with roofs, cavity pruning and the tray's rotations | +//! | [`canonical`] | when two assemblies are the same, and a canonical form | + +pub mod canonical; +pub mod contact_dfs; + +pub use canonical::Symmetry; diff --git a/docs/algorithms.md b/docs/algorithms.md index 7fcba85..72ff745 100644 --- a/docs/algorithms.md +++ b/docs/algorithms.md @@ -6,7 +6,7 @@ Statements marked **Argument** are reasoning about exact assemblies in exact ari ## Contact search by corners -Used by `python.contact_dfs`. The geometry is in `tiling-geometry` (`contact`, `graph`, `assembly`) and reaches Python as `_native.Assembly`. +Used by `python.contact_dfs` and by `rust.contact_dfs`, which adds the rules of [the next section](#the-rust-contact-search). The geometry is in `tiling-geometry` (`contact`, `graph`, `assembly`) and reaches Python as `_native.Assembly`. ### State @@ -80,7 +80,7 @@ Two repetitions are removed where the candidates are generated, because they wou Both are decided from the edge signatures, which is the job of the compatibility graph below. With them, four identical squares in a square tray are one assembly rather than 4! × 4⁴ labelled ones. -Rotations of the whole tray are *not* removed. A square tray gives each assembly four times unless the assembly has a rotational symmetry of its own. Removing them belongs to phase 5. +Rotations of the whole tray are *not* removed where candidates are generated. A square tray gives each assembly four times unless the assembly has a rotational symmetry of its own. The prototype returns all of them; `rust.contact_dfs` [removes them in the search](#the-trays-rotations). ### The edge compatibility graph @@ -88,13 +88,13 @@ Nodes are the oriented edges of the tray and of every piece; an arc from a fixed 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. -The prototype works in the footprint regime and so sees the unpruned graph. The pruned one is in place for the relief search of phase 5. +The prototype works in the footprint regime and so sees the unpruned graph. The relief search of `rust.contact_dfs` uses the pruned one. -### What is not here yet +### What the prototype leaves out -No pruning beyond the dead-end test: no check that a cavity can still be filled, no bound from areas or widths. These are phase 5. Their absence is visible in the numbers below. +No pruning beyond the dead-end test: no check that a cavity can still be filled, no bound from areas or widths. Their absence is visible in the numbers below, and they are the subject of the next section. -### Measurements +### Measurements of the prototype From `python.contact_dfs` run to the end of its search on the footprint fixtures, on one machine. Node counts are deterministic; times are indicative only. @@ -111,4 +111,154 @@ From `python.contact_dfs` run to the end of its search on the footprint fixtures Two findings, both relative to the candidates generated: - The 6-piece and 9-piece footprint puzzles have exactly one assembly each, up to turning the tray. -- `rat1` without its roofs has 101. Every one passes the validator as an exact tiling. Its pieces are mostly rectangles with commensurable sides, which can be rearranged in blocks. Whether the roofs single out one of the 101 is a question for the relief search. +- `rat1` without its roofs has 101. Every one passes the validator as an exact tiling. Its pieces are mostly rectangles with commensurable sides, which can be rearranged in blocks. The relief search answers whether the roofs single out one of the 101: [they do](#what-makes-a-puzzle-hard-and-what-helps). + +## The Rust contact search + +`rust.contact_dfs` (`tiling-search::contact_dfs`) is the search above, run entirely in Rust, with six additions. Each is an option that can be switched off (`SolverConfig.options`, listed in [solver-contract.md](solver-contract.md#options-of-rustcontact_dfs)), because the purpose of this solver is less to be fast than to show what makes a puzzle hard and which reasoning helps. With all of them off and `tray_rotations=all` it visits exactly the nodes the prototype visits, which a test checks count by count. + +None of the additions changes what a whole search finds. For each there is an argument below, and a test that the set of assemblies found is the same with the rule on and off: on the corpus (`tests/corpus/test_rust_contact_dfs.py`) and in Rust on random convex polygons cut into pieces by chords (`the_rules_change_the_work_and_not_what_is_found`). + +### Roofs + +In the relief regime a placement must continue the roofs already down. Two tests, both inside candidate generation, so that a placement refused for its roof never counts towards a corner: + +1. *At the corner, before any polygon work.* The corner's first side belongs to a placed piece. The roof of the candidate at its contact vertex must be as high as that piece's roof at the corner. This is one subtraction on numbers kept in the edge signatures. +2. *Along shared edges, after the placement is known to fit.* For every edge stretch the candidate shares with a placed piece, the two roofs are compared at both ends of the stretch. Roofs are planes, so their difference along a segment is largest at an end. + +The tolerance on a height is the contact noise times the steepest roof gradient in the puzzle, and at least the contact noise: a point misplaced by the contact noise changes a roof's height by that much times its slope. + +**Argument.** In an exact assembly with continuous roofs, every pair of neighbouring pieces agrees in height along the whole of their shared boundary, including the corner point. A placement that fails either test is part of no such assembly. + +The second test is compared with the validator's seam check on the corpus: with one piece's roof raised or tilted, the step `Assembly.roof_step` reports is the validator's worst mismatch to 1e-9 mm. + +### Cavity pruning (`cavity_pruning`) + +The uncovered region falls into *cavities*, its connected pieces. They are traced from the corners: from each corner along its first side to the next corner on the boundary, until the loop closes. A cavity's area comes from the shoelace formula on its loop, and if the loop is convex its least width is computed. A state in which the loops do not close, or in which the uncovered region has a hole (a placed piece touching nothing), is not judged at all: the rule then prunes nothing. + +A state is abandoned when + +- some cavity's area is not the sum of the areas of any set of remaining pieces that could go into it, a piece being able to go into a cavity if its area is no larger and, for a convex cavity, its least width no larger; or +- some remaining piece can go into no cavity. + +**Argument.** In a completion every remaining piece lies in the uncovered region. The interior of a piece is connected, so it lies in one cavity. The pieces in a cavity therefore tile it, and their areas add up to its area. A convex set inside another is no wider than it in any direction, so no wider in its narrowest. + +The subset-sum question is answered by a bounded search, largest areas first. If the bound is reached the answer is "perhaps", which prunes nothing. + +Cavities are compared with Shapely on partly assembled fixtures: `target − union(placed)` has the same components with the same areas and widths, and has a hole exactly when the trace declines. + +### Closure pruning (`closure_pruning`) + +Two necessary conditions that look only at the boundary of the uncovered region. + +- *Runs.* Take a straight stretch of the boundary between two consecutive corners that are both convex. Its length must be a sum of edge lengths, one edge each from different remaining pieces. +- *Corners.* The angle of a convex corner must be a sum of interior angles, one each from different remaining pieces. + +**Argument for runs.** Let the run go from A to B. In a completion, every point of the run is on the boundary of some remaining piece, and a convex piece that meets a line along more than a point, from one side, does so along a whole edge. At A the corner is convex: the uncovered region near A lies inside a wedge of less than a half turn, one of whose sides runs towards B. The continuation of the run backwards past A is outside that wedge, so no remaining piece has an edge reaching past A, and likewise past B. The edges lying on the run therefore lie within it, cover it and do not overlap: their lengths add up to its length. A convex piece has at most one edge on a line, so they belong to different pieces. + +**Argument for corners.** By the corner argument of the previous section, a piece that contains the corner point V has a vertex there, since the wedge is narrower than a half turn. The remaining pieces that contain V are wedges at V near V; together they fill the corner's wedge without overlapping, so their angles at V add up to its angle. A piece has one vertex at V. + +Both questions are "is this number a sum of one value each from some of these pieces", asked again and again about the same runs and corners as the search moves between neighbouring states. Answers are remembered per number: a set of pieces that supplied it still does while all of them are free, and a set that could not still cannot when pieces are taken away. The search for a sum is bounded, and reaching the bound answers "perhaps". + +Runs with a reflex corner at an end are not tested: a piece may reach past a reflex corner, so the run's length need not be a sum of whole edges. + +### Looking ahead (`lookahead`, off by default) + +With this on, a placement counts towards a corner only if the state it leads to is not a dead end by the pruning rules that are on. The corner branched on is then the one with the fewest placements that *survive*, and the dead ones are never descended into. Corners are examined shortest list first, and a corner is dropped as soon as it cannot beat the best so far. + +It is sound for the same reason the rules are: it removes only placements whose result the rules would abandon one node later. What it changes is the choice of corner, and the price is one placement, one corner scan and one round of pruning tests per candidate examined. The metric `pruned_lookahead` counts those; `nodes + pruned_lookahead` is the number of states the search examined, and that sum, not `nodes`, is what its time follows. + +### The tray's rotations + +(`tray_rotations`, `anchor`.) A tray with a rotational symmetry of order k gives every assembly k times, unless the assembly has that symmetry itself. With `tray_rotations=once` each family is returned once. + +*The anchor.* One piece, the anchor, is only ever placed with its centroid in one sector of the tray: directions 0 to 2π/k as seen from the tray's centroid. The anchor is the largest piece that is congruent to no other, so that "the anchor" names one place in any assembly. If every piece has a twin there is no anchor, and nothing is pruned. + +**Argument.** Take an assembly. Some rotation of the tray brings the anchor's centroid into the sector, because the k images of the sector cover the plane. That rotated assembly is a valid assembly and is not pruned. + +A centroid on a sector boundary, or at the centre, lies in the sector under more than one rotation, and without an anchor every rotation is found. So complete assemblies are compared before they are returned, and one that is a rotation of an earlier one is counted in `duplicates` and dropped. + +*Canonical form* (`tiling-search::canonical`). An assembly is described by a *seat* for each piece: where its centroid is, and how it is turned, the turn taken modulo the piece's own symmetry. Three things are removed: + +- *which twin sits where:* within a class of congruent pieces, the seats are sorted and dealt out in piece order; +- *a piece turned onto itself:* by taking the turn modulo 2π over the order of the piece's symmetry; +- *the tray turned:* the seats are computed for each of the k rotations and the first list in order is kept. + +Congruent pieces are not stored the same way round: the sanitizer turns each by its own random angle. A seat's turn is therefore measured for the first piece of the class, as the turn that piece would need to lie exactly there, and converted back for whichever twin receives the seat. + +The order is by x, then y, then turn, with two numbers within the tolerance counted as equal. That is a workable order only because, in an assembly, seats that differ do so by millimetres and seats that agree do so to rounding. + +Canonical forms are tested against an oracle that knows nothing of seats: two assemblies are the same when they put the same polygons in the same places (`tests/support/assemblies.py`). + +### The order of candidates (`order`) + +The branching rule fixes which corner is filled. The order in which that corner's placements are tried is free, changes nothing a whole search finds, and decides how soon the first solution turns up. + +- `generated`: by piece, then by vertex, as `propose` returns them. The prototype's order. +- `matched-edges` (the default): placements that share the most whole edges with pieces already down come first; ties stay in generated order. +- `random`: shuffled by a generator seeded from `SolverConfig.seed`. + +On the corpus, measured by nodes to the first solution with the default rules. The random column is five seeds: least, median, most. + +| Fixture | Pieces | `matched-edges` | `generated` | `random` | +| --- | --- | --- | --- | --- | +| `new5-flat` | 6 | 55 | 55 | 24, 46, 88 | +| `new3-flat` | 9 | 135 | 139 | 1 862, 3 044, 4 512 | +| `new4-flat` | 9 | 377 | 386 | 73, 347, 457 | +| `rev2-flat` | 9 | 30 | 31 | 13, 31, 44 | +| `rat1-flat` | 11 | 334 | 345 | 167, 664, 1 887 | +| `new1-flat` | 16 | 803 543 | 803 632 | 98 078, 382 284, 955 946 | +| `new2-flat` | 16 | 392 912 | 392 980 | 16 262, 523 407, 889 623 | +| `rat2-flat` | 20 | 5 555 | 6 265 | 15 584, 50 253, 69 562 | + +Preferring matched edges barely differs from the generated order: the corner rule already leaves few placements to order, and where the search goes wrong it does so near the root, where little is placed and nothing matches. A random order is sometimes fifty times quicker than either on the 16-piece puzzles and sometimes slower, which says the cost of the first solution there is mostly the luck of the first few placements. + +### What makes a puzzle hard, and what helps + +Whole searches of every corpus fixture with `rust.contact_dfs`, each rule switched off in turn. Counts are nodes; they are deterministic. "> n" is a search stopped at 90 s with n nodes visited. All statements are relative to the candidates generated, in `f64` with tolerances. + +**With roofs** (relief regime): + +| Fixture | Pieces | Assemblies | Nodes, default | Nodes, every rule off | Roof refusals, every rule off | +| --- | --- | --- | --- | --- | --- | +| `new5` | 6 | 1 | 26 | 41 | 200 | +| `new3` | 9 | 1 | 44 | 65 | 901 | +| `new4` | 9 | 1 | 45 | 65 | 720 | +| `rev2` | 9 | 1 | 26 | 49 | 21 | +| `rat1` | 11 | 1 | 90 | 122 | 1 924 | +| `new1` | 16 | 1 | 68 | 109 | 2 339 | +| `new2` | 16 | 1 | 68 | 110 | 2 390 | +| `rat2` | 20 | 1 | 94 | 146 | 1 458 | + +With every rule off the search has no anchor, so it finds the assembly in each of the tray's four orientations: 4 × 16 + 1 = 65 of `new1`'s 109 nodes lie on the way to a solution. + +**Without roofs** (footprint regime): + +| Fixture | Pieces | Assemblies | Default | No closure | No cavity | No anchor | Every rule off | Lookahead: nodes | Lookahead: states | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `new5-flat` | 6 | 1 | 90 | 145 | 90 | 111 | 166 | 16 | 144 | +| `new3-flat` | 9 | 1 | 6 104 | 8 990 | 6 104 | 6 160 | 9 080 | 453 | 8 146 | +| `new4-flat` | 9 | 1 | 510 | 2 671 | 510 | 572 | 2 862 | 35 | 1 193 | +| `rev2-flat` | 9 | 1 | 45 | 47 | 45 | 70 | 72 | 12 | 167 | +| `rat1-flat` | 11 | 101 | 17 425 | 38 710 | 17 521 | 18 258 | 30 596 | 845 | 10 612 | +| `new1-flat` | 16 | 1 | 1 064 878 | 1 240 046 | 1 064 878 | > 2 969 019 | > 1 664 612 | > 106 448 | > 3 276 307 | +| `new2-flat` | 16 | 1 | 909 750 | 1 173 124 | 909 750 | > 3 465 641 | > 1 700 428 | 22 979 | 890 708 | +| `rat2-flat` | 20 | 2 | 128 230 | 299 929 | 128 230 | 144 996 | 337 245 | 2 131 | 41 851 | + +"No closure", "no cavity" and "no anchor" are the default with that one rule off. The last two columns are the default with `lookahead` on: nodes visited, and states examined (nodes plus placements looked at one step ahead), which is the fairer comparison with the other columns. + +Times for the default, on one quiet machine and indicative only: `new1-flat` 23 s to its solution and 31 s to the end; `new2-flat` 9 s and 20 s; `rat2-flat` 0.2 s and 4.4 s; everything else under half a second, and every relief search under 20 ms. + +What the tables say: + +- **The roofs are what make these puzzles easy.** Every relief puzzle has one assembly, and the search for it hardly backtracks, with or without the other rules: 146 nodes for 20 pieces with everything off. The same pieces without roofs take up to a million. A roof plane is three numbers per piece, and it removes nearly every wrong placement at the corner where it is tried. This is the wall matching a person does by eye. +- **The roofs also decide uniqueness.** `rat1` has 101 footprint assemblies and one relief assembly; `rat2` two and one. The other six are unique either way. +- **The number of pieces is a poor measure of difficulty.** The 20-piece `rat2-flat` takes an eighth of the nodes of the 16-piece `new1-flat`. The 9-piece `new3-flat` takes 130 times the nodes of the 9-piece `rev2-flat`. +- **Finding and finishing are different costs.** `rat2-flat` gives its first assembly after 5 555 nodes and needs 128 230 to show there are two; `new1-flat` spends three quarters of its search before the only one turns up. The first is hard to certify, the second hard to find. +- **Closure pruning is the rule that works on small footprints.** On `new5-flat`, `new3-flat`, `new4-flat`, `rat1-flat` and `rat2-flat` it removes a third to four fifths of the nodes, and without it the search is close to having no rules at all (`rev2-flat` is nearly free of backtracking either way). On the two 16-piece puzzles it removes only a seventh to a fifth of the nodes, though those it removes are the expensive ones: the searches took two to three times as long without it. +- **The anchor matters most where the search is deepest.** On the 16-piece footprints, searching all four orientations instead of one multiplies the work by about three or more; neither search finished in the time allowed. On small puzzles it saves little, and it can cost: removing the anchor's placements changes which corner has the fewest, and `rat1-flat` visits more nodes with the anchor and no closure rule (38 710) than with no rules (30 596). +- **Cavity pruning does almost nothing here.** It fires a few thousand times in a million nodes and never changes a node count by more than one percent. Corner filling rarely leaves an enclosed cavity whose area or width is wrong before a corner or a run is; the closure rule sees the trouble first. +- **Looking ahead trades nodes for work per node, and the trade goes both ways.** It always cuts nodes, by a factor of 3 to 60. Counted in states it wins on `rat1-flat`, `rat2-flat` (three times fewer) and narrowly `new2-flat`, and loses on the other five, by more than a factor of three on `new1-flat`. It is off by default because its worst case is the corpus's hardest instance. +- **What is left.** The two 16-piece footprints are hard for every configuration tried. Their searches die five or six pieces deep, in states no present rule recognises as dead when they are created. That is where learning from dead ends, or a rule that sees further, would have to show its worth. + +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. diff --git a/docs/roadmap.md b/docs/roadmap.md index 12b8a8b..ee4cc44 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,8 +9,8 @@ Each phase is sized for one working session and ends with an exit criterion that | 2 | Independent validator | Done | | 3 | Rust geometry kernel | Done | | 4 | Contact candidates, Python prototype, solver contract | Done | -| 5 | Rust contact DFS | Next | -| 6 | CP-SAT backend | | +| 5 | Rust contact DFS | Done | +| 6 | CP-SAT backend | Next | | 7 | Benchmark and research platform | | 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. @@ -121,6 +121,24 @@ Done, with these decisions: **Exit:** all 16 fixtures are solved and validated. Time to first solution and time to exhaust the search are reported separately. On the small fixtures the solution set equals the Python prototype's. +Done, with these decisions: + +- The exit criterion is `tests/corpus/test_rust_contact_dfs.py`. Each of the 16 fixtures is searched to the end in its own regime; every assembly returned passes the validator as an exact tiling, with continuous roofs in relief; the answer key is among them. `first_solution_s` and `exhausted_s` are separate metrics. On the five footprint fixtures the prototype can finish, the two solvers return the same assemblies, and with its additions switched off the Rust search visits exactly the prototype's nodes. +- The lens is difficulty, not speed. Every rule beyond the prototype's is a switch in `SolverConfig.options`, and the whole search is tested to find the same assemblies with each switch on and off. What each rule buys is measured and tabulated in [algorithms.md](algorithms.md#what-makes-a-puzzle-hard-and-what-helps). +- Relief filtering is in candidate generation: a placement is refused if its roof height at the corner differs from the roof already there, before any polygon work, and if its roof steps along any edge stretch shared with a placed piece. The candidate set of the relief regime is named `corner-contact-relief/1`. +- Cavity pruning by area and by least width, as planned. It turned out to matter little: on the corpus it never changes a node count by more than one percent. +- Closure pruning, which the roadmap did not foresee and which is the pruning rule that works on footprints: a straight run of boundary between two convex corners must be a sum of whole edges of different remaining pieces, and a convex corner a sum of their angles. +- Looking one placement ahead is implemented and off by default. It cuts the nodes visited by a factor of 3 to 60; counted in states examined it wins on three footprint fixtures and loses on five, worst on the hardest. +- Symmetry: one piece, the largest that is congruent to no other, is held to one sector of the tray, and repeats are removed by comparing canonical forms. `tray_rotations=all` restores the prototype's counting. Congruent pieces and self-symmetric pieces were already handled where candidates are generated. +- Canonical form (`tiling-search::canonical`): seats, a centroid and a turn modulo the piece's symmetry, sorted within each class of congruent pieces, smallest over the tray's rotations. Congruent pieces are stored at unrelated rotations by the sanitizer; the turn is measured relative to the class's first piece. The validator caught the first version getting that wrong on the synthetic fixtures. +- Collinear-chain placements are not implemented. The corner argument of phase 4 shows they add no assemblies, and no measurement asked for them. +- Candidate ordering is an option: by matched edges (the default), as generated, or random from the seed. +- `SolverSpec` now maps each regime to its candidate set. `maxplus-solve` takes `--option NAME=VALUE` and defaults to `rust.contact_dfs`. +- `tiling-geometry` exposes its proptest strategies behind a `testing` feature, so that `tiling-search` tests its search on the same random tilings. +- Tests beyond the exit: cavities against a Shapely difference, the roof step of a placement against the validator's seam mismatch, canonical forms against the polygon-set oracle, properties in Rust over random tilings cut by chords (the search finds the tiling it was cut from; no rule changes what is found; roofs under one plane are continuous and a lifted one is not), and an architecture test that a production solver makes one `_native` call. The rules were each broken by hand once and the tests watched to fail. +- Findings, relative to the candidates generated. In relief every corpus puzzle has exactly one assembly, and the search for it is nearly free of backtracking: at most 146 nodes for 20 pieces with every rule off. As footprints, six of the eight have one assembly, `rat1-flat` has 101 and `rat2-flat` has 2. The roofs single out one of `rat1`'s 101. The hard instances are the 16-piece footprints: about a million nodes each to finish, and for `new1-flat` hundreds of thousands to the first solution. +- For later phases: the 16-piece footprint searches are the benchmark that pruning or learning has to move. Both are dominated by dead ends five or six pieces deep that no current rule sees coming. + ## Phase 6: CP-SAT backend - `enumerate(instance, policy)` builds a finite candidate set; pairwise conflicts are precomputed in Rust. diff --git a/docs/solver-contract.md b/docs/solver-contract.md index 35ae168..2a6d123 100644 --- a/docs/solver-contract.md +++ b/docs/solver-contract.md @@ -6,11 +6,12 @@ Every solver is called the same way and answers in the same form. This document from maxplus_solvers import SolverConfig, load_puzzle, solve puzzle = load_puzzle("new5-flat") -result = solve(puzzle, SolverConfig("python.contact_dfs", max_solutions=None), validate=True) +result = solve(puzzle, SolverConfig("rust.contact_dfs", max_solutions=None), validate=True) ``` ```sh maxplus-solve new5-flat --max-solutions all --validate +maxplus-solve new5 --mode relief --max-solutions all --option closure_pruning=false ``` ## The call @@ -23,7 +24,7 @@ maxplus-solve new5-flat --max-solutions all --validate | `mode` | The information regime the solver may use: `footprint`, `relief` or `tropical-aware`. Default `footprint`. | | `time_limit_s` | Wall-clock limit, or `None`. Checked between search nodes, so a run may exceed it by the cost of one node. | | `max_solutions` | Stop after this many solutions. `None` runs the search to its end. Default 1. | -| `seed` | For solvers that randomize. A deterministic solver ignores it and says so. | +| `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. | @@ -57,9 +58,10 @@ No solver in this repository sets `candidates_proven_complete` today, and a solv | Name | Solvers | Contents | | --- | --- | --- | -| `corner-contact/1` | `python.contact_dfs` | Placements with a piece vertex at a corner of the uncovered region and the edge leaving it flush against the corner's first side, within the contact noise. Complete for exact assemblies of convex pieces by the argument in [algorithms.md](algorithms.md#why-the-rule-loses-no-assembly), in exact arithmetic. It does not contain assemblies that only pass because of the validation tolerances. | +| `corner-contact/1` | `python.contact_dfs`, `rust.contact_dfs` (footprint) | Placements with a piece vertex at a corner of the uncovered region and the edge leaving it flush against the corner's first side, within the contact noise. Complete for exact assemblies of convex pieces by the argument in [algorithms.md](algorithms.md#why-the-rule-loses-no-assembly), in exact arithmetic. It does not contain assemblies that only pass because of the validation tolerances. | +| `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. | -A change to what a candidate set contains gets a new name. +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. ## Solutions @@ -76,8 +78,11 @@ Each solver states which differences it counts. | Solver | Counted once | Counted separately | | --- | --- | --- | | `python.contact_dfs` | Assemblies that differ by exchanging congruent pieces; assemblies that differ by turning a piece onto itself. | Assemblies that differ by a rotation of the whole tray. | +| `rust.contact_dfs` | The same, and with `tray_rotations=once` (the default) assemblies that differ by a rotation of the whole tray. | With `tray_rotations=all`, assemblies that differ by a rotation of the tray. Mirror images always: pieces are not turned over. | -A canonical form that also identifies rotations of the tray comes with phase 5. +In the relief regime "congruent" and "onto itself" include the roof: two pieces of one shape under different roofs are different pieces, and a rectangle under a sloping roof is not its own half turn. A footprint solution of a relief puzzle may therefore put a symmetric piece either way round, and need not pass the relief validator. + +`rust.contact_dfs` returns each solution in a canonical form: of the poses that describe the same assembly, a fixed one. With `tray_rotations=once` the orientation of the tray is part of that choice, so the assembly returned may be the answer key turned by a rotation of the tray. ## Metrics @@ -86,15 +91,22 @@ A canonical form that also identifies rotations of the tray comes with phase 5. | Name | Meaning | | --- | --- | | `nodes` | Search nodes expanded, the root included. | -| `backtracks` | Nodes abandoned as dead ends: no candidate for the corner branched on, or all pieces placed with something left uncovered. | +| `backtracks` | Nodes abandoned as dead ends: no candidate for the corner branched on, all pieces placed with something left uncovered, or a pruning rule. | | `placements` | Pieces put down, counting every attempt. | | `max_depth` | The largest number of pieces down at once. | | `candidates_generated` | Placements computed from contacts, before any check. | | `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. | +| `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. | +| `pruned_lookahead` | Placements examined one step ahead and found to lead to a dead end. Each costs about what a node does; `nodes + pruned_lookahead` is the number of states examined. | +| `duplicates` | Complete assemblies reached and not returned, being a tray rotation of one already found. | | `solutions` | Solutions returned. | | `wall_time_s`, `cpu_time_s` | Elapsed and processor time of the solve. | | `first_solution_s` | Wall time to the first solution. Absent if there was none. | +| `exhausted_s` | Wall time to the end of the search. Absent unless the result is `exhaustive`. With `first_solution_s` it separates finding an assembly from showing there is no other. | A solver for which a count has no meaning leaves it at zero. New metrics are added to `SearchMetrics` and to this table together. @@ -104,9 +116,9 @@ A result records `solver`, `solver_version`, `regime`, `instance_hash` and the w ## The command -`maxplus-solve PUZZLE [--solver NAME] [--mode REGIME] [--time-limit SECONDS] [--max-solutions N|all] [--seed N] [--validate] [--json]` +`maxplus-solve PUZZLE [--solver NAME] [--mode REGIME] [--time-limit SECONDS] [--max-solutions N|all] [--seed N] [--option NAME=VALUE]... [--validate] [--json]` -`PUZZLE` is an instance file or a fixture id. +`PUZZLE` is an instance file or a fixture id. The solver defaults to `rust.contact_dfs` and the mode to `footprint`. `--option` sets one entry of `SolverConfig.options`; the value is read as JSON where it is JSON (`false`, `1000`) and as a word otherwise (`random`). The summary prints the time to the first solution and, when the search ran to its end, the time that took. | Exit code | Meaning | | --- | --- | @@ -120,6 +132,21 @@ A result records `solver`, `solver_version`, `regime`, `instance_hash` and the w | Name | Regimes | What it is | | --- | --- | --- | | `python.contact_dfs` | footprint | The Python prototype of the corner contact search. Deterministic; ignores `seed`. Option `node_limit`: stop after that many nodes. | +| `rust.contact_dfs` | footprint, relief | The corner contact search in Rust, one call per solve. Deterministic unless `order=random`, which uses `seed`. Options below. | + +### Options of `rust.contact_dfs` + +Every rule the search adds to the prototype's can be switched off, so that its effect can be measured. None of the switches changes what a whole search finds; `tray_rotations` changes how it is counted. + +| Option | Default | Meaning | +| --- | --- | --- | +| `node_limit` | none | Stop after that many nodes. | +| `tray_rotations` | `once` | `once`: assemblies that are rotations of one another with the tray are one solution. `all`: each is returned, as the prototype does. | +| `anchor` | `true` | Hold one piece to a sector of the tray, so that rotated copies are not searched for at all. Only with `tray_rotations=once`; without it they are found and discarded. | +| `cavity_pruning` | `true` | Abandon a state with a cavity the remaining pieces cannot fill, by area or by width. | +| `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. | ## Adding a solver diff --git a/python/maxplus_solvers/_native.pyi b/python/maxplus_solvers/_native.pyi index 12612bb..7199a82 100644 --- a/python/maxplus_solvers/_native.pyi +++ b/python/maxplus_solvers/_native.pyi @@ -111,6 +111,7 @@ class Assembly: length_tol: float, angle_tol: float, slope_tol: float, + height_tol: float | None = None, ) -> Assembly: ... @property def piece_count(self) -> int: ... @@ -132,4 +133,94 @@ class Assembly: def frontier(self) -> list[Corner]: ... def propose(self, corner: Corner) -> list[Candidate]: ... def check_placement(self, piece: int, pose: _Pose) -> PlacementCheck: ... - def stats(self) -> tuple[int, int, int]: ... + def roof_step(self, piece: int, pose: _Pose) -> float: ... + def cavities(self) -> list[tuple[float, float | None, list[int]]] | None: ... + def stats(self) -> tuple[int, int, int, int]: ... + +def canonical_poses( + target: _Polygon, + pieces: Sequence[_Polygon], + roofs: Sequence[_Roof] | None, + poses: Sequence[_Pose], + *, + length_tol: float, + angle_tol: float, + slope_tol: float, + height_tol: float | None = None, +) -> list[_Pose]: ... +def same_assembly( + target: _Polygon, + pieces: Sequence[_Polygon], + roofs: Sequence[_Roof] | None, + first: Sequence[_Pose], + second: Sequence[_Pose], + *, + length_tol: float, + angle_tol: float, + slope_tol: float, + height_tol: float | None = None, +) -> bool: ... + +@final +class ContactDfsOutcome: + @property + def solutions(self) -> list[list[_Pose]]: ... + @property + def exhausted(self) -> bool: ... + @property + def nodes(self) -> int: ... + @property + def backtracks(self) -> int: ... + @property + def placements(self) -> int: ... + @property + def max_depth(self) -> int: ... + @property + def candidates_generated(self) -> int: ... + @property + def rejected_outside(self) -> int: ... + @property + def rejected_overlap(self) -> int: ... + @property + def rejected_roof(self) -> int: ... + @property + def pruned_cavity(self) -> int: ... + @property + def pruned_closure(self) -> int: ... + @property + def pruned_anchor(self) -> int: ... + @property + def pruned_lookahead(self) -> int: ... + @property + def duplicates(self) -> int: ... + @property + def cavities_unknown(self) -> int: ... + @property + def wall_time_s(self) -> float: ... + @property + def first_solution_s(self) -> float | None: ... + @property + def tray_order(self) -> int: ... + @property + def anchor(self) -> int | None: ... + +def contact_dfs( + target: _Polygon, + pieces: Sequence[_Polygon], + roofs: Sequence[_Roof] | None = None, + *, + length_tol: float, + angle_tol: float, + slope_tol: float, + height_tol: float | None = None, + max_solutions: int | None = 1, + time_limit_s: float | None = None, + node_limit: int | None = None, + all_tray_rotations: bool = False, + anchor: bool = True, + cavity_pruning: bool = True, + closure_pruning: bool = True, + lookahead: bool = False, + order: str = "matched-edges", + seed: int = 0, +) -> ContactDfsOutcome: ... diff --git a/python/maxplus_solvers/cli.py b/python/maxplus_solvers/cli.py index f599f81..5674508 100644 --- a/python/maxplus_solvers/cli.py +++ b/python/maxplus_solvers/cli.py @@ -23,13 +23,24 @@ def _max_solutions(text: str) -> int | None: return count +def _option(text: str) -> tuple[str, object]: + """``name=value``, the value read as JSON if it is JSON and as a word otherwise.""" + name, equals, value = text.partition("=") + if not (name and equals): + raise argparse.ArgumentTypeError("must be NAME=VALUE") + try: + return name, json.loads(value) + except json.JSONDecodeError: + return name, value + + def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="maxplus-solve", description="Solve a tiling puzzle and report what the search can and cannot claim.", ) parser.add_argument("puzzle", help="an instance file, or a fixture id such as new5-flat") - parser.add_argument("--solver", default="python.contact_dfs", choices=available_solvers()) + parser.add_argument("--solver", default="rust.contact_dfs", choices=available_solvers()) parser.add_argument( "--mode", default=Regime.FOOTPRINT.value, @@ -45,6 +56,14 @@ def _parser() -> argparse.ArgumentParser: help="stop after N solutions, or 'all' to run the search to its end (default: 1)", ) parser.add_argument("--seed", type=int, default=0) + parser.add_argument( + "--option", + action="append", + default=[], + type=_option, + metavar="NAME=VALUE", + help="a solver option, such as lookahead=false or order=random; may be repeated", + ) parser.add_argument( "--validate", action="store_true", @@ -65,11 +84,23 @@ def _summary(result: SolveResult) -> str: 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}") - shown = ("nodes", "backtracks", "placements", "candidates_generated", "wall_time_s") + shown = ("nodes", "backtracks", "placements", "candidates_generated") numbers = ", ".join( f"{name}={result.metrics[name]:.6g}" for name in shown if name in result.metrics ) lines.append(f" {numbers}") + # Two different questions: how soon a solution turns up, and how long the whole search is. + times = [ + f"{label} {result.metrics[name]:.3g} s" + for name, label in ( + ("first_solution_s", "first solution after"), + ("exhausted_s", "search finished after"), + ) + if name in result.metrics + ] + if "exhausted_s" not in result.metrics and "wall_time_s" in result.metrics: + times.append(f"stopped after {result.metrics['wall_time_s']:.3g} s") + lines.append(f" {'; '.join(times)}") return "\n".join(lines) @@ -84,6 +115,7 @@ def main(argv: Sequence[str] | None = None) -> int: time_limit_s=args.time_limit, max_solutions=args.max_solutions, seed=args.seed, + options=dict(args.option), ) result = solve(puzzle, config, validate=args.validate) except (FileNotFoundError, InstanceError, ValueError) as error: diff --git a/python/maxplus_solvers/metrics.py b/python/maxplus_solvers/metrics.py index 274c79e..1068ebf 100644 --- a/python/maxplus_solvers/metrics.py +++ b/python/maxplus_solvers/metrics.py @@ -13,9 +13,10 @@ class SearchMetrics: # Search nodes expanded, the root included. nodes: int = 0 - # Nodes left without success: no piece fits the corner branched on. + # Nodes left without success: no piece fits the corner branched on, a pruning + # rule calls the state a dead end, or every piece is down and something is uncovered. backtracks: int = 0 - # Pieces put down, counting every attempt. + # Pieces put down as a branch of the search, counting every attempt. placements: int = 0 # The largest number of pieces down at once. max_depth: int = 0 @@ -23,11 +24,21 @@ class SearchMetrics: candidates_generated: int = 0 rejected_outside: int = 0 rejected_overlap: int = 0 + rejected_roof: int = 0 + # Nodes given up by a pruning rule, and candidates dropped before they became nodes. + pruned_cavity: int = 0 + pruned_closure: int = 0 + pruned_anchor: int = 0 + pruned_lookahead: int = 0 + # Assemblies found that were a turn of one already found. + duplicates: int = 0 solutions: int = 0 wall_time_s: float = 0.0 cpu_time_s: float = 0.0 # Wall time until the first solution; absent if there was none. first_solution_s: float | None = None + # Wall time until the search had run to its end; absent if it was stopped first. + exhausted_s: float | None = None def to_dict(self) -> dict[str, float]: """The record as ``SolveResult.metrics`` carries it. Absent values are left out.""" diff --git a/python/maxplus_solvers/solvers/__init__.py b/python/maxplus_solvers/solvers/__init__.py index 971a013..0636ffa 100644 --- a/python/maxplus_solvers/solvers/__init__.py +++ b/python/maxplus_solvers/solvers/__init__.py @@ -6,7 +6,7 @@ reduced to the regime the configuration asks for. """ -from collections.abc import Callable +from collections.abc import Callable, Mapping from dataclasses import dataclass from maxplus_solvers.models import PuzzleInstance, Regime, SolverConfig, SolveResult @@ -20,12 +20,16 @@ class SolverSpec: name: str run: SolverFunction - # The information regimes it can work in. Results across regimes are not comparable. - regimes: frozenset[Regime] - # The name of the candidate set its completeness claims are relative to. - candidate_set: str + # For each information regime it can work in, the name of the candidate set + # its completeness claims are relative to there. Results across regimes are + # not comparable. + candidate_sets: Mapping[Regime, str] description: str + @property + def regimes(self) -> frozenset[Regime]: + return frozenset(self.candidate_sets) + _REGISTRY: dict[str, SolverSpec] = {} @@ -52,9 +56,11 @@ def get(name: str) -> SolverSpec: def _register_builtin() -> None: - from maxplus_solvers.solvers.prototypes import contact_dfs + from maxplus_solvers.solvers import contact_dfs + from maxplus_solvers.solvers.prototypes import contact_dfs as prototype register(contact_dfs.SPEC) + register(prototype.SPEC) _register_builtin() diff --git a/python/maxplus_solvers/solvers/contact_dfs.py b/python/maxplus_solvers/solvers/contact_dfs.py new file mode 100644 index 0000000..8211d5f --- /dev/null +++ b/python/maxplus_solvers/solvers/contact_dfs.py @@ -0,0 +1,180 @@ +"""``rust.contact_dfs``: the contact search, run entirely in Rust. + +The search rule is the prototype's: branch on the convex corner of the uncovered +region that the fewest placements fill. ``docs/algorithms.md`` gives the rule, +the argument for it, and each of the things this solver adds: + +* the relief regime, where a placement must also continue its neighbours' roofs; +* cavity pruning, closure pruning and an optional one-placement lookahead; +* the tray's rotations taken out, and solutions returned in canonical form; +* a choice of the order in which a node's candidates are tried. + +Every addition can be switched off through ``SolverConfig.options``, so that +its effect can be measured. None of them changes what a whole search finds; +``tray_rotations`` changes how the same assemblies are counted. + +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. +""" + +import math +import time +from collections.abc import Mapping +from typing import Any + +from maxplus_solvers import _native +from maxplus_solvers.metrics import SearchMetrics +from maxplus_solvers.models import ( + Pose, + PuzzleInstance, + Regime, + Solution, + SolverConfig, + SolveResult, + SolveStatus, + TolerancePolicy, +) +from maxplus_solvers.solvers import SolverSpec + +NAME = "rust.contact_dfs" +CANDIDATE_SETS = { + # Vertex-at-corner contacts with one edge flush: the prototype's set. + Regime.FOOTPRINT: "corner-contact/1", + # The same, kept only where the roofs are continuous across every shared edge. + Regime.RELIEF: "corner-contact-relief/1", +} + +ORDERS = ("matched-edges", "generated", "random") +TRAY_ROTATIONS = ("once", "all") + +# Option name -> default. The lookahead is off by default: it cuts the nodes visited but +# usually examines more states to do it. docs/algorithms.md has the measurements. +DEFAULTS: Mapping[str, Any] = { + "node_limit": None, + "tray_rotations": "once", + "anchor": True, + "cavity_pruning": True, + "closure_pruning": True, + "lookahead": False, + "order": "matched-edges", +} + + +def _options(given: Mapping[str, Any]) -> dict[str, Any]: + unknown = sorted(set(given) - set(DEFAULTS)) + if unknown: + raise ValueError(f"{NAME}: unknown options {', '.join(unknown)}") + 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"): + if not isinstance(options[switch], bool): + raise ValueError(f"{NAME}: {switch} must be true or false") + if options["order"] not in ORDERS: + raise ValueError(f"{NAME}: order must be one of {', '.join(ORDERS)}") + if options["tray_rotations"] not in TRAY_ROTATIONS: + raise ValueError(f"{NAME}: tray_rotations must be one of {', '.join(TRAY_ROTATIONS)}") + return options + + +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) + if config.seed < 0: + raise ValueError(f"{NAME}: the seed must not be negative") + + policy = config.tolerances or TolerancePolicy.from_instance(instance) + fit_mm = policy.contact_noise_mm + if not fit_mm > 0: + raise ValueError(f"{NAME}: the contact noise must be positive") + # A turn by this angle moves a point one span away by the contact noise. + fit_rad = fit_mm / instance.span_mm + roofs = None + height_mm = fit_mm + if instance.regime is Regime.RELIEF: + roofs = [] + for piece in instance.pieces: + assert piece.roof is not None, "a relief instance has a roof on every piece" + roofs.append((piece.roof.z0, piece.roof.gx, piece.roof.gy)) + # A point off by the contact noise changes a roof's height by that times its slope. + steepest = max(math.hypot(gx, gy) for _, gx, gy in roofs) + height_mm = fit_mm * max(1.0, steepest) + + cpu_started = time.process_time() + outcome = _native.contact_dfs( + instance.target, + [piece.polygon for piece in instance.pieces], + roofs, + length_tol=fit_mm, + angle_tol=fit_rad, + slope_tol=fit_rad, + height_tol=height_mm, + max_solutions=config.max_solutions, + time_limit_s=config.time_limit_s, + node_limit=options["node_limit"], + all_tray_rotations=options["tray_rotations"] == "all", + anchor=options["anchor"], + cavity_pruning=options["cavity_pruning"], + closure_pruning=options["closure_pruning"], + lookahead=options["lookahead"], + order=options["order"], + seed=config.seed, + ) + cpu_time_s = time.process_time() - cpu_started + + ids = [piece.id for piece in instance.pieces] + solutions = tuple( + Solution({pid: Pose(*pose) for pid, pose in zip(ids, poses, strict=True)}) + for poses in outcome.solutions + ) + metrics = SearchMetrics( + nodes=outcome.nodes, + backtracks=outcome.backtracks, + placements=outcome.placements, + max_depth=outcome.max_depth, + candidates_generated=outcome.candidates_generated, + rejected_outside=outcome.rejected_outside, + rejected_overlap=outcome.rejected_overlap, + rejected_roof=outcome.rejected_roof, + pruned_cavity=outcome.pruned_cavity, + pruned_closure=outcome.pruned_closure, + pruned_anchor=outcome.pruned_anchor, + pruned_lookahead=outcome.pruned_lookahead, + duplicates=outcome.duplicates, + solutions=len(solutions), + wall_time_s=outcome.wall_time_s, + cpu_time_s=cpu_time_s, + first_solution_s=outcome.first_solution_s, + exhausted_s=outcome.wall_time_s if outcome.exhausted else None, + ) + if solutions: + status = SolveStatus.SOLVED + elif outcome.exhausted: + status = SolveStatus.NO_SOLUTION_FOUND + else: + status = SolveStatus.INTERRUPTED + return SolveResult( + status=status, + solver=NAME, + regime=instance.regime, + instance_hash=instance.instance_hash(), + solutions=solutions, + exhaustive=outcome.exhausted, + # The arguments for the candidates and for the pruning rules are about exact + # assemblies in exact arithmetic; this is f64 with tolerances. + candidates_proven_complete=False, + metrics=metrics.to_dict(), + candidate_set=CANDIDATE_SETS[instance.regime], + config=config, + solver_version=_native.version(), + ) + + +SPEC = SolverSpec( + name=NAME, + run=solve, + candidate_sets=CANDIDATE_SETS, + description="Rust: depth-first search over corner contacts, with roofs and pruning", +) diff --git a/python/maxplus_solvers/solvers/prototypes/contact_dfs.py b/python/maxplus_solvers/solvers/prototypes/contact_dfs.py index 9533576..197433a 100644 --- a/python/maxplus_solvers/solvers/prototypes/contact_dfs.py +++ b/python/maxplus_solvers/solvers/prototypes/contact_dfs.py @@ -151,8 +151,12 @@ def solve(instance: PuzzleInstance, config: SolverConfig) -> SolveResult: descend = False metrics.solutions = len(solutions) - metrics.candidates_generated, metrics.rejected_outside, metrics.rejected_overlap = state.stats() + metrics.candidates_generated, metrics.rejected_outside, metrics.rejected_overlap, _ = ( + state.stats() + ) metrics.wall_time_s = time.perf_counter() - started + if exhausted: + metrics.exhausted_s = metrics.wall_time_s metrics.cpu_time_s = time.process_time() - cpu_started if solutions: @@ -181,7 +185,6 @@ def solve(instance: PuzzleInstance, config: SolverConfig) -> SolveResult: SPEC = SolverSpec( name=NAME, run=solve, - regimes=frozenset({Regime.FOOTPRINT}), - candidate_set=CANDIDATE_SET, + candidate_sets={Regime.FOOTPRINT: CANDIDATE_SET}, description="Python prototype: depth-first search over corner contacts, fewest first", ) diff --git a/tests/architecture/test_layering.py b/tests/architecture/test_layering.py index e1bb08c..c6a1799 100644 --- a/tests/architecture/test_layering.py +++ b/tests/architecture/test_layering.py @@ -122,12 +122,78 @@ def test_solvers_are_registered_under_the_family_they_live_in() -> None: spec = solvers.get(name) family, _, algorithm = name.partition(".") assert family and algorithm, name - assert spec.regimes and spec.candidate_set and spec.description, name + assert spec.regimes and all(spec.candidate_sets.values()) and spec.description, name module = spec.run.__module__ if family == "python": assert module == f"maxplus_solvers.solvers.prototypes.{algorithm}", name + else: + assert family == "rust", name + assert module == f"maxplus_solvers.solvers.{algorithm}", name contract = (ROOT / "docs" / "solver-contract.md").read_text(encoding="utf-8") - assert f"`{name}`" in contract and f"`{spec.candidate_set}`" in contract, name + assert f"`{name}`" in contract, name + for candidate_set in spec.candidate_sets.values(): + assert f"`{candidate_set}`" in contract, (name, candidate_set) + + +def native_calls(tree: ast.AST) -> list[str]: + """Names of the ``_native`` functions called under ``tree``, once per call.""" + return [ + node.func.attr + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "_native" + ] + + +def test_production_solvers_cross_into_rust_once_per_solve() -> None: + """A solver outside ``prototypes`` hands the instance over and gets the answer back. + + Its module makes one ``_native`` call that does work, outside any loop. + Reading the version is not work. The prototype is the counter-example + that shows the check sees calls: it drives ``_native`` step by step. + """ + loops = (ast.For, ast.While, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) + solvers_dir = PACKAGE / "solvers" + production = [p for p in sorted(solvers_dir.glob("*.py")) if p.name != "__init__.py"] + assert [p.name for p in production] == ["contact_dfs.py"], "a new solver: is it checked?" + for path in production: + tree = ast.parse(path.read_text(encoding="utf-8")) + work = [name for name in native_calls(tree) if name != "version"] + assert len(work) == 1, (path.name, work) + for node in ast.walk(tree): + if isinstance(node, loops): + assert not native_calls(node), f"{path.name} calls _native in a loop" + + prototype = ast.parse((solvers_dir / "prototypes" / "contact_dfs.py").read_text("utf-8")) + assert len(native_calls(prototype)) >= 1 + stepwise = [ + call + for node in ast.walk(prototype) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + for call in [node.func.attr] + if call in {"propose", "place", "undo", "frontier"} + ] + assert len(stepwise) >= 4, "the prototype no longer steps through the search" + + +def test_every_search_rule_is_a_documented_switch() -> None: + """The rules of ``rust.contact_dfs`` can be turned off, and the documents say what each is. + + The measurements are the product: an option nobody can find, or a rule + without an ablation row, is a rule whose effect is not known. + """ + from maxplus_solvers.solvers import contact_dfs + + switches = {name for name, default in contact_dfs.DEFAULTS.items() if isinstance(default, bool)} + assert {"anchor", "cavity_pruning", "closure_pruning", "lookahead"} <= switches + contract = (ROOT / "docs" / "solver-contract.md").read_text(encoding="utf-8") + algorithms = (ROOT / "docs" / "algorithms.md").read_text(encoding="utf-8") + for option in contact_dfs.DEFAULTS: + assert f"| `{option}` |" in contract, f"{option} is not in the options table" + for switch in switches: + assert f"`{switch}`" in algorithms, f"{switch} has no place in algorithms.md" def test_importing_the_package_does_not_need_the_optional_extras() -> None: diff --git a/tests/corpus/test_rust_contact_dfs.py b/tests/corpus/test_rust_contact_dfs.py new file mode 100644 index 0000000..ce0c8fc --- /dev/null +++ b/tests/corpus/test_rust_contact_dfs.py @@ -0,0 +1,321 @@ +"""Phase 5 exit criterion: ``rust.contact_dfs`` solves and validates all 16 corpus fixtures. + +Each fixture is searched to the end in its own regime. 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 +assemblies, and with its additions switched off the Rust search does exactly +the prototype's work. + +The counts pinned here are findings about the corpus, relative to the +candidates the search generates and in ``f64`` with tolerances. They are what +the search finds, not proven numbers of solutions. +""" + +from typing import Any + +import pytest + +from maxplus_solvers import PuzzleInstance, Regime, SolverConfig, SolveResult, SolveStatus, solve +from maxplus_solvers.validation import validate_solution +from support import assemblies, corpus, geometry + +DFS = "rust.contact_dfs" +PROTOTYPE = "python.contact_dfs" +SWITCHES = ("anchor", "cavity_pruning", "closure_pruning", "lookahead") +# The Rust search doing only what the prototype does, in the prototype's order. +AS_THE_PROTOTYPE = { + "tray_rotations": "all", + "anchor": False, + "cavity_pruning": False, + "closure_pruning": False, + "lookahead": False, + "order": "generated", +} + +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") +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"} + +# 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). +ASSEMBLIES = {"rat1-flat": 101, "rat2-flat": 2} + + +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 whole(mode: Regime, solver: str = DFS, **options: Any) -> SolverConfig: + """A search to the end, in the given regime.""" + return SolverConfig(solver, mode=mode, max_solutions=None, 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 + ] + + +def keyed(fixture_id: str) -> list[Any]: + return assemblies.world(corpus.fixture(fixture_id), corpus.key(fixture_id)["poses"]) + + +def turns_of_the_key(fixture_id: str, instance: PuzzleInstance, found: list[Any]) -> int: + """How many of the assemblies found are the answer key in some orientation of the tray.""" + centre = geometry.centroid(instance.target) + turned = [ + assemblies.turned(keyed(fixture_id), turn, centre) + for turn in assemblies.tray_turns(instance.target) + ] + return sum(any(assemblies.same(key, assembly) for key in turned) for assembly in found) + + +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_the_exit_criterion_covers_the_whole_corpus() -> None: + assert len(CORPUS) == 16 and len(FLAT) == 8 and len(RELIEF) == 8 + assert sorted(CORPUS) == sorted(FLAT + RELIEF) + assert sorted(SMALL) == ["new3-flat", "new4-flat", "new5-flat", "rat1-flat", "rev2-flat"] + assert set(FLAT) >= SLOW | set(ASSEMBLIES) + + +# --- the exit criterion ------------------------------------------------------------------- + + +@pytest.mark.parametrize("fixture_id", marked(CORPUS)) +def test_every_fixture_is_solved_and_validated_in_its_own_regime(fixture_id: str) -> None: + instance = instance_of(fixture_id) + result = solve(instance, whole(instance.regime), validate=True) + assert result.status is SolveStatus.SOLVED + assert result.regime is instance.regime + assert result.exhaustive + assert not result.candidates_proven_complete + assert result.candidate_set == ( + "corner-contact-relief/1" if instance.regime is Regime.RELIEF else "corner-contact/1" + ) + for solution in result.solutions: + assert solution.valid is True + # Checked again here, without going through solve(). + report = validate_solution(instance, solution.poses) + assert report.solved, report.failed + # An exact assembly, not one that merely squeezes inside the tolerances. + assert report.worst_overlap_depth_mm == pytest.approx(0.0, abs=1e-9) + assert report.worst_outside_mm == pytest.approx(0.0, abs=1e-9) + assert report.uncovered_area_mm2 == pytest.approx(0.0, abs=1e-6) + if instance.regime is Regime.RELIEF: + assert report.worst_roof_mismatch_mm == pytest.approx(0.0, abs=1e-9) + + found = placed(instance, result) + # The answer key is found, once. + assert turns_of_the_key(fixture_id, instance, found) == 1 + # No assembly is returned twice, in any orientation of the tray. + assert all(len(orbit) == 1 for orbit in assemblies.orbits(instance.target, found)) + assert len(found) == ASSEMBLIES.get(fixture_id, 1) + + # The two times are separate numbers, and in order. + metrics = result.metrics + assert metrics["solutions"] == len(found) + assert 0.0 <= metrics["first_solution_s"] <= metrics["exhausted_s"] + assert metrics["exhausted_s"] == metrics["wall_time_s"] + + +@pytest.mark.parametrize("fixture_id", [f for f in CORPUS if f not in SLOW]) +def test_the_first_solution_is_reported_before_the_search_is_finished(fixture_id: str) -> None: + """Stopped at its first solution, the search claims a solution and nothing more.""" + instance = instance_of(fixture_id) + result = solve(instance, SolverConfig(DFS, mode=instance.regime), validate=True) + assert result.status is SolveStatus.SOLVED + (solution,) = result.solutions + assert solution.valid is True + assert not result.exhaustive + assert result.metrics["first_solution_s"] >= 0.0 + assert "exhausted_s" not in result.metrics + + +# --- against the prototype ---------------------------------------------------------------- + + +@pytest.mark.parametrize("fixture_id", SMALL) +def test_the_solution_set_is_the_prototypes(fixture_id: str) -> None: + """Counting every orientation, the two searches return the same assemblies. + + Counting each once, the Rust search returns one assembly out of every four + of the prototype's: the tray is a square and no assembly here is its own + rotation. + """ + instance = instance_of(fixture_id) + prototype = placed(instance, solve(instance, whole(Regime.FOOTPRINT, PROTOTYPE))) + every = placed(instance, solve(instance, whole(instance.regime, tray_rotations="all"))) + assert same_set(every, prototype) + + once = placed(instance, solve(instance, whole(instance.regime))) + orbits = assemblies.orbits(instance.target, prototype) + assert len(once) == len(orbits) + for orbit in orbits: + members = [prototype[i] for i in orbit] + assert sum(any(assemblies.same(a, m) for m in members) for a in once) == 1 + + +@pytest.mark.parametrize("fixture_id", SMALL) +def test_with_its_additions_off_the_search_does_the_prototypes_work(fixture_id: str) -> None: + """Same nodes, same backtracks, same candidates: one algorithm written twice. + + The prototype's counts come from Python driving single geometry calls, the + Rust counts from one call that runs the whole search. + """ + instance = instance_of(fixture_id) + prototype = solve(instance, whole(Regime.FOOTPRINT, PROTOTYPE)).metrics + bare = solve(instance, whole(instance.regime, **AS_THE_PROTOTYPE)).metrics + for count in ( + "nodes", + "backtracks", + "placements", + "max_depth", + "candidates_generated", + "rejected_outside", + "rejected_overlap", + "solutions", + ): + assert bare[count] == prototype[count], count + + +# --- the rules can be switched off -------------------------------------------------------- + + +@pytest.mark.parametrize("fixture_id", SMALL + [f.removesuffix("-flat") for f in SMALL]) +def test_no_rule_changes_what_the_whole_search_finds(fixture_id: str) -> None: + """Pruning, lookahead, the anchor and the order change the work, never the answer.""" + instance = instance_of(fixture_id) + on = dict.fromkeys(SWITCHES, True) + reference_result = solve(instance, whole(instance.regime, **on)) + reference = placed(instance, reference_result) + assert reference + variants: list[dict[str, Any]] = [{**on, switch: False} for switch in SWITCHES] + variants.append(dict.fromkeys(SWITCHES, False)) + variants.append({**on, "order": "generated"}) + variants.append({**on, "order": "random"}) + for options in variants: + result = solve(instance, whole(instance.regime, **options)) + assert result.exhaustive, options + assert same_set(placed(instance, result), reference), options + # Nor does any rule cost nodes: with everything off the search visits at least as many. + bare = solve(instance, whole(instance.regime, **dict.fromkeys(SWITCHES, False))) + assert bare.metrics["nodes"] >= reference_result.metrics["nodes"] + + +@pytest.mark.parametrize("fixture_id", ["new3-flat", "rat1"]) +def test_a_random_order_is_fixed_by_its_seed(fixture_id: str) -> None: + instance = instance_of(fixture_id) + + def run(seed: int) -> SolveResult: + return solve( + instance, + SolverConfig(DFS, mode=instance.regime, seed=seed, options={"order": "random"}), + ) + + first, again = run(7), run(7) + assert placed(instance, first) == placed(instance, again) + assert first.metrics["nodes"] == again.metrics["nodes"] + # Other seeds reach a valid first solution by other routes. + nodes = {run(seed).metrics["nodes"] for seed in range(8)} + assert len(nodes) > 1 + + +# --- what the roofs do -------------------------------------------------------------------- + + +@pytest.mark.parametrize("fixture_id", 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. + + The bound on nodes is loose on purpose. With every rule off the largest + whole search is 146 nodes (``rat2``, 20 pieces); the footprint twins take + up to a million. It is the roofs that make these puzzles easy, not the + pruning. + """ + instance = instance_of(fixture_id) + result = solve(instance, whole(instance.regime, **dict.fromkeys(SWITCHES, False))) + assert result.exhaustive + assert len(result.solutions) == 1 + assert result.metrics["nodes"] <= 200 + assert result.metrics["rejected_roof"] > 0 + + +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") + result = solve(relief, whole(Regime.FOOTPRINT), validate=True) + assert result.regime is Regime.FOOTPRINT + assert result.exhaustive + assert all(solution.valid for solution in result.solutions) + assert len(result.solutions) == ASSEMBLIES["rat1-flat"] + assert "roof_mismatch_mm" not in (result.solutions[0].residuals or {}) + # The keyed assembly is one of them. Its poses here need not continue the roofs: six + # of the pieces are their own half turn as footprints, and a footprint search is free + # to return either way round. + assert turns_of_the_key("rat1", relief, placed(relief, result)) == 1 + + +# --- counts derived by hand --------------------------------------------------------------- + + +@pytest.mark.parametrize("fixture_id", SYNTHETIC) +def test_synthetic_puzzles_have_the_solution_counts_worked_out_by_hand(fixture_id: str) -> None: + """``canonical`` assemblies counting each once, ``assemblies`` counting every orientation. + + The counts are for footprints and are derived in ``synthetic.py``. + """ + expected = corpus.key(fixture_id)["solutionCount"] + instance = instance_of(fixture_id) + seen = instance.as_regime("footprint") + key = keyed(fixture_id) + + once = solve(instance, whole(Regime.FOOTPRINT), validate=True) + assert once.exhaustive + assert all(solution.valid for solution in once.solutions) + assert len(once.solutions) == expected["canonical"] + assert turns_of_the_key(fixture_id, instance, placed(seen, once)) == 1 + + every = solve(instance, whole(Regime.FOOTPRINT, tray_rotations="all"), validate=True) + assert every.exhaustive + found = placed(seen, every) + assert len(found) == expected["assemblies"] + for i, first in enumerate(found): + for second in found[i + 1 :]: + assert not assemblies.same(first, second), "one assembly returned twice" + assert any(assemblies.same(assembly, key) for assembly in found) + + +def test_the_ridge_has_one_assembly_in_relief_however_turns_are_counted() -> None: + """Two rectangles under one ridge: by hand, each half goes on its own side. + + As footprints the halves stand in four ways (side by side or one above + the other, in either order). The ridge runs one way across the tray, so + in relief only the keyed arrangement remains; turning the tray turns the + pieces' roofs with them, which is the same assembly seen from another + side and not a second one. + """ + fixture_id = "syn-two-rectangles-ridge" + instance = instance_of(fixture_id) + assert instance.regime is Regime.RELIEF + once = solve(instance, whole(instance.regime), validate=True) + assert once.exhaustive and len(once.solutions) == 1 + assert once.solutions[0].valid is True + assert turns_of_the_key(fixture_id, instance, placed(instance, once)) == 1 diff --git a/tests/corpus/test_search_geometry_agrees_with_shapely.py b/tests/corpus/test_search_geometry_agrees_with_shapely.py new file mode 100644 index 0000000..f3eeea4 --- /dev/null +++ b/tests/corpus/test_search_geometry_agrees_with_shapely.py @@ -0,0 +1,327 @@ +"""The geometry phase 5 added to the search, against Shapely, the validator and the test oracle. + +Three things the Rust search relies on are computed a second way here, on +partial and whole assemblies taken from the answer keys: + +* the cavities of a partial assembly, against a Shapely difference; +* the roof step a placement would make, against the validator's seam check; +* canonical forms and the "same assembly" test, against ``support.assemblies``. + +Tolerances: lengths ``1e-9`` mm; areas ``1e-6`` mm², except where a cavity is +compared with a Shapely polygon that was first shrunk by ``1e-7`` mm to pull +apart cavities that touch at a point, which changes its area by its perimeter +times that and is compared to ``1e-3`` mm². + +Agreement is numerical evidence that two implementations compute the same +thing. It is not a proof of either. +""" + +import dataclasses +import math +import random +from typing import Any + +import pytest +import shapely + +from maxplus_solvers import Pose, PuzzleInstance, Regime, Roof, SolverConfig, _native, solve +from maxplus_solvers.validation import validate_solution +from support import assemblies, corpus, geometry + +FLAT = corpus.fixture_ids(kind="corpus", regime="footprint") +RELIEF = corpus.fixture_ids(kind="corpus", regime="relief") +ALL = corpus.fixture_ids() + +LENGTH_TOL = 1e-9 +AREA_TOL = 1e-6 +# For a cavity against a Shapely polygon shrunk by SHRINK_MM (see the module docstring). +SHRINK_MM = 1e-7 +SHRUNK_AREA_TOL = 1e-3 + +# The search's own tolerances are of this order: far above rounding, far below a feature. +TOL = {"length_tol": 1e-6, "angle_tol": 1e-6, "slope_tol": 1e-6} + +CAVITY_TRIALS = 30 + + +def load(fixture_id: str) -> tuple[PuzzleInstance, dict[str, Pose]]: + instance = PuzzleInstance.from_dict(corpus.fixture(fixture_id)) + poses = {pid: Pose(**pose) for pid, pose in corpus.key(fixture_id)["poses"].items()} + return instance, poses + + +def rng_for(fixture_id: str, purpose: str) -> random.Random: + """Seeded by name, so every run and every platform sees the same choices.""" + return random.Random(f"phase-5:{purpose}:{fixture_id}") + + +def as_tuple(pose: Pose) -> tuple[float, float, float]: + return (pose.x, pose.y, pose.theta) + + +def roofs_of(instance: PuzzleInstance) -> list[tuple[float, float, float]] | None: + if instance.regime is not Regime.RELIEF: + return None + roofs = [] + for piece in instance.pieces: + assert piece.roof is not None + roofs.append((piece.roof.z0, piece.roof.gx, piece.roof.gy)) + return roofs + + +def assembly(instance: PuzzleInstance) -> Any: + return _native.Assembly( + instance.target, [piece.polygon for piece in instance.pieces], roofs_of(instance), **TOL + ) + + +# --- cavities ----------------------------------------------------------------------------- + + +def least_width(ring: list[tuple[float, float]]) -> float: + """The least distance between two parallel lines that hold a convex polygon. + + One of the lines lies along an edge, so: for each edge, the farthest vertex + from its line; the least of those. + """ + best = math.inf + for (ax, ay), (bx, by) in zip(ring, ring[1:] + ring[:1], strict=True): + length = math.hypot(bx - ax, by - ay) + if length < 1e-6: + continue + reach = max(abs((bx - ax) * (py - ay) - (by - ay) * (px - ax)) / length for px, py in ring) + best = min(best, reach) + return best + + +@pytest.mark.parametrize("fixture_id", FLAT) +def test_cavities_of_partial_assemblies(fixture_id: str) -> None: + """Some of the keyed pieces are placed; what is left uncovered is found both ways.""" + instance, poses = load(fixture_id) + tray = shapely.Polygon(instance.target) + rng = rng_for(fixture_id, "cavities") + traced = holed = convex_seen = 0 + for _ in range(CAVITY_TRIALS): + order = list(range(len(instance.pieces))) + rng.shuffle(order) + chosen = order[: rng.randrange(1, len(order))] + state = assembly(instance) + placed = [] + for index in chosen: + piece = instance.pieces[index] + state.place(index, as_tuple(poses[piece.id])) + placed.append(shapely.Polygon(piece.world_polygon(poses[piece.id]))) + covered = shapely.union_all(placed) + # Shrunk a little, so that cavities meeting at a point come apart as they do in a trace. + left = tray.difference(covered.buffer(SHRINK_MM)).buffer(-SHRINK_MM) + parts = [g for g in getattr(left, "geoms", [left]) if g.area > SHRUNK_AREA_TOL] + has_hole = any(len(part.interiors) > 0 for part in parts) + + cavities = state.cavities() + if cavities is None: + # A placed piece that touches nothing leaves a region with a hole: not traced. + assert has_hole + holed += 1 + continue + assert not has_hole + traced += 1 + assert len(cavities) == len(parts) + # Exactly: what is uncovered is the tray less the pieces placed. + uncovered = tray.area - sum(shape.area for shape in placed) + assert sum(area for area, _, _ in cavities) == pytest.approx(uncovered, abs=AREA_TOL) + + frontier = state.frontier() + unmatched = list(parts) + for area, width, corners in cavities: + part = min(unmatched, key=lambda g, area=area: abs(g.area - area)) + unmatched.remove(part) + assert area == pytest.approx(part.area, abs=SHRUNK_AREA_TOL) + # Its corners are on that part's boundary. + for index in corners: + corner = frontier[index] + point = shapely.Point(corner.x, corner.y) + assert part.exterior.distance(point) <= 10 * SHRINK_MM + # A width is given exactly when the cavity is convex. + hull = part.convex_hull + is_convex = hull.area - part.area <= SHRUNK_AREA_TOL + assert (width is not None) == is_convex + if width is not None: + convex_seen += 1 + ring = [(x, y) for x, y in hull.exterior.coords[:-1]] + assert width == pytest.approx(least_width(ring), abs=10 * SHRINK_MM) + # Each case was seen, or the comparisons above checked only some of them. + assert traced >= 10 and convex_seen >= 3, (traced, holed, convex_seen) + + +def test_a_cavity_with_a_hole_is_reported_as_unknown_on_some_fixture() -> None: + """The ``None`` branch above is reached: some trial places a piece touching nothing.""" + seen = 0 + for fixture_id in FLAT: + instance, poses = load(fixture_id) + # The piece whose keyed centre is nearest the middle of the tray, alone. + centre = geometry.centroid(instance.target) + index = min( + range(len(instance.pieces)), + key=lambda i: math.dist( + centre, (poses[instance.pieces[i].id].x, poses[instance.pieces[i].id].y) + ), + ) + piece = instance.pieces[index] + world = shapely.Polygon(piece.world_polygon(poses[piece.id])) + state = assembly(instance) + state.place(index, as_tuple(poses[piece.id])) + touches_the_wall = world.distance(shapely.Polygon(instance.target).exterior) <= 1e-6 + assert (state.cavities() is None) == (not touches_the_wall) + seen += not touches_the_wall + assert seen >= 3 + + +def test_the_least_width_helper_on_shapes_measured_by_hand() -> None: + """Guard the oracle: a 3 x 5 rectangle is 3 wide; a 3-4-5 triangle is 12/5, its least height.""" + assert least_width([(0, 0), (5, 0), (5, 3), (0, 3)]) == pytest.approx(3.0, abs=1e-12) + assert least_width([(0, 0), (4, 0), (0, 3)]) == pytest.approx(2.4, abs=1e-12) + + +# --- roof steps --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("fixture_id", RELIEF) +def test_the_roof_step_of_a_placement_is_the_validators_seam_mismatch(fixture_id: str) -> None: + """One piece's roof is raised, or tilted; the step it then makes is measured twice. + + Every other seam of the keyed assembly is continuous, so the validator's + worst mismatch is the step along the changed piece's seams. + """ + instance, poses = load(fixture_id) + rng = rng_for(fixture_id, "roofs") + indices = rng.sample(range(len(instance.pieces)), min(5, len(instance.pieces))) + for index in indices: + target = instance.pieces[index] + assert target.roof is not None + lifted = Roof(target.roof.z0 + rng.uniform(0.5, 3.0), target.roof.gx, target.roof.gy) + tilted = Roof( + target.roof.z0, + target.roof.gx + rng.uniform(-0.05, 0.05), + target.roof.gy + rng.uniform(-0.05, 0.05), + ) + for roof in (target.roof, lifted, tilted): + pieces = tuple( + dataclasses.replace(piece, roof=roof) if piece.id == target.id else piece + for piece in instance.pieces + ) + changed = dataclasses.replace(instance, pieces=pieces) + report = validate_solution(changed, poses) + assert report.worst_roof_mismatch_mm is not None + state = assembly(changed) + for other, piece in enumerate(changed.pieces): + if other != index: + state.place(other, as_tuple(poses[piece.id])) + step = state.roof_step(index, as_tuple(poses[target.id])) + assert step == pytest.approx(report.worst_roof_mismatch_mm, abs=LENGTH_TOL) + if roof is target.roof: + assert step == pytest.approx(0.0, abs=LENGTH_TOL) + else: + assert step > 1e-3 + + +# --- canonical forms ---------------------------------------------------------------------- + + +def turned_poses( + instance: PuzzleInstance, poses: dict[str, Pose], turn: float +) -> list[tuple[float, float, float]]: + """The poses of the assembly turned about the tray's centroid, worked out here. + + A pose turns its piece about the local origin and then moves it, so turning + the placed piece about the centre turns the pose's offset about the centre + and adds to its angle. + """ + cx, cy = geometry.centroid(instance.target) + c, s = math.cos(turn), math.sin(turn) + out = [] + for piece in instance.pieces: + pose = poses[piece.id] + dx, dy = pose.x - cx, pose.y - cy + out.append((cx + c * dx - s * dy, cy + s * dx + c * dy, pose.theta + turn)) + return out + + +def world(instance: PuzzleInstance, poses: list[tuple[float, float, float]]) -> list[Any]: + return [ + piece.world_polygon(Pose(*pose)) for piece, pose in zip(instance.pieces, poses, strict=True) + ] + + +@pytest.mark.parametrize("fixture_id", ALL) +def test_every_turn_of_the_key_has_the_same_canonical_form(fixture_id: str) -> None: + instance, poses = load(fixture_id) + polygons = [piece.polygon for piece in instance.pieces] + roofs = roofs_of(instance) + turns = assemblies.tray_turns(instance.target) + assert len(turns) >= 3, "every tray in the corpus has a rotation" + plain = turned_poses(instance, poses, 0.0) + form = _native.canonical_poses(instance.target, polygons, roofs, plain, **TOL) + centre = geometry.centroid(instance.target) + expected = [assemblies.turned(world(instance, plain), turn, centre) for turn in turns] + # The form is the keyed assembly in one of the tray's orientations. + assert sum(assemblies.same(world(instance, form), turn) for turn in expected) >= 1 + for turn in turns: + other = turned_poses(instance, poses, turn) + assert _native.same_assembly(instance.target, polygons, roofs, plain, other, **TOL) + again = _native.canonical_poses(instance.target, polygons, roofs, other, **TOL) + for (x, y, theta), (u, v, phi) in zip(form, again, strict=True): + assert math.hypot(x - u, y - v) <= 1e-6 + # Angles compared as turns: -pi and pi are one. + assert abs(math.remainder(theta - phi, 2 * math.pi)) <= 1e-9 + + +@pytest.mark.parametrize("fixture_id", ALL) +def test_a_moved_piece_makes_another_assembly(fixture_id: str) -> None: + instance, poses = load(fixture_id) + polygons = [piece.polygon for piece in instance.pieces] + roofs = roofs_of(instance) + plain = turned_poses(instance, poses, 0.0) + rng = rng_for(fixture_id, "moved") + for _ in range(5): + moved = list(plain) + index = rng.randrange(len(moved)) + x, y, theta = moved[index] + moved[index] = (x + rng.choice([-1.0, 1.0]), y, theta) + assert not _native.same_assembly(instance.target, polygons, roofs, plain, moved, **TOL) + assert not assemblies.same(world(instance, plain), world(instance, moved)) + + +def test_same_assembly_agrees_with_the_oracle_on_the_assemblies_of_rat1() -> None: + """Pairs out of 404 footprint assemblies: the same up to the tray's turns, or not. + + The oracle compares placed polygons; the Rust form compares seats. Pieces + here are their own half turns and the tray has four orientations, so both + notions of "same" are exercised. + """ + instance, _ = load("rat1-flat") + polygons = [piece.polygon for piece in instance.pieces] + result = solve( + instance, + SolverConfig("rust.contact_dfs", max_solutions=None, options={"tray_rotations": "all"}), + ) + found = [ + [as_tuple(solution.poses[piece.id]) for piece in instance.pieces] + for solution in result.solutions + ] + assert len(found) == 404 + rng = rng_for("rat1-flat", "pairs") + sample = rng.sample(found, 40) + placed = [world(instance, poses) for poses in sample] + groups = assemblies.orbits(instance.target, placed) + group_of = {member: g for g, group in enumerate(groups) for member in group} + together = 0 + for i in range(len(sample)): + for j in range(i + 1, len(sample)): + expected = group_of[i] == group_of[j] + together += expected + assert ( + _native.same_assembly(instance.target, polygons, None, sample[i], sample[j], **TOL) + == expected + ) + # 40 out of 404 in orbits of four: some pairs share an orbit, most do not. + assert together >= 1 diff --git a/tests/support/documents.py b/tests/support/documents.py index 7f944b6..ec51b18 100644 --- a/tests/support/documents.py +++ b/tests/support/documents.py @@ -62,3 +62,50 @@ def with_source(doc: dict[str, Any]) -> dict[str, Any]: "geometryHash": "feed", } return doc + + +# Three strips side by side in a 120 mm by 72 mm tray, 24, 36 and 60 mm wide, in +# that order from the left wall at x = -60. Their centres are at x = -48, -18 and 30. +THREE_STRIP_WIDTHS = (24.0, 36.0, 60.0) +THREE_STRIP_CENTRES = (-48.0, -18.0, 30.0) + + +def three_strips() -> dict[str, Any]: + """A footprint puzzle with 3! = 6 assemblies: the strips in any order. + + The tray is a rectangle, with a half turn and no quarter turn. The half + turn reverses an order, so the 6 are 3 pairs. + """ + + def strip(width: float) -> list[list[float]]: + half = width / 2 + return [[-half, -36.0], [half, -36.0], [half, 36.0], [-half, 36.0]] + + doc = footprint() + doc["id"] = "three-strips" + doc["spanMm"] = 120.0 + doc["target"] = {"vertices": [[-60.0, -36.0], [60.0, -36.0], [60.0, 36.0], [-60.0, 36.0]]} + doc["pieces"] = [ + {"id": f"p{index:02d}", "polygon": strip(width)} + for index, width in enumerate(THREE_STRIP_WIDTHS) + ] + return doc + + +def three_strips_relief() -> dict[str, Any]: + """The same strips, each with the roof it has under ``z = 20 + (x + 60) / 4``. + + From the left, the roofs run 20 to 26, 26 to 35 and 35 to 50 mm. Two + unturned strips meet only where one's right height is the other's left, + which is the order they were cut in. A strip turned half round shows its + other edge, and no two right heights or two left heights agree. So the + roofs are continuous in that one order, and in its half turn with the tray: + 2 assemblies, 1 pair. + """ + doc = three_strips() + doc["regime"] = "relief" + doc["reliefMm"] = 50.0 + doc["validation"]["roofMismatch"] = 0.05 + 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 diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index 0df84b3..85a50e0 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -32,25 +32,41 @@ def test_a_solved_puzzle_exits_zero_and_says_what_is_claimed( ) -> None: assert cli.main([str(strips)]) == cli.SOLVED out = capsys.readouterr().out - assert "python.contact_dfs" in out and "(footprint): solved" in out + assert "rust.contact_dfs" in out and "(footprint): solved" in out assert "stopped before its end" in out + assert "first solution after" in out and "search finished after" not in out assert "not proven complete" in out assert "solution 1: 2 pieces, not validated" in out def test_all_solutions_with_validation(strips: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Upright and lying are a quarter turn of the tray apart: one assembly, or two.""" assert cli.main([str(strips), "--max-solutions", "all", "--validate"]) == cli.SOLVED out = capsys.readouterr().out assert "ran to its end" in out + assert "solution 1: 2 pieces, valid" in out and "solution 2" not in out + assert "first solution after" in out and "search finished after" in out + + arguments = [str(strips), "--max-solutions", "all", "--validate"] + assert cli.main([*arguments, "--option", "tray_rotations=all"]) == cli.SOLVED + out = capsys.readouterr().out assert "solution 2: 2 pieces, valid" in out and "solution 3" not in out + assert cli.main([*arguments, "--solver", "python.contact_dfs"]) == cli.SOLVED + out = capsys.readouterr().out + assert "python.contact_dfs" in out and "solution 2: 2 pieces, valid" in out + def test_json_output_is_a_result_document(strips: Path, capsys: pytest.CaptureFixture[str]) -> None: - assert cli.main([str(strips), "--json", "--seed", "5", "--max-solutions", "2"]) == cli.SOLVED + arguments = ["--json", "--seed", "5", "--max-solutions", "2"] + options = ["--option", "tray_rotations=all", "--option", "lookahead=false"] + assert cli.main([str(strips), *arguments, *options]) == cli.SOLVED result = SolveResult.from_dict(json.loads(capsys.readouterr().out)) assert len(result.solutions) == 2 assert result.config is not None assert (result.config.seed, result.config.max_solutions) == (5, 2) + # A word stays a word, and JSON is read as JSON. + assert result.config.options == {"tray_rotations": "all", "lookahead": False} def test_no_solution_exits_one(unfillable: Path, capsys: pytest.CaptureFixture[str]) -> None: @@ -70,7 +86,11 @@ def test_a_fixture_is_found_by_id( ("arguments", "message"), [ (["--solver", "rust.nothing"], "invalid choice"), - (["--mode", "relief"], "does not work in relief mode"), + (["--mode", "relief"], "cannot turn a footprint instance"), + (["--solver", "python.contact_dfs", "--mode", "relief"], "does not work in relief mode"), + (["--option", "nonsense=1"], "unknown options nonsense"), + (["--option", "lookahead"], "must be NAME=VALUE"), + (["--option", "lookahead=perhaps"], "lookahead must be true or false"), (["--max-solutions", "0"], "must be at least 1"), (["--time-limit", "-1"], "time_limit_s must be positive"), ], @@ -99,7 +119,7 @@ def test_an_invalid_solution_exits_three( from maxplus_solvers import Pose, Solution, solvers - real = solvers.get("python.contact_dfs") + real = solvers.get("rust.contact_dfs") def overlapping(instance, config): # type: ignore[no-untyped-def] result = real.run(instance, config) diff --git a/tests/unit/test_native_assembly.py b/tests/unit/test_native_assembly.py index f78f043..0b3f9e4 100644 --- a/tests/unit/test_native_assembly.py +++ b/tests/unit/test_native_assembly.py @@ -82,7 +82,7 @@ def test_proposals_put_a_vertex_in_the_corner_and_an_edge_along_its_side() -> No assert (lying.x, lying.y, lying.theta) == lying.pose # A rectangle maps onto itself by a half turn, so vertices 2 and 3 are not tried. assert state.symmetry() == [2] - assert state.stats() == (2, 0, 0) + assert state.stats() == (2, 0, 0, 0) assert repr(lying).startswith("Candidate(piece=0, x=1.0, y=0.5, theta=0.0, vertex=0") @@ -94,7 +94,7 @@ def test_proposals_leave_out_twins_and_count_what_does_not_fit() -> None: gap = next(c for c in state.frontier() if (c.x, c.y) == (3.5, 0.0)) assert state.propose(gap) == [] # Piece 0 was tried lying and standing and reaches outside both ways; piece 1 was not tried. - assert state.stats() == (2, 2, 0) + assert state.stats() == (2, 2, 0, 0) def test_a_proposal_that_enters_a_placed_piece_is_counted_as_such() -> None: @@ -106,7 +106,7 @@ def test_a_proposal_that_enters_a_placed_piece_is_counted_as_such() -> None: # lies 3.5 wide and fits; with its long side there it comes down to y = 0.5, into the bar. (lying,) = state.propose(top_left) assert lying.pose == pytest.approx((1.75, 3.0, -QUARTER), abs=1e-12) - assert state.stats() == (2, 0, 1) + assert state.stats() == (2, 0, 1, 0) def test_check_placement_measures_outside_and_overlap() -> None: diff --git a/tests/unit/test_native_search.py b/tests/unit/test_native_search.py new file mode 100644 index 0000000..58e6b87 --- /dev/null +++ b/tests/unit/test_native_search.py @@ -0,0 +1,247 @@ +"""The search-level functions of ``_native``, on states small enough to work out by hand. + +Cavities and roof steps of an ``Assembly``, canonical forms, and the argument +checks of ``contact_dfs``. What the search finds is tested through ``solve()`` +in ``test_rust_contact_dfs.py``. +""" + +import math +from typing import Any + +import pytest + +from maxplus_solvers import _native + +TOL: dict[str, Any] = {"length_tol": 1e-7, "angle_tol": 1e-7, "slope_tol": 1e-7} +# A 4 by 4 tray with its corner at the origin. +TRAY = [(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)] + + +def rectangle(w: float, h: float) -> list[tuple[float, float]]: + return [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h / 2)] + + +# --- cavities ----------------------------------------------------------------------------- + + +def test_the_empty_tray_is_one_cavity_as_wide_as_the_tray() -> None: + state = _native.Assembly(TRAY, [rectangle(4, 1)], **TOL) + cavities = state.cavities() + assert cavities is not None + ((area, width, corners),) = cavities + assert area == pytest.approx(16.0, abs=1e-12) + assert width == pytest.approx(4.0, abs=1e-12) + assert sorted(corners) == [0, 1, 2, 3] + + +def test_a_strip_across_the_tray_leaves_two_cavities() -> None: + """The strip over 1 <= y <= 2 leaves 4 by 1 below it and 4 by 2 above.""" + state = _native.Assembly(TRAY, [rectangle(4, 1)], **TOL) + state.place(0, (2.0, 1.5, 0.0)) + cavities = state.cavities() + assert cavities is not None + assert sorted((round(area, 9), round(width or 0, 9)) for area, width, _ in cavities) == [ + (4.0, 1.0), + (8.0, 2.0), + ] + # Each corner of the frontier belongs to one cavity. + used = sorted(corner for _, _, corners in cavities for corner in corners) + assert used == list(range(len(state.frontier()))) + + +def test_a_cavity_with_a_reflex_corner_has_no_width() -> None: + """A 2 by 1 block in the corner leaves an L: 16 - 2 = 14.""" + state = _native.Assembly(TRAY, [rectangle(2, 1)], **TOL) + state.place(0, (1.0, 0.5, 0.0)) + cavities = state.cavities() + assert cavities is not None + ((area, width, corners),) = cavities + assert area == pytest.approx(14.0, abs=1e-12) + assert width is None + assert len(corners) == 6 + + +def test_a_piece_standing_in_the_open_gets_no_answer() -> None: + """It makes a hole in the uncovered region, which the cavity rules do not cover.""" + state = _native.Assembly(TRAY, [rectangle(1, 1)], **TOL) + state.place(0, (2.0, 2.0, 0.0)) + assert state.cavities() is None + + +def test_a_covered_tray_has_no_cavity() -> None: + state = _native.Assembly(TRAY, [rectangle(4, 4)], **TOL) + state.place(0, (2.0, 2.0, 0.0)) + assert state.cavities() == [] + + +# --- roofs -------------------------------------------------------------------------------- + +# Two 2 by 4 strips whose roofs rise towards the seam between them at 0.25 mm/mm: +# 20 mm at their centres, 20.25 at the seam. +RIDGE = [(20.0, 0.25, 0.0), (20.0, -0.25, 0.0)] + + +def ridge(roofs: list[tuple[float, float, float]] = RIDGE) -> _native.Assembly: + return _native.Assembly(TRAY, [rectangle(2, 4), rectangle(2, 4)], roofs, **TOL) + + +def test_roofs_that_meet_have_no_step() -> None: + state = ridge() + state.place(0, (1.0, 2.0, 0.0)) + assert state.roof_step(1, (3.0, 2.0, 0.0)) == pytest.approx(0.0, abs=1e-12) + # Away from the first strip there is no shared edge, and so no step. + assert state.roof_step(1, (3.5, 2.0, 0.0)) == 0.0 + + +def test_a_step_is_measured_where_it_is_largest() -> None: + """Turn the second strip half round: its roof now falls away from the seam. + + At the seam the first roof is at 20.25 and the second, with its low edge + there, at 20 - 0.25 = 19.75: a step of 0.5 all along. + + Give the second roof a slope along the seam instead and the step grows + along it: with gradient (-0.25, 0.1) the roofs agree at the seam's middle + and differ by 0.1 * 2 = 0.2 at its ends. + """ + state = ridge() + state.place(0, (1.0, 2.0, 0.0)) + assert state.roof_step(1, (3.0, 2.0, math.pi)) == pytest.approx(0.5, abs=1e-12) + tilted = ridge([RIDGE[0], (20.0, -0.25, 0.1)]) + tilted.place(0, (1.0, 2.0, 0.0)) + assert tilted.roof_step(1, (3.0, 2.0, 0.0)) == pytest.approx(0.2, abs=1e-12) + + +def test_proposals_leave_out_placements_whose_roofs_do_not_meet() -> None: + state = ridge() + state.place(0, (1.0, 2.0, 0.0)) + (corner,) = [c for c in state.frontier() if (c.x, c.y) == (2.0, 0.0)] + proposals = state.propose(corner) + # A roofed strip is not its own half turn, so each of its four corners is tried. + # Two lay it across the gap, 4 wide where 2 are left, and stick out of the tray. + # The other two fit; only one of them continues the roof. + assert [(c.piece, round(c.theta, 9)) for c in proposals] == [(1, 0.0)] + generated, outside, overlap, roof = state.stats() + assert (generated, outside + overlap, roof) == (4, 2, 1) + # Without roofs both ways are proposed, as one: the strip is its own half turn. + bare = _native.Assembly(TRAY, [rectangle(2, 4), rectangle(2, 4)], **TOL) + bare.place(0, (1.0, 2.0, 0.0)) + (corner,) = [c for c in bare.frontier() if (c.x, c.y) == (2.0, 0.0)] + assert len(bare.propose(corner)) == 1 + assert bare.stats()[3] == 0 + + +def test_a_height_tolerance_must_be_positive() -> None: + with pytest.raises(ValueError, match="finite and positive"): + _native.Assembly(TRAY, [rectangle(2, 4)], **TOL, height_tol=0.0) + with pytest.raises(ValueError, match="no piece 3"): + ridge().roof_step(3, (0.0, 0.0, 0.0)) + + +# --- canonical forms ---------------------------------------------------------------------- + +STRIPS = [rectangle(1, 4), rectangle(3, 4)] +# The narrow strip against the left wall, and that assembly turned with the tray by +# quarter turns about (2, 2): against the bottom, the right and the top. +LEFT = [(0.5, 2.0, 0.0), (2.5, 2.0, 0.0)] +TURNS = [ + LEFT, + [(2.0, 0.5, math.pi / 2), (2.0, 2.5, math.pi / 2)], + [(3.5, 2.0, math.pi), (1.5, 2.0, math.pi)], + [(2.0, 3.5, -math.pi / 2), (2.0, 1.5, -math.pi / 2)], +] + + +def test_the_turns_of_an_assembly_have_one_canonical_form() -> None: + form = _native.canonical_poses(TRAY, STRIPS, None, LEFT, **TOL) + for turn in TURNS: + assert _native.same_assembly(TRAY, STRIPS, None, LEFT, turn, **TOL) + again = _native.canonical_poses(TRAY, STRIPS, None, turn, **TOL) + for (x, y, theta), (u, v, phi) in zip(form, again, strict=True): + assert (x, y, theta) == pytest.approx((u, v, phi), abs=1e-9) + # The form is itself one of the four, with the strip's half turn taken out. + assert any( + all( + math.dist(p[:2], q[:2]) <= 1e-9 and abs(math.remainder(p[2] - q[2], math.pi)) <= 1e-9 + for p, q in zip(form, turn, strict=True) + ) + for turn in TURNS + ) + + +def test_a_shifted_piece_is_another_assembly() -> None: + shifted = [LEFT[0], (2.5, 2.0 + 1e-3, 0.0)] + assert not _native.same_assembly(TRAY, STRIPS, None, LEFT, shifted, **TOL) + # Within the tolerance it is the same one. + nudged = [LEFT[0], (2.5, 2.0 + 1e-9, 0.0)] + assert _native.same_assembly(TRAY, STRIPS, None, LEFT, nudged, **TOL) + + +def test_congruent_pieces_may_change_places_and_others_may_not() -> None: + tray = [(0.0, 0.0), (4.0, 0.0), (4.0, 3.0), (0.0, 3.0)] + pieces = [rectangle(1, 3), rectangle(1, 3), rectangle(2, 3)] + one = [(0.5, 1.5, 0.0), (1.5, 1.5, 0.0), (3.0, 1.5, 0.0)] + swapped = [one[1], one[0], one[2]] + between = [(0.5, 1.5, 0.0), (3.5, 1.5, 0.0), (2.0, 1.5, 0.0)] + assert _native.same_assembly(tray, pieces, None, one, swapped, **TOL) + assert not _native.same_assembly(tray, pieces, None, one, between, **TOL) + + +def test_a_roof_makes_a_turned_piece_a_different_piece() -> None: + """Without roofs a strip is its own half turn. With a sloping roof it is not.""" + half_turned = [(0.5, 2.0, math.pi), LEFT[1]] + assert _native.same_assembly(TRAY, STRIPS, None, LEFT, half_turned, **TOL) + roofs = [(20.0, 0.25, 0.0), (20.0, 0.25, 0.0)] + assert not _native.same_assembly(TRAY, STRIPS, roofs, LEFT, half_turned, **TOL) + + +def test_canonical_forms_refuse_what_does_not_fit_the_puzzle() -> None: + with pytest.raises(ValueError, match="1 poses for 2 pieces"): + _native.canonical_poses(TRAY, STRIPS, None, LEFT[:1], **TOL) + with pytest.raises(ValueError, match="3 poses for 2 pieces"): + _native.same_assembly(TRAY, STRIPS, None, LEFT, [*LEFT, LEFT[0]], **TOL) + with pytest.raises(ValueError, match="1 roofs for 2 pieces"): + _native.canonical_poses(TRAY, STRIPS, [(1.0, 0.0, 0.0)], LEFT, **TOL) + with pytest.raises(ValueError, match="not a strictly convex"): + _native.canonical_poses(TRAY, [STRIPS[0][::-1], STRIPS[1]], None, LEFT, **TOL) + + +# --- contact_dfs -------------------------------------------------------------------------- + + +def test_the_search_returns_poses_in_piece_order_and_its_counts() -> None: + outcome = _native.contact_dfs(TRAY, STRIPS, **TOL, max_solutions=None) + assert outcome.exhausted + assert outcome.tray_order == 4 + # The wide strip is the larger of two pieces that are congruent to nothing else. + assert outcome.anchor == 1 + (poses,) = outcome.solutions + assert len(poses) == 2 + assert any(_native.same_assembly(TRAY, STRIPS, None, poses, turn, **TOL) for turn in TURNS) + assert outcome.nodes >= 3 and outcome.max_depth == 2 + assert outcome.cavities_unknown == 0 + assert outcome.first_solution_s is not None + assert 0.0 <= outcome.first_solution_s <= outcome.wall_time_s + + every = _native.contact_dfs(TRAY, STRIPS, **TOL, max_solutions=None, all_tray_rotations=True) + assert len(every.solutions) == 4 and every.anchor is None + + +@pytest.mark.parametrize( + ("arguments", "message"), + [ + ({"order": "backwards"}, "order must be generated, matched-edges or random"), + ({"time_limit_s": -1.0}, "time_limit_s must be finite and not negative"), + ({"time_limit_s": math.inf}, "time_limit_s must be finite and not negative"), + ({"height_tol": -1.0}, "finite and positive"), + ], +) +def test_the_search_refuses_bad_arguments(arguments: dict[str, Any], message: str) -> None: + with pytest.raises(ValueError, match=message): + _native.contact_dfs(TRAY, STRIPS, **{**TOL, **arguments}) + + +def test_the_search_refuses_bad_puzzles() -> None: + with pytest.raises(ValueError, match="piece 0 is not a strictly convex"): + _native.contact_dfs(TRAY, [STRIPS[0][::-1]], **TOL) + with pytest.raises(ValueError, match="1 roofs for 2 pieces"): + _native.contact_dfs(TRAY, STRIPS, [(1.0, 0.0, 0.0)], **TOL) diff --git a/tests/unit/test_rust_contact_dfs.py b/tests/unit/test_rust_contact_dfs.py new file mode 100644 index 0000000..a4050c0 --- /dev/null +++ b/tests/unit/test_rust_contact_dfs.py @@ -0,0 +1,303 @@ +"""``rust.contact_dfs`` on puzzles whose assemblies can be listed by hand. + +The three strips of ``support.documents`` stand in any order in the footprint +regime and in one order once they have roofs. Everything here follows from +that, and from two more puzzles that cannot be assembled at all. +""" + +import math +from typing import Any + +import pytest + +from maxplus_solvers import ( + Pose, + PuzzleInstance, + Regime, + SolverConfig, + SolveResult, + SolveStatus, + solve, + solvers, +) +from maxplus_solvers.metrics import SearchMetrics +from maxplus_solvers.validation import validate_solution +from support import assemblies, documents, geometry + +DFS = "rust.contact_dfs" +SWITCHES = ("anchor", "cavity_pruning", "closure_pruning", "lookahead") +TIMES = {"wall_time_s", "cpu_time_s", "first_solution_s", "exhausted_s"} + + +def footprint() -> PuzzleInstance: + return PuzzleInstance.from_dict(documents.three_strips()) + + +def relief() -> PuzzleInstance: + return PuzzleInstance.from_dict(documents.three_strips_relief()) + + +def everything(mode: Regime = Regime.FOOTPRINT, **options: Any) -> SolverConfig: + return SolverConfig(DFS, mode=mode, max_solutions=None, 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 + ] + + +def in_order(*order: int) -> list[list[tuple[float, float]]]: + """The strips standing in the given order from the left wall, by hand.""" + polygons: list[list[tuple[float, float]]] = [[], [], []] + x = -60.0 + for strip in order: + width = documents.THREE_STRIP_WIDTHS[strip] + polygons[strip] = [(x, -36.0), (x + width, -36.0), (x + width, 36.0), (x, 36.0)] + x += width + return polygons + + +ORDERS = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] + + +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) + + +# --- what is found ------------------------------------------------------------------------ + + +def test_every_order_of_the_strips_is_found_when_turns_are_counted() -> None: + instance = footprint() + result = solve(instance, everything(tray_rotations="all"), validate=True) + assert result.status is SolveStatus.SOLVED and result.exhaustive + assert all(solution.valid for solution in result.solutions) + assert same_set(placed(instance, result), [in_order(*order) for order in ORDERS]) + + +def test_an_order_and_its_reverse_are_one_assembly() -> None: + """The tray's half turn reverses an order: 6 orders, 3 assemblies.""" + instance = footprint() + result = solve(instance, everything(), validate=True) + assert result.exhaustive + assert all(solution.valid for solution in result.solutions) + found = placed(instance, result) + assert len(found) == 3 + half_turn = [assemblies.turned(a, math.pi, (0.0, 0.0)) for a in found] + assert same_set(found + half_turn, [in_order(*order) for order in ORDERS]) + + +def test_roofs_leave_one_order() -> None: + """Worked out in ``documents.three_strips_relief``: the order the roofs were cut in.""" + instance = relief() + result = solve(instance, everything(Regime.RELIEF), validate=True) + assert result.status is SolveStatus.SOLVED and result.exhaustive + (solution,) = result.solutions + assert solution.valid is True + assert solution.residuals is not None + assert solution.residuals["roof_mismatch_mm"] == pytest.approx(0.0, abs=1e-9) + (found,) = placed(instance, result) + cut = in_order(0, 1, 2) + assert assemblies.same(found, cut) or assemblies.same( + found, assemblies.turned(cut, math.pi, (0.0, 0.0)) + ) + + both = solve(instance, everything(Regime.RELIEF, tray_rotations="all"), validate=True) + assert all(solution.valid for solution in both.solutions) + assert same_set(placed(instance, both), [cut, assemblies.turned(cut, math.pi, (0.0, 0.0))]) + assert both.metrics["rejected_roof"] > 0 + + +def test_the_roofs_are_hidden_in_footprint_mode() -> None: + result = solve(relief(), everything(Regime.FOOTPRINT)) + assert result.regime is Regime.FOOTPRINT + assert len(result.solutions) == 3 + assert result.metrics["rejected_roof"] == 0 + + +def test_a_roof_out_of_step_leaves_no_assembly() -> None: + """Lift the middle roof by 0.25 mm: every seam it could have now has a step.""" + doc = documents.three_strips_relief() + doc["pieces"][1]["roof"]["z0"] += 0.25 + instance = PuzzleInstance.from_dict(doc) + result = solve(instance, everything(Regime.RELIEF)) + assert result.status is SolveStatus.NO_SOLUTION_FOUND and result.exhaustive + # The validator agrees about the assembly the roofs were cut from: it is 0.25 mm out. + poses = { + piece.id: Pose(centre, 0.0, 0.0) + for piece, centre in zip(instance.pieces, documents.THREE_STRIP_CENTRES, strict=True) + } + report = validate_solution(instance, poses) + assert report.worst_roof_mismatch_mm == pytest.approx(0.25, abs=1e-9) + + +def test_strips_too_narrow_for_the_tray_are_refused_at_the_root() -> None: + """24 + 36 + 48 mm of strips for 120 mm of tray: the areas cannot add up.""" + doc = documents.three_strips() + doc["pieces"][2]["polygon"] = [[-24.0, -36.0], [24.0, -36.0], [24.0, 36.0], [-24.0, 36.0]] + instance = PuzzleInstance.from_dict(doc) + result = solve(instance, everything()) + assert result.status is SolveStatus.NO_SOLUTION_FOUND and result.exhaustive + assert (result.metrics["nodes"], result.metrics["pruned_cavity"]) == (1, 1) + assert "first_solution_s" not in result.metrics + # Without the pruning the same answer takes placements to reach. + plain = solve(instance, everything(cavity_pruning=False, closure_pruning=False)) + assert plain.status is SolveStatus.NO_SOLUTION_FOUND + assert plain.metrics["nodes"] > 1 and plain.metrics["pruned_cavity"] == 0 + + +# --- the switches change the work, not what is found -------------------------------------- + + +@pytest.mark.parametrize("instance", [footprint(), relief()], ids=["footprint", "relief"]) +def test_each_switch_can_be_turned_off_without_changing_what_is_found( + instance: PuzzleInstance, +) -> None: + on = dict.fromkeys(SWITCHES, True) + reference = placed(instance, solve(instance, everything(instance.regime, **on))) + assert reference + counted = { + "anchor": "pruned_anchor", + "cavity_pruning": "pruned_cavity", + "closure_pruning": "pruned_closure", + "lookahead": "pruned_lookahead", + } + for switch in SWITCHES: + result = solve(instance, everything(instance.regime, **{**on, switch: False})) + assert result.exhaustive + assert same_set(placed(instance, result), reference), switch + assert result.metrics[counted[switch]] == 0, switch + bare = solve(instance, everything(instance.regime, **dict.fromkeys(SWITCHES, False))) + assert same_set(placed(instance, bare), reference) + + +def test_the_order_of_trying_changes_only_which_comes_first() -> None: + instance = footprint() + reference = placed(instance, solve(instance, everything())) + firsts = [] + for order in ("matched-edges", "generated", "random"): + result = solve(instance, everything(order=order)) + assert same_set(placed(instance, result), reference), order + for seed in range(8): + config = SolverConfig(DFS, max_solutions=None, seed=seed, options={"order": "random"}) + result, again = solve(instance, config), solve(instance, config) + assert result.solutions == again.solutions, "a seed fixes the order" + assert same_set(placed(instance, result), reference) + firsts.append(placed(instance, result)[0]) + assert any(not assemblies.same(first, firsts[0]) for first in firsts), "8 seeds, one order" + + +def test_solutions_come_in_one_canonical_form() -> None: + """Whatever the order they were found in, an assembly is returned with the same poses.""" + instance = footprint() + reference = solve(instance, everything()).solutions + other = solve( + instance, SolverConfig(DFS, max_solutions=None, seed=3, options={"order": "random"}) + ).solutions + for solution in other: + twins = [ + r + for r in reference + if all( + math.dist((r.poses[k].x, r.poses[k].y), (p.x, p.y)) <= 1e-9 + and abs(r.poses[k].theta - p.theta) <= 1e-9 + for k, p in solution.poses.items() + ) + ] + assert len(twins) == 1 + + +def test_the_search_is_deterministic_and_ignores_the_seed_unless_asked() -> None: + instance = footprint() + first = solve(instance, everything()) + second = solve(instance, SolverConfig(DFS, max_solutions=None, seed=99)) + assert first.solutions == second.solutions + assert {k: v for k, v in first.metrics.items() if k not in TIMES} == { + k: v for k, v in second.metrics.items() if k not in TIMES + } + + +# --- limits and statuses ------------------------------------------------------------------ + + +def test_the_first_solution_is_returned_by_default_and_claims_no_more() -> None: + result = solve(footprint(), SolverConfig(DFS)) + assert result.status is SolveStatus.SOLVED + assert len(result.solutions) == 1 and not result.exhaustive + assert "first_solution_s" in result.metrics + assert "exhausted_s" not in result.metrics, "the search did not reach its end" + + +def test_the_two_times_are_reported_separately() -> None: + result = solve(footprint(), everything()) + assert result.exhaustive + first, end = result.metrics["first_solution_s"], result.metrics["exhausted_s"] + assert 0.0 <= first <= end + assert end == result.metrics["wall_time_s"] + + +def test_limits_interrupt() -> None: + limited = solve(footprint(), everything(node_limit=1)) + assert limited.status is SolveStatus.INTERRUPTED and not limited.exhaustive + assert limited.metrics["nodes"] == 1 + hurried = solve(footprint(), SolverConfig(DFS, max_solutions=None, time_limit_s=1e-12)) + assert hurried.status is SolveStatus.INTERRUPTED + assert hurried.metrics["nodes"] == 0 + + +# --- what a result records ---------------------------------------------------------------- + + +def test_a_result_names_the_candidate_set_of_its_regime() -> None: + spec = solvers.get(DFS) + assert spec.regimes == frozenset({Regime.FOOTPRINT, Regime.RELIEF}) + flat = solve(footprint(), everything(lookahead=True)) + assert (flat.solver, flat.candidate_set) == (DFS, "corner-contact/1") + assert flat.candidate_set == spec.candidate_sets[Regime.FOOTPRINT] + assert flat.candidates_proven_complete is False + assert flat.config is not None and flat.config.options == {"lookahead": True} + assert flat.solver_version.count(".") == 2 + assert set(flat.metrics) == set(SearchMetrics().to_dict()) | {"first_solution_s", "exhausted_s"} + roofed = solve(relief(), everything(Regime.RELIEF)) + assert roofed.candidate_set == "corner-contact-relief/1" + assert roofed.instance_hash == relief().instance_hash() + + +def test_the_tropical_regime_is_not_offered() -> None: + instance = PuzzleInstance.from_dict(documents.tropical_aware()) + with pytest.raises(ValueError, match="does not work in tropical-aware mode"): + solve(instance, SolverConfig(DFS, mode=Regime.TROPICAL_AWARE)) + with pytest.raises(ValueError, match="does not work in the tropical-aware regime"): + solvers.get(DFS).run(instance, SolverConfig(DFS, mode=Regime.TROPICAL_AWARE)) + + +@pytest.mark.parametrize( + ("options", "message"), + [ + ({"prune": True}, "unknown options prune"), + ({"node_limit": 0}, "node_limit must be a positive integer"), + ({"node_limit": True}, "node_limit must be a positive integer"), + ({"lookahead": "yes"}, "lookahead must be true or false"), + ({"anchor": 1}, "anchor must be true or false"), + ({"order": "sideways"}, "order must be one of"), + ({"tray_rotations": "twice"}, "tray_rotations must be one of"), + ], +) +def test_options_it_does_not_understand_are_refused(options: dict[str, Any], message: str) -> None: + with pytest.raises(ValueError, match=message): + solve(footprint(), SolverConfig(DFS, options=options)) + + +def test_a_negative_seed_is_refused() -> None: + with pytest.raises(ValueError, match="seed must not be negative"): + solve(footprint(), SolverConfig(DFS, seed=-1)) + + +def test_the_hand_made_assemblies_are_what_they_claim() -> None: + """Guard the expectations above: each order tiles the tray, by the test oracle.""" + for order in ORDERS: + polygons = in_order(*order) + assert sum(geometry.area(p) for p in polygons) == pytest.approx(120.0 * 72.0, abs=1e-9) + assert sorted(min(x for x, _ in p) for p in polygons)[0] == -60.0 diff --git a/tests/unit/test_solve.py b/tests/unit/test_solve.py index 3177cd4..b07cd99 100644 --- a/tests/unit/test_solve.py +++ b/tests/unit/test_solve.py @@ -105,7 +105,7 @@ def test_the_search_is_deterministic() -> None: first = solve(strips(), SolverConfig(DFS, max_solutions=None)) second = solve(strips(), SolverConfig(DFS, max_solutions=None, seed=99)) assert first.solutions == second.solutions - timed = {"wall_time_s", "cpu_time_s", "first_solution_s"} + timed = {"wall_time_s", "cpu_time_s", "first_solution_s", "exhausted_s"} assert {k: v for k, v in first.metrics.items() if k not in timed} == { k: v for k, v in second.metrics.items() if k not in timed } @@ -141,7 +141,11 @@ def test_a_result_says_what_produced_it_and_what_it_claims() -> None: assert result.candidate_set == "corner-contact/1" # f64 with tolerances proves nothing about completeness. assert result.candidates_proven_complete is False - assert set(result.metrics) == set(SearchMetrics().to_dict()) | {"first_solution_s"} + # The two times that are only there when they happened: a solution, and the end. + assert set(result.metrics) == set(SearchMetrics().to_dict()) | { + "first_solution_s", + "exhausted_s", + } assert SolveResult.from_dict(json.loads(json.dumps(result.to_dict()))) == result @@ -181,7 +185,7 @@ def everything(instance: PuzzleInstance, config: SolverConfig) -> SolveResult: raise AssertionError("the solver must not be reached") spec = solvers.SolverSpec( - "test.everything", everything, frozenset(Regime), "none", "accepts any regime" + "test.everything", everything, dict.fromkeys(Regime, "none"), "accepts any regime" ) solvers.register(spec) try: @@ -206,7 +210,8 @@ def test_the_registry_lists_the_prototype() -> None: assert available_solvers() == tuple(sorted(available_solvers())) spec = solvers.get(DFS) assert spec.regimes == frozenset({Regime.FOOTPRINT}) - assert spec.candidate_set and spec.description + assert spec.candidate_sets == {Regime.FOOTPRINT: "corner-contact/1"} + assert spec.description def test_an_unknown_solver_is_refused_with_the_known_ones_named() -> None: @@ -219,7 +224,7 @@ def test_a_name_is_registered_once_and_needs_a_regime() -> None: with pytest.raises(ValueError, match="already registered"): solvers.register(spec) with pytest.raises(ValueError, match="declares no regime"): - solvers.register(solvers.SolverSpec("test.none", spec.run, frozenset(), "x", "x")) + solvers.register(solvers.SolverSpec("test.none", spec.run, {}, "x")) assert "test.none" not in available_solvers()