diff --git a/CLAUDE.md b/CLAUDE.md index 2a50303..5968c98 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,6 +30,7 @@ cargo test -p tiling-search # the search, on random tili uv run maxplus-solve new5-flat --max-solutions all --validate # run a solver from the command line uv run maxplus-solve new5 --mode relief --option lookahead=true --option order=random --seed 3 +uv run maxplus-solve rat1-flat --solver cp_sat.placements --max-solutions all --option coverage=false # CP-SAT, needs the cp-sat extra uv run 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 ``` @@ -40,7 +41,7 @@ uv run python scripts/import_fixtures.py --source ../tropical-puzzle-lab --check - `crates/tiling-core`: domain types. No dependencies on the other crates. - `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-search`: custom solvers, one module each (`contact_dfs`), `enumerate`, which lists placements and their conflicts for solvers that choose from a list, 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. @@ -87,7 +88,8 @@ Rules: - **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. +- **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. `cp_sat.placements` makes its one call for the list of placements and their conflicts; everything it then needs, down to which placement a tray rotation turns each into, is in that answer. +- **A model solver knows no geometry.** `solvers/cp_sat.py` builds constraints from the indices `_native.placement_model` returns and never computes with a placement's coordinates. CP-SAT runs with one worker and no objective, so that its counts can be repeated. - **Units are millimetres and radians,** matching the browser player. Polygons are convex and counter-clockwise, in local coordinates about the area centroid. A pose rotates by `theta` then translates by `(x, y)`. - **`f64` with explicit tolerances is not exactness.** Don't describe a floating-point result as a mathematical proof. - **Optional dependencies stay optional.** OR-Tools, Shapely and the analysis stack are extras; the Rust solvers must run without them. diff --git a/README.md b/README.md index 0f1c11e..5ea3015 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. 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). +**Contracts and fixtures.** The instance format, the sanitizing importer and the benchmark corpus exist: 16 puzzles from Tropical Puzzle Lab and 4 synthetic ones with known solution counts, each with an answer key that only tests read. An independent validator checks an assembly against the browser player's completion rules. The Rust geometry kernel (separating-axis depth, convex clipping, containment, edge signatures, roof continuity) is in place and agrees with the validator on random poses of every fixture's pieces. Three solvers exist. `python.contact_dfs` is a Python prototype of the contact search. `rust.contact_dfs` is that search in Rust with roofs, pruning and symmetry handling: it solves all 16 corpus puzzles, runs every search to its end, and returns assemblies that pass the validator. `cp_sat.placements` hands the placements that search reaches to OR-Tools CP-SAT as a plain choice problem, and returns the same assemblies by other means. Each rule of either can be switched off, because the question here is what makes a puzzle hard and what helps, not how fast one solver is; [docs/algorithms.md](docs/algorithms.md) has the measurements. The work is laid out in [docs/roadmap.md](docs/roadmap.md), and the design in [docs/architecture.md](docs/architecture.md). ```python from maxplus_solvers import load_puzzle diff --git a/crates/tiling-geometry/src/assembly.rs b/crates/tiling-geometry/src/assembly.rs index 2d8d2d1..b78ff49 100644 --- a/crates/tiling-geometry/src/assembly.rs +++ b/crates/tiling-geometry/src/assembly.rs @@ -38,7 +38,7 @@ 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::relief::{roof_height, seam_step}; use crate::sat::penetration_depth; /// One way to put a piece down, and the contact that produced it. @@ -298,7 +298,6 @@ impl Assembly { 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 { @@ -311,39 +310,15 @@ impl Assembly { 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 = worst.max(seam_step( + world, + roof, + pose, + other_world, + other_roof, + other_pose, + self.tolerance.length, + )); } worst } diff --git a/crates/tiling-geometry/src/conflict.rs b/crates/tiling-geometry/src/conflict.rs new file mode 100644 index 0000000..56a7cb1 --- /dev/null +++ b/crates/tiling-geometry/src/conflict.rs @@ -0,0 +1,475 @@ +//! Which of a finite set of placements cannot be in one assembly together. +//! +//! A solver that chooses among placements listed in advance, CP-SAT for one, +//! needs to be told which pairs exclude each other. Two placements conflict +//! when they overlap by more than the length tolerance, or, if both have +//! roofs, when their roofs step by more than the height tolerance along an +//! edge stretch they share. +//! +//! Overlap is common: on the corpus about a third of all pairs conflict. +//! Listing them one by one would be millions of constraints for a few +//! thousand placements. Most are stated more compactly through *probes*: fixed +//! points of the target. Placements that all hold one probe well inside them +//! overlap one another, so "at most one of these" says in one constraint what +//! would otherwise take a pair for every two of them. The probes are a grid, +//! and then, for each overlap the grid missed, a point in the middle of what +//! the two placements share. Conflicts that no probe can witness, overlaps a +//! few tolerances thin and roof steps, are listed as pairs. +//! +//! Every clique holds only conflicting placements, and every conflicting pair +//! is in a clique or in the pair list. Both are tested against a pair-by-pair +//! comparison. +//! +//! The probes also say something no pair can: that the target is to be +//! covered. A probe inside the target lies in some piece of any assembly, so +//! of the placements that reach a probe an assembly holds at least one. These +//! *covers* follow from the rest when the areas of the pieces add up to the +//! target's, so they exclude nothing; they hand a solver that knows no +//! geometry the reason a half-built choice cannot be completed. + +use tiling_core::{Pose, Roof, Vec2}; + +use crate::clip::intersection; +use crate::contact::ContactTolerance; +use crate::polygon::centroid; +use crate::relief::seam_step; +use crate::sat::penetration_depth; + +/// A placement as the conflict test sees it. +#[derive(Debug, Clone, PartialEq)] +pub struct Placed { + /// The placed polygon, in world coordinates. + pub world: Vec, + /// The roof and the pose that placed it, for pieces with roofs. + pub roof: Option<(Roof, Pose)>, +} + +/// Why two placements cannot be in one assembly. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Conflict { + Overlap, + RoofStep, +} + +/// The conflicts among a set of placements, in a form a constraint solver takes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Conflicts { + /// Sets of placements of which an assembly holds at most one. Indices + /// into the placements, ascending within a set. + pub cliques: Vec>, + /// Conflicting pairs that no clique holds, lower index first. + pub pairs: Vec<(u32, u32)>, + /// Sets of placements of which an assembly that covers the target holds + /// at least one: for each probe inside the target, the placements that + /// reach it, boundary included. + pub covers: Vec>, + /// How many pairs overlap, whether a clique states it or the pair list. + pub overlapping: u64, + /// How many pairs fit side by side and are kept apart by their roofs alone. + pub roof_steps: u64, +} + +/// Whether, and why, two placements exclude each other. +pub fn conflict(a: &Placed, b: &Placed, tolerance: &ContactTolerance) -> Option { + if penetration_depth(&a.world, &b.world) > tolerance.length { + return Some(Conflict::Overlap); + } + let (Some((roof_a, pose_a)), Some((roof_b, pose_b))) = (&a.roof, &b.roof) else { + return None; + }; + let step = seam_step( + &a.world, + roof_a, + pose_a, + &b.world, + roof_b, + pose_b, + tolerance.length, + ); + (step > tolerance.height).then_some(Conflict::RoofStep) +} + +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 `point` is inside the convex counter-clockwise `polygon`, at least +/// `margin` from every edge. +fn well_inside(polygon: &[Vec2], point: Vec2, margin: f64) -> bool { + let n = polygon.len(); + (0..n).all(|i| { + let (a, b) = (polygon[i], polygon[(i + 1) % n]); + let (ex, ey) = (b[0] - a[0], b[1] - a[1]); + let cross = ex * (point[1] - a[1]) - ey * (point[0] - a[0]); + cross >= margin * ex.hypot(ey) + }) +} + +/// Offsets of the probe grid within a cell. Irrational, so that probes do not +/// fall on the lines a tiling of a square tray tends to have: halves, thirds, +/// the diagonals. +const OFFSET: Vec2 = [0.381_966_011_250_105, 0.618_033_988_749_895]; + +/// The conflicts among `placed`, using `grid` probes along each side of the +/// target's bounding box. +/// +/// More probes state more of the overlaps as cliques and fewer as pairs, at +/// the cost of more and smaller cliques. With `targeted`, an overlap the grid +/// missed gets a probe of its own where one fits; without, it is listed as a +/// pair. The answer says the same thing for any grid, either way. +pub fn conflicts( + target: &[Vec2], + placed: &[Placed], + tolerance: &ContactTolerance, + grid: usize, + targeted: bool, +) -> Conflicts { + let count = placed.len(); + let grid = grid.max(1); + let frame = bounds(target); + let step = [ + (frame[2] - frame[0]) / grid as f64, + (frame[3] - frame[1]) / grid as f64, + ]; + let probe = |i: usize, j: usize| { + [ + frame[0] + (i as f64 + OFFSET[0]) * step[0], + frame[1] + (j as f64 + OFFSET[1]) * step[1], + ] + }; + // Two polygons that hold a point this far inside them overlap by more than + // the tolerance: each holds the disc of this radius about the point. + let margin = 16.0 * tolerance.length; + + let words = (grid * grid).div_ceil(64); + let boxes: Vec<[f64; 4]> = placed.iter().map(|p| bounds(&p.world)).collect(); + let mut holds = vec![0u64; count * words]; + let mut at_probe: Vec> = vec![Vec::new(); grid * grid]; + let mut reaching: Vec> = vec![Vec::new(); grid * grid]; + for (index, piece) in placed.iter().enumerate() { + let b = &boxes[index]; + let cells = |low: f64, high: f64, origin: f64, size: f64| { + if size <= 0.0 { + return 0..0; + } + let first = ((low - origin) / size).floor().max(0.0) as usize; + let last = (((high - origin) / size).ceil().max(0.0) as usize).min(grid); + first.min(last)..last + }; + for i in cells(b[0], b[2], frame[0], step[0]) { + for j in cells(b[1], b[3], frame[1], step[1]) { + let cell = i * grid + j; + if well_inside(&piece.world, probe(i, j), margin) { + holds[index * words + cell / 64] |= 1 << (cell % 64); + at_probe[cell].push(index as u32); + } + // On the boundary, or outside by no more than the tolerance, still counts. + if well_inside(&piece.world, probe(i, j), -tolerance.length) { + reaching[cell].push(index as u32); + } + } + } + } + let mut cliques: Vec> = at_probe.into_iter().filter(|c| c.len() >= 2).collect(); + cliques.sort(); + cliques.dedup(); + // Only probes that an assembly must cover: those inside the target. + let mut covers: Vec> = (0..grid * grid) + .filter(|&cell| well_inside(target, probe(cell / grid, cell % grid), margin)) + .map(|cell| std::mem::take(&mut reaching[cell])) + .collect(); + covers.sort(); + covers.dedup(); + + let shares_a_probe = + |a: usize, b: usize| (0..words).any(|w| holds[a * words + w] & holds[b * words + w] != 0); + let mut found = Conflicts { + cliques, + covers, + ..Conflicts::default() + }; + // Probes added where the grid saw nothing: for each placement, the ones it + // holds, ascending. + let mut extra: Vec> = vec![Vec::new(); count]; + let mut extras = 0u32; + let shares_an_extra = |extra: &[Vec], a: usize, b: usize| { + let (mut i, mut j) = (0, 0); + while i < extra[a].len() && j < extra[b].len() { + match extra[a][i].cmp(&extra[b][j]) { + std::cmp::Ordering::Less => i += 1, + std::cmp::Ordering::Greater => j += 1, + std::cmp::Ordering::Equal => return true, + } + } + false + }; + for a in 0..count { + for b in a + 1..count { + let (p, q) = (&boxes[a], &boxes[b]); + let slack = tolerance.length; + if p[2] + slack < q[0] + || q[2] + slack < p[0] + || p[3] + slack < q[1] + || q[3] + slack < p[1] + { + continue; + } + // Holding one probe well inside is overlap enough; no need to measure it. + if shares_a_probe(a, b) || shares_an_extra(&extra, a, b) { + found.overlapping += 1; + continue; + } + match conflict(&placed[a], &placed[b], tolerance) { + Some(Conflict::Overlap) => { + found.overlapping += 1; + // A probe in the middle of what the two share. Whatever else + // holds it joins them in one clique, and so do many of the + // overlaps still to come. + let shared = intersection(&placed[a].world, &placed[b].world); + let middle = if targeted && shared.len() >= 3 { + centroid(&shared) + } else { + [f64::NAN, f64::NAN] + }; + if well_inside(&placed[a].world, middle, margin) + && well_inside(&placed[b].world, middle, margin) + { + let members: Vec = (0..count) + .filter(|&k| { + let r = &boxes[k]; + r[0] <= middle[0] + && middle[0] <= r[2] + && r[1] <= middle[1] + && middle[1] <= r[3] + && well_inside(&placed[k].world, middle, margin) + }) + .map(|k| k as u32) + .collect(); + for &k in &members { + extra[k as usize].push(extras); + } + extras += 1; + found.cliques.push(members); + } else { + found.pairs.push((a as u32, b as u32)); + } + } + Some(Conflict::RoofStep) => { + found.roof_steps += 1; + found.pairs.push((a as u32, b as u32)); + } + None => {} + } + } + } + found +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::polygon::transform; + use crate::testing::{TOL, convex_polygon, pose_near}; + use proptest::prelude::*; + + fn block(x0: f64, y0: f64, x1: f64, y1: f64) -> Placed { + Placed { + world: vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]], + roof: None, + } + } + + fn level(mut placed: Placed, height: f64) -> Placed { + placed.roof = Some(( + Roof { + z0: height, + gx: 0.0, + gy: 0.0, + }, + Pose { + x: 0.0, + y: 0.0, + theta: 0.0, + }, + )); + placed + } + + fn tray() -> Vec { + vec![[0.0, 0.0], [8.0, 0.0], [8.0, 8.0], [0.0, 8.0]] + } + + /// Every pair the answer excludes, from its cliques and its pairs. + fn excluded(found: &Conflicts) -> Vec<(u32, u32)> { + let mut all = found.pairs.clone(); + for clique in &found.cliques { + for (k, &a) in clique.iter().enumerate() { + for &b in &clique[k + 1..] { + all.push((a, b)); + } + } + } + all.sort_unstable(); + all.dedup(); + all + } + + #[test] + fn blocks_side_by_side_do_not_conflict_and_blocks_that_overlap_do() { + // Left half, right half, and the middle half that overlaps both by 2. + let placed = [ + block(0.0, 0.0, 4.0, 8.0), + block(4.0, 0.0, 8.0, 8.0), + block(2.0, 0.0, 6.0, 8.0), + ]; + assert_eq!(conflict(&placed[0], &placed[1], &TOL), None); + assert_eq!( + conflict(&placed[0], &placed[2], &TOL), + Some(Conflict::Overlap) + ); + for grid in [1, 2, 7, 48] { + let found = conflicts(&tray(), &placed, &TOL, grid, true); + assert_eq!(excluded(&found), [(0, 2), (1, 2)], "grid {grid}"); + assert_eq!((found.overlapping, found.roof_steps), (2, 0)); + } + } + + #[test] + fn one_probe_states_many_overlaps_at_once() { + // Four blocks that all hold the middle of the tray: six overlapping pairs. + let placed = [ + block(0.0, 0.0, 5.0, 5.0), + block(3.0, 0.0, 8.0, 5.0), + block(0.0, 3.0, 5.0, 8.0), + block(3.0, 3.0, 8.0, 8.0), + ]; + // With one probe, at (3.06, 4.94), inside all four. + let found = conflicts(&tray(), &placed, &TOL, 1, true); + assert_eq!(found.cliques, [vec![0, 1, 2, 3]]); + assert!(found.pairs.is_empty()); + assert_eq!(found.overlapping, 6); + } + + #[test] + fn every_probe_in_the_target_names_the_placements_that_reach_it() { + // Left half, right half, and a block over the lower left quarter. + let placed = [ + block(0.0, 0.0, 4.0, 8.0), + block(4.0, 0.0, 8.0, 8.0), + block(0.0, 0.0, 4.0, 4.0), + ]; + // Four probes: (1.53, 2.47), (1.53, 6.47), (5.53, 2.47), (5.53, 6.47). + let found = conflicts(&tray(), &placed, &TOL, 2, true); + assert_eq!(found.covers, [vec![0], vec![0, 2], vec![1]]); + // A probe nothing reaches still asks to be covered: no choice can. + let found = conflicts(&tray(), &placed[..1], &TOL, 2, true); + assert_eq!(found.covers, [vec![], vec![0]]); + // A probe outside the target asks for nothing. The tray's lower left + // triangle holds only the first of the four. + let triangle = vec![[0.0, 0.0], [8.0, 0.0], [0.0, 8.0]]; + let found = conflicts(&triangle, &placed, &TOL, 2, true); + assert_eq!(found.covers, [vec![0, 2]]); + } + + #[test] + fn an_overlap_the_grid_misses_gets_a_probe_of_its_own() { + // The two halves pushed 0.01 into each other, and a third block across + // the seam. The grid's probes are 2 apart and miss the sliver the + // halves share; the probe put in its middle, at (4.005, 4), is inside + // the third block as well. + let placed = [ + block(0.0, 0.0, 4.01, 8.0), + block(4.0, 0.0, 8.0, 8.0), + block(3.0, 3.0, 5.0, 5.0), + ]; + let found = conflicts(&tray(), &placed, &TOL, 4, true); + assert!(found.cliques.contains(&vec![0, 1, 2])); + assert!(found.pairs.is_empty()); + assert_eq!(excluded(&found), [(0, 1), (0, 2), (1, 2)]); + assert_eq!(found.overlapping, 3); + // Not asked for, the probe is not made, and the halves are a pair. So are + // the left half and the third block: the grid's probe in the block, + // at about (4.76, 3.24), is right of the left half. + let plain = conflicts(&tray(), &placed, &TOL, 4, false); + assert_eq!(plain.pairs, [(0, 1), (0, 2)]); + assert_eq!(excluded(&plain), [(0, 1), (0, 2), (1, 2)]); + } + + #[test] + fn an_overlap_too_thin_for_any_probe_is_listed_as_a_pair() { + // Ten tolerances of overlap: more than the tolerance, so a conflict, + // and less than the margin a probe needs on either side. + let placed = [ + block(0.0, 0.0, 4.0 + 10.0 * TOL.length, 8.0), + block(4.0, 0.0, 8.0, 8.0), + ]; + let found = conflicts(&tray(), &placed, &TOL, 4, true); + assert!(found.cliques.is_empty()); + assert_eq!(found.pairs, [(0, 1)]); + } + + #[test] + fn roofs_at_different_heights_keep_neighbours_apart() { + let low = level(block(0.0, 0.0, 4.0, 8.0), 1.0); + let same = level(block(4.0, 0.0, 8.0, 8.0), 1.0); + let high = level(block(4.0, 0.0, 8.0, 8.0), 1.5); + assert_eq!(conflict(&low, &same, &TOL), None); + assert_eq!(conflict(&low, &high, &TOL), Some(Conflict::RoofStep)); + // Without a roof on one of them there is nothing to compare. + assert_eq!(conflict(&low, &block(4.0, 0.0, 8.0, 8.0), &TOL), None); + // Blocks that only meet at a corner share no edge, whatever their roofs. + let corner = level(block(4.0, 8.0, 8.0, 12.0), 9.0); + assert_eq!(conflict(&low, &corner, &TOL), None); + let found = conflicts(&tray(), &[low, same, high], &TOL, 8, true); + // The two right halves overlap entirely; the high one also steps against the left. + assert_eq!(excluded(&found), [(0, 2), (1, 2)]); + assert_eq!((found.overlapping, found.roof_steps), (1, 1)); + } + + proptest! { + /// The cliques and pairs together exclude exactly the pairs that + /// conflict when compared one by one, whatever the grid. + #[test] + fn cliques_and_pairs_say_what_a_pairwise_comparison_says( + pieces in prop::collection::vec((convex_polygon(), pose_near()), 2..12), + grid in 1usize..40, + targeted in any::(), + ) { + let placed: Vec = pieces + .iter() + .map(|(polygon, pose)| Placed { world: transform(polygon, pose), roof: None }) + .collect(); + let target = vec![[-80.0, -80.0], [80.0, -80.0], [80.0, 80.0], [-80.0, 80.0]]; + let found = conflicts(&target, &placed, &TOL, grid, targeted); + let mut expected = Vec::new(); + for a in 0..placed.len() { + for b in a + 1..placed.len() { + if conflict(&placed[a], &placed[b], &TOL).is_some() { + expected.push((a as u32, b as u32)); + } + } + } + prop_assert_eq!(excluded(&found), expected.clone()); + prop_assert_eq!(found.overlapping as usize, expected.len()); + // A cover is asked for at each distinct set of placements a probe meets; + // the probes nothing reaches all ask for the same empty one. + prop_assert!(found.covers.iter().filter(|c| c.is_empty()).count() <= 1); + // A pair is not listed if a clique already states it. + for pair in &found.pairs { + prop_assert!(!found.cliques.iter().any(|c| c.contains(&pair.0) && c.contains(&pair.1))); + } + } + } +} diff --git a/crates/tiling-geometry/src/lib.rs b/crates/tiling-geometry/src/lib.rs index ca92187..a51c0a8 100644 --- a/crates/tiling-geometry/src/lib.rs +++ b/crates/tiling-geometry/src/lib.rs @@ -17,11 +17,13 @@ //! | [`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 | +//! | [`conflict`] | which of a finite set of placements exclude one another | //! | [`assembly`] | reversible partial assembly: `frontier`, `propose`, `check_placement` | pub mod assembly; pub mod cavity; pub mod clip; +pub mod conflict; pub mod contact; pub mod edges; pub mod graph; @@ -35,6 +37,7 @@ 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 conflict::{Conflict, Conflicts, Placed, conflict, conflicts}; pub use contact::{ContactTolerance, Corner, EdgeRef, free_corners, pose_at_corner}; pub use edges::{Edge, EdgeSignature, edge_signatures, edges}; pub use graph::{EdgeGraph, Shape, rotation_order}; @@ -42,5 +45,7 @@ pub use polygon::{ ConvexPolygon, NotConvex, centroid, contains_point, distance_to_segment, is_convex_ccw, outside_depth, point_outside_depth, signed_area, transform, }; -pub use relief::{roof_height, seam_mismatch, tangential_gradient_mismatch, world_gradient}; +pub use relief::{ + roof_height, seam_mismatch, seam_step, tangential_gradient_mismatch, world_gradient, +}; pub use sat::penetration_depth; diff --git a/crates/tiling-geometry/src/relief.rs b/crates/tiling-geometry/src/relief.rs index b13ee3c..2785ae5 100644 --- a/crates/tiling-geometry/src/relief.rs +++ b/crates/tiling-geometry/src/relief.rs @@ -36,6 +36,56 @@ pub fn seam_mismatch( at(p0).max(at(p1)) } +/// The largest roof step between two placed convex pieces along the edge +/// stretches they share: where an edge of one lies on the line of an edge of +/// the other, running the other way, for longer than `length_tolerance`. +/// Zero if they share no such stretch. +/// +/// The polygons are in world coordinates and counter-clockwise; each pose is +/// the one that placed its piece. +pub fn seam_step( + world_a: &[Vec2], + roof_a: &Roof, + pose_a: &Pose, + world_b: &[Vec2], + roof_b: &Roof, + pose_b: &Pose, + length_tolerance: f64, +) -> f64 { + let (n, m) = (world_a.len(), world_b.len()); + let mut worst: f64 = 0.0; + for i in 0..n { + let (a0, a1) = (world_a[i], world_a[(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]; + // 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(); + for j in 0..m { + let (b0, b1) = (world_b[j], world_b[(j + 1) % m]); + // A neighbour's edge on the same line runs the other way. + let (start, end) = (along(b1), along(b0)); + if end <= start || off(b0) > length_tolerance || off(b1) > length_tolerance { + continue; + } + let (from, to) = (start.max(0.0), end.min(length)); + if to - from <= length_tolerance { + continue; + } + let at = |t: f64| [a0[0] + t * u[0], a0[1] + t * u[1]]; + worst = worst.max(seam_mismatch( + roof_a, + pose_a, + roof_b, + pose_b, + at(from), + at(to), + )); + } + } + worst +} + /// `(g_a - g_b) . v` for the unit direction `v` of the world segment `p0`–`p1`: /// how fast the two roofs drift apart along it, in mm per mm. Zero is necessary /// for the roofs to agree along the segment, and it needs no polygon work, so diff --git a/crates/tiling-py/src/lib.rs b/crates/tiling-py/src/lib.rs index 886713f..9f07a8f 100644 --- a/crates/tiling-py/src/lib.rs +++ b/crates/tiling-py/src/lib.rs @@ -696,6 +696,18 @@ fn same_assembly( Ok(symmetry.same(&first, &second)) } +fn time_limit_of(seconds: Option) -> PyResult> { + match seconds { + None => Ok(None), + Some(seconds) if seconds.is_finite() && seconds >= 0.0 => { + Ok(Some(Duration::from_secs_f64(seconds))) + } + Some(_) => Err(PyValueError::new_err( + "time_limit_s must be finite and not negative", + )), + } +} + /// What `contact_dfs` found, and the work it took. #[pyclass(frozen, get_all, module = "maxplus_solvers._native")] struct ContactDfsOutcome { @@ -767,17 +779,7 @@ fn contact_dfs( 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 time_limit = time_limit_of(time_limit_s)?; let options = Options { max_solutions, time_limit, @@ -793,6 +795,7 @@ fn contact_dfs( lookahead, order, seed, + ..Options::default() }; let outcome = py .detach(|| solve(target, shapes, tolerance, &options)) @@ -826,6 +829,134 @@ fn contact_dfs( }) } +/// Placements to choose from and the constraints on the choice: what +/// `placement_model` built. +#[pyclass(frozen, get_all, module = "maxplus_solvers._native")] +struct PlacementModel { + /// The classes of congruent pieces, each as its members' indices. + classes: Vec>, + /// For each placement, the index of its class in `classes`. + placement_class: Vec, + /// For each placement, a pose for each member of its class, in the class's order. + placement_poses: Vec>, + /// Sets of placements of which an assembly holds at most one. + cliques: Vec>, + /// Conflicting pairs that no clique holds. + pairs: Vec<(u32, u32)>, + /// Sets of placements of which an assembly holds at least one. + covers: Vec>, + /// The areas of the pieces add up to the target's. If not, no choice is an assembly. + areas_add_up: bool, + /// For each turn of the tray onto itself, the placement each placement becomes. + turned: Vec>>, + overlapping_pairs: u64, + roof_step_pairs: u64, + /// The search that collected the placements ran to its end. + exhausted: bool, + /// Assemblies that search found on its way. + search_solutions: usize, + 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, + search_time_s: f64, + conflict_time_s: f64, +} + +/// The placements the corner search reaches and their conflicts, built in +/// Rust without the interpreter lock. +#[pyfunction] +#[pyo3(signature = ( + target, pieces, roofs=None, *, + length_tol, angle_tol, slope_tol, height_tol=None, + time_limit_s=None, node_limit=None, max_placements=None, + all_tray_rotations=false, anchor=true, cavity_pruning=true, closure_pruning=true, + targeted_probes=false, +))] +#[allow(clippy::too_many_arguments)] +fn placement_model( + py: Python<'_>, + target: Vec<[f64; 2]>, + pieces: Vec>, + roofs: Option>, + length_tol: f64, + angle_tol: f64, + slope_tol: f64, + height_tol: Option, + time_limit_s: Option, + node_limit: Option, + max_placements: Option, + all_tray_rotations: bool, + anchor: bool, + cavity_pruning: bool, + closure_pruning: bool, + targeted_probes: bool, +) -> PyResult { + use tiling_search::contact_dfs::{Options, Order, TrayRotations}; + use tiling_search::enumerate::reachable; + + let (shapes, tolerance) = + puzzle_parts(pieces, roofs, length_tol, angle_tol, slope_tol, height_tol)?; + let options = Options { + time_limit: time_limit_of(time_limit_s)?, + node_limit, + max_placements, + tray_rotations: if all_tray_rotations { + TrayRotations::All + } else { + TrayRotations::Once + }, + anchor, + cavity_pruning, + closure_pruning, + // The order of a whole search does not change what it places. + order: Order::Generated, + ..Options::default() + }; + let model = py + .detach(|| reachable(target, shapes, tolerance, &options, targeted_probes)) + .map_err(refused)?; + let stats = model.search; + Ok(PlacementModel { + classes: model.classes, + placement_class: model.class_of, + placement_poses: model + .poses + .into_iter() + .map(|poses| poses.into_iter().map(|p| (p.x, p.y, p.theta)).collect()) + .collect(), + cliques: model.conflicts.cliques, + pairs: model.conflicts.pairs, + covers: model.conflicts.covers, + turned: model.turned, + areas_add_up: model.areas_add_up, + overlapping_pairs: model.conflicts.overlapping, + roof_step_pairs: model.conflicts.roof_steps, + exhausted: model.exhausted, + search_solutions: model.search_solutions, + 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, + search_time_s: model.search_time.as_secs_f64(), + conflict_time_s: model.conflict_time.as_secs_f64(), + }) +} + #[pymodule] fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(version, m)?)?; @@ -854,5 +985,7 @@ fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(same_assembly, m)?)?; m.add_function(wrap_pyfunction!(contact_dfs, m)?)?; m.add_class::()?; + m.add_function(wrap_pyfunction!(placement_model, m)?)?; + m.add_class::()?; Ok(()) } diff --git a/crates/tiling-search/src/canonical.rs b/crates/tiling-search/src/canonical.rs index 1817fa4..bfaacae 100644 --- a/crates/tiling-search/src/canonical.rs +++ b/crates/tiling-search/src/canonical.rs @@ -35,6 +35,20 @@ struct Seat { turn: f64, } +/// One way of putting down a piece of a class, whichever member of the class +/// it is and whichever of the turns onto itself it has: the seat, with the +/// class it is a seat for. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Placement { + /// The class: its lowest-numbered piece. + pub class: usize, + /// The centroid of the placed piece, in the world. + pub x: f64, + pub y: f64, + /// The turn of the class's first piece that puts it there, in `[0, period)`. + pub turn: f64, +} + /// The symmetries of one puzzle: of its tray, and of and among its pieces. #[derive(Debug, Clone)] pub struct Symmetry { @@ -90,6 +104,40 @@ impl Symmetry { &self.classes } + /// The placement that `piece` at `pose` is. + pub fn placement(&self, piece: usize, pose: &Pose) -> Placement { + let seat = self.seat(piece, pose); + Placement { + class: self.classes[piece], + x: seat.x, + y: seat.y, + turn: seat.turn, + } + } + + /// A pose that puts `piece`, a member of the placement's class, there. + pub fn pose_for(&self, piece: usize, placement: &Placement) -> Pose { + debug_assert_eq!(self.classes[piece], placement.class); + self.pose( + piece, + &Seat { + x: placement.x, + y: placement.y, + turn: placement.turn, + }, + ) + } + + /// Whether two placements put the same polygon in the same place. + pub fn same_placement(&self, a: &Placement, b: &Placement) -> bool { + let seat = |p: &Placement| Seat { + x: p.x, + y: p.y, + turn: p.turn, + }; + a.class == b.class && self.compare(&seat(a), &seat(b)).is_eq() + } + /// 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 { @@ -389,6 +437,41 @@ mod tests { } } + #[test] + fn a_placement_is_the_same_for_twins_and_for_turns_onto_itself() { + // Two narrow strips, the second stored lying down, and a block. + 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); + // Either strip standing against the left wall, either way up. + let first = symmetry.placement(0, &at(0.5, 1.5, 0.0)); + assert_eq!(first.class, 0); + for (piece, theta) in [(0, PI), (1, FRAC_PI_2), (1, -FRAC_PI_2)] { + let other = symmetry.placement(piece, &at(0.5, 1.5, theta)); + assert!(symmetry.same_placement(&first, &other), "{piece} {theta}"); + } + // Not the strip one column along, nor the strip lying down, nor the block. + assert!(!symmetry.same_placement(&first, &symmetry.placement(0, &at(1.5, 1.5, 0.0)))); + assert!(!symmetry.same_placement(&first, &symmetry.placement(0, &at(0.5, 1.5, 1.0)))); + assert!(!symmetry.same_placement(&first, &symmetry.placement(2, &at(0.5, 1.5, 0.0)))); + // A pose made for either member puts it over x in [0, 1], y in [0, 3]. + for piece in [0, 1] { + let world = transform(&pieces[piece], &symmetry.pose_for(piece, &first)); + for corner in [[0.0, 0.0], [1.0, 0.0], [1.0, 3.0], [0.0, 3.0]] { + assert!( + world + .iter() + .any(|p| (p[0] - corner[0]).hypot(p[1] - corner[1]) <= 1e-9), + "{piece}: {world:?}" + ); + } + } + } + #[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 diff --git a/crates/tiling-search/src/contact_dfs.rs b/crates/tiling-search/src/contact_dfs.rs index 725e0ad..e61c73e 100644 --- a/crates/tiling-search/src/contact_dfs.rs +++ b/crates/tiling-search/src/contact_dfs.rs @@ -57,7 +57,7 @@ use tiling_geometry::{ Shape, centroid, least_width, signed_area, transform, }; -use crate::canonical::Symmetry; +use crate::canonical::{Placement, Symmetry}; /// What to do about assemblies that are turns of one another. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -91,6 +91,11 @@ pub struct Options { pub order: Order, /// For [`Order::Random`]. pub seed: u64, + /// Keep every distinct placement the search puts down, for + /// [`Outcome::placements`]. + pub collect_placements: bool, + /// Stop once this many distinct placements have been collected. + pub max_placements: Option, } /// The order in which the candidates of a node are tried. It decides how soon @@ -119,6 +124,8 @@ impl Default for Options { lookahead: false, order: Order::MatchedEdges, seed: 0, + collect_placements: false, + max_placements: None, } } } @@ -163,6 +170,47 @@ pub struct Outcome { pub tray_order: usize, /// The piece held to one sector, if any was. pub anchor: Option, + /// Every distinct placement the search put down, in the order first met. + /// Empty unless [`Options::collect_placements`]. + pub placements: Vec, +} + +/// The distinct placements met so far. +/// +/// Looked up by the cell of a coarse grid the centroid falls in and its +/// neighbours, then compared with the search's tolerances, so that a placement +/// on a cell boundary is still recognised. +#[derive(Default)] +struct Collected { + placements: Vec, + cells: HashMap<(usize, i64, i64), Vec>, +} + +impl Collected { + /// Millimetres. Far above the tolerance, far below the size of a piece. + const CELL: f64 = 0.01; + + fn add(&mut self, symmetry: &Symmetry, placement: Placement) { + let cell = |v: f64| (v / Self::CELL).floor() as i64; + let (cx, cy) = (cell(placement.x), cell(placement.y)); + for dx in -1..=1 { + for dy in -1..=1 { + let known = self.cells.get(&(placement.class, cx + dx, cy + dy)); + if known.is_some_and(|ids| { + ids.iter().any(|&id| { + symmetry.same_placement(&self.placements[id as usize], &placement) + }) + }) { + return; + } + } + } + self.cells + .entry((placement.class, cx, cy)) + .or_default() + .push(self.placements.len() as u32); + self.placements.push(placement); + } } /// Steps a question about areas may take before it is answered "perhaps". @@ -405,6 +453,7 @@ struct Search<'a> { first_solution: Option, stopped: bool, random: Random, + collected: Collected, } impl Search<'_> { @@ -704,6 +753,18 @@ impl Search<'_> { } } for candidate in candidates { + if self.options.collect_placements { + let placement = self.symmetry.placement(candidate.piece, &candidate.pose); + self.collected.add(&self.symmetry, placement); + if self + .options + .max_placements + .is_some_and(|most| self.collected.placements.len() > most) + { + self.stopped = true; + return; + } + } self.assembly .place(candidate.piece, candidate.pose) .expect("a proposed piece is free"); @@ -789,6 +850,7 @@ pub fn solve( stopped: false, random: Random(options.seed), symmetry, + collected: Collected::default(), }; search.expand(); search.stats.candidates = search.assembly.stats(); @@ -800,6 +862,7 @@ pub fn solve( first_solution: search.first_solution, tray_order: search.symmetry.tray_order(), anchor, + placements: search.collected.placements, }) } diff --git a/crates/tiling-search/src/enumerate.rs b/crates/tiling-search/src/enumerate.rs new file mode 100644 index 0000000..6e20bc5 --- /dev/null +++ b/crates/tiling-search/src/enumerate.rs @@ -0,0 +1,508 @@ +//! A finite set of placements, and which of them exclude one another. +//! +//! Some solvers do not generate placements as they go: they are handed a list +//! and choose from it. CP-SAT is one. This module builds the list. +//! +//! **The placements** are the ones the corner search of [`contact_dfs`] puts +//! down anywhere in its tree: the *reachable* placements. Every assembly that +//! search can find is made of them, since the search placed each of its pieces +//! on the way there. So choosing among the reachable placements loses no +//! assembly the search has. +//! +//! The set is small. The search visits the same placement in many states: on +//! the corpus a tree of a million nodes holds a few thousand distinct +//! placements. A set built without a search, by closing the contacts of +//! placements under further contacts, was tried and is not small: it forgets +//! which pieces a chain of contacts has already used, and on a six-piece +//! puzzle it passed three thousand placements while still growing. +//! +//! The price is that building the set costs one whole search. What a chooser +//! then adds is a second opinion on which of them fit together, reached by +//! other means. +//! +//! **The conflicts** come from [`tiling_geometry::conflicts`]: overlap, and +//! for pieces with roofs a step between neighbouring roofs. +//! +//! **Why choosing is enough.** Take one placement for every piece (for a class +//! of congruent pieces, as many placements as it has members), no two in +//! conflict. Every reachable placement lies inside the target. The areas of +//! the pieces add up to the target's. Pieces inside the target that do not +//! overlap and have its area cover it ([`Model::areas_add_up`] says whether +//! they have; if not, no choice is an assembly). So such a choice is an assembly, and +//! in the relief regime one whose roofs are continuous along every shared +//! edge stretch. This is an argument about exact figures; the code is `f64` +//! with tolerances. + +use std::collections::HashMap; +use std::f64::consts::TAU; +use std::time::{Duration, Instant}; + +use tiling_core::{Pose, Vec2}; +use tiling_geometry::{ + AssemblyError, Conflicts, ContactTolerance, EdgeGraph, Placed, Shape, conflicts, signed_area, + transform, +}; + +use crate::canonical::{Placement, Symmetry}; +use crate::contact_dfs::{Options, Stats, solve}; + +/// Probes along each side of the target's bounding box, for stating overlaps +/// as cliques. Three millimetres apart on the corpus's 144 mm tray. +pub const PROBE_GRID: usize = 48; + +/// Placements to choose from, and the constraints on the choice. +#[derive(Debug, Clone, PartialEq)] +pub struct Model { + /// The classes of congruent pieces: for each, its members in piece order. + /// A choice takes as many placements of a class as it has members. + pub classes: Vec>, + /// For each placement, the index of its class in `classes`. + pub class_of: Vec, + /// For each placement, a pose for each member of its class that puts that + /// member there, in the order of the class's members. + pub poses: Vec>, + /// The areas of the pieces add up to the target's, to within a boundary + /// off by the length tolerance all the way round. Without this a choice + /// with no conflict need not cover the target, and none is an assembly. + pub areas_add_up: bool, + /// What the placements exclude among themselves. + pub conflicts: Conflicts, + /// For each turn of the tray onto itself other than none, where it takes + /// each placement: the index of the placement it becomes, if that one is + /// in the model. A choice and its image under a turn are one assembly + /// when the tray's rotations are counted once. + pub turned: Vec>>, + /// The search that collected the placements ran to its end, so they are + /// all of the reachable ones. + pub exhausted: bool, + /// The work of that search. + pub search: Stats, + /// How many assemblies that search found on its way. A chooser should + /// find as many, counted the same way. + pub search_solutions: usize, + pub search_time: Duration, + pub conflict_time: Duration, +} + +/// Collect the placements the corner search reaches, and their conflicts. +/// +/// `options` are the search's: its rules, whether the tray's rotations are +/// searched once or all, and its limits. `max_solutions` and +/// `collect_placements` are set here. With a limit reached, the model holds +/// what was collected so far and says so in `exhausted`. `targeted_probes` +/// is [`tiling_geometry::conflicts`]'s `targeted`. +pub fn reachable( + target: Vec, + shapes: Vec, + tolerance: ContactTolerance, + options: &Options, + targeted_probes: bool, +) -> Result { + let options = Options { + max_solutions: None, + collect_placements: true, + ..options.clone() + }; + let outcome = solve(target.clone(), shapes.clone(), tolerance, &options)?; + + let started = Instant::now(); + let pieces: f64 = shapes.iter().map(|s| signed_area(&s.polygon)).sum(); + let perimeter: f64 = (0..target.len()) + .map(|i| { + let (p, q) = (target[i], target[(i + 1) % target.len()]); + (q[0] - p[0]).hypot(q[1] - p[1]) + }) + .sum(); + let areas_add_up = (pieces - signed_area(&target)).abs() <= tolerance.length * perimeter; + let graph = EdgeGraph::build(&shapes, &tolerance); + let symmetry = Symmetry::new(&target, &shapes, &graph, &tolerance); + let (model_classes, class_of, poses, placed) = lay_out(&symmetry, &shapes, &outcome.placements); + let found = conflicts(&target, &placed, &tolerance, PROBE_GRID, targeted_probes); + let turned = turned(&symmetry, &outcome.placements, &model_classes, &poses); + Ok(Model { + classes: model_classes, + class_of, + poses, + areas_add_up, + conflicts: found, + turned, + exhausted: outcome.exhausted, + search: outcome.stats, + search_solutions: outcome.solutions.len(), + search_time: outcome.elapsed, + conflict_time: started.elapsed(), + }) +} + +type LaidOut = (Vec>, Vec, Vec>, Vec); + +/// The classes, and for every placement its class, its poses and its polygon. +fn lay_out(symmetry: &Symmetry, shapes: &[Shape], placements: &[Placement]) -> LaidOut { + let of_piece = symmetry.classes(); + // Classes in the order of their first pieces. + let firsts: Vec = (0..shapes.len()).filter(|&p| of_piece[p] == p).collect(); + let classes: Vec> = firsts + .iter() + .map(|&first| { + (0..shapes.len()) + .filter(|&p| of_piece[p] == first) + .collect() + }) + .collect(); + let mut class_of = Vec::with_capacity(placements.len()); + let mut poses = Vec::with_capacity(placements.len()); + let mut placed = Vec::with_capacity(placements.len()); + for placement in placements { + let index = firsts + .iter() + .position(|&first| first == placement.class) + .expect("a placement's class is the first piece of a class"); + let members: Vec = classes[index] + .iter() + .map(|&piece| symmetry.pose_for(piece, placement)) + .collect(); + let first = placement.class; + placed.push(Placed { + world: transform(&shapes[first].polygon, &members[0]), + roof: shapes[first].roof.map(|roof| (roof, members[0])), + }); + class_of.push(index); + poses.push(members); + } + (classes, class_of, poses, placed) +} + +/// Where each turn of the tray takes each placement. +fn turned( + symmetry: &Symmetry, + placements: &[Placement], + classes: &[Vec], + poses: &[Vec], +) -> Vec>> { + // Millimetres. Far above the tolerance, far below the size of a piece. + const CELL: f64 = 0.01; + let cell = |v: f64| (v / CELL).floor() as i64; + let mut cells: HashMap<(usize, i64, i64), Vec> = HashMap::new(); + for (index, placement) in placements.iter().enumerate() { + cells + .entry((placement.class, cell(placement.x), cell(placement.y))) + .or_default() + .push(index as u32); + } + let [cx, cy] = symmetry.centre(); + let order = symmetry.tray_order(); + (1..order) + .map(|step| { + let angle = TAU * step as f64 / order as f64; + let (s, c) = angle.sin_cos(); + placements + .iter() + .enumerate() + .map(|(index, placement)| { + let first = classes + .iter() + .find(|members| members[0] == placement.class) + .expect("a placement's class is one of the classes")[0]; + let pose = poses[index][0]; + let (dx, dy) = (pose.x - cx, pose.y - cy); + let image = symmetry.placement( + first, + &Pose { + x: cx + c * dx - s * dy, + y: cy + s * dx + c * dy, + theta: pose.theta + angle, + }, + ); + let (ix, iy) = (cell(image.x), cell(image.y)); + (-1..=1) + .flat_map(|dx| (-1..=1).map(move |dy| (dx, dy))) + .filter_map(|(dx, dy)| cells.get(&(image.class, ix + dx, iy + dy))) + .flatten() + .copied() + .find(|&other| symmetry.same_placement(&placements[other as usize], &image)) + }) + .collect() + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::contact_dfs::TrayRotations; + use proptest::prelude::*; + 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 every_turn() -> Options { + Options { + tray_rotations: TrayRotations::All, + anchor: false, + ..Options::default() + } + } + + /// Every choice of one placement per class member with no conflict, by + /// trying them all. For models of a handful of placements. + fn choices(model: &Model) -> Vec> { + let n = model.class_of.len(); + let mut excluded = vec![vec![false; n]; n]; + for &(a, b) in &model.conflicts.pairs { + excluded[a as usize][b as usize] = true; + excluded[b as usize][a as usize] = true; + } + for clique in &model.conflicts.cliques { + for &a in clique { + for &b in clique { + excluded[a as usize][b as usize] = a != b; + } + } + } + let need: Vec = model.classes.iter().map(Vec::len).collect(); + let mut found = Vec::new(); + fn extend( + from: usize, + chosen: &mut Vec, + have: &mut Vec, + need: &[usize], + model: &Model, + excluded: &[Vec], + found: &mut Vec>, + ) { + if have == need { + found.push(chosen.clone()); + return; + } + for next in from..model.class_of.len() { + let class = model.class_of[next]; + if have[class] == need[class] || chosen.iter().any(|&c| excluded[c][next]) { + continue; + } + chosen.push(next); + have[class] += 1; + extend(next + 1, chosen, have, need, model, excluded, found); + have[class] -= 1; + chosen.pop(); + } + } + extend( + 0, + &mut Vec::new(), + &mut vec![0; need.len()], + &need, + model, + &excluded, + &mut found, + ); + found + } + + #[test] + fn three_strips_have_a_placement_for_every_column_and_six_orders() { + // Strips 2, 3 and 5 wide in a 10 x 12 tray, searched in both of its orientations. + // They are too tall to lie down in it. + let tray = vec![[0.0, 0.0], [10.0, 0.0], [10.0, 12.0], [0.0, 12.0]]; + let shapes = bare(&[ + rectangle(2.0, 12.0), + rectangle(3.0, 12.0), + rectangle(5.0, 12.0), + ]); + let model = reachable(tray, shapes, TOL, &every_turn(), false).unwrap(); + assert!(model.exhausted); + assert_eq!(model.classes, [vec![0], vec![1], vec![2]]); + // By hand. A strip stands with its left side at a sum of the widths of + // the strips to its left. The 2 strip: 0, 3, 5, 8. The 3 strip: 0, 2, + // 5, 7. The 5 strip: 0, 2, 3, 5. Twelve placements. + assert_eq!(model.class_of.len(), 12); + let mut lefts: Vec> = vec![Vec::new(); 3]; + for (placement, &class) in model.class_of.iter().enumerate() { + let width = [2.0, 3.0, 5.0][class]; + let pose = model.poses[placement][0]; + lefts[class].push((pose.x - width / 2.0).round()); + assert!((pose.y - 6.0).abs() <= 1e-9); + } + for list in &mut lefts { + list.sort_by(f64::total_cmp); + } + assert_eq!( + lefts, + [ + vec![0.0, 3.0, 5.0, 8.0], + vec![0.0, 2.0, 5.0, 7.0], + vec![0.0, 2.0, 3.0, 5.0] + ] + ); + // The search found the six orders, and so does choosing. + assert_eq!(model.search_solutions, 6); + assert_eq!(choices(&model).len(), 6); + } + + #[test] + fn a_turn_of_the_tray_takes_placements_to_placements() { + // The strips again. A half turn of the 10 x 12 tray takes a strip with + // its left side at x to one with its left side at 10 - width - x. + let tray = vec![[0.0, 0.0], [10.0, 0.0], [10.0, 12.0], [0.0, 12.0]]; + let shapes = bare(&[ + rectangle(2.0, 12.0), + rectangle(3.0, 12.0), + rectangle(5.0, 12.0), + ]); + let model = reachable(tray, shapes, TOL, &every_turn(), false).unwrap(); + assert_eq!(model.turned.len(), 1); + for (placement, image) in model.turned[0].iter().enumerate() { + let image = image.expect("every column's mirror column is reachable") as usize; + assert_eq!(model.class_of[image], model.class_of[placement]); + let sum = model.poses[placement][0].x + model.poses[image][0].x; + assert!((sum - 10.0).abs() <= 1e-9); + // Turning twice is not turning. + assert_eq!(model.turned[0][image], Some(placement as u32)); + } + // By hand: the six orders are three pairs of mirror images. + let found = choices(&model); + let mirrored = |choice: &Vec| { + let mut image: Vec = choice + .iter() + .map(|&p| model.turned[0][p].unwrap() as usize) + .collect(); + image.sort_unstable(); + image + }; + for choice in &found { + assert_ne!(&mirrored(choice), choice); + assert!(found.contains(&mirrored(choice))); + } + } + + #[test] + fn pieces_too_small_for_the_tray_are_reported() { + // 2 + 3 + 4 of strips for 10 of tray. With the pruning off the search + // still stands them against the walls and one another, and three of + // those placements can be chosen without conflict: not an assembly. + let tray = vec![[0.0, 0.0], [10.0, 0.0], [10.0, 12.0], [0.0, 12.0]]; + let shapes = bare(&[ + rectangle(2.0, 12.0), + rectangle(3.0, 12.0), + rectangle(4.0, 12.0), + ]); + let options = Options { + cavity_pruning: false, + closure_pruning: false, + ..every_turn() + }; + let model = reachable(tray.clone(), shapes, TOL, &options, false).unwrap(); + assert!(!model.areas_add_up); + assert_eq!(model.search_solutions, 0); + assert!(!choices(&model).is_empty()); + // The strips of the other tests fill it. + let shapes = bare(&[ + rectangle(2.0, 12.0), + rectangle(3.0, 12.0), + rectangle(5.0, 12.0), + ]); + assert!( + reachable(tray, shapes, TOL, &options, false) + .unwrap() + .areas_add_up + ); + } + + #[test] + fn twins_share_their_placements() { + // Two 2 x 4 strips, the second stored lying down, and a 4 x 4 block in an 8 x 4 tray. + let tray = vec![[0.0, 0.0], [8.0, 0.0], [8.0, 4.0], [0.0, 4.0]]; + let shapes = bare(&[ + rectangle(2.0, 4.0), + rectangle(4.0, 2.0), + rectangle(4.0, 4.0), + ]); + let model = reachable(tray, shapes.clone(), TOL, &every_turn(), false).unwrap(); + assert_eq!(model.classes, [vec![0, 1], vec![2]]); + // By hand: block left, middle or right, strips in the columns left over, + // or lying one above the other beside the block. + // block at x in [0,4]: strips at [4,6] and [6,8], or lying at y in [0,2] and [2,4] over [4,8] + // block at [4,8]: likewise on the left + // block at [2,6]: strips at [0,2] and [6,8] + // Five assemblies. + assert_eq!(model.search_solutions, 5); + let found = choices(&model); + assert_eq!(found.len(), 5); + // Each choice is two strip placements and one block placement, and a + // pose is given for both twins that puts either on the same rectangle. + for choice in &found { + let strips: Vec = choice + .iter() + .copied() + .filter(|&p| model.class_of[p] == 0) + .collect(); + assert_eq!(strips.len(), 2); + for &p in &strips { + let first = transform(&shapes[0].polygon, &model.poses[p][0]); + let second = transform(&shapes[1].polygon, &model.poses[p][1]); + for corner in &first { + assert!( + second + .iter() + .any(|q| (q[0] - corner[0]).hypot(q[1] - corner[1]) <= 1e-9) + ); + } + } + } + } + + #[test] + fn a_limit_leaves_the_model_incomplete_and_says_so() { + let tray = vec![[0.0, 0.0], [10.0, 0.0], [10.0, 6.0], [0.0, 6.0]]; + let shapes = bare(&[ + rectangle(2.0, 6.0), + rectangle(3.0, 6.0), + rectangle(5.0, 6.0), + ]); + let limited = Options { + max_placements: Some(4), + ..every_turn() + }; + let model = reachable(tray, shapes, TOL, &limited, false).unwrap(); + assert!(!model.exhausted); + assert_eq!(model.class_of.len(), 5); + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(48))] + + /// On a random tiling, choosing among the reachable placements gives + /// as many assemblies as the search found, with the rules on or off. + #[test] + fn choosing_finds_what_the_search_found(tiling in tiling(), rules in any::()) { + let Tiling { target, local: pieces, .. } = tiling; + prop_assume!(pieces.len() <= 6); + let options = Options { + cavity_pruning: rules, + closure_pruning: rules, + ..every_turn() + }; + let model = reachable(target, bare(&pieces), TOL, &options, false).unwrap(); + prop_assert!(model.exhausted); + prop_assert!(model.search_solutions >= 1); + prop_assume!(model.class_of.len() <= 60); + prop_assert_eq!(choices(&model).len(), model.search_solutions); + } + } +} diff --git a/crates/tiling-search/src/lib.rs b/crates/tiling-search/src/lib.rs index 4fab24a..aefcd31 100644 --- a/crates/tiling-search/src/lib.rs +++ b/crates/tiling-search/src/lib.rs @@ -8,8 +8,10 @@ //! | --- | --- | //! | [`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 | +//! | [`enumerate`] | a finite set of placements and their conflicts, for solvers that choose among placements | pub mod canonical; pub mod contact_dfs; +pub mod enumerate; -pub use canonical::Symmetry; +pub use canonical::{Placement, Symmetry}; diff --git a/docs/algorithms.md b/docs/algorithms.md index 72ff745..ac6d469 100644 --- a/docs/algorithms.md +++ b/docs/algorithms.md @@ -262,3 +262,79 @@ What the tables say: - **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. + +## Choosing from a list (CP-SAT) + +`cp_sat.placements` is a solver of another kind. It knows no geometry: it is handed a finite list of placements and what they exclude among themselves, and chooses. The list and the exclusions are built in Rust (`tiling-search::enumerate`, `tiling-geometry::conflict`) in one call; the choosing is OR-Tools CP-SAT with one worker and no objective, asked for every solution. + +### The list + +The placements are the ones the corner search puts down anywhere in its tree: the *reachable* placements, with the tolerances of `rust.contact_dfs` and with the listing rules (`anchor`, `cavity_pruning`, `closure_pruning`, `tray_rotations`) the options name. Every assembly that search finds is made of placements it made on the way, so choosing from the list loses none of them. A rule that is off makes the tree larger and the list longer, and by the arguments for the rules adds no assembly. + +Two things make this the list to use. + +*It is short.* The search puts the same placement down in many states. The table below has the counts: a tree of a million nodes holds some ten or twenty thousand distinct placements, and the small footprints a few dozen to a few thousand. + +*A list built without a search is not.* The first attempt closed the contacts under themselves: start from the placements against the tray's corners, and add every placement that makes a corner contact with one already listed. That forgets which pieces a chain of contacts has used and whether its members could stand together. On the six-piece `new5-flat` it had passed 3 000 placements with 177 of them expanded and was still growing; the reachable list for that puzzle is 59. + +The price is that the list costs one whole search, and that the solver can find nothing the search has no placements for. What it adds is a second route to the same assemblies. The model is built from pairwise geometry, and CP-SAT shares none of the search's bookkeeping of what is placed, its pruning, or its removal of repeats. And it measures something the search cannot: how hard the choice is once the geometry is out of it. + +Congruent pieces share their placements. A placement belongs to a class of congruent pieces, not to a piece, and a class of k pieces takes k of them. That removes the exchange of twins from the model the way the candidate generator removes it from the search. + +### The model + +One Boolean per placement, and: + +- **each class takes as many placements as it has pieces**; +- **at most one** of any set of placements that conflict pairwise; +- with `coverage`, **at least one** of the placements that reach each probe point of the target. + +**Why a choice is an assembly.** Every listed placement lies inside the target. If no two chosen placements overlap, and the areas of the pieces add up to the target's, the chosen pieces cover it. In relief, a conflict is also a step between the roofs of two placements along a stretch of edge they share, so a choice without conflict has continuous roofs. If the areas do not add up, no choice is an assembly and the model is made infeasible outright. All of this is about exact figures; the code is `f64` with tolerances, and the validator has the last word. + +**Conflicts as cliques.** About a third of all pairs of listed placements overlap: millions of pairs on the larger puzzles. Most of them are stated without being listed. Take a point. The placements that hold it well inside them, by a margin of sixteen length tolerances, overlap one another pairwise, so "at most one of these" states all of those pairs at once. The points are a 48 by 48 grid over the target's bounding box, shifted off any symmetric position. An overlap no grid point witnesses is listed as a pair, and so is a roof step. + +**Targeted probes** (`targeted_probes`, off by default). With this on, each overlapping pair the grid missed gets a point of its own, at the centroid of what the two share, and everything holding that point joins the clique. A pair is then listed only when that centroid is not well inside both, which means an overlap a few tolerances thin. It states the same exclusions in a different form: on `new2-flat`, 137 pairs and 17 062 cliques instead of 1 081 790 pairs and 1 971 cliques. It is off because the form is worse for CP-SAT; the numbers are below. + +**Coverage** (`coverage`, on by default). A point of the target lies in some piece of any assembly, so of the placements that reach a grid point, the boundary counted, an assembly holds at least one. These constraints follow from the others and the areas, and exclude nothing. They are in the model because pairwise exclusion says only what cannot go together. Left with that, a solver that knows no geometry finds out that a partial choice leaves a hole no remaining placement fits by trying the rest. The "at least one" constraints let unit propagation see it: when every placement reaching a point is excluded, the choice is dead. + +**The tray's rotations.** With `tray_rotations=once` a choice and its images under the tray's rotations are one assembly. Rust reports, for each rotation, which listed placement each placement becomes, if any. A choice is named by the least of its images, and one whose name was seen before is counted in `duplicates` and not returned. With the anchor on, the list mostly holds one orientation only and there is little to discard. + +### What the choosing costs + +Whole runs to the end, default options except where the column says. Counts are deterministic for one OR-Tools version (9.15 here). "Search nodes" is the listing search, which is the default `rust.contact_dfs` search of the earlier table. + +**With roofs.** Every relief fixture: 25 to 93 placements listed, one fewer than the nodes of the listing search or close to it, and CP-SAT returns the one assembly with no branch and no conflict, with coverage or without. + +**Without roofs:** + +| Fixture | Pieces | Assemblies | Search nodes | Placements | Cliques | Pairs | Branches | Conflicts | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `new5-flat` | 6 | 1 | 90 | 59 | 274 | 38 | 0 | 0 | +| `new3-flat` | 9 | 1 | 6 104 | 1 395 | 2 135 | 10 536 | 0 | 0 | +| `new4-flat` | 9 | 1 | 510 | 244 | 531 | 810 | 0 | 0 | +| `rev2-flat` | 9 | 1 | 45 | 44 | 297 | 10 | 0 | 0 | +| `rat1-flat` | 11 | 101 | 17 425 | 2 195 | 2 186 | 36 439 | 2 215 | 19 | +| `new1-flat` | 16 | 1 | 1 064 878 | 25 233 | 2 274 | 4 710 195 | 169 941 | 297 | +| `new2-flat` | 16 | 1 | 909 750 | 11 537 | 1 971 | 1 081 790 | 0 | 0 | +| `rat2-flat` | 20 | 2 | 128 230 | 24 868 | 2 301 | 4 850 911 | 597 140 | 2 048 | + +**Without coverage** (`coverage=false`), the four smallest footprints are still settled with no branch. `rat1-flat` is not: after 60 s CP-SAT had made 2 716 185 branches and 301 706 conflicts, had returned all 101 assemblies, and had not shown there is no other. With coverage the same model takes 19 conflicts and under a second. + +**With targeted probes** (`targeted_probes=true`, coverage on), the three largest: + +| Fixture | Cliques | Pairs | Branches | Conflicts | Listing | CP-SAT | Grid only: listing | Grid only: CP-SAT | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `new2-flat` | 17 062 | 137 | 0 | 0 | 30 s | 17 s | 18 s | 5 s | +| `new1-flat` | 34 368 | 249 | 0 | 0 | 109 s | 131 s | 32 s | 64 s | +| `rat2-flat` | 117 461 | 14 633 | 740 692 | 2 098 | 303 s | 494 s | 13 s | 58 s | + +Times are from one quiet machine and indicative only. "Listing" is the search and the conflict computation together. + +What the tables say, relative to the listed placements and in `f64` with tolerances: + +- **Under roofs there is nothing to choose.** The list is hardly longer than the assembly, and propagation alone settles it. This is the relief finding of the search again, from the other side. +- **Once the placements are listed, the choice is easy.** The search needs a million nodes for `new1-flat` and `new2-flat`. The same puzzles, as a choice among the 25 233 and 11 537 placements that search touched, take 297 conflicts and none. A million nodes are those few thousand placements met again and again in different company, and each time the search works out afresh that they do not fit. What makes these puzzles hard for the search is not the number of ways to combine placements; it is that the search does not remember, or see ahead, which combinations are dead. +- **Coverage is what makes it easy.** Pairwise exclusion alone leaves CP-SAT worse off than the search on `rat1-flat`. The constraint that every point of the tray is reached by some chosen placement is redundant for correctness and decisive for the work. It is a global statement of what the search's corner rule says locally: this spot must be filled, and these are the only placements that can fill it. +- **Many assemblies cost more than one.** The conflicts go to `rat1-flat` (101 assemblies), `rat2-flat` (2) and `new1-flat`; the other five footprints are settled by propagation and decisions that never fail. For the search it is the other way round: `rat2-flat` is cheap and the unique 16-piece puzzles are dear. +- **Stating overlaps more cleverly did not help.** Targeted probes remove nearly every listed pair and make every run slower, `rat2-flat` by a factor of ten. The cliques they add are large and many, and the solver spends its time on them. The switch stays, off, with these numbers. +- **The list is the cost.** `cp_sat.placements` cannot be quicker than the search that builds its list, and on the three largest footprints it takes from a third longer to nearly twenty times as long in all. Its use is as a check and as a measurement, and as a pointer: a search that kept coverage-style reasons for its dead ends, or learned from them as CP-SAT does, is the thing to try on the 16-piece footprints. diff --git a/docs/architecture.md b/docs/architecture.md index facec8e..babcd4b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -135,6 +135,8 @@ Conflicts are precomputed by the Rust geometry. If all pieces lie inside the tar `INFEASIBLE` means infeasible within the generated candidate set, unless that set has been proven complete. The API preserves the distinction. Complete enumeration in CP-SAT cannot use an objective and runs with a single search worker. +As built (phase 6), the candidate set is the placements the Rust contact search reaches, congruent pieces share their placements (a class of k pieces takes k of them), and conflicts are stated mostly as "at most one of the placements that hold this point" instead of pair by pair. Coverage constraints, "at least one of the placements that reach this point", are added although they follow from the rest: without them CP-SAT is far slower than the search. [algorithms.md](algorithms.md#choosing-from-a-list-cp-sat) has the model and the measurements. + ## Python to Rust Algorithms are prototyped in Python without making Python-specific machinery part of the design: integer piece and candidate indices, typed state, reversible assignments, deterministic iteration. Prototypes call the same Rust geometry as production solvers, so porting replaces search state and control flow, not geometry. diff --git a/docs/roadmap.md b/docs/roadmap.md index ee4cc44..ef735b3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -10,8 +10,8 @@ Each phase is sized for one working session and ends with an exit criterion that | 3 | Rust geometry kernel | Done | | 4 | Contact candidates, Python prototype, solver contract | Done | | 5 | Rust contact DFS | Done | -| 6 | CP-SAT backend | Next | -| 7 | Benchmark and research platform | | +| 6 | CP-SAT backend | Done | +| 7 | Benchmark and research platform | Next | 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. @@ -148,6 +148,20 @@ Done, with these decisions: **Exit:** CP-SAT and the Rust DFS produce the same canonical solution sets on every fixture where both exhaust. +Done, with these decisions: + +- The exit criterion is `tests/corpus/test_cp_sat.py`. On all 20 fixtures, in their own regimes, both solvers run to the end and return the same assemblies, compared as placed polygons by the test oracle and up to the tray's rotations; every one passes the validator. No fixture is left out. +- The candidate set is the placements the corner search reaches (`corner-contact-reachable/1` and its relief variant), collected by running the search of `rust.contact_dfs` to its end. A set built without a search, by closing contacts under contacts, was tried first and does not stay small: over 3 000 placements and growing on a six-piece puzzle whose reachable list is 59. +- So the solver finds nothing the search has no placements for. It checks the search's choosing, not its candidates, and it measures how hard the choice is with the geometry taken out. `candidates_proven_complete` stays false. +- Congruent pieces share placements: a class of k pieces takes k of them. "Exactly one placement per piece" in the plan became "as many per class as it has pieces". +- Conflicts are not only pairwise. Overlaps are stated as "at most one of the placements holding this point" for a grid of points, and the rest as pairs. Coverage, "at least one of the placements reaching this point", was not planned and is what makes the model workable: without it CP-SAT does not finish `rat1-flat` in a minute, with it in under a second. +- Tray rotations are removed after the fact. Rust reports which listed placement each rotation turns each placement into, and a choice that is a rotation of an earlier one is dropped. The solver still makes one call into `_native`. +- If the areas of the pieces do not add up to the target's, the model is made infeasible: without that, and without coverage, three strips too narrow for their tray could be chosen side by side. A unit test holds it. +- Switches: the listing search's `anchor`, `cavity_pruning`, `closure_pruning` and `tray_rotations`; `coverage`; and `targeted_probes`, a cleverer statement of overlaps that turned out slower and is off. +- Tests beyond the exit: the model's exclusions against Shapely pair by pair, cliques and covers against Shapely, hand-countable puzzles, every switch on and off, limits, and the solver broken by hand seven ways with the tests watched to fail. +- Findings, relative to the listed placements. In relief CP-SAT needs no branch at all. On the footprints the choice is easy once the placements are listed: none to a few hundred conflicts where the search takes up to a million nodes. The search's trouble is not the number of combinations but that it meets the same dead ends again and again. [algorithms.md](algorithms.md#what-the-choosing-costs) has the tables. +- For later phases: remembering dead ends, or reasoning from coverage as the model does, is the lead to follow on the 16-piece footprints. + ## Phase 7: benchmark and research platform - `benchmarks/manifests/` and `experiments/benchmark.py`, writing JSONL with solver version, input hash, seed, tolerances and configuration. diff --git a/docs/solver-contract.md b/docs/solver-contract.md index 2a6d123..7907959 100644 --- a/docs/solver-contract.md +++ b/docs/solver-contract.md @@ -60,6 +60,8 @@ No solver in this repository sets `candidates_proven_complete` today, and a solv | --- | --- | --- | | `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. | +| `corner-contact-reachable/1` | `cp_sat.placements` (footprint) | The placements of `corner-contact/1` that the search of `rust.contact_dfs` puts down somewhere in its tree, with the listing options the result records. A finite list, built by running that search to its end. It holds every assembly that search finds and, being a subset of `corner-contact/1`, no more. If the listing was cut short by a limit the list is a part of this set and the result is not `exhaustive`. | +| `corner-contact-relief-reachable/1` | `cp_sat.placements` (relief) | The same, of `corner-contact-relief/1`. | 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. @@ -82,8 +84,12 @@ Each solver states which differences it counts. 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. +| `cp_sat.placements` | As `rust.contact_dfs`. With `tray_rotations=once`, a choice that is a tray rotation of one already returned is recognised from the listed placements and counted in `duplicates`. | As `rust.contact_dfs`. | + `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. +`cp_sat.placements` returns the same assemblies but not in that form: of an assembly and its tray rotations it returns whichever it chose first, and congruent pieces take the chosen places in piece order. Compare its solutions with another solver's as placed polygons, not pose by pose. + ## Metrics `SolveResult.metrics` maps names to numbers. The search counts are deterministic for a deterministic solver; the times are not, and tests assert nothing about them. @@ -108,7 +114,18 @@ In the relief regime "congruent" and "onto itself" include the roof: two pieces | `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. +A solver that chooses from a list of placements (`cp_sat.placements`) reports the counts above for the search that built the list, with `duplicates` and `solutions` for the choosing, and adds: + +| Name | Meaning | +| --- | --- | +| `model_placements` | Placements listed: one Boolean each. | +| `model_cliques` | Sets of placements stated as "at most one": those that hold one probe point well inside them. | +| `model_pairs` | Conflicting pairs no clique states: overlaps too thin for a probe, and roof steps between neighbours. | +| `model_covers` | Sets of placements stated as "at least one": those that reach one probe point of the target. Zero with `coverage=false`. | +| `sat_branches`, `sat_conflicts` | CP-SAT's count of decisions and of conflicts, with one worker. Zero conflicts means propagation and decisions alone reached every answer. | +| `listing_s`, `model_s`, `sat_s` | Wall time of the listing search with its conflict computation, of building the model, and of CP-SAT. | + +A solver for which a count has no meaning leaves it at zero; the model metrics are absent from solvers that have no model. New metrics are added to `SearchMetrics` and to these tables together. ## Reproducibility @@ -133,6 +150,7 @@ A result records `solver`, `solver_version`, `regime`, `instance_hash` and the w | --- | --- | --- | | `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. | +| `cp_sat.placements` | footprint, relief | CP-SAT choosing among the placements the Rust search reaches: one call into Rust for the list, then OR-Tools with one worker and no objective. Needs the `cp-sat` extra. Deterministic for a given OR-Tools version; `seed` is CP-SAT's random seed. `time_limit_s` covers the listing and the choosing together. `no_solution_found` is CP-SAT's `INFEASIBLE` on a whole list: the list holds no assembly. Options below. | ### Options of `rust.contact_dfs` @@ -148,6 +166,21 @@ Every rule the search adds to the prototype's can be switched off, so that its e | `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. | +### Options of `cp_sat.placements` + +The first six shape the search that lists the placements and mean what they mean for `rust.contact_dfs`; a rule that is off makes the list longer and never changes what is chosen from it. `coverage` and `targeted_probes` shape the model. + +| Option | Default | Meaning | +| --- | --- | --- | +| `node_limit` | none | Stop the listing search after that many nodes. The list is then partial. | +| `max_placements` | none | Stop the listing search once that many placements are listed. The list is then partial. | +| `tray_rotations` | `once` | `once`: a choice and its tray rotations are one solution. `all`: each is returned. | +| `anchor` | `true` | List only placements the anchored search reaches, so that rotated copies are mostly not in the list. Without it they are chosen and discarded. | +| `cavity_pruning` | `true` | The listing search's cavity pruning. | +| `closure_pruning` | `true` | The listing search's closure pruning. | +| `coverage` | `true` | State, for each probe point of the target, that some chosen placement reaches it. Implied by the rest of the model, so it excludes nothing; it is what lets CP-SAT see that a partial choice cannot be completed. | +| `targeted_probes` | `false` | Give each overlap the probe grid missed a probe of its own, so that it is stated in a clique instead of as a pair. Far fewer pairs, many more cliques; the same exclusions. | + ## Adding a solver A solver is a function `(PuzzleInstance, SolverConfig) -> SolveResult`, registered with `solvers.register(SolverSpec(...))` under a name of the form `.`. It must: diff --git a/pyproject.toml b/pyproject.toml index b616509..7887436 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,6 +15,8 @@ dependencies = [] [project.optional-dependencies] # The independent solution validator. The solvers do not need it. validate = ["shapely>=2.0"] +# The CP-SAT backend, `cp_sat.placements`. The Rust solvers do not need it. +cp-sat = ["ortools>=9.10"] [project.scripts] maxplus-solve = "maxplus_solvers.cli:main" @@ -27,6 +29,7 @@ dev = [ "hypothesis>=6.100", "jsonschema>=4.20", "maturin>=1.9,<2", + "ortools>=9.10", "pyright>=1.1.400", "pytest>=8", "ruff>=0.9", diff --git a/python/maxplus_solvers/_native.pyi b/python/maxplus_solvers/_native.pyi index 7199a82..45dbdcc 100644 --- a/python/maxplus_solvers/_native.pyi +++ b/python/maxplus_solvers/_native.pyi @@ -224,3 +224,75 @@ def contact_dfs( order: str = "matched-edges", seed: int = 0, ) -> ContactDfsOutcome: ... + +@final +class PlacementModel: + @property + def classes(self) -> list[list[int]]: ... + @property + def placement_class(self) -> list[int]: ... + @property + def placement_poses(self) -> list[list[_Pose]]: ... + @property + def cliques(self) -> list[list[int]]: ... + @property + def pairs(self) -> list[tuple[int, int]]: ... + @property + def covers(self) -> list[list[int]]: ... + @property + def turned(self) -> list[list[int | None]]: ... + @property + def areas_add_up(self) -> bool: ... + @property + def overlapping_pairs(self) -> int: ... + @property + def roof_step_pairs(self) -> int: ... + @property + def exhausted(self) -> bool: ... + @property + def search_solutions(self) -> int: ... + @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 search_time_s(self) -> float: ... + @property + def conflict_time_s(self) -> float: ... + +def placement_model( + target: _Polygon, + pieces: Sequence[_Polygon], + roofs: Sequence[_Roof] | None = None, + *, + length_tol: float, + angle_tol: float, + slope_tol: float, + height_tol: float | None = None, + time_limit_s: float | None = None, + node_limit: int | None = None, + max_placements: int | None = None, + all_tray_rotations: bool = False, + anchor: bool = True, + cavity_pruning: bool = True, + closure_pruning: bool = True, + targeted_probes: bool = False, +) -> PlacementModel: ... diff --git a/python/maxplus_solvers/metrics.py b/python/maxplus_solvers/metrics.py index 1068ebf..95f5b96 100644 --- a/python/maxplus_solvers/metrics.py +++ b/python/maxplus_solvers/metrics.py @@ -39,6 +39,18 @@ class SearchMetrics: 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 + # For a solver that chooses from a list of placements: the size of the list and of + # the constraints on the choice, the work of the choosing, and where the time went. + # Absent for a solver that does not. + model_placements: int | None = None + model_cliques: int | None = None + model_pairs: int | None = None + model_covers: int | None = None + sat_branches: int | None = None + sat_conflicts: int | None = None + listing_s: float | None = None + model_s: float | None = None + sat_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 0636ffa..948ff97 100644 --- a/python/maxplus_solvers/solvers/__init__.py +++ b/python/maxplus_solvers/solvers/__init__.py @@ -56,10 +56,12 @@ def get(name: str) -> SolverSpec: def _register_builtin() -> None: - from maxplus_solvers.solvers import contact_dfs + from maxplus_solvers.solvers import contact_dfs, cp_sat from maxplus_solvers.solvers.prototypes import contact_dfs as prototype register(contact_dfs.SPEC) + # Registering needs no OR-Tools; running does. + register(cp_sat.SPEC) register(prototype.SPEC) diff --git a/python/maxplus_solvers/solvers/cp_sat.py b/python/maxplus_solvers/solvers/cp_sat.py new file mode 100644 index 0000000..f96901a --- /dev/null +++ b/python/maxplus_solvers/solvers/cp_sat.py @@ -0,0 +1,286 @@ +"""``cp_sat.placements``: choose an assembly from a list of placements, with CP-SAT. + +The solver knows no geometry. Rust hands it a finite list of placements and +what they exclude among themselves, and it chooses: one Boolean per placement, +as many placements of each class of congruent pieces as the class has members, +at most one from every set that overlaps at a point or disagrees about a roof. +``docs/algorithms.md`` says where the list comes from and why a choice with no +conflict is an assembly. + +The list is the placements the corner search of ``rust.contact_dfs`` reaches, +so building it costs one whole search, and this solver finds nothing that +search does not. What it adds is a second route to the same assemblies, through +a solver that shares none of the search's bookkeeping, and a measure of how +hard the choice is once the geometry has been taken out of it. + +``INFEASIBLE`` here means that the listed placements hold no assembly. It says +nothing about placements that were not listed. + +This module makes one call into ``_native``, for the list. OR-Tools is an +optional extra and is imported only when the solver runs. +""" + +import math +import time +from collections.abc import Mapping, Sequence +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 = "cp_sat.placements" +CANDIDATE_SETS = { + # The placements the corner search puts down anywhere in its tree. + Regime.FOOTPRINT: "corner-contact-reachable/1", + # The same for the search that also asks roofs to continue. + Regime.RELIEF: "corner-contact-relief-reachable/1", +} + +TRAY_ROTATIONS = ("once", "all") + +# Option name -> default. The first group shapes the search that lists the placements, +# and means there what it means for rust.contact_dfs; ``coverage`` and ``targeted_probes`` +# shape the model. Targeted probes are off by default: they turn nearly every listed pair +# into a clique and CP-SAT is slower for it. docs/algorithms.md has the measurements. +DEFAULTS: Mapping[str, Any] = { + "node_limit": None, + "max_placements": None, + "tray_rotations": "once", + "anchor": True, + "cavity_pruning": True, + "closure_pruning": True, + "coverage": True, + "targeted_probes": False, +} + + +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} + for limit in ("node_limit", "max_placements"): + value = options[limit] + if value is not None and ( + isinstance(value, bool) or not isinstance(value, int) or value < 1 + ): + raise ValueError(f"{NAME}: {limit} must be a positive integer") + for switch in ("anchor", "cavity_pruning", "closure_pruning", "coverage", "targeted_probes"): + if not isinstance(options[switch], bool): + raise ValueError(f"{NAME}: {switch} must be true or false") + if options["tray_rotations"] not in TRAY_ROTATIONS: + raise ValueError(f"{NAME}: tray_rotations must be one of {', '.join(TRAY_ROTATIONS)}") + return options + + +def _form(choice: tuple[int, ...], turned: Sequence[Sequence[int | None]]) -> tuple[int, ...]: + """One name for a choice and for its images under the tray's turns: the least of them. + + A turn that takes some chosen placement to one that is not listed gives an + image nobody can choose, and is left out. + """ + form = choice + for images in turned: + image = [images[placement] for placement in choice] + if all(index is not None for index in image): + form = min(form, tuple(sorted(index for index in image if index is not None))) + return form + + +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") + try: + from ortools.sat.python import cp_model + except ImportError as error: + raise ImportError( + f"{NAME} needs OR-Tools: install maxplus-solvers with the 'cp-sat' extra" + ) from error + + 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") + # The tolerances of rust.contact_dfs, so that the two list and judge alike. + 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)) + steepest = max(math.hypot(gx, gy) for _, gx, gy in roofs) + height_mm = fit_mm * max(1.0, steepest) + + started = time.perf_counter() + cpu_started = time.process_time() + listed = _native.placement_model( + 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, + time_limit_s=config.time_limit_s, + node_limit=options["node_limit"], + max_placements=options["max_placements"], + all_tray_rotations=options["tray_rotations"] == "all", + anchor=options["anchor"], + cavity_pruning=options["cavity_pruning"], + closure_pruning=options["closure_pruning"], + targeted_probes=options["targeted_probes"], + ) + classes = listed.classes + of_class: list[list[int]] = [[] for _ in classes] + for placement, index in enumerate(listed.placement_class): + of_class[index].append(placement) + + model_started = time.perf_counter() + model = cp_model.CpModel() + chosen = [model.new_bool_var(f"p{index}") for index in range(len(listed.placement_class))] + for members, placements in zip(classes, of_class, strict=True): + # As many placements as the class has pieces. A class nothing was listed for + # asks for a sum of nothing to be positive, and the model is infeasible. + model.add(sum(chosen[index] for index in placements) == len(members)) + for clique in listed.cliques: + model.add_at_most_one(chosen[index] for index in clique) + for first, second in listed.pairs: + model.add_at_most_one((chosen[first], chosen[second])) + if not listed.areas_add_up: + # Pieces that cannot cover the target: a choice with no conflict would not be + # an assembly, so none is allowed. + model.add_bool_or([]) + covers = listed.covers if options["coverage"] else [] + for cover in covers: + # A point of the target that no listed placement reaches cannot be covered. + model.add_bool_or(chosen[index] for index in cover) + + turned = listed.turned if options["tray_rotations"] == "once" else [] + limit = config.max_solutions + + class Collect(cp_model.CpSolverSolutionCallback): + def __init__(self) -> None: + super().__init__() + self.choices: dict[tuple[int, ...], tuple[int, ...]] = {} + self.duplicates = 0 + self.first_s: float | None = None + + def on_solution_callback(self) -> None: + choice = tuple(index for index, var in enumerate(chosen) if self.boolean_value(var)) + form = _form(choice, turned) + if form in self.choices: + self.duplicates += 1 + return + self.choices[form] = choice + if self.first_s is None: + self.first_s = time.perf_counter() - started + if limit is not None and len(self.choices) >= limit: + self.stop_search() + + solver = cp_model.CpSolver() + solver.parameters.enumerate_all_solutions = True + # One worker, so that a run can be repeated and its counts mean something. + solver.parameters.num_workers = 1 + solver.parameters.random_seed = config.seed + model_s = time.perf_counter() - model_started + collect = Collect() + remaining = None + if config.time_limit_s is not None: + remaining = config.time_limit_s - (time.perf_counter() - started) + ran = remaining is None or remaining > 0 + if ran: + if remaining is not None: + solver.parameters.max_time_in_seconds = remaining + status = solver.solve(model, collect) + # With every solution asked for, OPTIMAL says they have all been given. + finished = status in (cp_model.OPTIMAL, cp_model.INFEASIBLE) + else: + finished = False + exhaustive = listed.exhausted and finished + wall_time_s = time.perf_counter() - started + + ids = [piece.id for piece in instance.pieces] + solutions = [] + for choice in collect.choices.values(): + poses: dict[str, Pose] = {} + for members, placements in zip(classes, of_class, strict=True): + taken = [index for index in placements if index in set(choice)] + for seat, (piece, placement) in enumerate(zip(members, taken, strict=True)): + poses[ids[piece]] = Pose(*listed.placement_poses[placement][seat]) + solutions.append(Solution({pid: poses[pid] for pid in ids})) + + metrics = SearchMetrics( + # The search that listed the placements. + nodes=listed.nodes, + backtracks=listed.backtracks, + placements=listed.placements, + max_depth=listed.max_depth, + candidates_generated=listed.candidates_generated, + rejected_outside=listed.rejected_outside, + rejected_overlap=listed.rejected_overlap, + rejected_roof=listed.rejected_roof, + pruned_cavity=listed.pruned_cavity, + pruned_closure=listed.pruned_closure, + pruned_anchor=listed.pruned_anchor, + duplicates=collect.duplicates, + solutions=len(solutions), + wall_time_s=wall_time_s, + cpu_time_s=time.process_time() - cpu_started, + first_solution_s=collect.first_s, + exhausted_s=wall_time_s if exhaustive else None, + # The model, and the choosing. + model_placements=len(chosen), + model_cliques=len(listed.cliques), + model_pairs=len(listed.pairs), + model_covers=len(covers), + sat_branches=solver.num_branches if ran else 0, + sat_conflicts=solver.num_conflicts if ran else 0, + listing_s=listed.search_time_s + listed.conflict_time_s, + model_s=model_s, + sat_s=solver.wall_time if ran else 0.0, + ) + if solutions: + outcome = SolveStatus.SOLVED + elif exhaustive: + outcome = SolveStatus.NO_SOLUTION_FOUND + else: + outcome = SolveStatus.INTERRUPTED + return SolveResult( + status=outcome, + solver=NAME, + regime=instance.regime, + instance_hash=instance.instance_hash(), + solutions=tuple(solutions), + exhaustive=exhaustive, + # The list is what one search reached, in f64 with tolerances. Nothing is proven + # about placements outside it. + 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="CP-SAT: choose among the placements the Rust contact search reaches", +) diff --git a/tests/architecture/test_layering.py b/tests/architecture/test_layering.py index c6a1799..acb8a62 100644 --- a/tests/architecture/test_layering.py +++ b/tests/architecture/test_layering.py @@ -114,7 +114,10 @@ def test_no_solver_reaches_the_validator() -> None: def test_solvers_are_registered_under_the_family_they_live_in() -> None: - """``python.*`` are the prototypes; every solver declares its regimes and its candidate set.""" + """``python.*`` are the prototypes, ``rust.*`` the Rust solvers, ``cp_sat.*`` the models. + + Every solver declares its regimes and its candidate set. + """ from maxplus_solvers import solvers assert solvers.available(), "nothing is registered" @@ -126,6 +129,8 @@ def test_solvers_are_registered_under_the_family_they_live_in() -> None: module = spec.run.__module__ if family == "python": assert module == f"maxplus_solvers.solvers.prototypes.{algorithm}", name + elif family == "cp_sat": + assert module == "maxplus_solvers.solvers.cp_sat", name else: assert family == "rust", name assert module == f"maxplus_solvers.solvers.{algorithm}", name @@ -157,7 +162,8 @@ def test_production_solvers_cross_into_rust_once_per_solve() -> None: 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?" + names = [p.name for p in production] + assert names == ["contact_dfs.py", "cp_sat.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"] @@ -179,21 +185,50 @@ def test_production_solvers_cross_into_rust_once_per_solve() -> None: 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 rules of the production solvers 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 + from maxplus_solvers.solvers import contact_dfs, cp_sat - 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" + expected = { + contact_dfs: {"anchor", "cavity_pruning", "closure_pruning", "lookahead"}, + cp_sat: {"anchor", "cavity_pruning", "closure_pruning", "coverage"}, + } + for solver, rules in expected.items(): + defaults = solver.DEFAULTS + switches = {name for name, default in defaults.items() if isinstance(default, bool)} + assert rules <= switches, solver.NAME + # Each solver has its own options table, under a heading that names it. + _, _, section = contract.partition(f"### Options of `{solver.NAME}`") + assert section, f"{solver.NAME} has no options table" + table = section.split("\n#", 1)[0] + for option in defaults: + assert f"| `{option}` |" in table, f"{solver.NAME}: {option} is not in its table" + for switch in switches: + assert f"`{switch}`" in algorithms, f"{switch} has no place in algorithms.md" + + +def test_cp_sat_is_given_one_worker_and_no_objective() -> None: + """A run that can be repeated, and counts that mean something. + + Several workers race, and the conflicts and branches reported depend on + who wins. An objective would turn listing assemblies into ranking them. + """ + source = (PACKAGE / "solvers" / "cp_sat.py").read_text(encoding="utf-8") + assert "parameters.num_workers = 1" in source + assert "parameters.enumerate_all_solutions = True" in source + tree = ast.parse(source) + called = { + node.func.attr + for node in ast.walk(tree) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + } + assert not called & {"minimize", "maximize", "Minimize", "Maximize"} + assert "solve" in called, "the check no longer sees the solver's calls" def test_importing_the_package_does_not_need_the_optional_extras() -> None: diff --git a/tests/corpus/test_cp_sat.py b/tests/corpus/test_cp_sat.py new file mode 100644 index 0000000..9f4be04 --- /dev/null +++ b/tests/corpus/test_cp_sat.py @@ -0,0 +1,206 @@ +"""Phase 6 exit criterion: CP-SAT and the Rust search return the same assemblies. + +On every fixture, in its own regime, ``cp_sat.placements`` and +``rust.contact_dfs`` are both run to the end, and the two sets of assemblies +are compared polygon by polygon with the test oracle. Both exhaust on every +fixture, so the comparison leaves none out. + +The agreement is less than it sounds and more than nothing. CP-SAT chooses +among the placements a run of the same search listed, so it cannot find an +assembly the search has no placements for. What it checks is the search's +choosing: its bookkeeping of what is placed, its pruning, its duplicate +removal. The model is built from pairwise geometry alone and solved by code +that shares none of that. + +The counts pinned here are findings, relative to the listed placements and in +``f64`` with tolerances. +""" + +from typing import Any + +import pytest + +from maxplus_solvers import PuzzleInstance, Regime, SolverConfig, SolveResult, SolveStatus, solve +from support import assemblies, corpus, geometry + +CP_SAT = "cp_sat.placements" +DFS = "rust.contact_dfs" + +PIECES = {entry["id"]: entry["pieceCount"] for entry in corpus.index()["fixtures"]} +CORPUS = corpus.fixture_ids(kind="corpus") +FLAT = corpus.fixture_ids(kind="corpus", regime="footprint") +RELIEF = corpus.fixture_ids(kind="corpus", regime="relief") +SYNTHETIC = corpus.fixture_ids(kind="synthetic") +SMALL = [f for f in FLAT if PIECES[f] <= 11] +# Listing the placements of these is a whole search of tens of seconds, and the +# model has thousands of them. +SLOW = {"new1-flat", "new2-flat", "rat2-flat"} +# As in test_rust_contact_dfs.py. Not in this table: one. +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 = CP_SAT, **options: Any) -> SolverConfig: + 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 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 same_up_to_turns(instance: PuzzleInstance, a: list[Any], b: list[Any]) -> bool: + """The same assemblies, each allowed to be a turn of its counterpart with the tray. + + Counting turns once, a solver returns one member of each family, and which + one depends on its options. + """ + centre = geometry.centroid(instance.target) + turns = assemblies.tray_turns(instance.target) + + def alike(x: Any, y: Any) -> bool: + return any(assemblies.same(assemblies.turned(x, turn, centre), y) for turn in turns) + + return len(a) == len(b) and all(sum(alike(x, y) for y in b) == 1 for x in a) + + +def test_the_exit_criterion_covers_every_fixture() -> None: + assert len(CORPUS) == 16 and len(SYNTHETIC) == 4 + assert set(FLAT) >= SLOW | set(ASSEMBLIES) + + +# --- the exit criterion ------------------------------------------------------------------- + + +@pytest.mark.parametrize("fixture_id", marked(CORPUS + SYNTHETIC)) +def test_cp_sat_and_the_search_return_the_same_assemblies(fixture_id: str) -> None: + instance = instance_of(fixture_id) + chosen = solve(instance, whole(instance.regime), validate=True) + searched = solve(instance, whole(instance.regime, DFS)) + assert chosen.status is SolveStatus.SOLVED + # Both ran to the end: this fixture is not left out of the comparison. + assert chosen.exhaustive and searched.exhaustive + assert not chosen.candidates_proven_complete + assert chosen.candidate_set == ( + "corner-contact-relief-reachable/1" + if instance.regime is Regime.RELIEF + else "corner-contact-reachable/1" + ) + assert all(solution.valid is True for solution in chosen.solutions) + + found = placed(instance, chosen) + # One of each family of turns from either solver; which member is each solver's choice. + assert same_up_to_turns(instance, found, placed(instance, searched)) + if fixture_id in CORPUS: + assert len(found) == ASSEMBLIES.get(fixture_id, 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)) + # The answer key is among them, in one orientation. + centre = geometry.centroid(instance.target) + key = assemblies.world(corpus.fixture(fixture_id), corpus.key(fixture_id)["poses"]) + turns = [assemblies.turned(key, t, centre) for t in assemblies.tray_turns(instance.target)] + assert sum(any(assemblies.same(k, a) for k in turns) for a in found) == 1 + + # The listing search is the search: same rules, same tree. + for count in ("nodes", "backtracks", "placements", "candidates_generated"): + assert chosen.metrics[count] == searched.metrics[count], count + assert chosen.metrics["solutions"] == len(found) + + +@pytest.mark.parametrize("fixture_id", SMALL + [f.removesuffix("-flat") for f in SMALL]) +def test_counting_every_orientation_the_two_agree_as_well(fixture_id: str) -> None: + instance = instance_of(fixture_id) + chosen = solve(instance, whole(instance.regime, tray_rotations="all"), validate=True) + searched = solve(instance, whole(instance.regime, DFS, tray_rotations="all")) + assert chosen.exhaustive and searched.exhaustive + assert all(solution.valid is True for solution in chosen.solutions) + assert chosen.metrics["duplicates"] == 0 + found = placed(instance, chosen) + assert same_set(found, placed(instance, searched)) + # The tray is a square and no assembly here is its own turn: four of each. + orbits = assemblies.orbits(instance.target, found) + assert all(len(orbit) == 4 for orbit in orbits) + assert len(orbits) == ASSEMBLIES.get(fixture_id, 1) + + +# --- the switches ------------------------------------------------------------------------- + + +@pytest.mark.parametrize("fixture_id", [f for f in SMALL if f != "rat1-flat"] + ["rat1", "new3"]) +def test_no_switch_changes_what_is_chosen(fixture_id: str) -> None: + """The listing rules and the coverage constraints change the model, never the answer. + + ``rat1-flat`` is left to the test below: without coverage CP-SAT does not + finish it in a minute. + """ + instance = instance_of(fixture_id) + reference = placed(instance, solve(instance, whole(instance.regime))) + assert reference + switches = ("anchor", "cavity_pruning", "closure_pruning", "coverage") + variants: list[dict[str, Any]] = [{switch: False} for switch in switches] + variants.append(dict.fromkeys(switches, False)) + variants.append({"targeted_probes": True}) + for options in variants: + result = solve(instance, whole(instance.regime, **options), validate=True) + assert result.exhaustive, options + assert all(solution.valid is True for solution in result.solutions), options + assert same_up_to_turns(instance, placed(instance, result), reference), options + + +def test_without_the_anchor_the_turns_are_found_and_recognised() -> None: + """``rat1-flat``: 404 choices, 303 of them turns of the other 101.""" + instance = instance_of("rat1-flat") + anchored = solve(instance, whole(instance.regime)) + free = solve(instance, whole(instance.regime, anchor=False), validate=True) + assert free.exhaustive + assert len(free.solutions) == 101 and free.metrics["duplicates"] == 303 + assert anchored.metrics["duplicates"] == 0 + assert free.metrics["model_placements"] > anchored.metrics["model_placements"] + assert same_up_to_turns(instance, placed(instance, free), placed(instance, anchored)) + + +# --- what the model looks like ------------------------------------------------------------ + + +@pytest.mark.parametrize("fixture_id", [f for f in CORPUS if f not in SLOW]) +def test_the_list_is_far_shorter_than_the_search_that_made_it(fixture_id: str) -> None: + """A finding: the search puts the same few placements down again and again. + + Every placement listed was placed, so the list is no longer than the + count of placements made. On the footprints it is much shorter. + """ + instance = instance_of(fixture_id) + metrics = solve(instance, whole(instance.regime)).metrics + assert PIECES[fixture_id] <= metrics["model_placements"] <= metrics["placements"] + # Overlaps are stated at points, in cliques, and the grid leaves some as pairs. With + # a probe for each of those, nearly all become cliques and nothing else changes. + assert metrics["model_cliques"] > 0 + targeted = solve(instance, whole(instance.regime, targeted_probes=True)).metrics + assert targeted["model_placements"] == metrics["model_placements"] + assert targeted["model_pairs"] <= metrics["model_pairs"] + assert targeted["model_cliques"] >= metrics["model_cliques"] + + +@pytest.mark.parametrize("fixture_id", RELIEF) +def test_under_roofs_the_choice_takes_no_search(fixture_id: str) -> None: + """A finding: in relief, propagation alone settles the choice.""" + instance = instance_of(fixture_id) + result = solve(instance, whole(instance.regime)) + assert result.exhaustive and len(result.solutions) == 1 + assert result.metrics["sat_conflicts"] == 0 diff --git a/tests/corpus/test_placement_model_agrees_with_shapely.py b/tests/corpus/test_placement_model_agrees_with_shapely.py new file mode 100644 index 0000000..3385458 --- /dev/null +++ b/tests/corpus/test_placement_model_agrees_with_shapely.py @@ -0,0 +1,179 @@ +"""The conflicts of a placement model, against Shapely. + +``_native.placement_model`` says which listed placements exclude one another, +mostly as cliques at probe points. Here every pair of placements is intersected +with Shapely and the two are compared: + +* two placements the model lets stand together share no more area than a sliver + one length tolerance deep; +* two it excludes overlap, or, under roofs, share a stretch of edge; +* the members of a clique have a region in common, as placements holding one + point must. + +Tolerances: the model is built with a length tolerance of ``1e-6`` mm. An +overlap is "none" below that depth along the shorter of the two perimeters, +plus ``1e-6`` mm² for the arithmetic, and "some" above ``1e-9`` mm². Shapely +rarely reports the common part of two nearly collinear edges, so a shared +stretch of edge is found by growing one placement by ``1e-3`` mm. + +Agreement is numerical evidence that two implementations compute the same +thing. It is not a proof of either. +""" + +from itertools import combinations + +import pytest +import shapely + +from maxplus_solvers import PuzzleInstance, Regime, _native +from support import corpus + +PIECES = {entry["id"]: entry["pieceCount"] for entry in corpus.index()["fixtures"]} +# Lists short enough to intersect every pair: up to a few hundred placements. +FLAT = ["new5-flat", "rev2-flat", "new4-flat"] +RELIEF = corpus.fixture_ids(kind="corpus", regime="relief") +SYNTHETIC = corpus.fixture_ids(kind="synthetic") + +LENGTH_TOL = 1e-6 +AREA_TOL = 1e-6 +SOME_AREA = 1e-9 +# Two placements share a stretch of edge if one, grown by this much, takes this much +# area of the other: a stretch of more than a hundredth of a millimetre. Placements that +# only touch at a corner share about the square of the growth. +GROWTH_MM = 1e-3 +SEAM_AREA = 1e-5 + + +def model_of(fixture_id: str, targeted: bool) -> tuple[PuzzleInstance, _native.PlacementModel]: + instance = PuzzleInstance.from_dict(corpus.fixture(fixture_id)) + roofs = None + if instance.regime is Regime.RELIEF: + roofs = [] + for piece in instance.pieces: + assert piece.roof is not None + roofs.append((piece.roof.z0, piece.roof.gx, piece.roof.gy)) + model = _native.placement_model( + instance.target, + [piece.polygon for piece in instance.pieces], + roofs, + length_tol=LENGTH_TOL, + angle_tol=1e-6, + slope_tol=1e-6, + # Every orientation and no anchor: the longest list the search makes. + all_tray_rotations=True, + anchor=False, + targeted_probes=targeted, + ) + assert model.exhausted + return instance, model + + +def polygons_of(instance: PuzzleInstance, model: _native.PlacementModel) -> list[shapely.Polygon]: + placed = [] + for index, poses in zip(model.placement_class, model.placement_poses, strict=True): + first = instance.pieces[model.classes[index][0]] + x, y, theta = poses[0] + placed.append(shapely.Polygon(_native.transform(first.polygon, (x, y, theta)))) + return placed + + +def excluded_pairs(model: _native.PlacementModel) -> set[tuple[int, int]]: + pairs = {(min(a, b), max(a, b)) for a, b in model.pairs} + for clique in model.cliques: + pairs.update(combinations(sorted(clique), 2)) + return pairs + + +@pytest.mark.parametrize("targeted", [False, True], ids=["grid", "targeted"]) +@pytest.mark.parametrize("fixture_id", FLAT + RELIEF + SYNTHETIC) +def test_the_model_excludes_the_pairs_shapely_finds_overlapping( + fixture_id: str, targeted: bool +) -> None: + instance, model = model_of(fixture_id, targeted) + placed = polygons_of(instance, model) + assert len(placed) >= PIECES[fixture_id] - sum(len(c) - 1 for c in model.classes) + excluded = excluded_pairs(model) + if fixture_id not in SYNTHETIC: + # The smallest synthetic lists are a tiling and nothing else. + assert excluded, "the model excludes nothing" + + overlapping = 0 + steps = 0 + for a, b in combinations(range(len(placed)), 2): + shared = placed[a].intersection(placed[b]).area + if (a, b) in excluded: + if shared > SOME_AREA: + overlapping += 1 + else: + # Only a roof can keep apart two placements that do not overlap, and + # only across an edge they share. + assert instance.regime is Regime.RELIEF, (a, b) + seam = placed[a].buffer(GROWTH_MM).intersection(placed[b]).area + assert seam > SEAM_AREA, (a, b, seam) + steps += 1 + else: + sliver = LENGTH_TOL * min(placed[a].length, placed[b].length) + AREA_TOL + assert shared <= sliver, (a, b, shared) + # The model calls a pair an overlap first and looks at roofs only if it is not one. + # An overlap thinner than SOME_AREA across a shared edge is counted here as a step, + # so the two tallies may trade a pair and must agree in sum. + assert overlapping + steps == model.overlapping_pairs + model.roof_step_pairs + assert overlapping <= model.overlapping_pairs + assert model.overlapping_pairs - overlapping <= max(1, len(excluded) // 1000) + if instance.regime is Regime.FOOTPRINT: + assert model.roof_step_pairs == 0 + + # A pair is stated once: not listed if a clique already holds it. + in_cliques = set() + for clique in model.cliques: + in_cliques.update(combinations(sorted(clique), 2)) + assert not in_cliques & {(min(a, b), max(a, b)) for a, b in model.pairs} + + +@pytest.mark.parametrize("fixture_id", FLAT + RELIEF[:3]) +def test_the_members_of_a_clique_have_a_region_in_common(fixture_id: str) -> None: + instance, model = model_of(fixture_id, True) + placed = polygons_of(instance, model) + assert model.cliques + for clique in model.cliques: + assert len(clique) >= 2 and sorted(set(clique)) == list(clique) + common = placed[clique[0]] + for member in clique[1:]: + common = common.intersection(placed[member]) + assert common.area > SOME_AREA, clique + + +@pytest.mark.parametrize("fixture_id", FLAT + RELIEF[:3]) +def test_targeted_probes_change_how_overlaps_are_stated_and_not_which(fixture_id: str) -> None: + _, grid = model_of(fixture_id, False) + _, targeted = model_of(fixture_id, True) + assert grid.placement_poses == targeted.placement_poses + assert excluded_pairs(grid) == excluded_pairs(targeted) + assert len(targeted.pairs) <= len(grid.pairs) + assert grid.covers == targeted.covers + + +@pytest.mark.parametrize("fixture_id", FLAT + RELIEF) +def test_every_cover_is_reached_by_a_placement_and_lies_in_the_target(fixture_id: str) -> None: + """A cover is the placements reaching one point of the target. + + So its members have a point in common, boundaries counted, and no listed + placement outside it contains all that its members share. + """ + instance, model = model_of(fixture_id, False) + placed = polygons_of(instance, model) + target = shapely.Polygon(instance.target) + assert model.covers + for cover in model.covers: + assert cover, "a point of the target that nothing listed reaches" + # Reaching counts the boundary, and a point outside by no more than the tolerance. + common = placed[cover[0]].buffer(2 * LENGTH_TOL) + for member in cover[1:]: + common = common.intersection(placed[member].buffer(2 * LENGTH_TOL)) + assert not common.is_empty, cover + assert common.intersects(target) + # A placement that held every point the members share would reach the probe too. + if common.area > SOME_AREA: + inside = common.buffer(-LENGTH_TOL) + for other in set(range(len(placed))) - set(cover): + assert not placed[other].contains(inside) or inside.is_empty, (cover, other) diff --git a/tests/unit/test_cp_sat.py b/tests/unit/test_cp_sat.py new file mode 100644 index 0000000..2e38c3d --- /dev/null +++ b/tests/unit/test_cp_sat.py @@ -0,0 +1,352 @@ +"""``cp_sat.placements`` on puzzles whose assemblies can be listed by hand. + +The same three strips as ``test_rust_contact_dfs.py``: any order as footprints, +one order under their roofs. The expectations are the hand-made assemblies and +the strips' arithmetic, never the search the solver's list comes from. +""" + +import math +import sys +from typing import Any + +import pytest + +from maxplus_solvers import ( + PuzzleInstance, + Regime, + SolverConfig, + SolveResult, + SolveStatus, + solve, + solvers, +) +from maxplus_solvers.solvers import cp_sat +from support import assemblies, documents, geometry + +CP_SAT = "cp_sat.placements" +TIMES = { + "wall_time_s", + "cpu_time_s", + "first_solution_s", + "exhausted_s", + "listing_s", + "model_s", + "sat_s", +} +ORDERS = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)] + + +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(CP_SAT, 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 + + +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 same_up_to_turns(instance: PuzzleInstance, a: list[Any], b: list[Any]) -> bool: + """The same assemblies, each allowed to be a turn of its counterpart with the tray. + + Counting turns once, a solver returns one member of each family, and which + one depends on its options. + """ + centre = geometry.centroid(instance.target) + turns = assemblies.tray_turns(instance.target) + + def alike(x: Any, y: Any) -> bool: + return any(assemblies.same(assemblies.turned(x, turn, centre), y) for turn in turns) + + return len(a) == len(b) and all(sum(alike(x, y) for y in b) == 1 for x in a) + + +# --- what is found ------------------------------------------------------------------------ + + +def test_every_order_of_the_strips_is_chosen_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]) + # By hand: a strip's left side stands at a sum of widths of strips to its left, + # four places each. The list is longer than those twelve: the search also lays + # strips on their sides, which fits the tray and is part of no assembly. + assert result.metrics["model_placements"] >= 12 + assert result.metrics["duplicates"] == 0 + + +@pytest.mark.parametrize("anchor", [True, False]) +def test_an_order_and_its_reverse_are_one_assembly(anchor: bool) -> None: + """The tray's half turn reverses an order: 6 orders, 3 assemblies. + + With the anchor the list holds one of each pair to begin with. Without it + the list holds every placement, the chooser finds all six orders, and + three of them are recognised as turns of the others. + """ + instance = footprint() + result = solve(instance, everything(anchor=anchor), 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]) + if not anchor: + assert result.metrics["duplicates"] == 3 + + +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) + turned = assemblies.turned(cut, math.pi, (0.0, 0.0)) + assert assemblies.same(found, cut) or assemblies.same(found, turned) + + 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, turned]) + + +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 + + +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 + result = solve(PuzzleInstance.from_dict(doc), everything(Regime.RELIEF)) + assert result.status is SolveStatus.NO_SOLUTION_FOUND and result.exhaustive + assert not result.candidates_proven_complete + + +@pytest.mark.parametrize("coverage", [True, False]) +@pytest.mark.parametrize("pruning", [True, False]) +def test_strips_too_narrow_for_the_tray_are_never_an_assembly( + coverage: bool, pruning: bool +) -> None: + """24 + 36 + 48 mm of strips for 120 mm of tray. + + With the pruning the listing search stops at its root and lists nothing. + Without it, strips are listed that stand clear of one another: 24 at the + left wall, 36 beside it, 48 at the right wall, 12 mm of tray bare. Nothing + excludes that choice pair by pair, so the model must refuse it by other + means, with the coverage constraints or without them. + """ + 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(coverage=coverage, cavity_pruning=pruning, closure_pruning=pruning), + ) + assert result.status is SolveStatus.NO_SOLUTION_FOUND and result.exhaustive + assert result.solutions == () + assert (result.metrics["model_placements"] == 0) is pruning + + +# --- 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: + switches = [name for name, default in cp_sat.DEFAULTS.items() if isinstance(default, bool)] + assert sorted(switches) == [ + "anchor", + "cavity_pruning", + "closure_pruning", + "coverage", + "targeted_probes", + ] + reference = placed(instance, solve(instance, everything(instance.regime))) + assert reference + # Each switch moved from its default, alone and then all together. + flipped = {switch: not cp_sat.DEFAULTS[switch] for switch in switches} + for switch in switches: + result = solve(instance, everything(instance.regime, **{switch: flipped[switch]})) + assert result.exhaustive, switch + assert same_up_to_turns(instance, placed(instance, result), reference), switch + other = solve(instance, everything(instance.regime, **flipped)) + assert same_up_to_turns(instance, placed(instance, other), reference) + assert other.metrics["model_covers"] == 0 + + +def test_coverage_adds_constraints_and_no_placements() -> None: + instance = footprint() + with_covers = solve(instance, everything()).metrics + without = solve(instance, everything(coverage=False)).metrics + assert with_covers["model_covers"] > 0 and without["model_covers"] == 0 + for count in ("model_placements", "model_cliques", "model_pairs", "nodes"): + assert with_covers[count] == without[count], count + + +def test_the_solver_is_deterministic() -> None: + instance = footprint() + first, second = solve(instance, everything()), solve(instance, everything()) + 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(CP_SAT), validate=True) + assert result.status is SolveStatus.SOLVED + (solution,) = result.solutions + assert solution.valid is True + assert not result.exhaustive + assert "first_solution_s" in result.metrics + assert "exhausted_s" not in result.metrics + + +def test_two_of_three_can_be_asked_for() -> None: + config = SolverConfig(CP_SAT, max_solutions=2) + result = solve(footprint(), config, validate=True) + assert len(result.solutions) == 2 and not result.exhaustive + assert all(solution.valid for solution in result.solutions) + first, second = placed(footprint(), result) + assert not assemblies.same(first, second) + + +def test_a_list_cut_short_is_not_exhaustive_whatever_is_chosen_from_it() -> None: + """Three of the placements cannot hold all three assemblies, and the result says so.""" + cut = solve(footprint(), everything(max_placements=3), validate=True) + assert not cut.exhaustive + whole = solve(footprint(), everything()).metrics["model_placements"] + # The limit is looked at between nodes, so a node's last placement may pass it. + assert 3 <= cut.metrics["model_placements"] < whole + assert len(cut.solutions) < 3 + assert all(solution.valid for solution in cut.solutions) + assert cut.status is (SolveStatus.SOLVED if cut.solutions else SolveStatus.INTERRUPTED) + + one_node = solve(footprint(), everything(node_limit=1)) + assert one_node.status is SolveStatus.INTERRUPTED and not one_node.exhaustive + assert one_node.metrics["nodes"] == 1 and one_node.metrics["model_placements"] < whole + + hurried = solve(footprint(), SolverConfig(CP_SAT, max_solutions=None, time_limit_s=1e-12)) + assert hurried.status is SolveStatus.INTERRUPTED and not hurried.exhaustive + assert hurried.metrics["sat_branches"] == 0 + + +# --- what a result records ---------------------------------------------------------------- + + +def test_a_result_names_the_candidate_set_of_its_regime() -> None: + spec = solvers.get(CP_SAT) + assert spec.regimes == frozenset({Regime.FOOTPRINT, Regime.RELIEF}) + flat = solve(footprint(), everything(coverage=False)) + assert (flat.solver, flat.candidate_set) == (CP_SAT, "corner-contact-reachable/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 == {"coverage": False} + assert flat.solver_version.count(".") == 2 + assert flat.metrics["solutions"] == 3 + for name in ("model_placements", "model_cliques", "model_pairs", "sat_branches", "sat_s"): + assert name in flat.metrics + roofed = solve(relief(), everything(Regime.RELIEF)) + assert roofed.candidate_set == "corner-contact-relief-reachable/1" + assert roofed.instance_hash == relief().instance_hash() + + +def test_the_other_solvers_do_not_report_a_model() -> None: + result = solve(footprint(), SolverConfig("rust.contact_dfs")) + assert not [name for name in result.metrics if name.startswith(("model_", "sat_"))] + + +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(CP_SAT, mode=Regime.TROPICAL_AWARE)) + with pytest.raises(ValueError, match="does not work in the tropical-aware regime"): + solvers.get(CP_SAT).run(instance, SolverConfig(CP_SAT, mode=Regime.TROPICAL_AWARE)) + + +@pytest.mark.parametrize( + ("options", "message"), + [ + ({"lookahead": True}, "unknown options lookahead"), + ({"node_limit": 0}, "node_limit must be a positive integer"), + ({"max_placements": True}, "max_placements must be a positive integer"), + ({"max_placements": 1.5}, "max_placements must be a positive integer"), + ({"coverage": "yes"}, "coverage must be true or false"), + ({"anchor": 1}, "anchor must be true or false"), + ({"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(CP_SAT, options=options)) + + +def test_a_negative_seed_is_refused() -> None: + with pytest.raises(ValueError, match="seed must not be negative"): + solve(footprint(), SolverConfig(CP_SAT, seed=-1)) + + +def test_without_or_tools_the_solver_says_what_to_install(monkeypatch: pytest.MonkeyPatch) -> None: + """The solver is registered either way; only running it needs the extra.""" + for module in ("ortools", "ortools.sat", "ortools.sat.python"): + monkeypatch.setitem(sys.modules, module, None) + assert CP_SAT in solvers.available() + with pytest.raises(ImportError, match="'cp-sat' extra"): + solve(footprint(), SolverConfig(CP_SAT)) + + +# --- one name for a choice and its turns -------------------------------------------------- + + +def test_a_choice_and_its_turn_have_one_form() -> None: + # Four placements; a half turn swaps 0 with 3 and 1 with 2. + half = [3, 2, 1, 0] + assert cp_sat._form((0, 1), [half]) == (0, 1) + assert cp_sat._form((2, 3), [half]) == (0, 1) + assert cp_sat._form((0, 2), [half]) == (0, 2) + assert cp_sat._form((1, 3), [half]) == (0, 2) + # With no turns a choice is its own form. + assert cp_sat._form((2, 3), []) == (2, 3) + + +def test_a_turn_that_leaves_the_list_is_no_turn() -> None: + # Placement 3's image is not listed, so (2, 3) has no listed turn to be confused with. + assert cp_sat._form((2, 3), [[3, 2, 1, None]]) == (2, 3) + assert cp_sat._form((1, 2), [[3, 2, 1, None]]) == (1, 2) diff --git a/uv.lock b/uv.lock index 5be4fb9..d33a7af 100644 --- a/uv.lock +++ b/uv.lock @@ -2,8 +2,24 @@ version = 1 revision = 3 requires-python = ">=3.11" resolution-markers = [ - "python_full_version >= '3.12'", - "python_full_version < '3.12'", + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] + +[[package]] +name = "absl-py" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/1d/58e2b5a6e4d703ccb2a029943d665974cb3d5a4fb2b3e3675dd03a9df10e/absl_py-2.5.1.tar.gz", hash = "sha256:286e71c82c1a38e75bbcf185f9b37d0305ad7786535107cb49bf4df9ff2e1f95", size = 118387, upload-time = "2026-10-09T08:38:58.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/7d/01e62f59e4166af1be6238d9f2b7f3453630c51b8044b412d05b5606532a/absl_py-2.5.1-py3-none-any.whl", hash = "sha256:721200f2f0e9960f2ca9dc3a2a706b201f5f75d812c158f059cbbe29eeafbdb8", size = 137673, upload-time = "2026-10-09T08:38:56.629Z" }, ] [[package]] @@ -117,6 +133,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/03/f5/410ff24a49dd645f651732f45e466cbb73f4bb73d1c54eaa5a07b832b0a2/hypothesis-6.170.15-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:d25e9a3f92e9f824bb110679506ece2b8fd7d093f1fa7d819ca46278a681a1f1", size = 692539, upload-time = "2026-11-06T09:53:30.812Z" }, ] +[[package]] +name = "immutabledict" +version = "4.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1d/e6/718471048fea0366c3e3d1df3acfd914ca66d571cdffcf6d37bbcd725708/immutabledict-4.3.1.tar.gz", hash = "sha256:f844a669106cfdc73f47b1a9da003782fb17dc955a54c80972e0d93d1c63c514", size = 7806, upload-time = "2026-02-15T10:32:34.668Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/ce/f9018bf69ae91b273b6391a095e7c93fa5e1617f25b6ba81ad4b20c9df10/immutabledict-4.3.1-py3-none-any.whl", hash = "sha256:c9facdc0ff30fdb8e35bd16532026cac472a549e182c94fa201b51b25e4bf7bf", size = 5000, upload-time = "2026-02-15T10:32:33.672Z" }, +] + [[package]] name = "iniconfig" version = "2.3.1" @@ -180,6 +205,9 @@ version = "0.1.0" source = { editable = "." } [package.optional-dependencies] +cp-sat = [ + { name = "ortools" }, +] validate = [ { name = "shapely" }, ] @@ -189,6 +217,7 @@ dev = [ { name = "hypothesis" }, { name = "jsonschema" }, { name = "maturin" }, + { name = "ortools" }, { name = "pyright" }, { name = "pytest" }, { name = "ruff" }, @@ -196,14 +225,18 @@ dev = [ ] [package.metadata] -requires-dist = [{ name = "shapely", marker = "extra == 'validate'", specifier = ">=2.0" }] -provides-extras = ["validate"] +requires-dist = [ + { name = "ortools", marker = "extra == 'cp-sat'", specifier = ">=9.10" }, + { name = "shapely", marker = "extra == 'validate'", specifier = ">=2.0" }, +] +provides-extras = ["validate", "cp-sat"] [package.metadata.requires-dev] dev = [ { name = "hypothesis", specifier = ">=6.100" }, { name = "jsonschema", specifier = ">=4.20" }, { name = "maturin", specifier = ">=1.9,<2" }, + { name = "ortools", specifier = ">=9.10" }, { name = "pyright", specifier = ">=1.1.400" }, { name = "pytest", specifier = ">=8" }, { name = "ruff", specifier = ">=0.9" }, @@ -224,7 +257,9 @@ name = "numpy" version = "2.4.6" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version < '3.12'", + "python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" } wheels = [ @@ -306,7 +341,12 @@ name = "numpy" version = "2.5.4" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.12'", + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'emscripten'", + "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/95/b0/c7453d0b6e2073c3264468b106ee1563750cecc910965e67357e3698c83e/numpy-2.5.4.tar.gz", hash = "sha256:9a94cf751c9ad8ebaa835bcd3d40dacf8534ad086b88c38029b65123c7999d2a", size = 20866315, upload-time = "2026-10-10T20:05:31.422Z" } wheels = [ @@ -377,6 +417,46 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/48/7f/c2d1b436b6e7cfebac140c2579a298344b85f2991a2ce5c3615cefb29400/numpy-2.5.4-cp315-cp315t-win_arm64.whl", hash = "sha256:7a14a461d9340f1b46b8648578aed9cdb8b3b018a8fac6c1dde2c9192a01a87f", size = 10883718, upload-time = "2026-10-10T20:05:28.547Z" }, ] +[[package]] +name = "ortools" +version = "9.15.6755" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "absl-py" }, + { name = "immutabledict" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "pandas" }, + { name = "protobuf" }, + { name = "typing-extensions" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/16/a08369f1d2022b5aea8d9ceede08df417622015447b817019e11ef4a1d9b/ortools-9.15.6755-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:55e291560d2fdb9590656cbee06ba99ee7f2476bd7d316ff757eeab33e9b20d6", size = 23886068, upload-time = "2026-01-14T15:38:55.095Z" }, + { url = "https://files.pythonhosted.org/packages/62/0f/302f019d08ec5870fae6d0d2075d2fbcef2f39ef8104d2ae6563b2c7a0b5/ortools-9.15.6755-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e51ae55569650e5381fd6e50c655ccf6368a9532f5720ea41396bb90e0247a21", size = 21910495, upload-time = "2026-01-14T15:38:58.429Z" }, + { url = "https://files.pythonhosted.org/packages/e2/0a/aca166f878189acadaadb43d6f97aab1288a082947e7aeb56d866915daed/ortools-9.15.6755-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c3bcccd15ef3fc6ac10bfa11630ba6dfe437d4fd1374a5b33f4773b7fee0f877", size = 27649965, upload-time = "2026-01-14T15:37:50.311Z" }, + { url = "https://files.pythonhosted.org/packages/0a/7c/8c732ddea429ad009553ee278f9a4aacb1e8b950a76647c36514d5619a1d/ortools-9.15.6755-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7a85a68ffb3fc1967e78624f40d3707aae459e82e3f2d9fe02e91788b3c7bf2a", size = 29821193, upload-time = "2026-01-14T15:37:53.961Z" }, + { url = "https://files.pythonhosted.org/packages/a3/30/2574d469613b8fe14664ffc7b01887a0afa385f6052bb8a1194e3df15e4a/ortools-9.15.6755-cp311-cp311-win_amd64.whl", hash = "sha256:781fb09d6c9f46015291f706bd7c7e0815db1bec6e92c74716342fb7ea2d0532", size = 23861559, upload-time = "2026-01-14T15:39:42.166Z" }, + { url = "https://files.pythonhosted.org/packages/6a/fc/9fa53f1a13710e6183df4d00fe4988c79a55b501e282645d49f1e250437f/ortools-9.15.6755-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:ae1c6e1fd844b4d756b22eb6c0ed574ea4342ee206d807c4f903039e748228fa", size = 23926322, upload-time = "2026-01-14T15:39:01.626Z" }, + { url = "https://files.pythonhosted.org/packages/f1/b6/7e6618ef7a88e8eb706a8a876806b4d336f1bef8c574f8a02d2da3e483ef/ortools-9.15.6755-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e16686c2b457fa6242c474ab890ee1712347ab53678e0d2fab307ae03e97a4b", size = 21912940, upload-time = "2026-01-14T15:39:04.403Z" }, + { url = "https://files.pythonhosted.org/packages/86/a9/37cb31fc5ffbec2650ebb0d2538a83842b5693a788a0ec6057559dab1169/ortools-9.15.6755-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3cd6bec0a2e00e3891a53e3b436f45a1000269f302085572f49e9856b7f8eaf0", size = 27646561, upload-time = "2026-01-14T15:37:57.414Z" }, + { url = "https://files.pythonhosted.org/packages/49/0f/6d6d722102a0ceccf4a5038e2bc91d023da84a6dba98482a4634df3d27ab/ortools-9.15.6755-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:033836c0eb33bc72697a299e0caedbb25fc9d1cee0b13832d69cb30405f57b3e", size = 29838435, upload-time = "2026-01-14T15:38:01.047Z" }, + { url = "https://files.pythonhosted.org/packages/83/a2/5aaf12e34bcd47ae16e70ae81b5c7fbc209da0615c0b79a93c9a0b1cda02/ortools-9.15.6755-cp312-cp312-win_amd64.whl", hash = "sha256:487796301fd9dad55f9cf21f9313c834697f74306d1a59f002e152862f8eb1b5", size = 23883161, upload-time = "2026-01-14T15:39:45.104Z" }, + { url = "https://files.pythonhosted.org/packages/f1/53/e21c54ff10002cc2e2b9748012ffc324ec32ea4acdcc85e190a920ab2766/ortools-9.15.6755-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:27a10474e62c9dceed37cfa0e4845c5ffaf792138ebf5b61483771b96f1290b6", size = 23927705, upload-time = "2026-01-14T15:39:07.29Z" }, + { url = "https://files.pythonhosted.org/packages/ce/e6/f7019048ffdf41f8a1bff6815b2203cf7b9117ba9e26bf46c4585421d1c4/ortools-9.15.6755-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:076565b803c85c4f87863e0616f537dd37f99c03e6f092e4068404f7b425d2b0", size = 21914246, upload-time = "2026-01-14T15:39:10.584Z" }, + { url = "https://files.pythonhosted.org/packages/8d/ad/aaacd340918b03e22c42f6ae4a9c72aac09810b4b398e99a7eeee58d9c42/ortools-9.15.6755-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b85bd20259b146abce5e0721ce1bfd8fd273efc904216aa3be178c31b6d34057", size = 27646600, upload-time = "2026-01-14T15:38:04.79Z" }, + { url = "https://files.pythonhosted.org/packages/08/b9/28d5efb832190b6edfccc5a703e88e64779c1eda34a42ea96d03307236c0/ortools-9.15.6755-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ebd5aea00374e3aad7a78de59058aca5e871a26a3c385cd0860ef1d685d03c9a", size = 29838741, upload-time = "2026-01-14T15:38:07.945Z" }, + { url = "https://files.pythonhosted.org/packages/be/22/ab894b6f846b4b1a89795c1ba966834e56cac394c4cf2b72433909739982/ortools-9.15.6755-cp313-cp313-win_amd64.whl", hash = "sha256:caac1d48b967adb877da2abcaf82c28f0f908a7cc208a6a1bbe01bc69590816c", size = 23908100, upload-time = "2026-01-14T15:39:48.398Z" }, + { url = "https://files.pythonhosted.org/packages/a3/53/ada4146ae491d7798c6eb045d93135158c0b66030853c7cd9607768dda59/ortools-9.15.6755-cp313-cp313t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:82b4a8e6e4f9380b453ab5fa4382ea7ee91e628f9b8be89d9ad760b33fca3323", size = 27681510, upload-time = "2026-01-14T15:38:11.033Z" }, + { url = "https://files.pythonhosted.org/packages/32/e6/239e96912fc8c4e0e917e72ec413983bc042cd9a0b20c3c6a7e43fc3002b/ortools-9.15.6755-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2d1f2fb2088e8953ccb902e68ffd06032cce0c7dcf7268b6135f3b6c553ca52b", size = 29850935, upload-time = "2026-01-14T15:38:14.595Z" }, + { url = "https://files.pythonhosted.org/packages/53/ef/53a172ad12cf0d762b9a5af681b1f13f1b4105b38bf65c2b383d530ed97f/ortools-9.15.6755-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:acdf06a167933307608e7eba23a9490255933504df44c8de5f62c48656c29688", size = 23916963, upload-time = "2026-01-14T15:39:13.282Z" }, + { url = "https://files.pythonhosted.org/packages/13/54/ed73ec00369fb6d6c71049d62e4b7c87c918b61f86ddd55a11c20ada395e/ortools-9.15.6755-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1a0677270b0cd317a6b8dae42514264eaf5da5756c5bc7215eeea409424577df", size = 21923649, upload-time = "2026-01-14T15:39:16.831Z" }, + { url = "https://files.pythonhosted.org/packages/1c/e0/ac57dd43eaadd73748bb542b30912e16c7dbf3a75f393f69efb8a1a2f032/ortools-9.15.6755-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:899b92afe3f775ab5867b9a8aa2850f81f2d95232db9b4ceec3456d69e6b8528", size = 27657273, upload-time = "2026-01-14T15:38:18.375Z" }, + { url = "https://files.pythonhosted.org/packages/b2/e0/11144feb4ddadc491dc9d833d3a2080e6556245f912bebe2c0c7e174f2a1/ortools-9.15.6755-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7181183cdcafe2b0d83ca5505b65048c7953dc7b5ad479361dded607964cc1b3", size = 29843939, upload-time = "2026-01-14T15:38:21.457Z" }, + { url = "https://files.pythonhosted.org/packages/96/97/771515ba3a05da3903b7da55a190d9f88f36a08c4bf848852e0ea4e3a731/ortools-9.15.6755-cp314-cp314-win_amd64.whl", hash = "sha256:afabb869e5fabeb704bd8147b22bf8139dee042e55fabd0d447a996428009e0c", size = 24673633, upload-time = "2026-01-14T15:39:51.212Z" }, + { url = "https://files.pythonhosted.org/packages/46/99/0932d6d7d6ad326adf68f4ce9063ef07db7e9859859dddbcd200102aedff/ortools-9.15.6755-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9d07cddca201e25e2e219006a9d6cda10c7e9ee2c712c50d19d508f9ed8a888", size = 27682088, upload-time = "2026-01-14T15:38:25.174Z" }, + { url = "https://files.pythonhosted.org/packages/0e/4d/bd75961e2c82db69bb41dd2c4a82131ca580e997485be2d5f59f8d26f31e/ortools-9.15.6755-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:990838ad66a052e72a50e69da500878710e3420e91717fe88bf3071995caba9e", size = 29851493, upload-time = "2026-01-14T15:38:28.168Z" }, +] + [[package]] name = "packaging" version = "26.3" @@ -386,6 +466,77 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, ] +[[package]] +name = "pandas" +version = "3.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/17/ca/24c6bc92aca3d366146358e47f1d374c0e1a50763ef226fc71eff20a63fb/pandas-3.1.1.tar.gz", hash = "sha256:05fed3e3b7c99b226f160e29d7d6cb7ef39638c758cbfe42b3f24ba34f04b859", size = 5936163, upload-time = "2026-11-04T15:08:01.994Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/cb/b86de1e20580311aeec0fd8fe3b1c8b4e955c423f77c735066a57a32ae09/pandas-3.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:e30c12af3911e750b9c073e0bbc6460655753d0121c5d8c4a1d942462d45eee0", size = 11600479, upload-time = "2026-11-04T15:05:30.116Z" }, + { url = "https://files.pythonhosted.org/packages/2f/26/7d09df74cfc4e97f9b58ec17a9f15a3b53db41699e156a8ee37267ad94e8/pandas-3.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:78837bfc15a272896def947e9b47a671363f5291c5266105c68c06d6a1b0045e", size = 11163217, upload-time = "2026-11-04T15:05:33.542Z" }, + { url = "https://files.pythonhosted.org/packages/33/b8/f771130a0d12b7664c4427b6f4b8a5f5352029c31a0cc2876e3259a4ab6a/pandas-3.1.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:593fb29eb5e51ab77ee37bda7ab2232aa1077088af7b4acbd18ca2f43f6c02f5", size = 11752167, upload-time = "2026-11-04T15:05:36.219Z" }, + { url = "https://files.pythonhosted.org/packages/3a/a9/0770e9316611d45b9eb7bc5d1266a327b21d3c237fb288aa679ce419296e/pandas-3.1.1-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f1602f614bb83f443381dbcbb94c4ac764b2e50c8d6c965614c5cd83e328c47", size = 12356904, upload-time = "2026-11-04T15:05:38.583Z" }, + { url = "https://files.pythonhosted.org/packages/53/2a/c1d4846917260b6415d3ce2085928474554b237ccb0a62e56b027dc26a68/pandas-3.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f61231dec5cf7317b68e1933d342538e8e880055ddb4fdb380095ae77f714322", size = 12774924, upload-time = "2026-11-04T15:05:41.255Z" }, + { url = "https://files.pythonhosted.org/packages/85/85/5bcd7f17690c24b7db74e1fd63989298e2f7aa8925251408e351cee9d3cb/pandas-3.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2bfb3810c303fd084fb101bf11c4a2ce8228eb8e15e411801f1d5e6ea383ee4e", size = 13430820, upload-time = "2026-11-04T15:05:44.095Z" }, + { url = "https://files.pythonhosted.org/packages/69/7c/8da507fc9ef7218aba9f6d66be872e3db09d3d4aa4b540ad27885ad89f02/pandas-3.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:48066660db2f0d652b0f4df5743ca975e9b568043084c86e575b0eda648f7c64", size = 10981564, upload-time = "2026-11-04T15:05:46.677Z" }, + { url = "https://files.pythonhosted.org/packages/fe/2d/83c44ef37d16fdd2e076e5fd7270f506e9a3add0b3f9ee5b1d0845f26039/pandas-3.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:cf17a15b2b9d5d03888f94a50777b2c7c7502cd78063832866e1ce0be4ac8d85", size = 10309019, upload-time = "2026-11-04T15:05:49.006Z" }, + { url = "https://files.pythonhosted.org/packages/11/90/a0212e039b49c058e1286f57a9864c23a65d7be05195b8f22a783638fd33/pandas-3.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4ac114c27f10b8783a9c3bbf1b08a08494e1fafb17c2a0c8db54e06180874c01", size = 11590674, upload-time = "2026-11-04T15:05:51.818Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e2/dbcb8b3639358f49a723cbe7e9e505be378a981b5e5dbc403bca978b368a/pandas-3.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3b10ae67d301ea84d0969388557cf8b90ea7870def14fd743614bde890104163", size = 11173287, upload-time = "2026-11-04T15:05:54.207Z" }, + { url = "https://files.pythonhosted.org/packages/e4/f4/ef17ed877969e869a673a6506bb3ebb038b071af434a99e9bb610bb0bd97/pandas-3.1.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0f628bb9a4681695da1dcc04efef86bc8c67095300d8da928b9886259cb0dada", size = 11494640, upload-time = "2026-11-04T15:05:57.056Z" }, + { url = "https://files.pythonhosted.org/packages/0b/b6/f9c0c52f7a2fcd828e336dd143001b0bcbc1276c90187dfa104458528e2e/pandas-3.1.1-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:028490c8ac2e03e18c9b08b7f3612e149b03570209bcf741d23833a7a5377ab2", size = 12031410, upload-time = "2026-11-04T15:05:59.531Z" }, + { url = "https://files.pythonhosted.org/packages/4a/89/f19b6b9baf210d020e6694462158c3e7c813acf7e4252caf86defeab7a1e/pandas-3.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d15b83c79bafbce2cb7707f609dd0eb7c57545abcd3f93398e9272adee17f81a", size = 12511367, upload-time = "2026-11-04T15:06:02.31Z" }, + { url = "https://files.pythonhosted.org/packages/0f/dc/f414405c5971eacf2865125e6869b842b66e5cd2a80bc8b9d78836914ef9/pandas-3.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:255fab1fee49783494ec2e8fc5ed27bf896c5e05e9266826d4a9738bfd77d56c", size = 13109983, upload-time = "2026-11-04T15:06:04.653Z" }, + { url = "https://files.pythonhosted.org/packages/37/39/46c0cc0c270e084af94f112f958c338c3ef067be38d2cfa34fe7a7c8f110/pandas-3.1.1-cp312-cp312-pyemscripten_2024_0_wasm32.whl", hash = "sha256:6705575b65750e4494b4f9328eed8cb263b4b809984d4eeb8f492a3e804b0c53", size = 8092796, upload-time = "2026-11-04T15:06:07.051Z" }, + { url = "https://files.pythonhosted.org/packages/c8/35/54c22df9e6bdb0fa001da2b8855f997addafd9575f14f25c166a8ef96b6e/pandas-3.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:eef35cb3f07dbc8e10e298b8a55ee4aa04d6511f27d5277f13c3df45d3bbef5c", size = 10751076, upload-time = "2026-11-04T15:06:09.397Z" }, + { url = "https://files.pythonhosted.org/packages/03/e3/76e8a1131d819c6ef7a9f943f7f4148e0112e02a7a25815143c875aa9a10/pandas-3.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:f13731c5f3c610c4584dd4f80df0f1279c657a0b3eff32205cda5d541f5385cf", size = 10133045, upload-time = "2026-11-04T15:06:11.847Z" }, + { url = "https://files.pythonhosted.org/packages/f6/ee/2f6c4419fa2bf476ba2776c0fbae91e8bf6ab15c6b3e038d66da4d7824da/pandas-3.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:01bd1d4c5fc999324382d55499cef0f9cc7c1b09d91ae6dabe82f0237e43b3a0", size = 11612513, upload-time = "2026-11-04T15:06:14.21Z" }, + { url = "https://files.pythonhosted.org/packages/95/c0/6f818fd16987eba5ad77fcf8ba8a19e9cf19fad7df7f38ed61b933196d97/pandas-3.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:269716b079899a92953837d13ed215ef2d36dbf8dd3787faf617f1160a2f5062", size = 11189204, upload-time = "2026-11-04T15:06:17.012Z" }, + { url = "https://files.pythonhosted.org/packages/49/f7/5c2c9b7b3e3d08a8bc7f40e4e066d395d388c7b08b3788e6149a32e2f37a/pandas-3.1.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:57112bab44e336758121435cd01ccebc1e4fca56c28d95d7c03bf2418dedea6a", size = 11426801, upload-time = "2026-11-04T15:06:19.468Z" }, + { url = "https://files.pythonhosted.org/packages/79/c2/c8bc972d6dcba13910fc92b622420704a2f655dd6b01ed54269a1bf7c2d2/pandas-3.1.1-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:645fa00fd85cfced2d2c09dc116d3694f578501b1ce4899153fbe64788ecda98", size = 11978871, upload-time = "2026-11-04T15:06:21.974Z" }, + { url = "https://files.pythonhosted.org/packages/ac/35/69a3466b849afcf4d2b9a491e2e33264a34f5b201d74fcc3194c14c1c672/pandas-3.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:aafbba6ea1fb58f4e254823bf390f4efeced3b15ad4d06e86493ee0c22b35e7f", size = 12458201, upload-time = "2026-11-04T15:06:24.573Z" }, + { url = "https://files.pythonhosted.org/packages/d2/14/00f118829158f8b77f1f78434d6efafc4d65c16a2cca4f1b80c8a4e3f463/pandas-3.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dedc76bfbba83fe43734ba9229190b4a987f6263ad734726bb28b4ecb93f4bf7", size = 13040280, upload-time = "2026-11-04T15:06:27.522Z" }, + { url = "https://files.pythonhosted.org/packages/38/ef/15b6a24451e75f2d48931062f73a5ebbd00d86394d750699dbd8d6b159b6/pandas-3.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:6d84760cc1bd799440a66b4df2ceb7a508870f3b8b4d8dda21befd62779cd3b4", size = 10732758, upload-time = "2026-11-04T15:06:29.957Z" }, + { url = "https://files.pythonhosted.org/packages/27/f3/0b64bded0e8003ba54589e03896edffd7aea543949f3d3c654cd10225a92/pandas-3.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:1eb3cca75e64bb1c0aab36e74413ad319f2f102daee222db7019c68e4f30cab5", size = 10119360, upload-time = "2026-11-04T15:06:32.623Z" }, + { url = "https://files.pythonhosted.org/packages/29/0f/d9931577227ee434184eaa122b768bbc6fa03f07e181eecadd2ee9efdd95/pandas-3.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a5f29016e40682637b16acb96bd3327120c05d673c4f2d1961481728e6b0a4c4", size = 11676136, upload-time = "2026-11-04T15:06:35.089Z" }, + { url = "https://files.pythonhosted.org/packages/0a/da/a1077d57b531ab1123119d4117ddb78b6e039119b2ff7658cc53c6196636/pandas-3.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:862f6fbef3f05005d78df13ffd9c44606fdcb76af8748ab14c901f6181bf3789", size = 11268452, upload-time = "2026-11-04T15:06:37.595Z" }, + { url = "https://files.pythonhosted.org/packages/e0/13/becef2d3d8544ca4ad1d910414d24df87664566082db3529ffb65e7082ec/pandas-3.1.1-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf0cf825769b60f9a01a8ff77ed82cfca9ccf2609170814f8f00810f5eaeae71", size = 11547130, upload-time = "2026-11-04T15:06:40.763Z" }, + { url = "https://files.pythonhosted.org/packages/23/c3/dcf098d687f1f31c97b9c3869809fa2cdb6598039299167f6dfe0cf0c3a5/pandas-3.1.1-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:326459d8a9be11b5f48c7fc1d63e38ba7cfeaebe5d41bd19e4c5f4f11dc9ac91", size = 12029794, upload-time = "2026-11-04T15:06:43.68Z" }, + { url = "https://files.pythonhosted.org/packages/59/70/0d0f9ebddae0a449af531858674a897d0902c12d95d154a6865bb3e42b68/pandas-3.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9c69786754f997cb401b98328678cfd9c7ac64bd111a27e305b44624fcaad5c2", size = 12576463, upload-time = "2026-11-04T15:06:46.31Z" }, + { url = "https://files.pythonhosted.org/packages/f5/ec/94125072c82e75ebd1c5a9fcb0bb0a778d3ac1cbc7f44b93bddacc0bfae0/pandas-3.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8e95649e97b925ac63204075233e395250d38ea4051d0540f32df9e08e557654", size = 13104015, upload-time = "2026-11-04T15:06:49.085Z" }, + { url = "https://files.pythonhosted.org/packages/c8/ea/c002d6c9ec0ab90b82eb4ff3d23816dc4e0ccf77821abb11bb78b9d9df1c/pandas-3.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:fdd87cf4d59a3c45f17af6ec965d0bd10b9f15e1b5082d2da11a577439551bcd", size = 10888164, upload-time = "2026-11-04T15:06:52.025Z" }, + { url = "https://files.pythonhosted.org/packages/0f/59/c5e10c034421175579e2375bcc43222a8d06d5440b1f5b09c80bf88ddd2d/pandas-3.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:42283f38afc154980f7a9c7964161ecc94de8c1bdebaf42528a18d40b556debd", size = 10287699, upload-time = "2026-11-04T15:06:54.519Z" }, + { url = "https://files.pythonhosted.org/packages/aa/e9/70433ed8a4ed227a35c41e68fd7ae0c516b5623eb003dbe13a6cf2138fed/pandas-3.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e3b7740decda762970df4b32edae1450630c77c10c5efb4c73a4437727dc7a5c", size = 12136868, upload-time = "2026-11-04T15:06:57.897Z" }, + { url = "https://files.pythonhosted.org/packages/08/d1/03a5eb23b0418c5724fd1659d225503ca0305da5683a080ab7eb089d692e/pandas-3.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:cbe426189f238bee1d05a5ebe11919db8302d397e31d61b10ca0f9a19c75f70e", size = 11735549, upload-time = "2026-11-04T15:07:00.623Z" }, + { url = "https://files.pythonhosted.org/packages/e9/43/c93e7487f34001aaaee1fdc9e20e3bc24adc017c72bd4e67503ec9c45799/pandas-3.1.1-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55eb3ed76e7f707786468c1cbf7bdf26f4cbed077487f09f0af474a302b9b079", size = 11414807, upload-time = "2026-11-04T15:07:03.377Z" }, + { url = "https://files.pythonhosted.org/packages/bf/c3/05a7b023e31c22137f3807a044c21da7255f5e233b32199842fb580a72c3/pandas-3.1.1-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211aabaf3f6aec76d87c69522a3e7b26f9e33cb9dc2336359a92b209de582899", size = 11869658, upload-time = "2026-11-04T15:07:05.963Z" }, + { url = "https://files.pythonhosted.org/packages/5c/b3/3cb6e73af148937766b7a68c93512707560058d817cc77f5931ce2995e0c/pandas-3.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:34e62b61a1e16e125239300f3503f54c4419eabe7df8a364f88cbda2ee289201", size = 12429463, upload-time = "2026-11-04T15:07:08.495Z" }, + { url = "https://files.pythonhosted.org/packages/f0/36/890746861b103d9da38b8b01317ad215f1495fe9bc2c7611f27d93917c46/pandas-3.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:42160e7f78b8a74df8c00e4f3a6010a47bba567fc514dc5029b5a722c2f37ef5", size = 12951459, upload-time = "2026-11-04T15:07:11.194Z" }, + { url = "https://files.pythonhosted.org/packages/70/b6/b3e0c6308d5ab92aa6a0c7f96020e8244bd77d87659343366c2c0e0ab84d/pandas-3.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:78978d0bf2fdb23f2eab1791abd685f03eb580f9247ab1583be8b74e4e270dbb", size = 11303679, upload-time = "2026-11-04T15:07:13.937Z" }, + { url = "https://files.pythonhosted.org/packages/7a/b3/2906768f0a40eccd37610b8bd6a4abd6938a89f01939bb2e22855085c4bb/pandas-3.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:f6c63d287fc2eddf698ebd3bd82089aba2dd4f520f6e4f341d28e125644a6137", size = 10634727, upload-time = "2026-11-04T15:07:16.571Z" }, + { url = "https://files.pythonhosted.org/packages/53/f9/ec5d115b70790acbe1623d72c0d0e50210efa415c27e3bfeb2f3d6067690/pandas-3.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:b80ff163f9d8af866c102976ef727e10a93b1ff04134eb356d3547bd42392857", size = 11668344, upload-time = "2026-11-04T15:07:19.401Z" }, + { url = "https://files.pythonhosted.org/packages/fd/63/084626245db789e30c816c19919c9f1fe69772effe86b24a2e8153632de2/pandas-3.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:1e13eb2650f438ee4acda9c50ab7692ea2bc2c5fd5959d1284c83bc7eb287e5e", size = 11260058, upload-time = "2026-11-04T15:07:22.095Z" }, + { url = "https://files.pythonhosted.org/packages/5c/9b/bdb3cbf0c4a8155f4f221752af2b8ea7fdd28d1f66f29c61f79eb57c7d02/pandas-3.1.1-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b71ab4607da4c1665f3db3bba62dfe7222f66a0ca353de0e2d9d934480dc19bf", size = 11541410, upload-time = "2026-11-04T15:07:24.74Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c1/85fbd576bfe7096260f4e2bd6883485a8e23a3783284712bed679c886731/pandas-3.1.1-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2b6f34c1fd341128317fd880aee0365020fd14be573c375fb4c72e63567c6ba4", size = 12028228, upload-time = "2026-11-04T15:07:27.541Z" }, + { url = "https://files.pythonhosted.org/packages/4f/ae/fcdb22a703b614d524ec7d002fb0631f5c44baae2d195a40f574d10a7aa0/pandas-3.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8603f29efe58c21729e57d2feb3e86f4c19378242e1e2aeece5f8c3807c421c6", size = 12564972, upload-time = "2026-11-04T15:07:30.486Z" }, + { url = "https://files.pythonhosted.org/packages/ad/6b/707e906369750d8b785ff188d93a897bf3bbd60db3617074d548054ceed0/pandas-3.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:9c6737e125607799df55584c682ff05db4ae4db09180e300448781b7e4448bca", size = 13097497, upload-time = "2026-11-04T15:07:33.198Z" }, + { url = "https://files.pythonhosted.org/packages/1d/fc/13d84a0b63f6e1c1374d3b455e5f54fae8a4ba69b873829d72c84de96ec4/pandas-3.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:07998b563a4e1ff2d6062ead5a7b145bb7f70096bbd428b7dc556672970ff0ed", size = 10880612, upload-time = "2026-11-04T15:07:36.083Z" }, + { url = "https://files.pythonhosted.org/packages/e3/df/eb01eb04fc58681afbfeeb51179d03c1ef14544e5257e107cb3312b9a98a/pandas-3.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:1983c990935a389b0d0d84f278a60ddfe5fcc5a9dc8a10e11a1e26b5d1220552", size = 10280721, upload-time = "2026-11-04T15:07:38.417Z" }, + { url = "https://files.pythonhosted.org/packages/75/8b/74ec73f8cca62692835d16ee80648d937cdf204427bf5b1a57fca991ea30/pandas-3.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:77c2f479cfd0bc76a6c2aeee74d5d8814864ebbee9d351dc5e3a1864e95edbc0", size = 12111709, upload-time = "2026-11-04T15:07:40.919Z" }, + { url = "https://files.pythonhosted.org/packages/66/35/5a21b5ae27f8dac664938ba41ca506db46988df8fc98c6f3f27534bff431/pandas-3.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:560614c776ea303182708c5ad6ad7e5350645b90ca96f9b955773453622885e0", size = 11710870, upload-time = "2026-11-04T15:07:43.715Z" }, + { url = "https://files.pythonhosted.org/packages/db/e7/47cbfb78ff93f5fb5dfe8d930059749f7e1df0d40d12ee7d30c9006e4c89/pandas-3.1.1-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:408067fdb3fcc794836bbcb320d4f15d546f39638156e00b5a2dd6616ee0f388", size = 11382425, upload-time = "2026-11-04T15:07:46.479Z" }, + { url = "https://files.pythonhosted.org/packages/ec/10/a6e8b8f7b76b144857fe3c1c8afabcfb261c682e43b8d39c15d1dcdb46a5/pandas-3.1.1-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b826e9052502570cd4449aeb0209bcc01e4c25baf774678ddeca225a92302359", size = 11854999, upload-time = "2026-11-04T15:07:49.158Z" }, + { url = "https://files.pythonhosted.org/packages/52/73/e48611971651d165154595ce4008090863293ed6e5d8b6068881d672757e/pandas-3.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:198a8ee3276344a99bb2b05e0a92380b1d5f51469a193b8dcac7cfd1b34af23e", size = 12395695, upload-time = "2026-11-04T15:07:52.134Z" }, + { url = "https://files.pythonhosted.org/packages/4b/1a/01d622913e6a65d447eb9a42d1ed71d2a50c4244de24091128aaab023875/pandas-3.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:daf86c882e376ae2a8a459b2f769258d2b6d75e09f6327440cf6eb8d425c5ceb", size = 12913291, upload-time = "2026-11-04T15:07:54.651Z" }, + { url = "https://files.pythonhosted.org/packages/69/73/76b46776b10c6ff7c2037e3748eeb713df8391a34b7768efa81a08c2a77a/pandas-3.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:f89fb8e88cc5791995cc076c526eac605adc157b6ac6cc619a33ddd0b8bf5871", size = 11273592, upload-time = "2026-11-04T15:07:57.141Z" }, + { url = "https://files.pythonhosted.org/packages/08/ab/cce173d73200410f06306a89dbbb5f2125bd64f66ca5eff393d53d813288/pandas-3.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:4e6f9a3036fc6a40c5ba00efe4092a45844212bdb6a63eda4ad5a5a4c8da45eb", size = 10604158, upload-time = "2026-11-04T15:07:59.733Z" }, +] + [[package]] name = "pluggy" version = "1.7.0" @@ -395,6 +546,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, ] +[[package]] +name = "protobuf" +version = "6.33.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/66/70/e908e9c5e52ef7c3a6c7902c9dfbb34c7e29c25d2f81ade3856445fd5c94/protobuf-6.33.6.tar.gz", hash = "sha256:a6768d25248312c297558af96a9f9c929e8c4cee0659cb07e780731095f38135", size = 444531, upload-time = "2026-03-18T19:05:00.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/9f/2f509339e89cfa6f6a4c4ff50438db9ca488dec341f7e454adad60150b00/protobuf-6.33.6-cp310-abi3-win32.whl", hash = "sha256:7d29d9b65f8afef196f8334e80d6bc1d5d4adedb449971fefd3723824e6e77d3", size = 425739, upload-time = "2026-03-18T19:04:48.373Z" }, + { url = "https://files.pythonhosted.org/packages/76/5d/683efcd4798e0030c1bab27374fd13a89f7c2515fb1f3123efdfaa5eab57/protobuf-6.33.6-cp310-abi3-win_amd64.whl", hash = "sha256:0cd27b587afca21b7cfa59a74dcbd48a50f0a6400cfb59391340ad729d91d326", size = 437089, upload-time = "2026-03-18T19:04:50.381Z" }, + { url = "https://files.pythonhosted.org/packages/5c/01/a3c3ed5cd186f39e7880f8303cc51385a198a81469d53d0fdecf1f64d929/protobuf-6.33.6-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:9720e6961b251bde64edfdab7d500725a2af5280f3f4c87e57c0208376aa8c3a", size = 427737, upload-time = "2026-03-18T19:04:51.866Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/b3c01fdec7d2f627b3a6884243ba328c1217ed2d978def5c12dc50d328a3/protobuf-6.33.6-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:e2afbae9b8e1825e3529f88d514754e094278bb95eadc0e199751cdd9a2e82a2", size = 324610, upload-time = "2026-03-18T19:04:53.096Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ca/25afc144934014700c52e05103c2421997482d561f3101ff352e1292fb81/protobuf-6.33.6-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:c96c37eec15086b79762ed265d59ab204dabc53056e3443e702d2681f4b39ce3", size = 339381, upload-time = "2026-03-18T19:04:54.616Z" }, + { url = "https://files.pythonhosted.org/packages/16/92/d1e32e3e0d894fe00b15ce28ad4944ab692713f2e7f0a99787405e43533a/protobuf-6.33.6-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:e9db7e292e0ab79dd108d7f1a94fe31601ce1ee3f7b79e0692043423020b0593", size = 323436, upload-time = "2026-03-18T19:04:55.768Z" }, + { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, +] + [[package]] name = "pygments" version = "2.21.0" @@ -433,6 +599,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, ] +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + [[package]] name = "referencing" version = "0.37.0" @@ -699,3 +877,12 @@ sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3 wheels = [ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +]