diff --git a/CHANGELOG.md b/CHANGELOG.md index fd88afa..eb7c883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,54 @@ What changed in `packvium` on crates.io, release by release. The format follows [Keep a Changelog](https://keepachangelog.com/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.5.0] + +Every error names a closed code. A misspelt configuration key is now refused (see *Fixed*). + +### Added + +- **`pack_json_with(input, ExecutionOptions)`.** `pack_json` with explicit execution options; + `ExecutionOptions { parallel: false }` runs independent search starts in sequence. The + answer is the same either way. +- **`PackError::code()`** — the machine-readable code of every variant: `invalid_input`, + `invalid_request`, `invalid_fixed_placement`, `unsupported_feature`, `unsupported_unit`, + `invalid_number`, `solution_failed_validation`, `time_limit`. Branch on it instead of on the + message. +- **`PackError::request_error()`** — the `RequestError` behind `invalid_request` and + `invalid_fixed_placement`, with its `reason()` and JSON Pointer `field()`, when there is one. + +### Changed + +- **Up to 41% faster on beam searches, same results.** The collision index keeps its cells in a + flat array instead of a tree and sizes each query's result once. Measured: beam requests 41% + faster, a 60-item order 34%, a 250-item order 18%, peak memory within 4%. Every result is + byte-identical. +- **`pack_nested` chains levels.** A level whose request lists no items packs the previous + level's containers, one item each; it is not run after a level that left something unpacked. + A level that lists its own items runs on them as before. A non-zero `beam_width` now sets + every level's `container_plan_beam_width`; it was ignored. + +### Fixed + +- **`quality` with `minimum_support_ratio` answers instead of failing.** The homogeneous block + solver ran even when the request asked for support, and a block set on a smaller one + overhangs it, so the request ended in `solution_failed_validation`. Such a request is now + left to the per-item search. A block answer also reports the support each item really has; + it wrote `support_ratio` 1.0 for every item. +- **A misspelt `configuration` key is refused.** A key the request schema does not declare in + `configuration` or its `effort_budget` (`profile` for `solver_profile`, `top_k` for + `alternatives`) was silently ignored, so the request ran on defaults. `pack_json` now returns + `PackError::InvalidRequest` with reason `not_allowed` and the key's pointer, for example + `/configuration/profile`. `parallel`, which this engine read although the schema never + declared it, is refused too; pass `ExecutionOptions { parallel: false }` to `pack_json_with` + to run search starts in sequence. +- **An item that fits no orientation no longer spends the exact search's budget.** One such + item made a scene solved in about 1 ms run to its whole budget (2.7 s and `effort_limit` at + 1M); it is now set aside before the search, which finishes in about 1 ms. Placements are + unchanged. +- **An unknown `objective` or access direction is refused with its pointer** (`not_allowed`), + and refusal messages match the documentation. + ## [1.4.0] Replanning a job that has already started, a beam search that no longer trades memory for diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000..9992097 --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,25 @@ +cff-version: 1.2.0 +message: "If you use Packvium in your research, please cite it as below." +title: "Packvium for Rust" +type: software +authors: + - name: "Packvium contributors" + website: "https://packvium.com" +version: "1.5.0" +license: MIT +url: "https://packvium.com" +repository-code: "https://github.com/toxakara/packvium-rust" +repository-artifact: "https://crates.io/crates/packvium" +abstract: >- + Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results. +keywords: + - 3d-bin-packing + - bin-packing + - 3d-packing + - cartonization + - container-loading + - pallet-packing + - truck-loading + - packing-algorithm + - logistics + - deterministic diff --git a/Cargo.toml b/Cargo.toml index 1d9d51d..e551477 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,15 +1,15 @@ [package] name = "packvium" -version = "1.4.0" +version = "1.5.0" edition = "2024" rust-version = "1.88" license = "MIT" -description = "Deterministic, extensible 3D cartonization and rectangular bin-packing engine" +description = "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results." readme = "README.md" repository = "https://github.com/toxakara/packvium-rust" homepage = "https://packvium.com" -documentation = "https://docs.rs/packvium" -keywords = ["3d-bin-packing", "cartonization", "packaging", "container-loading", "logistics"] +documentation = "https://packvium.com/docs" +keywords = ["3d-bin-packing", "bin-packing", "3d-packing", "cartonization", "container-loading"] categories = ["algorithms", "mathematics", "data-structures"] authors = ["Packvium contributors"] diff --git a/README.md b/README.md index 8706281..79b184c 100644 --- a/README.md +++ b/README.md @@ -1,112 +1,170 @@ # Packvium for Rust -Deterministic 3D cartonization and rectangular bin packing. No unsafe code, no runtime -dependencies beyond `serde`, exact integer geometry. +Deterministic 3D cartonization and rectangular bin packing with exact integer geometry. +No `unsafe` code. Five runtime dependencies: `serde`, `serde_json`, `sha2` (the digests that +chain plan revisions), `thiserror` and `web-time` (a clock that also works in WebAssembly). + +Use it to pick the smallest carton for an order, build a pallet, load a shipping container, +or load a truck within its axle ratings and delivery-stop order. Every answer comes back as +coordinates and rotations for each item, with a reason for anything that did not fit. Full documentation, the constraint reference and benchmarks live at [packvium.com](https://packvium.com). -> **Version 1.4.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.5.0 — the public API is frozen.** Field names, status codes and the > objective vector do not change without a major version, so any `1.x` is a safe upgrade > from any earlier `1.x`. -> Read [docs/GUARANTEES.md](docs/GUARANTEES.md) before relying on a result. +> Read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-rust/blob/main/docs/GUARANTEES.md) +> before relying on a result. ```toml [dependencies] -packvium = "1.0" +packvium = "1.5" ``` ## Quick start -The crate's API is a JSON contract — one request in, one result out — the same contract -every language binding built on this engine speaks: +The crate speaks a JSON contract — one request in, one result out — the same contract every +Packvium package speaks, so a request built here packs the same way in Python, PHP or Node.js: ```rust -let request = r#"{ - "items": [ - {"id": "book", "quantity": 4, - "dimensions": {"length": "210", "width": "140", "height": "30"}} - ], - "containers": [ - {"id": "box", "inner_dimensions": {"length": "400", "width": "300", "height": "250"}} - ] -}"#; - -let result = packvium_core::pack_json(request)?; +fn main() -> Result<(), Box> { + let request = r#"{ + "units": {"length": "mm"}, + "configuration": { + "time_limit_ms": 60000, + "effort_budget": {"max_search_nodes": 1000000} + }, + "items": [ + {"id": "book", "quantity": 4, "weight": "650 g", + "dimensions": {"length": "210", "width": "140", "height": "30"}} + ], + "containers": [ + {"id": "box", "inner_dimensions": {"length": "400", "width": "300", "height": "250"}} + ] + }"#; + + let result = packvium_core::pack_json(request)?; + println!("{result}"); + Ok(()) +} ``` -`use packvium_core::...` is correct even though the package is `packvium` in -`Cargo.toml` — that is the crate's own internal name, kept stable across the release. +The package is `packvium` in `Cargo.toml`, and the library is `packvium_core` in code — the +crate's own name, kept stable across releases. + +The result is JSON text. Read it with `serde_json` into your own `#[derive(Deserialize)]` +structs, naming only the fields you use; [`basic.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/basic.rs) +does exactly that. Every length and weight comes back as exact integer `ticks` beside a +rendered decimal `value`: compute with the ticks, print the value. + +## Examples + +Runnable, each a single file you can read top to bottom: ```bash cargo run --example basic ``` +| File | What it shows | +| --- | --- | +| [`basic.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/basic.rs) | An order into a carton, read back into typed structs; an item that cannot fit, and why. | +| [`constraints.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/constraints.rs) | Rotations and keep-upright, stacking limits and top load, support ratio and incompatible tags — each shown with and without the rule. | +| [`objectives.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/objectives.rs) | The six objectives, and the scenes where two of them pick different containers. | +| [`units.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/units.rs) | What you can type (fractions, inches, pounds), why nothing is a float, and exact fits. | +| [`errors.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/errors.rs) | Branching on a refused request with `code()`, `reason()` and `field()`, and why an item that does not fit is not an error. | +| [`trucking.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/trucking.rs) | A delivery van: stops unloaded in route order through a named door, and axle loads kept inside their ratings. | +| [`nested.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/nested.rs) | Mugs and plates into cartons, cartons onto a pallet, with the typed `PackingRequest` API and `pack_nested`. | +| [`execution.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/execution.rs) | A result turned into a numbered work order, with a safe loading order computed from the placed geometry. | +| [`reproducibility.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/reproducibility.rs) | `effort_budget` against `time_limit_ms`: the same answer on every run and every machine. | +| [`shapes.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/shapes.rs) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, and a cushion that compresses under load until the crush limit refuses it. | +| [`commerce.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/commerce.rs) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | +| [`artifacts.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/artifacts.rs) | Hand a result to a system with no engine: one document with the plan, geometry and the request that produced it, exported as CSV and a printable HTML work order — byte-identical to the other three engines. | +| [`revisions.rs`](https://github.com/toxakara/packvium-rust/blob/main/examples/revisions.rs) | Replan a half-loaded job: a missing item and a locked placement recorded against the approved plan, a replan that keeps the locked item in place, and a hash-chained record that notices an edit — the same revision bytes as the other three engines. | + ## Errors +There are two kinds of failure, and only one of them is an `Err`. + A request that no engine may answer returns `PackError::InvalidRequest(RequestError)` before anything is solved. It names the problem instead of describing it: ```rust use packvium_core::PackError; -match packvium_core::pack_json(&request) { - Ok(result) => println!("{result}"), - Err(PackError::InvalidRequest(error)) => { - error.code(); // "invalid_request" - error.reason(); // "below_minimum" - error.field(); // "/items/0/quantity" -- a JSON Pointer into your request - // Display: "invalid_request: /items/0/quantity: must be at least 1" +fn pack(request: &str) -> Result { + match packvium_core::pack_json(request) { + Ok(result) => Ok(result), + Err(PackError::InvalidRequest(error)) => { + // error.code() -> "invalid_request" + // error.reason() -> "below_minimum" + // error.field() -> "/items/0/quantity", a JSON Pointer into your request + // Display -> "invalid_request: /items/0/quantity: must be at least 1" + Err(format!("{} at {}: {error}", error.reason(), error.field())) + } + // `PackError` is `#[non_exhaustive]`, so keep a wildcard arm. + Err(other) => Err(format!("{}: {other}", other.code())), } - Err(other) => eprintln!("{other}"), } ``` -`reason()` is one of `missing_field`, `wrong_type`, `below_minimum`, `above_maximum`, `negative_measure`, `invalid_unit`, `duplicate_id`, `not_allowed` or `invalid_value`. `PackError` is `#[non_exhaustive]`, so keep a wildcard arm. -The message is the same in every Packvium engine. Branch on `reason` and `field`; show the -message to a person. A request that is valid but does not fit completely is not an error: the -result lists what was left out, and why, in `unpacked_items`. +`reason()` is one of `missing_field`, `wrong_type`, `below_minimum`, `above_maximum`, +`negative_measure`, `invalid_unit`, `duplicate_id`, `not_allowed` or `invalid_value`. A fixed +placement that is malformed or cannot hold has the code `invalid_fixed_placement` and the +reason `malformed` or `cannot_hold`. -## Examples +Every `PackError` has `code()`, one closed string per kind of refusal: `invalid_request`, +`invalid_fixed_placement`, `invalid_input`, `unsupported_feature`, `unsupported_unit`, +`invalid_number`, `solution_failed_validation` or `time_limit`. Branch on the code, the reason +and the field; show the message to a person. The message is the same text in every Packvium +engine. -Runnable, in [`examples/`](examples). Each one is a single file you can read top to bottom -and execute without a project around it. +A request that is valid but does not fit completely is not an error. The result lists what was +left out, and why, in `unpacked_items`, and `packvium_core::explain_reason` turns each reason +code into a sentence. -| File | What it shows | -| --- | --- | -| [`basic.rs`](examples/basic.rs) | The smallest useful call: items in, placements out. | -| [`shapes.rs`](examples/shapes.rs) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, and a cushion that compresses under load until the crush limit refuses it. | -| [`pack-stdin.rs`](examples/pack-stdin.rs) | Read a shared-contract request on stdin and write the result to stdout. | -| [`commerce.rs`](examples/commerce.rs) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | -| [`commerce-stdin.rs`](examples/commerce-stdin.rs) | The same three functions over stdin/stdout. | -| [`artifacts.rs`](examples/artifacts.rs) | Hand a result to a system with no engine: one document with the plan, geometry and the request that produced it, exported as CSV and a printable HTML work order — byte-identical to the other three engines. | -| [`revisions.rs`](examples/revisions.rs) | Replan a half-loaded job: a missing item and a locked placement recorded against the approved plan, a replan that keeps the locked item in place, and a hash-chained record that notices an edit — the same revision bytes as the other three engines. | +## Determinism -```bash -cargo run --example basic -``` +The same request gives the same placements: the only randomness is seeded from the request's +`seed`, and no result depends on hash-map order. The one way to lose that is the wall clock: `time_limit_ms` stops the search when a +clock says so, and how far a search gets in that time depends on the machine and its load. + +To get the same answer on every run and every host, bound the search by counted work with +`configuration.effort_budget` (`max_candidates_evaluated`, `max_placement_attempts`, +`max_search_nodes`, `max_restarts`) and set `time_limit_ms` far above what that budget needs, +as a fuse against a genuine hang. A search stopped by the budget says `effort_limit` in +`termination.code` and is still reproducible; one stopped by the clock says `time_limit`, and +an operational artifact built from it records its replay as `not_guaranteed`. `seed` is part +of the request, so a different seed is a different, equally reproducible request. ## What it does - **Exact arithmetic.** Length is measured in ticks of 1/16000 mm and weight in 1/8 µg. No coordinate is ever a float, so no placement decision depends on rounding. - **Real constraints.** Weight and payload limits, permitted rotations, keep-upright, - floor-only, non-stackable, top-load limits, minimum support ratio, tag incompatibility, - clearance and rectangular obstacles. + floor-only, non-stackable, stack-count and top-load limits, minimum support ratio, tag + incompatibility, clearance and rectangular obstacles; and for vehicles, route order by + `stop_index`, unloading doors by `access_directions`, and two-axle load limits. +- **Six objectives.** Fewest containers, packaging cost, carrier-billable weight, carrier + rate cards, open-dimension height and value kept — each a vector of exact integers. - **A solver portfolio, not one algorithm.** Regular-grid, layer, extreme-point, maximal-space and bounded exact search, selected by problem shape and profile. - **Answers you can check.** Every solution is re-validated by logic independent of the search. Unplaced items come back with a reason code, not silently missing. -- **Deterministic.** The same input and seed produce the same result, always. -- **Multi-container and nested.** Split across containers, or pack containers into - containers. -- **Extensible.** Register your own constraints, item orderings, candidate scorers, - container selectors or complete solvers. +- **Multi-container and nested.** A request splits across as many containers as it needs; + `pack_nested` solves caller-defined levels — cartons, then pallets — in order; a level with no + items of its own packs the previous level's containers, and the chain stops at the first level + that cannot pack everything. +- **In-process extension points.** `SolverRegistry` accepts your own `PlacementConstraint`, + `CandidateScorer`, `ItemOrderStrategy` or `Solver` for a typed `PackingRequest`. They live in + your process only: nothing about them travels in the JSON contract, so a rule every caller + must honour belongs in the request as data instead. - **Work orders and portable artifacts.** `execution::build_plan_json` turns a result into - an operator's step list. `artifacts::build_artifact_json` wraps that plan with geometry, - display values and the request that produced it, and `artifact_exports` writes it as - canonical JSON, CSV or a self-contained HTML work order, byte for byte what the Python, - PHP and JavaScript packages write. + an operator's step list, with the loading order from `safe_loading_order`. + `artifacts::build_artifact_json` wraps that plan with geometry, display values and the + request that produced it, and `artifact_exports` writes it as canonical JSON, CSV or a + self-contained HTML work order, byte for byte what the Python, PHP and JavaScript packages + write. - **Items already in place, and replanning around them.** A request's `fixed_placements` pins items to known positions before the solve: they keep their place, carry weight and support, and come back marked `fixed: true`. `revisions` records what changed on the dock — a missing @@ -118,9 +176,10 @@ cargo run --example basic | Document | Covers | | --- | --- | -| [docs/GUARANTEES.md](docs/GUARANTEES.md) | What is promised and what is not. Start here. | -| [docs/PUBLIC-API.md](docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | -| [docs/UNITS-AND-NUMERICS.md](docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | +| [docs/GUARANTEES.md](https://github.com/toxakara/packvium-rust/blob/main/docs/GUARANTEES.md) | What is promised and what is not. Start here. | +| [docs/PUBLIC-API.md](https://github.com/toxakara/packvium-rust/blob/main/docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | +| [docs/UNITS-AND-NUMERICS.md](https://github.com/toxakara/packvium-rust/blob/main/docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | +| [docs/COMMERCE-API.md](https://github.com/toxakara/packvium-rust/blob/main/docs/COMMERCE-API.md) | Carrier rating, eligibility rules and catalog versions. | ## Requirements @@ -129,7 +188,9 @@ Rust 1.88 or newer (edition 2024). ## The Packvium family One request and result contract, implemented independently in four engines (Rust, -Python, PHP, JavaScript) and held to identical placements on a shared fixture set. +Python, PHP, JavaScript) and checked against each other on a shared fixture set: every +engine's answer is independently validated, and none may score below the agreed floor for +a fixture. Engines may return different, equally valid arrangements for the same request. Pick the package for your stack; mixing them in one system is safe. Documentation, the constraint reference and the benchmarks are at @@ -139,7 +200,7 @@ Documentation, the constraint reference and the benchmarks are at | --- | --- | --- | | Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/toxakara/packvium-python) | | PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/toxakara/packvium-php) | -| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.0"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.5"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | | Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/toxakara/packvium-node) | | Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/toxakara/packvium-wasm) | | PHP FFI bridge — [`packvium/native-bridge`](https://packagist.org/packages/packvium/native-bridge) | `composer require packvium/native-bridge` | [packvium-php-bridge](https://github.com/toxakara/packvium-php-bridge) | @@ -147,9 +208,27 @@ Documentation, the constraint reference and the benchmarks are at ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md). Security reports go through the process in -[SECURITY.md](SECURITY.md), not public issues. +See [CONTRIBUTING.md](https://github.com/toxakara/packvium-rust/blob/main/CONTRIBUTING.md). +Security reports go through the process in +[SECURITY.md](https://github.com/toxakara/packvium-rust/blob/main/SECURITY.md), not public issues. + +## Citation + +If Packvium supports your research, cite it as software. GitHub's **Cite this repository** +button reads [`CITATION.cff`](https://github.com/toxakara/packvium-rust/blob/main/CITATION.cff), and +[`codemeta.json`](https://github.com/toxakara/packvium-rust/blob/main/codemeta.json) carries the same record in +CodeMeta form. + +```bibtex +@software{packvium_rust, + author = {{Packvium contributors}}, + title = {Packvium for Rust}, + version = {1.5.0}, + license = {MIT}, + url = {https://packvium.com} +} +``` ## License -MIT. See [LICENSE](LICENSE). +MIT. See [LICENSE](https://github.com/toxakara/packvium-rust/blob/main/LICENSE). diff --git a/codemeta.json b/codemeta.json new file mode 100644 index 0000000..4bc5765 --- /dev/null +++ b/codemeta.json @@ -0,0 +1,31 @@ +{ + "@context": "https://w3id.org/codemeta/3.0", + "@type": "SoftwareSourceCode", + "name": "Packvium for Rust", + "description": "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", + "version": "1.5.0", + "license": "https://spdx.org/licenses/MIT", + "author": [ + { + "@type": "Organization", + "name": "Packvium contributors", + "url": "https://packvium.com" + } + ], + "url": "https://packvium.com", + "codeRepository": "https://github.com/toxakara/packvium-rust", + "issueTracker": "https://github.com/toxakara/packvium-rust/issues", + "programmingLanguage": "Rust", + "keywords": [ + "3d-bin-packing", + "bin-packing", + "3d-packing", + "cartonization", + "container-loading", + "pallet-packing", + "truck-loading", + "packing-algorithm", + "logistics", + "deterministic" + ] +} diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 11d9696..6f2b855 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -15,7 +15,9 @@ After a result reports `feasible` or `optimal` and passes independent validation 1/8 µg for weight. No coordinate is ever a binary floating-point number, so no placement decision depends on rounding; - **determinism** — identical input and identical seed produce an identical result, on - any platform and in any of the implementations; + any platform, when the search completes or stops on `configuration.effort_budget`. A + search stopped by `time_limit_ms` stops where the host's speed let it, so it may differ + between runs; the result says which limit stopped it; - **complete accounting** — every requested item instance appears exactly once, either placed or listed as unpacked with a reason code. @@ -31,9 +33,10 @@ After a result reports `feasible` or `optimal` and passes independent validation - **That your inputs are right.** Dimensions, weights and clearances are taken as given. Round item exteriors outward, container interiors inward, and clearance outward before you build the request. -- **Support for non-rectangular shapes.** Items and containers are rigid axis-aligned - cuboids; obstacles are rectangular. No cylinders, deformable bags, meshes or - irregular geometry. +- **Arbitrary shapes.** Containers are axis-aligned cuboids. An item is a cuboid, a convex + hull of vertices, or a cuboid that compresses by a declared ratio; obstacles are cuboids + or unions of them. Concave meshes, curved surfaces and free-form deformable bags are not + modelled — approximate them with a convex hull or a bounding cuboid. - **A result before the deadline.** With a time limit set, the search may return `time_limit` with a partial packing, or nothing placed at all. - **Full load propagation.** Top-load limits are enforced against what rests *directly* @@ -41,14 +44,15 @@ After a result reports `feasible` or `optimal` and passes independent validation ## Not modelled at all -Deformable goods, dynamic shipping physics, contact-load propagation through arbitrary -support graphs, pallet-overhang standards, axle loads, unloading-route optimization, and -carrier tariff or rating catalogs. None of these are built in, and none are approximated +Dynamic shipping physics, contact-load propagation through arbitrary support graphs, +pallet-overhang standards, and route optimization. Axle loads, the unloading order of a +given stop sequence (`stop_index`, `access_directions`) and carrier rate tables are +modelled; choosing the route itself is not. None of the unmodelled items is approximated silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.4.0` freezes the public API. Field names, status codes, the objective +Version `1.5.0` freezes the public API. Field names, status codes, the objective vector, the numeric policy and the validation rules do not change without a major version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde constraint on `1.0` is enough; an exact pin is no longer required. diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index 1badad2..272c4ee 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -8,7 +8,7 @@ One internal length tick is `1/16000 mm`. - `1 international inch = 25.4 mm = 406,400 ticks` - common fractional inches through at least `1/128 in` are exact integers -Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. Binary floating-point input is intentionally rejected by the Python API; PHP type declarations accept only integer/string/structured values. +Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. A binary float with a fractional part is intentionally rejected by the Python API, by `Length` and `Weight` alike (`TypeError`); an integral float such as `100.0` is exact, and is what JavaScript sends for `100`, so it is accepted as that integer. PHP type declarations accept only integer/string/structured values. ## Weight diff --git a/examples/basic.rs b/examples/basic.rs index b589a51..cfa212e 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -1,18 +1,157 @@ -//! Pack a handful of items into a container and print the result. +//! Pack an order into cartons and read the answer as Rust types. //! //! cargo run --example basic +//! +//! The engine speaks one JSON contract in every language: a request goes in as text and a +//! result comes out as text. In Rust you build the request with `serde_json::json!` and read +//! the result back into your own `#[derive(Deserialize)]` structs, naming only the fields +//! you use. Every length and weight arrives as a measure carrying exact integer `ticks` +//! beside a rendered decimal `value`, so you compute with the ticks and print the value. + +use packvium_core::{PackError, explain_reason}; +use serde::Deserialize; +use serde_json::json; + +/// The part of a packing result this program reads. Unknown fields are ignored, so a +/// result that gains a field later still deserializes. +#[derive(Debug, Deserialize)] +struct Outcome { + status: String, + complete: bool, + /// The objective vector: exact integers compared left to right, fewest unpacked first. + score: Vec, + termination: Fact, + containers: Vec, + unpacked_items: Vec, +} + +#[derive(Debug, Deserialize)] +struct Fact { + code: String, +} + +#[derive(Debug, Deserialize)] +struct PackedContainer { + id: String, + payload_weight: Measure, + volume_utilization: String, + placements: Vec, +} + +#[derive(Debug, Deserialize)] +struct Placement { + item_id: String, + orientation: String, + position: Position, +} -fn main() { - let request = r#"{ +#[derive(Debug, Deserialize)] +struct Position { + x: Measure, + y: Measure, + z: Measure, +} + +/// A length or a weight: `ticks` is the exact integer, `value` the same number rendered +/// in `unit` for a person. +#[derive(Debug, Deserialize)] +struct Measure { + ticks: i64, + value: String, + unit: String, +} + +#[derive(Debug, Deserialize)] +struct UnpackedItem { + item_id: String, + reason: String, +} + +fn main() -> Result<(), Box> { + let request = json!({ + "units": { "length": "mm" }, + "configuration": { + // Bound the search by counted work rather than by the clock, so the same request + // gives the same answer on a fast laptop and on a loaded CI runner. The generous + // time limit is only a safety fuse against a genuine hang. + "time_limit_ms": 60000, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }, "items": [ - {"id": "book", "quantity": 4, - "dimensions": {"length": "210", "width": "140", "height": "30"}} + { "id": "book", "quantity": 4, "weight": "650 g", + "dimensions": { "length": "210", "width": "140", "height": "30" } }, + { "id": "mug", "quantity": 2, "weight": "350 g", + "dimensions": { "length": "120", "width": "90", "height": "100" } }, + // Longer than the carton in every orientation, so it cannot ship in one. + { "id": "umbrella", "quantity": 1, "weight": "500 g", + "dimensions": { "length": "900", "width": "80", "height": "80" } } ], "containers": [ - {"id": "box", "inner_dimensions": {"length": "400", "width": "300", "height": "250"}} + { "id": "carton", "max_payload": "10 kg", + "inner_dimensions": { "length": "400", "width": "300", "height": "250" } } ] - }"#; + }); + + let text = match packvium_core::pack_json(&request.to_string()) { + Ok(text) => text, + // A request the engine refuses names the offending field; see the errors example. + Err(PackError::InvalidRequest(error)) => { + return Err(format!("fix {}: {}", error.field(), error.detail()).into()); + } + Err(other) => return Err(other.into()), + }; + let outcome: Outcome = serde_json::from_str(&text)?; + + println!("status: {}", outcome.status); + println!("complete: {}", outcome.complete); + println!("termination: {}", outcome.termination.code); + println!("score: {:?}", outcome.score); + + for container in &outcome.containers { + println!( + "\n{}: {} item(s), {} {} payload, {} of the volume used", + container.id, + container.placements.len(), + container.payload_weight.value, + container.payload_weight.unit, + container.volume_utilization, + ); + for placement in &container.placements { + let at = &placement.position; + println!( + " {:<10} {} at ({}, {}, {}) {}", + placement.item_id, + placement.orientation, + at.x.value, + at.y.value, + at.z.value, + at.x.unit, + ); + } + // Arithmetic belongs on ticks, never on the rendered decimals: the highest point + // any item's origin reaches, exactly. + let highest = container + .placements + .iter() + .map(|placement| placement.position.z.ticks) + .max() + .unwrap_or(0); + println!(" highest origin: {highest} ticks (1 mm = 16000 ticks)"); + } - let result = packvium_core::pack_json(request).expect("well-formed request"); - println!("{result}"); + // An item that does not fit is part of the answer, not an error. Each one carries a + // closed reason code, and `explain_reason` turns the code into a sentence. + for unpacked in &outcome.unpacked_items { + println!( + "\nnot packed: {} -- {}: {}", + unpacked.item_id, + unpacked.reason, + explain_reason(&unpacked.reason)? + ); + } + Ok(()) } diff --git a/examples/commerce-stdin.rs b/examples/commerce-stdin.rs deleted file mode 100644 index 0590c7a..0000000 --- a/examples/commerce-stdin.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Read a commerce case as JSON on stdin, write the canonical result on stdout. -//! -//! Mirrors the Python, PHP and JavaScript adapters so the cross-language commerce -//! conformance runner can drive all four implementations through one interface. -//! -//! cargo run -q -p packvium-core --example commerce-stdin < case.json -//! -//! A case is `{"operation": ..., "document": ..., "request": ...}`. An input error -//! exits non-zero with the message on stderr; a rejection is a normal result document -//! and exits zero, because a rejection is an answer. - -use std::io::{Read, Write}; - -use serde_json::{Value, json}; - -fn main() -> std::process::ExitCode { - let mut input = String::new(); - if let Err(error) = std::io::stdin().read_to_string(&mut input) { - eprintln!("commerce-stdin: cannot read stdin: {error}"); - return std::process::ExitCode::from(2); - } - let case: Value = match serde_json::from_str(&input) { - Ok(value) => value, - Err(error) => { - eprintln!("commerce-stdin: invalid JSON: {error}"); - return std::process::ExitCode::from(2); - } - }; - let call = - json!({"document": case.get("document"), "request": case.get("request")}).to_string(); - let outcome = match case.get("operation").and_then(Value::as_str) { - Some("quote") => packvium_core::commerce::quote_json(&call), - Some("evaluate_policy") => packvium_core::commerce::evaluate_policy_json(&call), - Some("catalog_version_info") => packvium_core::commerce::catalog_version_info_json(&call), - other => { - eprintln!("commerce-stdin: unknown operation {other:?}"); - return std::process::ExitCode::from(2); - } - }; - match outcome { - Ok(result) => { - let mut stdout = std::io::stdout(); - if stdout.write_all(result.as_bytes()).is_err() { - return std::process::ExitCode::from(2); - } - std::process::ExitCode::SUCCESS - } - Err(error) => { - eprintln!("commerce-stdin: input error: {error}"); - std::process::ExitCode::from(1) - } - } -} diff --git a/examples/constraints.rs b/examples/constraints.rs new file mode 100644 index 0000000..6cc75cb --- /dev/null +++ b/examples/constraints.rs @@ -0,0 +1,228 @@ +//! Constraints: how to say "this may not go there", and get told why. +//! +//! cargo run --example constraints +//! +//! Most real packing rules are refusals -- this side up, nothing on top of that, keep the +//! bleach away from the flour -- and the useful part of an answer is often the item that did +//! *not* fit and the reason it did not. Every rule below is a field on an item or a +//! container in the request. None needs code of your own, and none changes how you call +//! `pack_json`. +//! +//! Each rule is shown twice: the same goods in the same container, once without the rule and +//! once with it. A constraint you cannot watch change the answer is one you have to take on +//! faith. Often the rule does not refuse anything -- the solver satisfies it by opening +//! another container, which costs money and is the answer you wanted to see coming. + +use serde_json::{Value, json}; + +/// Counted work bounds the search, so the answer is the same on every host; the time limit +/// is only a safety fuse. +fn configuration() -> Value { + json!({ + "time_limit_ms": 60000, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }) +} + +fn pack(items: Value, containers: Value) -> Result> { + let request = json!({ + "units": { "length": "mm" }, + "configuration": configuration(), + "items": items, + "containers": containers, + }); + Ok(serde_json::from_str(&packvium_core::pack_json( + &request.to_string(), + )?)?) +} + +fn list(value: &Value) -> &[Value] { + value.as_array().map_or(&[], Vec::as_slice) +} + +fn text(value: &Value) -> &str { + value.as_str().unwrap_or_default() +} + +/// The reason code as a sentence, or the bare code for one this version cannot phrase. +fn explain(reason: &str) -> String { + packvium_core::explain_reason(reason).map_or_else(|_| reason.to_owned(), str::to_owned) +} + +fn print_refusals(result: &Value) { + for unpacked in list(&result["unpacked_items"]) { + println!( + " {} -- {}: {}", + text(&unpacked["item_id"]), + text(&unpacked["reason"]), + explain(text(&unpacked["reason"])) + ); + } +} + +/// Pack the same goods with and without one rule, and print what the rule changed. +fn compare( + rule: &str, + without: Value, + with_rule: Value, + containers: &Value, +) -> Result<(), Box> { + println!("\n{rule}"); + for (label, items) in [ + ("without the rule", without), + ("with the rule ", with_rule), + ] { + let result = pack(items, containers.clone())?; + let containers_used = list(&result["containers"]); + let placed: usize = containers_used + .iter() + .map(|container| list(&container["placements"]).len()) + .sum(); + println!( + " {label}: {} container(s), {placed} placed, {} refused", + containers_used.len(), + list(&result["unpacked_items"]).len() + ); + print_refusals(&result); + } + Ok(()) +} + +fn item(id: &str, length: &str, width: &str, height: &str, weight: &str) -> Value { + json!({ "id": id, "quantity": 1, "weight": weight, + "dimensions": { "length": length, "width": width, "height": height } }) +} + +/// `item` with extra fields merged in: the rule under test, or a quantity. +fn with(mut base: Value, rule: Value) -> Value { + if let (Some(target), Some(extra)) = (base.as_object_mut(), rule.as_object()) { + target.extend(extra.clone()); + } + base +} + +fn container(id: &str, length: &str, width: &str, height: &str) -> Value { + json!([{ "id": id, "max_payload": "40 kg", + "inner_dimensions": { "length": length, "width": width, "height": height } }]) +} + +fn main() -> Result<(), Box> { + // ------------------------------------------------------------ rotations + // + // `allowed_rotations` narrows the six orientations to the ones you permit; `LWH` and + // `WLH` are the two that keep the item's own height vertical. `keep_upright` says the + // same thing in one word, for anything with an open top or a "this side up" arrow. The + // pole is 700 mm tall and the shelf 500 mm high, so it fits only lying down. + let shelf = container("shelf", "800", "400", "500"); + let pole = item("pole", "90", "90", "700", "1 kg"); + compare( + "allowed_rotations -- a pole that only fits lying down, forbidden from lying down", + json!([pole.clone()]), + json!([with( + pole.clone(), + json!({ "allowed_rotations": ["LWH", "WLH"] }) + )]), + &shelf, + )?; + compare( + "keep_upright -- the same rule, spelled for a paint tin rather than a pole", + json!([pole.clone()]), + json!([with(pole, json!({ "keep_upright": true }))]), + &shelf, + )?; + + // ------------------------------------------------------------ stacking + // + // `max_stacked_items` caps how many units may stand on one item -- a pallet pattern's + // "three high, no more", not a weight limit. The column is one tin wide, so height is + // the only way to fit more, and a second column is the price of the cap. + let column = container("column", "160", "160", "600"); + let tins = with( + item("tin", "150", "150", "120", "800 g"), + json!({ "quantity": 5 }), + ); + compare( + "max_stacked_items -- five tins fit one column; three high needs two", + json!([tins.clone()]), + json!([with(tins, json!({ "max_stacked_items": 2 }))]), + &column, + )?; + + // `stackable: false` means nothing may rest on the item at all; `max_top_load` caps + // the weight resting *directly* on it. A flat-packed glass tabletop fills the floor of + // a tray, so the only place left for the 5 kg parcel is on top of it -- until the + // tabletop says nothing may stand on it, or that 2 kg is its limit. (`keep_upright` + // stops the solver from simply standing the tabletop on its edge.) + let tray = container("tray", "400", "300", "300"); + let panel = with( + item("tabletop", "400", "300", "40", "8 kg"), + json!({ "must_be_on_floor": true, "keep_upright": true }), + ); + let parcel = item("parcel", "400", "300", "200", "5 kg"); + compare( + "stackable -- a tabletop that nothing may be put on", + json!([panel.clone(), parcel.clone()]), + json!([ + with(panel.clone(), json!({ "stackable": false })), + parcel.clone() + ]), + &tray, + )?; + compare( + "max_top_load -- a tabletop that carries 2 kg and no more", + json!([panel.clone(), parcel.clone()]), + json!([with(panel, json!({ "max_top_load": "2 kg" })), parcel]), + &tray, + )?; + + // ------------------------------------------------------------ support + // + // `minimum_support_ratio` is how much of an item's base must rest on something solid. + // The plinth stands on the floor under a quarter of the ledge, and the ledge is too low + // for the slab to stand on edge -- so the only place the slab fits is perched on the + // plinth, on a quarter of its base. At 0.9 that is refused and a second ledge opens. + let ledge = container("ledge", "400", "400", "350"); + let plinth = with( + item("plinth", "200", "200", "300", "5 kg"), + json!({ "must_be_on_floor": true }), + ); + let slab = item("slab", "400", "400", "60", "9 kg"); + compare( + "minimum_support_ratio -- a slab perched on a quarter of its base", + json!([plinth.clone(), slab.clone()]), + json!([plinth, with(slab, json!({ "minimum_support_ratio": 0.9 }))]), + &ledge, + )?; + + // ------------------------------------------------------------ separation + // + // Tags are how two items refuse each other. `incompatible_tags` is checked both ways, so + // tagging one side is enough; the bleach opens a crate of its own rather than travel + // with the flour. + let crate_ = container("crate", "600", "500", "500"); + let bleach = with( + item("bleach", "120", "120", "300", "2 kg"), + json!({ "tags": ["hazmat"] }), + ); + let flour = with( + item("flour", "200", "150", "100", "1500 g"), + json!({ "tags": ["food"] }), + ); + compare( + "incompatible_tags -- bleach that may not share a crate with food", + json!([bleach.clone(), flour.clone()]), + json!([ + with(bleach, json!({ "incompatible_tags": ["food"] })), + flour + ]), + &crate_, + )?; + + // Every reason printed above is a fact about the request, not a solver failure -- + // which is why it can be turned into a sentence a customer is allowed to read. + Ok(()) +} diff --git a/examples/errors.rs b/examples/errors.rs new file mode 100644 index 0000000..3ace6a2 --- /dev/null +++ b/examples/errors.rs @@ -0,0 +1,160 @@ +//! Errors: what you get back when the engine cannot answer, and how to branch on it. +//! +//! cargo run --example errors +//! +//! There are two kinds of failure, and only one of them is an `Err`. +//! +//! - **The request is wrong.** A value is missing, mistyped, below its minimum, in an unknown +//! unit, or the fixed placements it names cannot hold. Nothing was solved, and retrying the +//! same request gives the same error. That is `PackError::InvalidRequest(RequestError)`, +//! which names the rule it broke (`reason`) and where (`field`, a JSON Pointer into the +//! request you sent). +//! - **The request is fine, but not everything fits.** That is not an error: the result says +//! so, with a reason for every item left out. +//! +//! Every `PackError` also has `code()`, one closed string per kind of refusal. Branch on +//! `code`, `reason` and `field`; show the message to a person. The message is the same text +//! the Python, PHP and JavaScript engines produce for the same request. + +use packvium_core::PackError; +use serde_json::{Value, json}; + +/// A small valid request: one carton, one kind of item. Each case below breaks one thing. +fn request() -> Value { + json!({ + "units": { "length": "mm" }, + "configuration": { + "time_limit_ms": 60000, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }, + "items": [{ "id": "jar", "quantity": 2, "weight": "400 g", + "dimensions": { "length": "80", "width": "80", "height": "120" } }], + "containers": [{ "id": "carton", "max_payload": "10 kg", + "inner_dimensions": { "length": "300", "width": "200", "height": "150" } }] + }) +} + +/// Set the value at a JSON Pointer, adding the last key when it is not there yet, so each +/// case reads as the one edit it makes. +fn with(pointer: &str, value: Value) -> Value { + let mut request = request(); + let (parent, key) = pointer.rsplit_once('/').unwrap_or(("", pointer)); + match request.pointer_mut(parent) { + Some(Value::Object(map)) => { + map.insert(key.to_owned(), value); + } + Some(Value::Array(list)) => { + if let Some(slot) = key + .parse::() + .ok() + .and_then(|index| list.get_mut(index)) + { + *slot = value; + } + } + _ => {} + } + request +} + +/// What a caller does with each kind of answer. +fn describe(outcome: Result) { + match outcome { + Ok(text) => { + let result: Value = serde_json::from_str(&text).unwrap_or_default(); + let left_out = result["unpacked_items"] + .as_array() + .map_or(&[][..], Vec::as_slice); + println!( + " Ok: status {}, {} item(s) left out", + result["status"], + left_out.len() + ); + for unpacked in left_out { + println!(" {} -- {}", unpacked["item_id"], unpacked["reason"]); + } + } + // The one to branch on in code: highlight `field` in a form, or map `reason` to + // your own message. `detail` is the fixed text the message ends with. + Err(PackError::InvalidRequest(error)) => { + println!(" code: {}", error.code()); + println!(" reason: {}", error.reason()); + println!(" field: {:?}", error.field()); + println!(" detail: {}", error.detail()); + println!(" shown: {error}"); + } + // Everything else still has a closed code. `PackError` is `#[non_exhaustive]`, so a + // wildcard arm is required, and `code()` is how that arm stays specific. + Err(other) => { + println!(" code: {}", other.code()); + println!(" shown: {other}"); + } + } +} + +fn case(title: &str, request: &Value) { + println!("\n{title}"); + describe(packvium_core::pack_json(&request.to_string())); +} + +fn main() { + println!("== The request is wrong: nothing was solved =="); + case( + "a negative measure", + &with("/items/0/dimensions/width", json!("-80")), + ); + case( + "a quantity below its minimum", + &with("/items/0/quantity", json!(0)), + ); + case( + "a mistyped value: a quantity sent as text", + &with("/items/0/quantity", json!("2")), + ); + case( + "a unit nobody uses", + &with("/units/length", json!("furlong")), + ); + case( + "a value outside its closed set", + &with("/configuration/solver_profile", json!("thorough")), + ); + case("a missing required field", &{ + let mut request = request(); + if let Some(dimensions) = request.pointer_mut("/items/0/dimensions") { + dimensions.as_object_mut().map(|map| map.remove("height")); + } + request + }); + + // Items already in place are checked before any search: two jars fixed at the same + // spot cannot both be there. The code is `invalid_fixed_placement`, and `field` points + // at the whole list because the conflict is between entries, not inside one. + let mut fixed = request(); + fixed["fixed_placements"] = json!([ + { "item_type": "jar", "container_type": "carton", "container_instance": 1, + "position": { "x": "0", "y": "0", "z": "0" }, "orientation": "LWH" }, + { "item_type": "jar", "container_type": "carton", "container_instance": 1, + "position": { "x": "0", "y": "0", "z": "0" }, "orientation": "LWH" } + ]); + case("two fixed placements in the same spot", &fixed); + + println!("\n== Other refusals: each has its own code =="); + case( + "a field this engine deliberately does not implement", + &with("/containers/0/pallet_overhang_limit", json!("10")), + ); + case("JSON, but a string instead of an object", &json!("items")); + println!("\nthe bytes themselves are not JSON"); + describe(packvium_core::pack_json("{\"items\": [")); + + println!("\n== Not an error: the request is fine, the jar is too tall =="); + case( + "a jar taller than the carton in every orientation", + &with("/items/0/dimensions/height", json!("400")), + ); +} diff --git a/examples/execution.rs b/examples/execution.rs new file mode 100644 index 0000000..fb162a0 --- /dev/null +++ b/examples/execution.rs @@ -0,0 +1,177 @@ +//! Execution plans: turn a packing result into instructions someone can follow on a dock. +//! +//! cargo run --example execution +//! +//! `pack_json` answers where every box goes. That is not yet a work order: it does not say +//! what to lift first, and it does not separate what the solver *decided* from what a screen +//! should *say*. The execution plan is that second document. It is derived from a result that +//! was already validated -- it calls no solver, reads no clock, and the same result always +//! gives the same bytes, in this crate and in the Python, PHP and JavaScript packages. +//! +//! The step order is not invented by the plan. You compute a safe loading order from the +//! placed geometry with `safe_loading_order` and hand it in; without one, the plan lists +//! every placement unnumbered rather than pass off array order as a safe order to lift in. + +use packvium_core::execution::build_plan_json; +use packvium_core::{Aabb, Dimensions, Length, Point, safe_loading_order}; +use serde_json::{Value, json}; + +/// One crate, a printer that must stay upright, four toner cartridges, and a pallet jack +/// that was never going to fit. A plan has to say what is *not* going on the truck as +/// clearly as what is. +fn request() -> Value { + json!({ + "units": { "length": "mm" }, + "configuration": { + // Counted work bounds the search; the time limit is only a safety fuse. The + // pallet jack fits no orientation of the crate, so the search sets it aside + // before it starts and finishes well inside this budget. + "time_limit_ms": 60000, + "effort_budget": { + "max_candidates_evaluated": 100000, + "max_placement_attempts": 100000, + "max_search_nodes": 100000 + } + }, + "items": [ + { "id": "printer", "quantity": 1, "weight": "9 kg", "keep_upright": true, + "dimensions": { "length": "420", "width": "340", "height": "260" } }, + { "id": "toner", "quantity": 4, "weight": "900 g", + "dimensions": { "length": "180", "width": "120", "height": "100" } }, + { "id": "pallet-jack", "quantity": 1, "weight": "80 kg", + "dimensions": { "length": "1200", "width": "550", "height": "1200" } } + ], + "containers": [ + { "id": "crate", "quantity": 1, "max_payload": "30 kg", + "inner_dimensions": { "length": "600", "width": "400", "height": "400" } } + ] + }) +} + +fn ticks(measure: &Value) -> i64 { + measure["ticks"].as_i64().unwrap_or_default() +} + +fn dimensions(value: &Value) -> Dimensions { + Dimensions { + length: Length(ticks(&value["length"])), + width: Length(ticks(&value["width"])), + height: Length(ticks(&value["height"])), + } +} + +/// The placed boxes of one result container, exactly, in the order the result lists them. +fn boxes(container: &Value) -> Vec { + container["placements"] + .as_array() + .into_iter() + .flatten() + .map(|placement| { + let at = &placement["position"]; + Aabb { + origin: Point { + x: ticks(&at["x"]), + y: ticks(&at["y"]), + z: ticks(&at["z"]), + }, + dimensions: dimensions(&placement["dimensions"]), + } + }) + .collect() +} + +fn text(value: &Value) -> &str { + value.as_str().unwrap_or_default() +} + +fn section(title: &str) { + println!("\n{}\n{title}\n{}", "=".repeat(78), "=".repeat(78)); +} + +fn main() -> Result<(), Box> { + let result_text = packvium_core::pack_json(&request().to_string())?; + let result: Value = serde_json::from_str(&result_text)?; + + section("1. What the solver decided, kept apart from what a screen says"); + let plan: Value = serde_json::from_str(&build_plan_json(&result_text, "{}")?)?; + println!(" format: {}", text(&plan["format"])); + println!(" status: {}", text(&plan["facts"]["status"])); + println!(" containers used: {}", plan["facts"]["container_count"]); + println!(" score: {}", plan["facts"]["score"]); + println!(); + println!(" Everything above is under `facts`: the solver's own answer, copied rather than"); + println!(" re-derived, so a system that reads only `facts` loses nothing it may rely on."); + + section("2. The step order is computed from geometry and handed in"); + let unordered = &plan["containers"][0]; + println!( + " without an order: `order` is {}", + text(&unordered["order"]) + ); + for step in unordered["steps"].as_array().into_iter().flatten() { + println!(" - {}", text(&step["placement"]["item_type"])); + } + + // The crate is loaded from the top, so the only way in is down along -z; the order is + // the reverse of a safe removal upwards, `+z`. It is replayed before it is returned, so + // no box is ever lowered through another or set down before what it rests on. + let crate_ = &result["containers"][0]; + let order = safe_loading_order( + &boxes(crate_), + dimensions(&crate_["inner_dimensions"]), + &["+z"], + )?; + let orders = json!({ "0": order }).to_string(); + let ordered: Value = serde_json::from_str(&build_plan_json(&result_text, &orders)?)?; + let container = &ordered["containers"][0]; + println!(); + println!( + " with an order: `order` is {}", + text(&container["order"]) + ); + for step in container["steps"].as_array().into_iter().flatten() { + let placement = &step["placement"]; + let at = &placement["position_ticks"]; + println!( + " {}. {:<8} {} at ({}, {}, {}) ticks", + step["sequence"], + text(&placement["item_type"]), + text(&placement["orientation"]), + at["x"], + at["y"], + at["z"] + ); + } + + section("3. Every sentence names the fields it was built from"); + for entry in plan["unplaced"].as_array().into_iter().flatten() { + let facts = &entry["facts"]; + let presentation = &entry["presentation"]; + println!(" facts: item_type={}", facts["item_type"]); + println!( + " reason={} proof_level={}", + facts["reason"], facts["proof_level"] + ); + println!(" presentation: {}", text(&presentation["summary"])); + println!(" cites: {}", presentation["cites"]); + } + println!(); + println!(" `proven` is a claim about the search: no orientation of the pallet jack fits"); + println!(" any offered crate, so nothing needed to be tried. A sentence with no citation"); + println!(" would be one nobody can check, which is why `cites` is part of the format."); + + section("4. The same result gives the same bytes, in every language"); + let first = build_plan_json(&result_text, &orders)?; + let second = build_plan_json(&result_text, &orders)?; + println!( + " canonical form: {} bytes, built twice, identical: {}", + first.len(), + first == second + ); + println!(" {}...", &first[..first.len().min(68)]); + println!(); + println!(" That is a promise about the plan, not about the search: given the same result,"); + println!(" every engine's plan is byte-identical; given the same request, engines may"); + println!(" reach different valid packings, and each plan describes its own faithfully."); + Ok(()) +} diff --git a/examples/nested.rs b/examples/nested.rs new file mode 100644 index 0000000..3b5ed36 --- /dev/null +++ b/examples/nested.rs @@ -0,0 +1,220 @@ +//! Nested packing: units into cartons, cartons onto a pallet. +//! +//! cargo run --example nested +//! +//! Real fulfilment is rarely one level. Mugs and plates go into cartons, and the cartons go +//! onto a pallet. `pack_nested` takes those levels as data -- a name and an ordinary typed +//! `PackingRequest` each -- solves them in order, and hands every level's result back under +//! its name, so a two-level plan can be stored, replayed and audited as one thing. +//! +//! A level with no items of its own takes the previous level's result: each packed carton +//! becomes one item with the carton's *outer* dimensions and its gross weight, as Python's +//! `NestedPacker` does. A level that lists its own items keeps them. The levels stay +//! independent otherwise -- a carton already taped shut is not repacked to make a better +//! pallet -- and the chain stops at the first level that cannot pack everything. +//! +//! This is also the typed side of the API: `Item`, `Container` and `PackingRequest` are +//! plain structs with public fields, and `pack_request` returns a `PackingResult` whose +//! placements and weights are exact integers. + +use packvium_core::{ + Container, Dimensions, Item, Length, NestedLevel, NestedPackingRequest, PackResult, + PackingConfig, PackingRequest, Rotation, ShapeType, SolverProfile, Weight, pack_nested, +}; +use serde_json::json; +use std::collections::{BTreeMap, BTreeSet}; + +fn length(text: &str) -> PackResult { + Length::parse(&json!(text), "mm") +} + +fn weight(text: &str) -> PackResult { + Weight::parse(&json!(text), "g") +} + +fn dimensions(length_mm: &str, width_mm: &str, height_mm: &str) -> PackResult { + Ok(Dimensions { + length: length(length_mm)?, + width: length(width_mm)?, + height: length(height_mm)?, + }) +} + +/// An item with no rule beyond its size, weight and count. Every field is public and has to +/// be named; these are the values a JSON request gets when it leaves the field out. +fn item(id: &str, size: Dimensions, item_weight: Weight, quantity: usize) -> Item { + Item { + id: id.into(), + dimensions: size, + weight: item_weight, + quantity, + allowed_rotations: Rotation::ALL.to_vec(), + stackable: true, + must_be_on_floor: false, + max_top_load: None, + minimum_support_ratio: 0.0, + group: None, + tags: BTreeSet::new(), + incompatible_tags: BTreeSet::new(), + priority: 0, + metadata: BTreeMap::new(), + nesting_height: None, + max_stacked_items: None, + ground_contact_rule: None, + stop_index: None, + eligible_container_tags: BTreeSet::new(), + value: None, + shape_type: ShapeType::RigidCuboid, + hull_vertices: None, + compression_ratio_ppm: None, + max_compression_pressure_kpa: None, + } +} + +struct ContainerSpec<'a> { + id: &'a str, + inner: Dimensions, + outer: Option, + tare: Weight, + max_payload: Weight, + cost_minor: i64, +} + +fn container(spec: ContainerSpec<'_>) -> Container { + Container { + id: spec.id.into(), + inner_dimensions: spec.inner, + outer_dimensions: spec.outer, + tare_weight: spec.tare, + max_payload: Some(spec.max_payload), + cost_minor: spec.cost_minor, + quantity: None, + obstacles: Vec::new(), + tags: BTreeSet::new(), + max_items: None, + metadata: BTreeMap::new(), + axles: None, + void_fill_reserve_ppm: 0, + tag_limits: BTreeMap::new(), + max_stack_density: None, + rate_table: None, + access_directions: Vec::new(), + preloaded: Vec::new(), + } +} + +/// Counted work bounds the search, so each level gives the same answer on every host; the +/// time limit is only a safety fuse. One deterministic start is plenty for this scene. +fn configuration() -> PackingConfig { + let mut config = PackingConfig { + profile: SolverProfile::Fast, + time_limit_ms: 60_000, + ..PackingConfig::default() + }; + let mut budget = config.effort_budget.unwrap_or_default(); + budget.max_candidates_evaluated = Some(1_000_000); + budget.max_placement_attempts = Some(1_000_000); + budget.max_search_nodes = Some(1_000_000); + config.effort_budget = Some(budget); + config +} + +fn request(items: Vec, containers: Vec) -> PackingRequest { + PackingRequest { + items, + containers, + config: configuration(), + output_length_unit: "mm".into(), + output_weight_unit: "kg".into(), + catalog_versions_used: Vec::new(), + fixed_placements: Vec::new(), + fixed_containers: Vec::new(), + } +} + +fn kilograms(value: Weight) -> String { + let grams = value.0 / Weight::TICKS_PER_G; + format!("{}.{:03} kg", grams / 1000, grams % 1000) +} + +fn main() -> PackResult<()> { + // What the customer ordered. + let order = vec![ + item("mug", dimensions("120", "120", "100")?, weight("400")?, 24), + item("plate", dimensions("260", "260", "20")?, weight("600")?, 16), + ]; + + // Level 1: choose cartons. `outer_dimensions` matters here -- the pallet packs the + // outside of each carton, wall thickness included. + let cartons = vec![ + container(ContainerSpec { + id: "box-s", + inner: dimensions("300", "300", "300")?, + outer: Some(dimensions("310", "310", "310")?), + tare: weight("300")?, + max_payload: weight("15000")?, + cost_minor: 120, + }), + container(ContainerSpec { + id: "box-l", + inner: dimensions("400", "400", "400")?, + outer: Some(dimensions("412", "412", "412")?), + tare: weight("500")?, + max_payload: weight("25000")?, + cost_minor: 180, + }), + ]; + let carton_level = NestedLevel { + name: "carton".into(), + request: request(order, cartons), + }; + + // Level 2: put those cartons on a pallet. The deck is the inner footprint and the + // usable stack height is the rest. + let pallet = container(ContainerSpec { + id: "euro", + inner: dimensions("1200", "800", "1400")?, + outer: None, + tare: weight("25000")?, + max_payload: weight("700000")?, + cost_minor: 1500, + }); + // No items: this level packs whatever the carton level packed. + let pallet_level = NestedLevel { + name: "pallet".into(), + request: request(Vec::new(), vec![pallet]), + }; + + // The whole plan as one value: both levels, solved in order, each result under its name. + let plan = pack_nested(&NestedPackingRequest { + levels: vec![carton_level, pallet_level], + beam_width: 1, + })?; + + for (name, result) in &plan.levels { + println!("== {name} =="); + println!(" status: {}", result.status.as_str()); + println!(" containers used: {}", result.containers.len()); + for packed in &result.containers { + println!( + " {:<8} holding {:>2} item(s), gross {}", + packed.id(), + packed.placement_count(), + kilograms(packed.gross_weight()) + ); + } + if !result.unpacked.is_empty() { + println!(" left over: {}", result.unpacked.len()); + } + println!(); + } + + let (cartons, pallets) = (&plan.levels[0].1, &plan.levels[1].1); + println!( + "{} carton(s) travelling on {} pallet(s); every carton is on a pallet: {}", + cartons.containers.len(), + pallets.containers.len(), + pallets.packed_item_count() == cartons.containers.len() + ); + Ok(()) +} diff --git a/examples/objectives.rs b/examples/objectives.rs new file mode 100644 index 0000000..08b1001 --- /dev/null +++ b/examples/objectives.rs @@ -0,0 +1,185 @@ +//! Objectives: six ways to be "best", and the scenes where they disagree. +//! +//! cargo run --example objectives +//! +//! Every solve returns the arrangement that scores best -- but "best" is a choice, and it is +//! the setting most likely to make the engine look wrong when it is merely answering a +//! different question than you meant to ask. Each scene below is built so that two +//! objectives genuinely pick different containers, so the difference is visible rather than +//! asserted. +//! +//! The score is always a vector of exact integers compared left to right, never a float, and +//! its first key is always the number of unpacked items: no objective will leave an item +//! behind to save money. Ratios are parts per million. + +use serde_json::{Value, json}; + +type Outcome = Result; + +/// Solve `items` into `containers` under `objective`, with any extra configuration merged in. +fn solve(objective: &str, extra: Value, items: &Value, containers: Value) -> Outcome { + let mut configuration = json!({ + "objective": objective, + // Counted work bounds the search; the time limit is only a safety fuse. + "time_limit_ms": 60000, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }); + if let (Some(target), Some(extra)) = (configuration.as_object_mut(), extra.as_object()) { + target.extend(extra.clone()); + } + let request = json!({ + "units": { "length": "mm" }, + "configuration": configuration, + "items": items, + "containers": containers, + }); + let text = packvium_core::pack_json(&request.to_string())?; + Ok(serde_json::from_str(&text)?) +} + +/// Which container type won, and the score that decided it. +fn report(label: &str, outcome: Outcome) { + match outcome { + Ok(result) => { + let chosen = result["containers"][0]["container_type"] + .as_str() + .unwrap_or("none"); + println!("{label:<18} {chosen:<6} score {}", result["score"]); + } + Err(refusal) => println!("{label:<18} refused: {} -- {refusal}", refusal.code()), + } +} + +fn container(id: &str, edge: &str, fields: Value) -> Value { + let mut container = json!({ + "id": id, "max_payload": "20 kg", + "inner_dimensions": { "length": edge, "width": edge, "height": edge } + }); + if let (Some(target), Some(fields)) = (container.as_object_mut(), fields.as_object()) { + target.extend(fields.clone()); + } + container +} + +/// The divisor carriers bill dimensional weight with. Without one, the two carrier +/// objectives refuse rather than guess: a wrong divisor silently misprices every shipment. +fn dimensional() -> Value { + json!({ + "dimensional_weight_divisor": 5000, + "dimensional_weight_length_unit": "cm", + "dimensional_weight_weight_unit": "kg" + }) +} + +fn main() { + let widgets = json!([{ "id": "widget", "quantity": 8, "weight": "500 g", + "dimensions": { "length": "100", "width": "100", "height": "100" } }]); + let snug = container("snug", "300", json!({ "cost_minor": 500 })); + let roomy = container("roomy", "400", json!({ "cost_minor": 150 })); + let both = json!([snug, roomy]); + + // `default` -- fewest containers, then the tightest fit. What you want when the + // containers are interchangeable and you are simply trying not to open another box. + report( + "default", + solve("default", json!({}), &widgets, both.clone()), + ); + + // `lowest_cost` -- the cheapest *packaging*. `cost_minor` is what the box itself costs + // you, so this is the objective for a warehouse buying cartons, not for a shipper paying + // a carrier. It prefers the roomy box precisely because the snug one costs more. + report( + "lowest_cost", + solve("lowest_cost", json!({}), &widgets, both.clone()), + ); + + // `shipping_cost` -- carrier-billable *weight*: the greater of gross weight and + // dimensional weight, so a big light box can bill more than a small heavy one. The roomy + // box is cheaper to buy and dearer to ship. + report( + "shipping_cost", + solve("shipping_cost", dimensional(), &widgets, both.clone()), + ); + + // `lowest_landed_cost` -- carrier-billable *money*, from a rate card carried in the + // request as data. Weight and money do not always agree: here the roomy box bills + // heavier (12,800 g dimensional against 5,400 g) and still costs less, because the snug + // box's carrier charges a steep first bracket. Rank by weight and you pick the wrong box. + let rated = |id: &str, edge: &str, prices: [i64; 2]| { + container( + id, + edge, + json!({ "rate_table": { "weight_brackets_g": [6000, 20000], "prices_minor": prices } }), + ) + }; + report( + "lowest_landed_cost", + solve( + "lowest_landed_cost", + dimensional(), + &widgets, + json!([ + rated("snug", "300", [2400, 3100]), + rated("roomy", "400", [900, 1500]) + ]), + ), + ); + + // A rate card that stops short of the shipment is a refusal, never a silent clamp to the + // top bracket: you would otherwise be quoted a price the carrier never published. + let too_narrow = container( + "roomy", + "400", + json!({ "rate_table": { "weight_brackets_g": [2000], "prices_minor": [900] } }), + ); + report( + " (narrow card)", + solve( + "lowest_landed_cost", + dimensional(), + &widgets, + json!([too_narrow]), + ), + ); + + // `open_dimension_height` -- the shortest stack. For a container with no lid, or a + // pallet whose load must stay under a doorway. + report( + "open_dimension", + solve("open_dimension_height", json!({}), &widgets, both), + ); + + // `maximum_value` -- when not everything fits, leave the *cheap* things behind. Ranked + // by value forgone, after unpacked count. `quantity: 1` on the container is what makes + // this a choice at all: with unlimited boxes the packer would simply open a second one. + let mixed = json!([ + { "id": "gold", "quantity": 2, "weight": "500 g", "value": 90000, + "dimensions": { "length": "100", "width": "100", "height": "100" } }, + { "id": "gravel", "quantity": 2, "weight": "500 g", "value": 10, + "dimensions": { "length": "100", "width": "100", "height": "100" } } + ]); + let tiny = json!([{ "id": "tiny", "quantity": 1, "max_payload": "20 kg", + "inner_dimensions": { "length": "200", "width": "100", "height": "100" } }]); + match solve("maximum_value", json!({}), &mixed, tiny) { + Ok(result) => { + let ids = |list: &Value, key: &str| -> Vec { + let mut ids: Vec = list + .as_array() + .into_iter() + .flatten() + .filter_map(|entry| entry[key].as_str().map(str::to_owned)) + .collect(); + ids.sort(); + ids + }; + let kept = ids(&result["containers"][0]["placements"], "item_type"); + let left = ids(&result["unpacked_items"], "item_type"); + println!("maximum_value packed {kept:?}, left behind {left:?}"); + } + Err(refusal) => println!("maximum_value refused: {refusal}"), + } +} diff --git a/examples/pack-stdin.rs b/examples/pack-stdin.rs deleted file mode 100644 index 521f6d3..0000000 --- a/examples/pack-stdin.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! Read a packing request as JSON on stdin, write the result as JSON on stdout. -//! -//! This mirrors the Python and PHP CLIs so the cross-language conformance runner can -//! drive all implementations through one interface. -//! -//! cargo run -q -p packvium-core --example pack-stdin < request.json - -use std::io::{Read, Write}; - -fn main() -> std::process::ExitCode { - let mut input = String::new(); - if let Err(error) = std::io::stdin().read_to_string(&mut input) { - eprintln!("pack-stdin: cannot read stdin: {error}"); - return std::process::ExitCode::from(2); - } - match packvium_core::pack_json(&input) { - Ok(output) => { - let mut stdout = std::io::stdout(); - if stdout.write_all(output.as_bytes()).is_err() { - return std::process::ExitCode::from(2); - } - let _ = stdout.write_all(b"\n"); - std::process::ExitCode::SUCCESS - } - Err(error) => { - eprintln!("pack-stdin: {error}"); - std::process::ExitCode::from(1) - } - } -} diff --git a/examples/reproducibility.rs b/examples/reproducibility.rs new file mode 100644 index 0000000..3abeadd --- /dev/null +++ b/examples/reproducibility.rs @@ -0,0 +1,136 @@ +//! Reproducibility: bound the search by counted work, and keep the clock as a fuse. +//! +//! cargo run --example reproducibility +//! +//! The engine is deterministic: the same request, configuration and seed give the same +//! placements. There is one way to lose that, and it is the setting most callers reach for +//! first. `time_limit_ms` stops the search when a wall clock says so, and how far a search +//! gets in 200 ms depends on the machine and on what else it is doing. Two runs of the same +//! request can then keep different best answers. +//! +//! `effort_budget` stops the search by counting work instead -- candidates evaluated, +//! placements attempted, search nodes expanded -- and a count does not depend on the host. +//! The pattern is to set the budget you mean and a time limit far above what the budget can +//! take, so the clock never decides anything and only guards against a genuine hang. + +use packvium_core::artifacts::build_artifact_json; +use serde_json::{Value, json}; + +/// A mixed order: several item sizes, two carton sizes, more than one carton needed. +fn request(configuration: Value) -> Value { + json!({ + "units": { "length": "mm" }, + "configuration": configuration, + "items": [ + { "id": "large", "quantity": 4, "weight": "3 kg", + "dimensions": { "length": "300", "width": "250", "height": "200" } }, + { "id": "medium", "quantity": 8, "weight": "1500 g", + "dimensions": { "length": "220", "width": "160", "height": "120" } }, + { "id": "flat", "quantity": 6, "weight": "800 g", + "dimensions": { "length": "350", "width": "250", "height": "40" } }, + { "id": "small", "quantity": 12, "weight": "300 g", + "dimensions": { "length": "110", "width": "90", "height": "70" } } + ], + "containers": [ + { "id": "carton-m", "cost_minor": 90, + "inner_dimensions": { "length": "400", "width": "300", "height": "300" } }, + { "id": "carton-l", "cost_minor": 140, + "inner_dimensions": { "length": "600", "width": "400", "height": "400" } } + ] + }) +} + +fn solve(request: &Value) -> Result<(String, Value), Box> { + let text = packvium_core::pack_json(&request.to_string())?; + let mut result: Value = serde_json::from_str(&text)?; + without_durations(&mut result); + Ok((text, result)) +} + +/// How long a solve took is a measurement of the run, not part of the answer, and it is the +/// one number that legitimately differs between two identical solves. Drop every +/// `duration_ms` -- the result's own and each alternative's -- before comparing. +fn without_durations(value: &mut Value) { + match value { + Value::Object(map) => { + map.remove("duration_ms"); + map.values_mut().for_each(without_durations); + } + Value::Array(list) => list.iter_mut().for_each(without_durations), + _ => {} + } +} + +fn placed(result: &Value) -> usize { + result["containers"] + .as_array() + .into_iter() + .flatten() + .map(|container| container["placements"].as_array().map_or(0, Vec::len)) + .sum() +} + +/// Solve twice and report what a caller can rely on. +fn twice(title: &str, configuration: Value) -> Result<(), Box> { + let request = request(configuration); + let (text, first) = solve(&request)?; + let (_, second) = solve(&request)?; + println!("\n{title}"); + println!(" termination: {}", first["termination"]["code"]); + println!( + " effort limit: {}", + first["algorithm"]["effort_limit_reached"] + ); + println!( + " placed: {} in {} container(s), {} left out", + placed(&first), + first["containers"].as_array().map_or(0, Vec::len), + first["unpacked_items"].as_array().map_or(0, Vec::len) + ); + println!(" score: {}", first["score"]); + println!(" second run identical: {}", first == second); + // The operational artifact records whether a replay of the embedded request is promised + // to reproduce this result. A search that the clock stopped is never promised one. + let artifact: Value = + serde_json::from_str(&build_artifact_json(&request.to_string(), &text, "{}")?)?; + println!( + " artifact replay: {}", + artifact["provenance"]["replay"]["level"] + ); + Ok(()) +} + +fn main() -> Result<(), Box> { + // A budget far above what this order needs, and a 60 s fuse. The search finishes on its + // own, and nothing about the host can change the answer. + twice( + "effort budget, 60 s fuse", + json!({ + "solver_profile": "balanced", + "time_limit_ms": 60000, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }), + )?; + + // A budget small enough to bind. The search stops early and says so -- `effort_limit`, + // not `complete` -- and it still stops at exactly the same point on every run and every + // machine, so the shorter answer is just as reproducible. + twice( + "a budget that binds", + json!({ + "solver_profile": "balanced", + "time_limit_ms": 60000, + "effort_budget": { "max_search_nodes": 12 } + }), + )?; + + // What not to do is not printed here, because its output is not the same on every run: + // a request with only `"time_limit_ms": 200` answers whatever the search reached in + // 200 ms on this machine at this moment. When the clock does stop such a search, the + // result says `time_limit`, and its artifact says the replay is `not_guaranteed`. + Ok(()) +} diff --git a/examples/shapes.rs b/examples/shapes.rs index a4f4030..786c6a5 100644 --- a/examples/shapes.rs +++ b/examples/shapes.rs @@ -18,7 +18,17 @@ use serde_json::{Value, json}; /// Pack one request and print only what the shape changed. -fn summarise(label: &str, request: Value) { +fn summarise(label: &str, mut request: Value) { + // Counted work bounds the search, so the answer is the same on every host; the time + // limit is only a safety fuse against a genuine hang. + request["configuration"] = json!({ + "time_limit_ms": 60000, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }); let packed = packvium_core::pack_json(&request.to_string()).expect("well-formed request"); let result: Value = serde_json::from_str(&packed).expect("the engine answers JSON"); let containers = result["containers"].as_array().map_or(0, Vec::len); diff --git a/examples/trucking.rs b/examples/trucking.rs new file mode 100644 index 0000000..4ef9f44 --- /dev/null +++ b/examples/trucking.rs @@ -0,0 +1,183 @@ +//! Trucking: a multi-stop delivery van, loaded so each stop can be unloaded in turn and +//! neither axle is overloaded. +//! +//! cargo run --example trucking +//! +//! Three request fields turn a box-packing problem into a vehicle-loading one: +//! +//! - `stop_index` on an item: the stop it comes off at. Stops are visited in ascending order, +//! so nothing due later may rest on top of something due earlier. +//! - `access_directions` on a container: the walls it can be unloaded through. With a door +//! named, nothing due later may stand between an earlier item and that door either. A +//! container that names no door is not checked for this at all -- which is not the same as +//! one with every wall open. +//! - `axles` on a container: exactly two, front and rear, each at a position along the +//! container's length with an optional `max_load`. The load on each is solved as a +//! two-point beam over the gross weight -- the container's tare plus everything in it. +//! +//! All three are data in the request, so the same JSON loads the same van in the Python, PHP +//! and JavaScript engines. + +use serde_json::{Value, json}; + +/// Weight ticks per kilogram: a weight is an exact count of eighths of a microgram. +const TICKS_PER_KG: i128 = 8_000_000_000; + +fn configuration() -> Value { + // Counted work bounds the search; the time limit is only a safety fuse. + json!({ + "time_limit_ms": 60000, + // Without a support rule an item may rest on nothing at all: the default ratio is 0, + // which suits a solver test and never a truck. Ask for three quarters of every base. + "minimum_support_ratio": 0.75, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }) +} + +/// A 600 x 800 crate that must stay upright, due off at `stop` when it has one. +fn crate_for(stop: Option, id: &str, quantity: u64, weight: &str) -> Value { + let mut item = json!({ "id": id, "quantity": quantity, "weight": weight, "keep_upright": true, + "dimensions": { "length": "600", "width": "800", "height": "700" } }); + if let Some(stop) = stop { + item["stop_index"] = json!(stop); + } + item +} + +/// One van, one crate wide and one crate high: a 3.2 m cargo box whose door is named by +/// `doors` (`+x` is the far end of its length, the back). The front axle sits 400 mm behind +/// the bulkhead and the rear axle 2.6 m behind that; the front one may carry a rating. +fn van(doors: &[&str], front_limit: Option<&str>) -> Value { + let mut front = json!({ "position": "400" }); + if let Some(limit) = front_limit { + front["max_load"] = json!(limit); + } + json!({ + "id": "van", "quantity": 1, "tare_weight": "900 kg", "max_payload": "1500 kg", + "inner_dimensions": { "length": "3200", "width": "850", "height": "800" }, + "access_directions": doors, + "axles": [front, { "position": "3000" }] + }) +} + +fn pack(items: &Value, van: Value) -> Result> { + let request = json!({ + "units": { "length": "mm" }, + "configuration": configuration(), + "items": items, + "containers": [van], + }); + let text = packvium_core::pack_json(&request.to_string())?; + Ok(serde_json::from_str(&text)?) +} + +fn integer(value: &Value) -> i128 { + value + .as_str() + .and_then(|text| text.parse().ok()) + .unwrap_or(0) +} + +/// Axle loads come back as exact fractions of weight ticks; truncate to kilograms to print. +fn axle_kg(van: &Value) -> (i128, i128) { + let reactions = &van["axle_reactions"]; + let denominator = integer(&reactions["denominator"]).max(1) * TICKS_PER_KG; + ( + integer(&reactions["front_numerator"]) / denominator, + integer(&reactions["rear_numerator"]) / denominator, + ) +} + +fn show(title: &str, result: &Value, stops: &Value) { + println!("\n{title}"); + let stop_of = |item_type: &str| { + stops + .as_array() + .into_iter() + .flatten() + .find(|item| item["id"] == item_type) + .and_then(|item| item["stop_index"].as_u64()) + .map_or_else(|| "-".to_owned(), |stop| stop.to_string()) + }; + for van in result["containers"].as_array().into_iter().flatten() { + let mut placements: Vec<&Value> = + van["placements"].as_array().into_iter().flatten().collect(); + // Front of the van first, so the door is at the bottom of the list. + placements.sort_by_key(|placement| { + let at = &placement["position"]; + (at["x"]["ticks"].as_i64(), at["z"]["ticks"].as_i64()) + }); + for placement in placements { + let at = &placement["position"]; + println!( + " stop {:<2} {:<12} x {:>4} mm z {:>3} mm", + stop_of(placement["item_type"].as_str().unwrap_or_default()), + placement["item_id"].as_str().unwrap_or_default(), + at["x"]["value"].as_str().unwrap_or_default(), + at["z"]["value"].as_str().unwrap_or_default(), + ); + } + let (front, rear) = axle_kg(van); + println!(" axles: front {front} kg, rear {rear} kg"); + } + for unpacked in result["unpacked_items"].as_array().into_iter().flatten() { + println!( + " left behind: {} ({})", + unpacked["item_id"].as_str().unwrap_or_default(), + unpacked["reason"].as_str().unwrap_or_default() + ); + } +} + +fn main() -> Result<(), Box> { + // Three drops on one route. Stop 0 is visited first, so its crates must come out first. + let route = json!([ + crate_for(Some(0), "bakery", 2, "120 kg"), + crate_for(Some(1), "pharmacy", 1, "90 kg"), + crate_for(Some(2), "hardware", 2, "200 kg"), + ]); + + // ------------------------------------------------------------ the door decides + // + // The van is one crate wide and one crate high, so every crate is in the same lane. + // With the door at the back, the first stop's crates must be the ones nearest the back. + // Move the door to the front bulkhead (`-x`) and the same route loads the other way + // round. The crates are the same; only the door moved. + show( + "door at the back (+x): stop 0 nearest the door", + &pack(&route, van(&["+x"], None))?, + &route, + ); + show( + "door at the front (-x): the same route, mirrored", + &pack(&route, van(&["-x"], None))?, + &route, + ); + + // ------------------------------------------------------------ the axles decide + // + // No route this time: four light crates and an engine block that weighs more than all + // of them together. Packing prefers the front of the van, and right behind the bulkhead + // is exactly where 600 kg overloads the front axle once it is rated for less. With a + // limit set, the engine moves back towards the middle of the wheelbase, and both + // reactions stay inside their ratings. + let workshop = json!([ + crate_for(None, "engine", 1, "600 kg"), + crate_for(None, "parts", 4, "60 kg"), + ]); + show( + "an engine block, axles unrated", + &pack(&workshop, van(&["+x"], None))?, + &workshop, + ); + show( + "the same load, front axle rated 900 kg", + &pack(&workshop, van(&["+x"], Some("900 kg")))?, + &workshop, + ); + Ok(()) +} diff --git a/examples/units.rs b/examples/units.rs new file mode 100644 index 0000000..546d4ee --- /dev/null +++ b/examples/units.rs @@ -0,0 +1,155 @@ +//! Units: why there are no floats anywhere, and what you can type. +//! +//! cargo run --example units +//! +//! Packing is arithmetic about physical space, and floating point is the wrong tool for it: +//! `0.1 + 0.2` is not `0.3`, and a box that "almost" fits either fits or does not. So every +//! length and weight is an exact integer count of ticks -- 1/16000 mm for length, 1/8 +//! microgram for weight -- and nothing in the request, the search or the result is a float. + +use packvium_core::{Dimensions, Length, PackResult, Weight}; +use serde_json::{Value, json}; + +fn length(text: &str) -> PackResult { + // The second argument is the unit a bare number is read in; a unit in the text wins. + Length::parse(&json!(text), "mm") +} + +fn weight(text: &str) -> PackResult { + Weight::parse(&json!(text), "g") +} + +/// A measure rendered for a person: `to_json` returns the exact ticks beside a decimal +/// string in the unit you ask for. +fn rendered(measure: &Value) -> String { + format!( + "{} {}", + measure["value"].as_str().unwrap_or_default(), + measure["unit"].as_str().unwrap_or_default() + ) +} + +fn cube(edge: Length) -> Dimensions { + Dimensions { + length: edge, + width: edge, + height: edge, + } +} + +fn main() -> Result<(), Box> { + // ------------------------------------------------------------ what you can type + // + // Integers, decimals, fractions and mixed fractions, in mm, cm, m, in and ft -- because + // a spec sheet says "12 3/8 in", and retyping that as 12.375 is a step where mistakes + // live. + for text in ["30", "30.5 mm", "3/16 in", "12 3/8 in", "2 ft", "1.5 m"] { + let parsed = length(text)?; + println!( + "{text:>12} -> {:>12} ticks = {}", + parsed.0, + rendered(&parsed.to_json("mm")) + ); + } + println!(); + for text in ["450 g", "12 oz", "1.5 kg", "2 3/4 lb"] { + let parsed = weight(text)?; + println!( + "{text:>12} -> {:>14} ticks = {}", + parsed.0, + rendered(&parsed.to_json("g")) + ); + } + + // ------------------------------------------------------------ exact inches + // + // 1/16000 mm was chosen so that every binary fraction of an inch down to 1/128 lands + // on a whole number of ticks: an imperial spec survives the trip to millimetres and back. + println!(); + println!( + "1 inch is {} ticks, so 1/128 in is {} ticks exactly", + Length::TICKS_PER_INCH, + Length::TICKS_PER_INCH / 128 + ); + println!( + "128 x (1/128 in) == 1 in ? {}", + Length(length("1/128 in")?.0 * 128) == length("1 in")? + ); + // The honest other half: a third of an inch is not a binary fraction, so it cannot land + // on a whole tick. It is rounded once, deterministically, rather than carried as an + // error that only shows up as a box that "almost" fits. + println!( + " 3 x (1/3 in) == 1 in ? {} -- 1/3 in is {}/3 ticks, which is not an integer", + Length(length("1/3 in")?.0 * 3) == length("1 in")?, + Length::TICKS_PER_INCH + ); + + // ------------------------------------------------------------ where floats bite + println!(); + println!("0.1 + 0.2 == 0.3 in floats: {}", 0.1_f64 + 0.2 == 0.3); + println!( + "the same three tenths as lengths: {}", + length("0.1 mm")?.0 + length("0.2 mm")?.0 == length("0.3 mm")?.0 + ); + + // The same exactness decides whether something fits: a 100 mm cube into a 100 mm + // opening fits, and one tick over is refused, with no tolerance to tune. + println!(); + let opening = cube(length("100 mm")?); + let one_tick_over = Dimensions { + length: Length(opening.length.0 + 1), + ..opening + }; + println!( + "exactly 100 mm fits: {}", + cube(length("100")?).fits_inside(opening) + ); + println!( + "one tick over does not: {}", + one_tick_over.fits_inside(opening) + ); + + // ------------------------------------------------------------ in a request + // + // A request states its default length unit once; any measure may still carry its own. + // The result is rendered in the unit you ask for under `output`, and its ticks are the + // same whichever unit you choose. + let request = json!({ + "units": { "length": "in" }, + "output": { "length_unit": "mm", "weight_unit": "lb" }, + "configuration": { + "time_limit_ms": 60000, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + } + }, + "items": [{ "id": "shelf", "quantity": 3, "weight": "2 3/4 lb", + "dimensions": { "length": "12 3/8", "width": "9 1/2", "height": "3/4" } }], + "containers": [{ "id": "carton", "max_payload": "20 lb", + "inner_dimensions": { "length": "13", "width": "10", "height": "4" } }] + }); + let result: Value = serde_json::from_str(&packvium_core::pack_json(&request.to_string())?)?; + let carton = &result["containers"][0]; + let placements = carton["placements"].as_array().map_or(0, Vec::len); + println!(); + println!( + "packed {placements} shelves, {} left over; payload {}", + result["unpacked_items"].as_array().map_or(0, Vec::len), + rendered(&carton["payload_weight"]) + ); + let top = carton["placements"] + .as_array() + .into_iter() + .flatten() + .map(|placement| &placement["position"]["z"]) + .max_by_key(|z| z["ticks"].as_i64()) + .ok_or("the carton holds no shelves")?; + println!( + "top shelf sits at {} = {} ticks, which is exactly 2 x 3/4 in", + rendered(top), + top["ticks"] + ); + Ok(()) +} diff --git a/src/api.rs b/src/api.rs index d5cfe91..a344157 100644 --- a/src/api.rs +++ b/src/api.rs @@ -15,8 +15,33 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; pub fn pack_json(input: &str) -> PackResult { + pack_json_with(input, ExecutionOptions::default()) +} + +/// How one solve may use the machine. +/// +/// Deliberately not part of the JSON request: it changes wall-clock time, never the +/// answer, and the request is the portable contract every engine shares and every +/// digest hashes. Python and PHP keep the same kind of setting on their typed +/// configuration for the same reason. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ExecutionOptions { + /// Run independent search starts on scoped threads; `false` runs them in sequence, + /// which is what measuring total work needs. The result is the same either way. + pub parallel: bool, +} + +impl Default for ExecutionOptions { + fn default() -> Self { + Self { parallel: true } + } +} + +/// [`pack_json`] with explicit [`ExecutionOptions`]. +pub fn pack_json_with(input: &str, options: ExecutionOptions) -> PackResult { let value: Value = serde_json::from_str(input)?; - let request = request_from_json(&value)?; + let mut request = request_from_json(&value)?; + request.config.parallel = options.parallel; let result = pack_request_with_policy(&request, &PolicyRuleSet::parse(value.get("policy"))?)?; Ok(serde_json::to_string(&result.to_json( &request.output_length_unit, @@ -957,7 +982,8 @@ fn parse_config(value: Option<&Value>, length_unit: &str) -> PackResult(result: PackResult) -> String { + result.expect_err("the builder refuses").to_string() + } + + fn object(value: Value) -> Map { + value.as_object().expect("an object").clone() + } + + fn config(value: Value) -> String { + refusal(parse_config(Some(&value), "mm")) + } + + fn item(extra: Value) -> String { + let mut value = + json!({"id": "a", "dimensions": {"length": "10", "width": "10", "height": "10"}}); + value + .as_object_mut() + .expect("item object") + .extend(object(extra)); + refusal(parse_item(&value, "mm")) + } + + fn container(extra: Value) -> String { + let mut value = + json!({"id": "c", "inner_dimensions": {"length": "20", "width": "20", "height": "20"}}); + value + .as_object_mut() + .expect("container object") + .extend(object(extra)); + refusal(parse_container(&value, "mm")) + } + + fn valid_request() -> PackingRequest { + parse_request(&object(json!({ + "items": [{"id": "a", "dimensions": {"length": "10", "width": "10", "height": "10"}}], + "containers": [{"id": "c", "inner_dimensions": {"length": "20", "width": "20", "height": "20"}}] + }))) + .expect("a valid request") + } + + #[test] + fn catalog_references_must_be_canonical() { + let reference = + json!({"catalog_id": "items", "version": 1, "effective_at": 0, "resolved_at": 0}); + assert!(refusal(parse_catalog_versions(Some(&json!([1])))).contains("must be an object")); + assert!( + refusal(parse_catalog_versions(Some( + &json!([{"catalog_id": "items"}]) + ))) + .contains("exactly the canonical fields") + ); + let mut unnamed = reference.clone(); + unnamed["catalog_id"] = json!(""); + assert!( + refusal(parse_catalog_versions(Some(&json!([unnamed])))).contains("must be non-empty") + ); + let mut unversioned = reference; + unversioned["version"] = json!(0); + assert!( + refusal(parse_catalog_versions(Some(&json!([unversioned])))) + .contains("version must be >= 1") + ); + } + + #[test] + fn configuration_values_outside_their_domain_are_refused() { + assert!(config(json!({"objective": "cheapest"})).contains("unknown objective")); + // The rule table refuses these first on every public path; the builder still holds + // its own line for a caller that reaches it with an unchecked value. + assert!( + config(json!({"objective": 5})).contains("configuration.objective must be a string") + ); + for (directions, expected) in [ + (json!(["+x", 5]), "entries must be strings"), + (json!(["upwards"]), "unknown movement direction upwards"), + ] { + assert!(refusal(parse_access_directions(Some(&directions))).contains(expected)); + } + assert!( + config(json!({"dimensional_weight_divisor": 0})) + .contains("dimensional_weight_divisor must be a positive integer") + ); + assert!(config(json!({"solvers": [1]})).contains("must contain strings")); + assert!(config(json!({"solvers": "grid"})).contains("must be an array")); + assert!(config(json!({"solvers": ["annealing"]})).contains("unknown solver")); + assert!(config(json!({"dimensional_weight_length_unit": 1})).contains("must be a string")); + assert!( + config(json!({"dimensional_weight_weight_unit": "stone"})).contains("must be one of") + ); + assert!(config(json!({"effort_budget": 1})).contains("effort_budget must be object")); + assert!( + config(json!({"effort_budget": {"max_search_nodes": 0}})) + .contains("effort_budget.max_search_nodes must be positive") + ); + } + + #[test] + fn every_floored_configuration_count_names_its_floor() { + for (field, value, expected) in [ + ("max_candidates_per_item", 0, "must be a positive integer"), + ("max_candidate_points", 1, "must be an integer >= 16"), + ("container_plan_beam_width", 0, "must be a positive integer"), + ("container_plan_node_limit", 0, "must be a positive integer"), + ] { + let message = config(json!({ field: value })); + assert!( + message.contains(&format!("configuration.{field} {expected}")), + "{message}" + ); + } + assert_eq!( + below_floor("container", "cost_minor", 0), + "container.cost_minor must be a non-negative integer" + ); + } + + #[test] + fn item_fields_outside_their_domain_are_refused() { + assert!(item(json!({"allowed_rotations": ["XYZ"]})).contains("has no allowed rotations")); + assert!(item(json!({"shape_type": "sphere"})).contains("is not a known shape")); + assert!( + item(json!({"shape_type": "compressible", "compression_ratio": 2.0})) + .contains("between zero and one") + ); + assert!( + item(json!({"shape_type": "convex_hull", "hull_vertices": [1]})) + .contains("entries must be objects") + ); + assert!(item(json!({"eligible_container_tags": [1]})).contains("must contain strings")); + assert!(item(json!({"eligible_container_tags": "x"})).contains("must be an array")); + assert!(item(json!({"stop_index": -1})).contains("non-negative safe integer")); + assert!(item(json!({"value": -1})).contains("item.value must be a non-negative integer")); + assert!( + item(json!({"ground_contact_rule": 1})) + .contains("ground_contact_rule must be a string") + ); + } + + #[test] + fn shape_admission_refuses_inconsistent_shapes() { + let dimensions = Dimensions { + length: Length(10), + width: Length(10), + height: Length(10), + }; + let cube = |side: i64| { + let mut vertices = Vec::new(); + for x in [0, side] { + for y in [0, side] { + for z in [0, side] { + vertices.push([x, y, z]); + } + } + } + vertices + }; + assert!( + refusal(admit_shape( + ShapeType::ConvexHull, + Some(cube(10)), + None, + None, + dimensions, + Some(Length(1)), + )) + .contains("nesting_height with shape_type convex_hull") + ); + assert!( + refusal(admit_shape( + ShapeType::ConvexHull, + Some(cube(20)), + None, + None, + dimensions, + None, + )) + .contains("does not fit inside dimensions") + ); + assert!( + refusal(admit_shape( + ShapeType::Compressible, + None, + Some(500_000), + None, + dimensions, + None, + )) + .contains("requires both compression_ratio") + ); + assert!( + refusal(admit_shape( + ShapeType::Compressible, + None, + Some(2_000_000), + Some(10), + dimensions, + None, + )) + .contains("between zero and one") + ); + assert!( + refusal(admit_shape( + ShapeType::Compressible, + None, + Some(500_000), + Some(-1), + dimensions, + None, + )) + .contains("cannot be negative") + ); + } + + #[test] + fn container_fields_outside_their_domain_are_refused() { + assert!( + container(json!({"tag_limits": {"cold": 0}})) + .contains("tag_limits.cold must be positive") + ); + assert!(container(json!({"tag_limits": []})).contains("tag_limits must be an object")); + assert!( + container(json!({"rate_table": {"weight_brackets_g": [1000], "prices_minor": [-1]}})) + .contains("prices_minor must hold integers >= 0") + ); + assert!(container(json!({"axles": [{}]})).contains("exactly front and rear")); + assert!(container(json!({"axles": [{"position": "x"}, {"position": "10"}]})).contains("x")); + assert!( + container(json!({"obstacles": [{"id": "o", "dimensions": {"length": "1", "width": "1", "height": "1"}, "additional_boxes": [1]}]})) + .contains("additional box must be object") + ); + assert!(container(json!({"void_fill_reserve_ratio": "half"})).contains("must be a number")); + assert!(container(json!({"void_fill_reserve_ratio": 2.0})).contains("between 0 and 1")); + } + + #[test] + fn dimensions_must_be_positive_numbers() { + for (dimensions, expected) in [ + (json!({"length": "x", "width": "1", "height": "1"}), "x"), + (json!({"length": "1", "width": "x", "height": "1"}), "x"), + (json!({"length": "1", "width": "1", "height": "x"}), "x"), + ( + json!({"length": "0", "width": "1", "height": "1"}), + "dimensions must be positive", + ), + ] { + let message = refusal(parse_dimensions(Some(&dimensions), "mm")); + assert!(message.contains(expected), "{message}"); + } + } + + #[test] + fn a_fixed_placement_needs_a_known_orientation() { + let placement = json!({"item_type": "a", "container_type": "c", "orientation": "XYZ"}); + assert!( + refusal(parse_fixed_placement(&placement, "mm")).contains("orientation is invalid") + ); + } + + #[test] + fn a_built_request_is_rechecked_before_rebalancing() { + let mut ratio = valid_request(); + ratio.config.minimum_support_ratio = 2.0; + assert!(refusal(validate_request(&ratio)).contains("minimum_support_ratio")); + + let mut duplicate_item = valid_request(); + duplicate_item.items.push(duplicate_item.items[0].clone()); + assert!(refusal(validate_request(&duplicate_item)).contains("duplicate item id")); + + let mut item_ratio = valid_request(); + item_ratio.items[0].minimum_support_ratio = -1.0; + assert!(refusal(validate_request(&item_ratio)).contains("invalid minimum_support_ratio")); + + let mut stacked = valid_request(); + stacked.items[0].max_stacked_items = Some(0); + assert!(refusal(validate_request(&stacked)).contains("max_stacked_items")); + + let mut contact = valid_request(); + contact.items[0].ground_contact_rule = Some("floating".into()); + assert!(refusal(validate_request(&contact)).contains("ground_contact_rule")); + + let mut duplicate_container = valid_request(); + duplicate_container + .containers + .push(duplicate_container.containers[0].clone()); + assert!(refusal(validate_request(&duplicate_container)).contains("duplicate container id")); + + let mut reserve = valid_request(); + reserve.containers[0].void_fill_reserve_ppm = 2_000_000; + assert!(refusal(validate_request(&reserve)).contains("void_fill_reserve_ratio")); + + let mut axles = valid_request(); + axles.containers[0].axles = Some([ + Axle { + position: Length(10), + max_load: None, + }, + Axle { + position: Length(5), + max_load: None, + }, + ]); + assert!(refusal(validate_request(&axles)).contains("invalid axle positions")); + } + + /// Every optional field at once, so this copy of the builders runs their success paths + /// as well as the refusals above. + #[test] + fn a_request_using_every_field_builds_its_model() { + let request = parse_request(&object(json!({ + "units": {"length": "mm"}, + "output": {"length_unit": "cm", "weight_unit": "kg"}, + "catalog_versions_used": [ + {"catalog_id": "items", "version": 1, "effective_at": 0, "resolved_at": 0} + ], + "configuration": { + "objective": "shipping_cost", "dimensional_weight_divisor": 139, + "solvers": ["grid"], "solver_profile": "quality", + "time_limit_ms": 5, "alternatives": 2, "seed": 7, "max_containers": 3, + "clearance": "1", "minimum_support_ratio": 0.5, "exact_item_limit": 4, + "multi_start_orders": 2, "max_candidates_per_item": 2, + "max_candidate_points": 32, + "effort_budget": {"max_candidates_evaluated": 1, "max_placement_attempts": 2, + "max_search_nodes": 3, "max_restarts": 4}, + "require_placement_coordinates": false, + "container_plan_beam_width": 2, "container_plan_node_limit": 9 + }, + "items": [ + {"id": "cup", "quantity": 2, "weight": "5", + "dimensions": {"length": "10", "width": "10", "height": "10"}, + "keep_upright": true, "nesting_height": "2", "max_top_load": "50", + "stackable": false, "must_be_on_floor": true, "minimum_support_ratio": 0.25, + "group": "set", "tags": ["a"], "incompatible_tags": ["b"], "priority": 3, + "metadata": {"sku": 1}, "max_stacked_items": 2, "ground_contact_rule": "single", + "stop_index": 4, "eligible_container_tags": ["cold"], "value": 9}, + {"id": "wedge", "shape_type": "convex_hull", + "dimensions": {"length": "10", "width": "10", "height": "10"}, + "hull_vertices": [{"x": "0", "y": "0", "z": "0"}, {"x": "10", "y": "0", "z": "0"}, + {"x": "0", "y": "10", "z": "0"}, {"x": "0", "y": "0", "z": "10"}]}, + {"id": "pillow", "shape_type": "compressible", "compression_ratio": 0.5, + "max_compression_pressure_kpa": 3, + "dimensions": {"length": "10", "width": "10", "height": "10"}} + ], + "containers": [{ + "id": "box", "inner_dimensions": {"length": "100", "width": "100", "height": "100"}, + "outer_dimensions": {"length": "110", "width": "110", "height": "110"}, + "tare_weight": "10", "max_payload": "1000", "cost_minor": 5, "quantity": 2, + "obstacles": [{"id": "post", "origin": {"x": "1", "y": "2", "z": "3"}, + "dimensions": {"length": "5", "width": "5", "height": "5"}, + "additional_boxes": [{"dimensions": {"length": "1", "width": "1", "height": "1"}}]}], + "tags": ["cold"], "max_items": 4, "metadata": {"dock": 2}, + "axles": [{"position": "10", "max_load": "500"}, {"position": "90"}], + "void_fill_reserve_ratio": 0.1, "tag_limits": {"a": 2}, + "max_stack_density": "100", + "rate_table": {"weight_brackets_g": [100, 200], "prices_minor": [5, 9], + "minimum_charge_minor": 1, "fuel_surcharge_permille": 2}, + "access_directions": ["+x", "-x"] + }], + "fixed_placements": [{"item_type": "cup", "container_type": "box", + "container_instance": 1, "orientation": "LWH", + "position": {"x": "0", "y": "0", "z": "0"}}] + }))) + .expect("every field is admissible"); + assert_eq!(request.output_length_unit, "cm"); + assert_eq!( + request + .config + .effort_budget + .and_then(|budget| budget.max_restarts), + Some(4) + ); + assert_eq!( + request.items[0].allowed_rotations, + Rotation::UPRIGHT.to_vec() + ); + assert_eq!(request.items.len(), 3); + assert_eq!(request.containers[0].access_directions, ["+x", "-x"]); + assert_eq!(request.fixed_placements.len(), 1); + validate_request(&request).expect("the built model is consistent"); + } + + #[test] + fn every_builder_refuses_a_value_of_the_wrong_shape() { + for (request, expected) in [ + ( + json!({"items": {}, "containers": []}), + "items must be an array", + ), + ( + json!({"items": [], "containers": {}}), + "containers must be an array", + ), + ( + json!({"items": [], "containers": [], "catalog_versions_used": {}}), + "catalog_versions_used must be an array", + ), + ] { + assert!(refusal(parse_request(&object(request))).contains(expected)); + } + assert!(refusal(parse_item(&json!(1), "mm")).contains("item must be object")); + assert!(refusal(parse_container(&json!(1), "mm")).contains("container must be object")); + assert!( + item(json!({"shape_type": "convex_hull", "hull_vertices": {}})) + .contains("must be an array") + ); + assert!( + item(json!({"shape_type": "convex_hull", "hull_vertices": [{"x": "0", "y": "0"}]})) + .contains("entry needs z") + ); + assert!(item(json!({"shape_type": "convex_hull"})).contains("requires hull_vertices")); + let flat = item( + json!({"shape_type": "convex_hull", "hull_vertices": [{"x": "0", "y": "0", "z": "0"}]}), + ); + assert!(!flat.is_empty(), "a single vertex encloses no volume"); + assert!(container(json!({"rate_table": []})).contains("rate_table must be an object")); + assert!( + container(json!({"rate_table": {"weight_brackets_g": [1], "prices_minor": [1], "minimum_charge_minor": -1}})) + .contains("minimum_charge_minor") + ); + assert!(container(json!({"axles": {}})).contains("axles must be an array")); + assert!(container(json!({"axles": [1, 2]})).contains("axle must be object")); + assert!(container(json!({"axles": [{}, {}]})).contains("axle.position is required")); + assert!(container(json!({"obstacles": [1]})).contains("obstacle must be object")); + assert!(container(json!({"id": ""})).contains("missing id")); + assert!(refusal(parse_fixed_placement(&json!(1), "mm")).contains("must be object")); + assert!( + refusal(parse_fixed_placement( + &json!({"container_instance": "one"}), + "mm" + )) + .contains("counts from 1") + ); + for (dimensions, expected) in [ + (json!(1), "dimensions must be object"), + (json!({"width": "1", "height": "1"}), "missing length"), + (json!({"length": "1", "height": "1"}), "missing width"), + (json!({"length": "1", "width": "1"}), "missing height"), + ] { + assert!(refusal(parse_dimensions(Some(&dimensions), "mm")).contains(expected)); + } + } + + /// Every `?` in the builders forwards a refusal from a field parser; one bad value per + /// field walks each of them. + #[test] + fn a_bad_value_in_any_field_is_forwarded() { + for extra in [ + json!({"id": ""}), + json!({"dimensions": 1}), + json!({"nesting_height": "x"}), + json!({"weight": "x"}), + json!({"quantity": 0}), + json!({"max_top_load": "x"}), + json!({"max_stacked_items": -1}), + json!({"ground_contact_rule": 1}), + json!({"shape_type": "convex_hull", "hull_vertices": [{"x": "x", "y": "0", "z": "0"}]}), + ] { + assert!(!item(extra.clone()).is_empty(), "{extra}"); + } + for extra in [ + json!({"id": ""}), + json!({"inner_dimensions": 1}), + json!({"outer_dimensions": 1}), + json!({"tare_weight": "x"}), + json!({"max_payload": "x"}), + json!({"cost_minor": -1}), + json!({"quantity": 0}), + json!({"max_items": 0}), + json!({"max_stack_density": "x"}), + json!({"access_directions": "x"}), + json!({"rate_table": {"weight_brackets_g": [1], "prices_minor": [1], "fuel_surcharge_permille": -1}}), + json!({"axles": [{"position": "1", "max_load": "x"}, {"position": "2"}]}), + json!({"axles": [{"position": "1"}, {"position": "x"}]}), + json!({"obstacles": [{"dimensions": {"length": "1", "width": "1", "height": "1"}}]}), + json!({"obstacles": [{"id": "o", "origin": {"x": "x"}, "dimensions": {"length": "1", "width": "1", "height": "1"}}]}), + json!({"obstacles": [{"id": "o", "origin": {"y": "x"}, "dimensions": {"length": "1", "width": "1", "height": "1"}}]}), + json!({"obstacles": [{"id": "o", "origin": {"z": "x"}, "dimensions": {"length": "1", "width": "1", "height": "1"}}]}), + json!({"obstacles": [{"id": "o", "dimensions": 1}]}), + ] { + assert!(!container(extra.clone()).is_empty(), "{extra}"); + } + for extra in [ + json!({"objective": "shipping_cost"}), + json!({"time_limit_ms": 0}), + json!({"alternatives": 0}), + json!({"max_containers": 0}), + json!({"clearance": "x"}), + json!({"exact_item_limit": 0}), + json!({"multi_start_orders": 0}), + json!({"effort_budget": {"max_candidates_evaluated": 0}}), + json!({"effort_budget": {"max_placement_attempts": 0}}), + json!({"effort_budget": {"max_restarts": 0}}), + ] { + assert!(!config(extra.clone()).is_empty(), "{extra}"); + } + for placement in [ + json!({"container_type": "c", "orientation": "LWH"}), + json!({"item_type": "a", "orientation": "LWH"}), + json!({"item_type": "a", "container_type": "c", "orientation": "LWH", "position": {"x": "x"}}), + ] { + assert!( + !refusal(parse_fixed_placement(&placement, "mm")).is_empty(), + "{placement}" + ); + } + let items = + json!([{"id": "a", "dimensions": {"length": "1", "width": "1", "height": "1"}}]); + for (bad_items, fixed) in [ + (json!([1]), json!([])), + (items.clone(), json!("x")), + ( + items, + json!([{"item_type": "a", "container_type": "c", "orientation": "LWH", + "position": {"x": "1/0"}}]), + ), + ] { + let request = json!({"items": bad_items, "containers": [], "fixed_placements": fixed}); + assert!(!refusal(parse_request(&object(request))).is_empty()); + } + for request in [ + json!({"items": [], "containers": [1]}), + json!({"items": [], "containers": [], "catalog_versions_used": [1]}), + ] { + assert!(!refusal(parse_request(&object(request))).is_empty()); + } + } + + #[test] + fn a_built_request_needs_items_nesting_and_obstacles_that_fit() { + let mut empty = valid_request(); + empty.items.clear(); + assert!(refusal(validate_request(&empty)).contains("items and containers are required")); + + let mut nested = valid_request(); + nested.items[0].nesting_height = Some(nested.items[0].dimensions.height); + assert!(refusal(validate_request(&nested)).contains("invalid nesting_height")); + + let mut blocked = valid_request(); + let outside = Aabb { + origin: Point { x: 0, y: 0, z: 0 }, + dimensions: Dimensions { + length: Length(i64::MAX / 4), + width: Length(1), + height: Length(1), + }, + }; + blocked.containers[0].obstacles.push(Obstacle { + id: "wall".into(), + box_: outside, + additional_boxes: Vec::new(), + }); + assert!(refusal(validate_request(&blocked)).contains("obstacle wall outside c")); + } + + #[test] + fn null_stripping_leaves_non_objects_alone() { + assert_eq!(without_null_optionals(&json!(5)), json!(5)); + assert_eq!( + without_null_optionals(&json!({"configuration": 3, "items": [1]})), + json!({"configuration": 3, "items": [1]}) + ); + } + + #[test] + fn the_unsupported_field_guard_skips_entries_that_are_not_objects() { + assert!(reject_unsupported(&object(json!({"items": [1], "containers": [2]}))).is_ok()); + } +} diff --git a/src/error.rs b/src/error.rs index 5e478c3..79e4234 100644 --- a/src/error.rs +++ b/src/error.rs @@ -27,6 +27,32 @@ pub enum PackError { TimeLimit, } +impl PackError { + /// The closed, machine-readable code a caller branches on instead of parsing the message. + /// + /// The match is exhaustive on purpose: a new variant does not compile until it names its + /// code, so a transport that maps codes (the hosted API's HTTP statuses) cannot drift. + pub fn code(&self) -> &str { + match self { + Self::InvalidInput(_) | Self::Serialization(_) => "invalid_input", + Self::InvalidRequest(error) => error.code(), + Self::UnsupportedFeature(_) => "unsupported_feature", + Self::UnsupportedUnit(_) => "unsupported_unit", + Self::InvalidNumber(_) => "invalid_number", + Self::InvalidSolution(_) => "solution_failed_validation", + Self::TimeLimit => "time_limit", + } + } + + /// The named refusal behind `invalid_request` / `invalid_fixed_placement`, if this is one. + pub fn request_error(&self) -> Option<&RequestError> { + match self { + Self::InvalidRequest(error) => Some(error), + _ => None, + } + } +} + impl From for PackError { fn from(error: RequestError) -> Self { Self::InvalidRequest(error) diff --git a/src/fixed.rs b/src/fixed.rs index a32c4e1..9e289b5 100644 --- a/src/fixed.rs +++ b/src/fixed.rs @@ -81,7 +81,7 @@ fn entry_shape_fault(entry: &Value, place: &str, field: &str, unit: &str) -> Opt let unknown = unknown_keys(map, &FIELDS); if !unknown.is_empty() { return fault( - format!("{place} does not carry {}", spell_names(&unknown)), + format!("{place} cannot carry {}", spell_names(&unknown)), field, ); } @@ -139,7 +139,7 @@ fn point_shape_fault(point: &Value, place: &str, field: &str) -> Option { let unknown = unknown_keys(map, &AXES); if !unknown.is_empty() { return fault( - format!("{place} does not carry {}", spell_names(&unknown)), + format!("{place} cannot carry {}", spell_names(&unknown)), field, ); } diff --git a/src/lib.rs b/src/lib.rs index 626627d..b3da175 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,7 +30,7 @@ mod units; mod validation; mod value_text; -pub use api::{pack_json, pack_request, rebalance_json}; +pub use api::{ExecutionOptions, pack_json, pack_json_with, pack_request, rebalance_json}; pub use deadline::{Clock, Deadline}; pub use error::{PackError, PackResult, RequestError}; pub use explain::{ diff --git a/src/model.rs b/src/model.rs index 8c4713b..b3db7bc 100644 --- a/src/model.rs +++ b/src/model.rs @@ -897,6 +897,42 @@ impl PackedContainer { pub fn axle_reactions(&self) -> Option<(i128, i128, i128)> { axle_reactions(&self.container, &self.placements, None) } + + /// Turns an already-packed container into an item for multi-level nesting. + pub fn as_item(&self) -> Item { + Item { + id: self.id(), + dimensions: self + .container + .outer_dimensions + .unwrap_or(self.container.inner_dimensions), + weight: self.gross_weight(), + quantity: 1, + allowed_rotations: Rotation::ALL.to_vec(), + stackable: true, + must_be_on_floor: false, + max_top_load: None, + minimum_support_ratio: 0.0, + group: None, + tags: BTreeSet::new(), + incompatible_tags: BTreeSet::new(), + priority: 0, + metadata: BTreeMap::from([( + "source_packed_container".into(), + Value::String(self.id()), + )]), + nesting_height: None, + max_stacked_items: None, + ground_contact_rule: None, + stop_index: None, + eligible_container_tags: BTreeSet::new(), + value: None, + shape_type: ShapeType::RigidCuboid, + hull_vertices: None, + compression_ratio_ppm: None, + max_compression_pressure_kpa: None, + } + } } pub fn axle_reactions( diff --git a/src/nested.rs b/src/nested.rs index eb8f072..076a1ad 100644 --- a/src/nested.rs +++ b/src/nested.rs @@ -17,12 +17,30 @@ pub struct NestedPackingResult { pub levels: Vec<(String, PackingResult)>, } -/// Executes explicitly supplied levels in order. Cross-level transformation -/// and Pareto beam optimization are intentionally left to the caller in 0.1.0. +/// Executes explicitly supplied levels in order. +/// +/// A level whose request lists no items packs the previous level's containers instead, each +/// as one item (`PackedContainer::as_item`), as Python's `NestedPacker` does. Such a level is +/// not run after a level that left something unpacked: the chain ends there, since packing +/// part of an order onto a pallet would pass for the whole of it. A level that lists its own +/// items always runs on them, exactly as before chaining existed. A non-zero `beam_width` +/// sets every level's `container_plan_beam_width`. pub fn pack_nested(request: &NestedPackingRequest) -> PackResult { - let mut levels = Vec::new(); + let mut levels: Vec<(String, PackingResult)> = Vec::new(); for level in &request.levels { - levels.push((level.name.clone(), pack_request(&level.request)?)); + let mut level_request = level.request.clone(); + if level_request.items.is_empty() + && let Some((_, previous)) = levels.last() + { + if !previous.complete() { + break; + } + level_request.items = previous.containers.iter().map(|c| c.as_item()).collect(); + } + if request.beam_width > 0 { + level_request.config.container_plan_beam_width = request.beam_width; + } + levels.push((level.name.clone(), pack_request(&level_request)?)); } Ok(NestedPackingResult { levels }) } diff --git a/src/request_errors.rs b/src/request_errors.rs index ec66a20..8f0a820 100644 --- a/src/request_errors.rs +++ b/src/request_errors.rs @@ -9,6 +9,7 @@ use crate::canonical_json::{MAX_EXACT_MAGNITUDE, json_integer, json_spelling}; use crate::error::RequestError; +use crate::fixed::unknown_keys; use crate::units::{MeasureKind, measure_ticks}; use serde_json::{Map, Value}; use std::collections::BTreeSet; @@ -16,6 +17,15 @@ use std::collections::BTreeSet; type Checked = Result; const SOLVER_PROFILES: [&str; 4] = ["fast", "balanced", "quality", "exact_small"]; +const OBJECTIVES: [&str; 6] = [ + "default", + "lowest_cost", + "shipping_cost", + "lowest_landed_cost", + "open_dimension_height", + "maximum_value", +]; +const ACCESS_DIRECTIONS: [&str; 6] = ["+x", "-x", "+y", "-y", "+z", "-z"]; const CONFIGURATION_INTEGERS: [(&str, i64); 10] = [ ("time_limit_ms", 1), ("alternatives", 1), @@ -34,6 +44,29 @@ const EFFORT_LIMITS: [&str; 4] = [ "max_search_nodes", "max_restarts", ]; +/// Every key the request schema's `configuration` declares; it sets `additionalProperties: false`. +const CONFIGURATION_FIELDS: [&str; 20] = [ + "alternatives", + "clearance", + "container_plan_beam_width", + "container_plan_node_limit", + "dimensional_weight_divisor", + "dimensional_weight_length_unit", + "dimensional_weight_weight_unit", + "effort_budget", + "exact_item_limit", + "max_candidate_points", + "max_candidates_per_item", + "max_containers", + "minimum_support_ratio", + "multi_start_orders", + "objective", + "require_placement_coordinates", + "seed", + "solver_profile", + "solvers", + "time_limit_ms", +]; const SIDES: [&str; 3] = ["length", "width", "height"]; const AXES: [&str; 3] = ["x", "y", "z"]; @@ -83,7 +116,13 @@ fn check_configuration(raw: Option<&Value>, unit: &str) -> Checked { }; let configuration = object(raw, "/configuration")?; let at = "/configuration"; - optional(configuration, "solver_profile", at, one_of_profiles)?; + known_fields(configuration, at, &CONFIGURATION_FIELDS)?; + optional(configuration, "solver_profile", at, |value, field| { + one_of(value, field, &SOLVER_PROFILES) + })?; + optional(configuration, "objective", at, |value, field| { + one_of(value, field, &OBJECTIVES) + })?; for (name, minimum) in CONFIGURATION_INTEGERS { optional(configuration, name, at, |value, field| { integer(value, field, minimum) @@ -103,6 +142,7 @@ fn check_configuration(raw: Option<&Value>, unit: &str) -> Checked { }; let at = "/configuration/effort_budget"; let budget = object(effort, at)?; + known_fields(budget, at, &EFFORT_LIMITS)?; for name in EFFORT_LIMITS { optional(budget, name, at, |value, field| integer(value, field, 1))?; } @@ -171,6 +211,7 @@ fn check_container(raw: &Value, at: &str, unit: &str) -> Checked { optional(container, "void_fill_reserve_ratio", at, |value, field| { ratio(value, field, Some(1)) })?; + optional(container, "access_directions", at, access_directions)?; optional(container, "tag_limits", at, tag_limits)?; optional(container, "rate_table", at, rate_table)?; optional(container, "obstacles", at, |value, field| { @@ -307,24 +348,45 @@ fn ratio(value: &Value, field: &str, maximum: Option) -> Checked { } } -fn one_of_profiles(value: &Value, field: &str) -> Checked { - if value - .as_str() - .is_some_and(|profile| SOLVER_PROFILES.contains(&profile)) - { +/// The schema closes this object: a key it does not name is refused, never ignored. The first +/// unknown key in code-point order is named, the order every engine can share. +fn known_fields(map: &Map, at: &str, known: &[&str]) -> Checked { + match unknown_keys(map, known).first() { + Some(key) => Err(RequestError::new( + "not_allowed", + join(at, key), + "is not a known field", + )), + None => Ok(()), + } +} + +fn one_of(value: &Value, field: &str, allowed: &[&str]) -> Checked { + if value.as_str().is_some_and(|item| allowed.contains(&item)) { return Ok(()); } - let allowed = SOLVER_PROFILES + let allowed_values = allowed .iter() - .map(|profile| Value::String((*profile).to_owned())) + .map(|item| Value::String((*item).to_owned())) .collect(); Err(RequestError::new( "not_allowed", field, - format!("must be one of {}", json_spelling(&Value::Array(allowed))), + format!( + "must be one of {}", + json_spelling(&Value::Array(allowed_values)) + ), )) } +fn access_directions(raw: &Value, at: &str) -> Checked { + let directions = list(raw, at)?; + for (index, direction) in directions.iter().enumerate() { + one_of(direction, &join(at, &index.to_string()), &ACCESS_DIRECTIONS)?; + } + Ok(()) +} + /// A measure is an integer, a string or `{value, unit}`, in a known unit, and never negative. fn measure(value: &Value, field: &str, kind: MeasureKind, unit: &str) -> Checked { match value { diff --git a/src/solvers/blocks.rs b/src/solvers/blocks.rs index b9f5835..067c3e4 100644 --- a/src/solvers/blocks.rs +++ b/src/solvers/blocks.rs @@ -187,6 +187,9 @@ pub(crate) fn pack_homogeneous_blocks( fn supports(request: &PackingRequest, constraints: &[Arc]) -> bool { constraints.is_empty() + // A block set on a smaller one overhangs it, so a request that asks for support + // is left to the per-item search. + && request.config.minimum_support_ratio == 0.0 && request.fixed_containers.is_empty() && request.containers.iter().all(|container| { container.obstacles.is_empty() @@ -211,6 +214,24 @@ fn supports(request: &PackingRequest, constraints: &[Arc f64 { + if origin.z == 0 { + return 1.0; + } + let base = Aabb { + origin, + dimensions: envelope, + }; + let area = placements + .iter() + .map(Placement::envelope_box) + .filter(|below| below.z2() == origin.z) + .map(|below| below.overlap_area_xy(base)) + .sum::(); + (area as f64 / envelope.base_area() as f64).min(1.0) +} + fn pack_one( container: &Container, sequence: usize, @@ -428,7 +449,13 @@ fn pack_mode( dimensions: block.physical, envelope_origin: origin, envelope_dimensions: block.envelope, - support_ratio: 1.0, + // Above its bottom layer a member rests on an identical + // footprint; the bottom layer rests on whatever is there. + support_ratio: if z == 0 { + member_support(&packed.placements, origin, block.envelope) + } else { + 1.0 + }, top_load: Weight(0), fixed: false, }); @@ -475,6 +502,104 @@ mod tests { }).to_string() } + /// One 60x60x40 base and three 40x60x50 tops in a 100 mm crate: the base ends on two + /// tops and overhangs them. + fn a_base_and_three_tops(minimum_support_ratio: f64) -> serde_json::Value { + let request = serde_json::json!({ + "units": {"length": "mm"}, + "configuration": { + "solver_profile": "quality", + "solvers": ["homogeneous_blocks"], + "time_limit_ms": 60_000, + "effort_budget": {"max_search_nodes": 100_000}, + "minimum_support_ratio": minimum_support_ratio + }, + "items": [ + {"id":"base","quantity":1,"dimensions":{"length":"60","width":"60","height":"40"}}, + {"id":"top","quantity":3,"dimensions":{"length":"40","width":"60","height":"50"}} + ], + "containers": [{"id":"crate","quantity":1,"inner_dimensions":{"length":"100","width":"100","height":"100"}}] + }) + .to_string(); + serde_json::from_str(&pack_json(&request).expect("solve")).unwrap() + } + + /// Each placement's reported support next to the share of its base that rests on the + /// floor or on a top face, from geometry alone. + fn reported_and_resting_support(result: &serde_json::Value) -> Vec<(f64, f64)> { + let ticks = |value: &serde_json::Value| value["ticks"].as_i64().unwrap(); + let boxes = result["containers"][0]["placements"] + .as_array() + .unwrap() + .iter() + .map(|p| { + let (x, y, z) = ( + ticks(&p["position"]["x"]), + ticks(&p["position"]["y"]), + ticks(&p["position"]["z"]), + ); + let reported = p["support_ratio"].as_str().unwrap().parse::().unwrap(); + ( + [x, y, z], + [ + x + ticks(&p["dimensions"]["length"]), + y + ticks(&p["dimensions"]["width"]), + z + ticks(&p["dimensions"]["height"]), + ], + reported, + ) + }) + .collect::>(); + boxes + .iter() + .map(|(low, high, reported)| { + if low[2] == 0 { + return (*reported, 1.0); + } + let resting = boxes + .iter() + .filter(|(_, below, _)| below[2] == low[2]) + .map(|(other_low, other_high, _)| { + (high[0].min(other_high[0]) - low[0].max(other_low[0])).max(0) + * (high[1].min(other_high[1]) - low[1].max(other_low[1])).max(0) + }) + .sum::(); + let area = (high[0] - low[0]) * (high[1] - low[1]); + (*reported, resting as f64 / area as f64) + }) + .collect() + } + + #[test] + fn a_block_set_on_a_smaller_one_reports_the_support_it_really_has() { + let result = a_base_and_three_tops(0.0); + let support = reported_and_resting_support(&result); + assert_eq!( + support.iter().filter(|(_, resting)| *resting < 1.0).count(), + 1 + ); + assert!( + support + .iter() + .any(|(reported, resting)| (*reported - 5.0 / 6.0).abs() < 1e-6 + && (*resting - 5.0 / 6.0).abs() < 1e-6) + ); + for (reported, resting) in support { + assert!( + (reported - resting).abs() < 1e-6, + "{reported} reported, {resting} resting" + ); + } + } + + #[test] + fn the_block_solver_leaves_a_request_that_asks_for_support_to_the_per_item_search() { + let result = a_base_and_three_tops(1.0); + let support = reported_and_resting_support(&result); + assert!(!support.is_empty()); + assert!(support.iter().all(|(_, resting)| *resting == 1.0)); + } + #[test] fn more_counted_block_effort_cannot_worsen_the_objective() { let low: serde_json::Value = diff --git a/src/solvers/exact.rs b/src/solvers/exact.rs index 2b567b5..f4a90ad 100644 --- a/src/solvers/exact.rs +++ b/src/solvers/exact.rs @@ -57,14 +57,19 @@ pub fn pack_exact_one( .filter(|(_, container)| container.quantity != Some(0)) .map(|(position, container)| { let initial = ContainerState::new(container, 1); - let floor = optimistic_completion_score(&initial, &profiled, &request.config); - (floor, position, initial) + let (can_fit, cannot_fit): (Vec<_>, Vec<_>) = + profiled.iter().cloned().partition(|(item, _)| { + item_can_fit_container(item, &initial.packed.container, &request.config) + }); + let floor = + optimistic_completion_score(&initial, &can_fit, &cannot_fit, &request.config); + (floor, position, initial, can_fit, cannot_fit) }) .collect::>(); planned.sort_by(|left, right| (&left.0, left.1).cmp(&(&right.0, right.1))); let mut best_position = usize::MAX; - for (root_floor, position, initial) in planned { + for (root_floor, position, initial, can_fit, cannot_fit) in planned { if deadline.expired() || effort_exhausted(request, &metrics) { searched_all_containers = false; break; @@ -76,7 +81,7 @@ pub fn pack_exact_one( } let mut best_state = initial.clone(); - let mut best_state_score = score_state(&best_state, &profiled, &request.config); + let mut best_state_score = score_state(&best_state, &can_fit, &cannot_fit, &request.config); let complete_lower_bound = root_floor; let mut visited = VisitedStates { keys: StateKeys::new( @@ -84,7 +89,7 @@ pub fn pack_exact_one( constraints.is_empty() && scorers.is_empty() && initial.packed.container.max_stack_density.is_none() - && profiled.iter().all(|(instance, _)| { + && can_fit.iter().all(|(instance, _)| { !instance.item.is_stack_sensitive() && instance.item.shape_type != ShapeType::Compressible }), @@ -92,7 +97,8 @@ pub fn pack_exact_one( seen: BTreeSet::new(), }; search( - profiled.clone(), + can_fit, + &cannot_fit, request, constraints, scorers, @@ -261,6 +267,39 @@ fn exact_item_profile(item: &ItemInstance, config: &PackingConfig) -> ExactItemP } } +fn item_can_fit_container( + item: &ItemInstance, + container: &Container, + config: &PackingConfig, +) -> bool { + if container.max_items == Some(0) { + return false; + } + if !item.item.eligible_container_tags.is_empty() + && item + .item + .eligible_container_tags + .is_disjoint(&container.tags) + { + return false; + } + if container + .max_payload + .is_some_and(|max| item.item.weight.0 > max.0) + { + return false; + } + item.item + .dimensions + .unique_rotations(&item.item.allowed_rotations) + .iter() + .any(|(_, dimensions)| { + dimensions + .expand(config.clearance) + .fits_inside(container.inner_dimensions) + }) +} + /// Reuses the canonical finished-result objective at every visited exact-search node. /// This adds `O(n^2)` scoring work per node because nesting-aware used volume checks /// placement pairs, and no asymptotic live-space growth to the @@ -268,10 +307,12 @@ fn exact_item_profile(item: &ItemInstance, config: &PackingConfig) -> ExactItemP fn score_state( state: &ContainerState, remaining: &[(ItemInstance, ExactItemProfile)], + unfit: &[(ItemInstance, ExactItemProfile)], config: &PackingConfig, ) -> Vec { let unpacked = remaining .iter() + .chain(unfit.iter()) .map(|(instance, _)| { UnpackedItem::new( instance.clone(), @@ -306,9 +347,10 @@ fn score_state( fn optimistic_completion_score( state: &ContainerState, remaining: &[(ItemInstance, ExactItemProfile)], + unfit: &[(ItemInstance, ExactItemProfile)], config: &PackingConfig, ) -> Vec { - if state.packed.placements.is_empty() && remaining.is_empty() { + if state.packed.placements.is_empty() && remaining.is_empty() && unfit.is_empty() { return score_solution(&[], &[], config); } @@ -371,7 +413,7 @@ fn optimistic_completion_score( placeable = placeable.min(maximum.saturating_sub(state.packed.placements.len())); } let smallest_volume_sum = volumes.iter().take(placeable).sum::(); - let unpacked_floor = (remaining.len() - placeable) as i128; + let unpacked_floor = (remaining.len() - placeable) as i128 + unfit.len() as i128; if placeable == 0 && state.packed.placements.is_empty() { // No descendant can open this container at all: every one scores exactly @@ -511,6 +553,7 @@ impl StateKeys { #[allow(clippy::too_many_arguments)] fn search( remaining: Vec<(ItemInstance, ExactItemProfile)>, + unfit: &[(ItemInstance, ExactItemProfile)], request: &PackingRequest, constraints: &[Arc], scorers: &[Arc], @@ -533,11 +576,12 @@ fn search( return; } metrics.search_nodes_expanded = metrics.search_nodes_expanded.saturating_add(1); - // This node's own score leads with `remaining.len()` unpacked, so it can only + // This node's own score leads with `remaining.len() + unfit.len()` unpacked, so it can only // beat the incumbent when that count does not already lose the first element; // skipping the `O(n^2)` scoring otherwise changes no incumbent decision. - if remaining.len() as i128 <= best_score[0] { - let score = score_state(state, &remaining, &request.config); + let total_unpacked = (remaining.len() + unfit.len()) as i128; + if total_unpacked <= best_score[0] { + let score = score_state(state, &remaining, unfit, &request.config); if score < *best_score { *best = state.clone(); *best_score = score; @@ -557,7 +601,7 @@ fn search( // cannot change the result. Without this the removal of the first-complete // shortcut left the DFS exploring the entire permutation tree whenever the // complete floor is geometrically unreachable. - if optimistic_completion_score(state, &remaining, &request.config) >= *best_score { + if optimistic_completion_score(state, &remaining, unfit, &request.config) >= *best_score { return; } @@ -593,6 +637,7 @@ fn search( next_remaining.remove(index); search( next_remaining, + unfit, request, constraints, scorers, @@ -735,4 +780,43 @@ mod tests { .all(|item| item["proof"]["level"] == "unknown_due_to_limit") ); } + + #[test] + fn exact_small_stops_early_when_an_item_is_proven_not_to_fit() { + // 's scene: without the pallet jack the search finishes in about a hundred + // candidates. Before the jack alone spent the whole budget (106 861 + // candidates at 1M, `effort_limit`); this budget is small enough to show that fast. + let request = r#"{ + "units":{"length":"mm"}, + "configuration":{ + "time_limit_ms":300000, + "effort_budget":{ + "max_candidates_evaluated":20000, + "max_placement_attempts":20000, + "max_search_nodes":20000 + } + }, + "items":[ + {"id":"printer","quantity":1,"weight":"9 kg","keep_upright":true, + "dimensions":{"length":"420","width":"340","height":"260"}}, + {"id":"toner","quantity":4,"weight":"900 g", + "dimensions":{"length":"180","width":"120","height":"100"}}, + {"id":"pallet-jack","quantity":1,"weight":"80 kg", + "dimensions":{"length":"1200","width":"550","height":"1200"}} + ], + "containers":[ + {"id":"crate","quantity":1,"max_payload":"30 kg", + "inner_dimensions":{"length":"600","width":"400","height":"400"}} + ] + }"#; + + let output = pack_json(request).expect("a request with an unfittable item"); + let result: serde_json::Value = serde_json::from_str(&output).unwrap(); + assert_eq!(result["algorithm"]["effort_limit_reached"], false); + assert_eq!(result["algorithm"]["time_limit_reached"], false); + let unpacked = result["unpacked_items"].as_array().unwrap(); + assert_eq!(unpacked.len(), 1); + assert_eq!(unpacked[0]["item_id"], "pallet-jack#1"); + assert_eq!(unpacked[0]["proof"]["level"], "proven"); + } } diff --git a/src/solvers/extreme.rs b/src/solvers/extreme.rs index 12c73bb..6203983 100644 --- a/src/solvers/extreme.rs +++ b/src/solvers/extreme.rs @@ -561,7 +561,8 @@ pub fn find_candidates_at_points( state .spatial_index .query(envelope_box) - .into_iter() + .iter() + .copied() .any(|index| { metrics.collision_checks = metrics.collision_checks.saturating_add(1); let existing = &state.packed.placements[index]; @@ -2502,24 +2503,16 @@ struct ContainerBeamNode { unplaced: Vec, } -fn count_with_capacity(sorted_costs: &[i128], capacity: i128) -> usize { - let mut used = 0_i128; - sorted_costs - .iter() - .take_while(|cost| { - if used.saturating_add(**cost) > capacity { - false - } else { - used = used.saturating_add(**cost); - true - } - }) - .count() +/// How many of the cheapest costs fit in `capacity`, read off their prefix sums. Costs are +/// non-negative, so the sums never decrease and the count is one binary search: `O(log f)` +/// per node instead of the `O(f)` walk. +fn count_with_capacity(cumulative_costs: &[i128], capacity: i128) -> usize { + cumulative_costs.partition_point(|&used| used <= capacity) } -/// The future items' costs, sorted once for a whole beam step rather than per node: the -/// bound below reads them for every node in the beam, and sorting them there was the loop's -/// own cost, not the search's. +/// Prefix sums of the future items' ascending costs, built once for a whole beam step rather +/// than per node: the bound below reads them for every node in the beam, and sorting them +/// there was the loop's own cost, not the search's. struct PrecomputedFuture { volumes: Option>, weights: Option>, @@ -2540,9 +2533,9 @@ impl PrecomputedFuture { let volumes = future .iter() .all(|item| item.item.nesting_height.is_none()) - .then(|| sorted(future.iter().map(|item| item.item.dimensions.volume()))); + .then(|| cumulative(future.iter().map(|item| item.item.dimensions.volume()))); let weights = - weighed.then(|| sorted(future.iter().map(|item| i128::from(item.item.weight.0)))); + weighed.then(|| cumulative(future.iter().map(|item| i128::from(item.item.weight.0)))); Self { volumes, weights, @@ -2551,9 +2544,14 @@ impl PrecomputedFuture { } } -fn sorted(costs: impl Iterator) -> Vec { +fn cumulative(costs: impl Iterator) -> Vec { let mut costs: Vec = costs.collect(); costs.sort_unstable(); + let mut used = 0_i128; + for cost in &mut costs { + used = used.saturating_add(*cost); + *cost = used; + } costs } @@ -3263,6 +3261,28 @@ pub(super) fn explain_unfit(request: &PackingRequest, item: &ItemInstance) -> St mod tests { use super::*; + #[test] + fn prefix_sum_count_is_the_largest_cardinality_the_resource_admits() { + let cases: [&[i128]; 4] = [&[2, 3, 5], &[1, 4, 4, 9], &[3, 3, 3, 7, 8], &[0, 0, 2, 6]]; + for costs in cases { + let prefix = cumulative(costs.iter().copied()); + for capacity in 0..=costs.iter().sum::() { + let exact = (0_u32..1 << costs.len()) + .filter(|mask| { + (0..costs.len()) + .filter(|bit| mask & (1 << bit) != 0) + .map(|bit| costs[bit]) + .sum::() + <= capacity + }) + .map(|mask| mask.count_ones() as usize) + .max() + .unwrap_or(0); + assert_eq!(count_with_capacity(&prefix, capacity), exact); + } + } + } + fn dimensions(length: i64, width: i64, height: i64) -> Dimensions { Dimensions { length: Length(length), diff --git a/src/solvers/maximal.rs b/src/solvers/maximal.rs index c71bd45..7ff3ee3 100644 --- a/src/solvers/maximal.rs +++ b/src/solvers/maximal.rs @@ -276,20 +276,8 @@ pub(crate) fn subtract_all( .collect::>(); let mut result = Vec::with_capacity(pieces.len()); for (index, (space, is_new)) in pieces.iter().enumerate() { - if *is_new { - let candidate = extents[index]; - let dominated = extents.iter().enumerate().any(|(other_index, other)| { - other_index != index - && other[0] <= candidate[0] - && other[1] <= candidate[1] - && other[2] <= candidate[2] - && candidate[3] <= other[3] - && candidate[4] <= other[4] - && candidate[5] <= other[5] - }); - if dominated { - continue; - } + if *is_new && is_contained(&extents, index) { + continue; } result.push(*space); } @@ -317,6 +305,27 @@ pub(crate) fn subtract_all( result } +/// Whether another extent contains `extents[index]`, for extents ordered by origin x. +/// +/// A container starts at or before what it contains, so the scan stops at the first +/// extent that starts further along x: `O(prefix)` instead of `O(s)`, with no index to +/// build. +fn is_contained(extents: &[[i64; 6]], index: usize) -> bool { + let candidate = extents[index]; + extents + .iter() + .enumerate() + .take_while(|(_, other)| other[0] <= candidate[0]) + .any(|(other_index, other)| { + other_index != index + && other[1] <= candidate[1] + && other[2] <= candidate[2] + && candidate[3] <= other[3] + && candidate[4] <= other[4] + && candidate[5] <= other[5] + }) +} + fn subtract(space: Space, occupied: Aabb) -> Vec { let source = space.0; if !source.intersects(occupied) { diff --git a/src/spatial_index.rs b/src/spatial_index.rs index 3952b8e..438a521 100644 --- a/src/spatial_index.rs +++ b/src/spatial_index.rs @@ -7,76 +7,114 @@ //! box is never omitted. use crate::geometry::{Aabb, Dimensions, Point}; +use std::borrow::Cow; use std::collections::BTreeMap; type CellRange = (i64, i64); type CellRanges = (CellRange, CellRange, CellRange); +type Cell = (i64, i64, i64); + +/// Cells per axis inside the container; `cell_size` makes it at most 8. +const CELLS_PER_AXIS: i64 = 8; #[derive(Clone, Debug)] pub(crate) struct SpatialIndex { cell_x: i64, cell_y: i64, cell_z: i64, - cells: BTreeMap<(i64, i64, i64), Vec>, + /// How many cells cover the container on each axis. + grid: (i64, i64, i64), + /// The container's cells, x-major: a bucket is one multiply-add away, where a tree + /// lookup per cell was the query's dominant cost. At most 512 buckets. + cells: Vec>, + /// Cells outside the container. Nothing placed lies there on a valid request; the + /// map keeps the index exact for any box it is given rather than assuming so. + outside: BTreeMap>, } impl SpatialIndex { pub(crate) fn new(container: Dimensions) -> Self { + let cell_x = cell_size(container.length.0); + let cell_y = cell_size(container.width.0); + let cell_z = cell_size(container.height.0); + let grid = ( + ceil_div(container.length.0.max(1), cell_x), + ceil_div(container.width.0.max(1), cell_y), + ceil_div(container.height.0.max(1), cell_z), + ); Self { - cell_x: cell_size(container.length.0), - cell_y: cell_size(container.width.0), - cell_z: cell_size(container.height.0), - cells: BTreeMap::new(), + cell_x, + cell_y, + cell_z, + grid, + cells: Vec::new(), + outside: BTreeMap::new(), } } pub(crate) fn add(&mut self, index: usize, box_: Aabb) { let ((x1, x2), (y1, y2), (z1, z2)) = self.cell_ranges(box_); + if self.cells.is_empty() { + // Allocated on first use, so an empty state -- and every clone of one -- costs + // nothing for the buckets it has not filled. + let (gx, gy, gz) = self.grid; + self.cells = vec![Vec::new(); (gx * gy * gz) as usize]; + } for x in x1..x2 { for y in y1..y2 { for z in z1..z2 { - self.cells.entry((x, y, z)).or_default().push(index); + match self.slot((x, y, z)) { + Some(slot) => self.cells[slot].push(index), + None => self.outside.entry((x, y, z)).or_default().push(index), + } } } } } - pub(crate) fn query(&self, box_: Aabb) -> Vec { - // A contiguous buffer is materially cheaper in this hot path than allocating - // one tree node per unique placement. Sorting restores the exact ascending - // index order the former BTreeSet returned, so collision short-circuit order - // and deterministic metrics remain unchanged. O(q log q) time, O(q) space -- - // the one allocation the query makes; the cell walk itself allocates nothing, - // and this is the innermost call of every candidate sweep. + pub(crate) fn query(&self, box_: Aabb) -> Cow<'_, [usize]> { + // Sorting restores the exact ascending index order the former BTreeSet returned, + // so collision short-circuit order and deterministic metrics remain unchanged. + // Multi-cell: O(c + q log q) time for c cells and q hits, O(q) space, sized once + // up front instead of grown. A single cell borrows its bucket without allocating. let ((x1, x2), (y1, y2), (z1, z2)) = self.cell_ranges(box_); if x2 == x1 + 1 && y2 == y1 + 1 && z2 == z1 + 1 { - return self.cells.get(&(x1, y1, z1)).cloned().unwrap_or_default(); + return Cow::Borrowed(self.bucket((x1, y1, z1))); } - let mut result = Vec::new(); - for x in x1..x2 { - for y in y1..y2 { - for z in z1..z2 { - if let Some(indices) = self.cells.get(&(x, y, z)) { - result.extend_from_slice(indices); - } - } - } + let cells = || { + (x1..x2).flat_map(move |x| (y1..y2).flat_map(move |y| (z1..z2).map(move |z| (x, y, z)))) + }; + let hits = cells().map(|cell| self.bucket(cell).len()).sum(); + let mut result = Vec::with_capacity(hits); + for cell in cells() { + result.extend_from_slice(self.bucket(cell)); } if result.len() > 1 { result.sort_unstable(); result.dedup(); } - result + Cow::Owned(result) } pub(crate) fn bucket_at(&self, point: Point) -> &[usize] { - let ix = point.x.div_euclid(self.cell_x); - let iy = point.y.div_euclid(self.cell_y); - let iz = point.z.div_euclid(self.cell_z); - self.cells - .get(&(ix, iy, iz)) - .map(|v| v.as_slice()) - .unwrap_or(&[]) + self.bucket(( + point.x.div_euclid(self.cell_x), + point.y.div_euclid(self.cell_y), + point.z.div_euclid(self.cell_z), + )) + } + + fn bucket(&self, cell: Cell) -> &[usize] { + match self.slot(cell) { + Some(slot) => self.cells.get(slot).map_or(&[], Vec::as_slice), + None => self.outside.get(&cell).map_or(&[], Vec::as_slice), + } + } + + fn slot(&self, (x, y, z): Cell) -> Option { + let (gx, gy, gz) = self.grid; + let inside = (0..gx).contains(&x) && (0..gy).contains(&y) && (0..gz).contains(&z); + inside.then(|| ((x * gy + y) * gz + z) as usize) } fn cell_ranges(&self, box_: Aabb) -> CellRanges { @@ -89,7 +127,7 @@ impl SpatialIndex { } fn cell_size(axis: i64) -> i64 { - ceil_div(axis.max(1), 8).max(1) + ceil_div(axis.max(1), CELLS_PER_AXIS).max(1) } fn cell_range(start: i64, end: i64, size: i64) -> (i64, i64) { @@ -120,6 +158,18 @@ mod tests { } } + #[test] + fn single_cell_queries_borrow_the_bucket_without_allocating() { + let mut index = SpatialIndex::new(box_at(0, 0, 0, 800, 800, 800).dimensions); + index.add(0, box_at(0, 0, 0, 50, 50, 50)); + let query = index.query(box_at(0, 0, 0, 60, 60, 60)); + assert_eq!(&query[..], &[0]); + assert_eq!( + query.as_ptr(), + index.bucket_at(Point { x: 0, y: 0, z: 0 }).as_ptr() + ); + } + #[test] fn every_exact_collision_is_present_in_the_broad_phase_result() { let container = box_at(0, 0, 0, 800, 800, 800).dimensions; @@ -145,7 +195,7 @@ mod tests { 60, 60, ); - let broad = index.query(query).into_iter().collect::>(); + let broad = index.query(query).iter().copied().collect::>(); let exact = boxes .iter() .enumerate() @@ -158,6 +208,28 @@ mod tests { } } + #[test] + fn a_box_outside_the_container_is_still_found() { + let mut index = SpatialIndex::new(box_at(0, 0, 0, 800, 800, 800).dimensions); + index.add(0, box_at(-150, 0, 0, 100, 100, 100)); + index.add(1, box_at(780, 0, 0, 100, 100, 100)); + index.add(2, box_at(0, 0, 0, 50, 50, 50)); + + assert_eq!(&index.query(box_at(-140, 10, 10, 20, 20, 20))[..], &[0]); + assert_eq!( + &index.query(box_at(-150, 0, 0, 1000, 60, 60))[..], + &[0, 1, 2] + ); + assert_eq!(index.bucket_at(Point { x: 850, y: 0, z: 0 }), &[1]); + } + + #[test] + fn an_empty_index_answers_every_query_with_nothing() { + let index = SpatialIndex::new(box_at(0, 0, 0, 800, 800, 800).dimensions); + assert!(index.query(box_at(0, 0, 0, 800, 800, 800)).is_empty()); + assert!(index.bucket_at(Point { x: 0, y: 0, z: 0 }).is_empty()); + } + #[test] fn a_local_query_does_not_degenerate_to_the_whole_container() { let container = box_at(0, 0, 0, 800, 800, 800).dimensions; diff --git a/src/validation.rs b/src/validation.rs index bc21572..912e482 100644 --- a/src/validation.rs +++ b/src/validation.rs @@ -140,8 +140,8 @@ impl IndependentValidator { if placements_collide(placement, other) && !valid_nesting(placement, other) { issue( &mut issues, - "overlap", - &format!("{} and {}", id, other.instance.id()), + "collision", + &format!("{} with {}", id, other.instance.id()), ); } } diff --git a/tests/access_directions.rs b/tests/access_directions.rs index c172ebc..0c4cca1 100644 --- a/tests/access_directions.rs +++ b/tests/access_directions.rs @@ -16,6 +16,10 @@ use serde_json::{Value, json}; +/// Counted work, not a clock, decides where the search stops: under the default wall-clock +/// limit a loaded host truncated one of two otherwise identical solves, and the comparisons +/// below reported the host rather than the engine. The time limit is only a fuse, far above +/// what one cube needs. fn request(doors: Option) -> String { let mut container = json!({ "id": "van", @@ -26,6 +30,7 @@ fn request(doors: Option) -> String { } json!({ "units": { "length": "mm" }, + "configuration": { "effort_budget": { "max_search_nodes": 20000 }, "time_limit_ms": 60000 }, "items": [{ "id": "cube", "quantity": 1, "dimensions": { "length": "100", "width": "100", "height": "100" } }], "containers": [container] @@ -95,15 +100,15 @@ fn an_empty_door_list_is_accepted_and_matches_the_absent_field() { #[test] fn a_door_list_that_is_not_an_array_is_refused() { - assert!(refusal(json!("-x")).contains("must be an array")); - assert!(refusal(json!({ "wall": "-x" })).contains("must be an array")); + assert!(refusal(json!("-x")).contains("must be a list")); + assert!(refusal(json!({ "wall": "-x" })).contains("must be a list")); } #[test] fn a_non_string_entry_is_refused() { - assert!(refusal(json!([1])).contains("must be strings")); - assert!(refusal(json!([null])).contains("must be strings")); - assert!(refusal(json!([["-x"]])).contains("must be strings")); + assert!(refusal(json!([1])).contains("must be one of")); + assert!(refusal(json!([null])).contains("must be one of")); + assert!(refusal(json!([["-x"]])).contains("must be one of")); } /// Refused, not filtered out. Silently discarding an unrecognised door would leave a @@ -114,7 +119,7 @@ fn an_unknown_direction_is_refused_rather_than_dropped() { for direction in ["north", "x", "+X", "+w", "", "-x "] { let message = refusal(json!([direction])); assert!( - message.contains("unknown movement direction"), + message.contains("must be one of"), "{direction:?} produced {message}" ); } @@ -124,5 +129,8 @@ fn an_unknown_direction_is_refused_rather_than_dropped() { /// something the caller did not write. #[test] fn one_bad_direction_refuses_the_whole_list() { - assert!(refusal(json!(["-x", "sideways", "+z"])).contains("unknown movement direction")); + assert!( + refusal(json!(["-x", "sideways", "+z"])) + .contains("/containers/0/access_directions/1: must be one of") + ); } diff --git a/tests/bound_ceilings.rs b/tests/bound_ceilings.rs index 31737db..ad04644 100644 --- a/tests/bound_ceilings.rs +++ b/tests/bound_ceilings.rs @@ -18,8 +18,11 @@ //! `registry_and_nested.rs` records: an in-file module counts towards its own file's //! coverage, which is the inflation the instrument exists to avoid. +mod support; + +use packvium_core::ItemInstance; use packvium_core::bounds::{ - Bounds, ContainerType, Instance, MAX_BOUND_SUM, MAX_BOUND_VALUE, from_reduced, + Bounds, ContainerType, Instance, MAX_BOUND_SUM, MAX_BOUND_VALUE, compute, from_reduced, }; fn instance(volume: i128) -> Instance { @@ -153,3 +156,101 @@ fn no_key_of_a_bound_is_ever_negative() { } } } + +/// `compute` is `from_reduced` over the engine's own objects; the reduction is what is +/// checked here, by comparing the two on the same request. +#[test] +fn computing_from_engine_objects_matches_the_reduced_form() { + let mut item = support::item("cube"); + item.quantity = 2; + let instances = (1..=2) + .map(|sequence| ItemInstance { + item: item.clone(), + sequence, + }) + .collect::>(); + let container = support::container(); + let reduced = from_reduced( + &[Instance { + volume: item.dimensions.volume(), + weight: i128::from(item.weight.0), + shrinks: false, + }; 2], + &[ContainerType { + usable: container.inner_dimensions.volume(), + inner: container.inner_dimensions.volume(), + base_area: container.inner_dimensions.base_area(), + height: i128::from(container.inner_dimensions.height.0), + payload: None, + max_items: None, + quantity: None, + cost_minor: 0, + }], + ); + assert_eq!(compute(&instances, &[container]), reduced); +} + +/// A declared inventory multiplies a per-container capacity; both the multiplication and +/// the running sum are refused past the ceiling rather than wrapped. +#[test] +fn an_inventory_capacity_past_the_ceiling_is_refused() { + let counted = |usable: i128, quantity: i128| ContainerType { + quantity: Some(quantity), + ..roomy(usable) + }; + for container in [ + counted(i128::MAX / 2, 3), + counted(MAX_BOUND_SUM / 2 + 1, 2), + ContainerType { + payload: Some(i128::MAX / 2), + ..counted(1_000, 3) + }, + ] { + let error = from_reduced(&[instance(1_000)], &[container]) + .expect_err("an overflowing capacity is refused"); + assert!(error.to_string().contains("container capacity"), "{error}"); + } +} + +/// A container type with no floor or no volume makes the geometric keys vacuous rather than +/// dividing by zero. +#[test] +fn a_degenerate_container_type_leaves_the_geometric_keys_at_zero() { + let flat = ContainerType { + base_area: 0, + ..roomy(10_000) + }; + let hollow = ContainerType { + inner: 0, + usable: 0, + ..roomy(0) + }; + for containers in [vec![flat], vec![hollow, roomy(10_000)]] { + let bounds = from_reduced(&[instance(1_000)], &containers).expect("answerable"); + assert_eq!(bounds.stack_height_ppm.min(bounds.unused_volume_ppm), 0); + } +} + +/// Two volumes whose running sum wraps `i128` are refused by the checked addition, not the +/// ceiling, because the first stays under it. +#[test] +fn a_sum_that_would_wrap_is_refused_before_it_can() { + let error = from_reduced(&[instance(1), instance(i128::MAX)], &[roomy(10_000)]) + .expect_err("a wrapping sum is refused"); + assert!( + error.to_string().contains("overflows the exact range"), + "{error}" + ); +} + +#[test] +fn computing_reads_payload_and_item_limits_from_the_container() { + let mut container = support::container(); + container.max_payload = Some(packvium_core::Weight(1_000)); + container.max_items = Some(1); + let instance = ItemInstance { + item: support::item("cube"), + sequence: 1, + }; + compute(&[instance], &[container]).expect("answerable"); +} diff --git a/tests/constraints.rs b/tests/constraints.rs index 7ea9644..8635b2d 100644 --- a/tests/constraints.rs +++ b/tests/constraints.rs @@ -1,4 +1,7 @@ -use packvium_core::{ReasonProof, ResultFact, StartRecord, aggregate_termination, pack_json}; +use packvium_core::{ + ExecutionOptions, ReasonProof, ResultFact, StartRecord, aggregate_termination, pack_json, + pack_json_with, +}; use serde_json::{Value, json}; fn solve(mut value: Value) -> Value { @@ -252,11 +255,10 @@ fn a_high_priority_item_leads_every_built_in_ordering() { } #[test] -fn deterministic_placements_ignore_runtime_metadata() { +fn concurrent_starts_leave_the_answer_unchanged() { let request = json!({ "configuration": { "solver_profile": "quality", - "parallel": true, "time_limit_ms": 300000, "seed": 77 }, @@ -266,10 +268,34 @@ fn deterministic_placements_ignore_runtime_metadata() { ], "containers": [{"id": "box", "inner_dimensions": {"length": "200", "width": "100", "height": "100"}}] }); - let first = solve(request.clone()); - let second = solve(request); - assert_eq!(first["containers"], second["containers"]); - assert_eq!(first["unpacked_items"], second["unpacked_items"]); + let run = |parallel| -> Value { + let output = pack_json_with(&request.to_string(), ExecutionOptions { parallel }) + .expect("packing request should solve"); + serde_json::from_str(&output).expect("result should be JSON") + }; + let (concurrent, sequential) = (run(true), run(false)); + assert_eq!(concurrent["containers"], sequential["containers"]); + assert_eq!(concurrent["unpacked_items"], sequential["unpacked_items"]); + assert_eq!(concurrent["score"], sequential["score"]); +} + +#[test] +fn parallel_is_an_execution_option_not_a_request_field() { + let refused = pack_json( + &json!({ + "configuration": {"parallel": false}, + "items": [{"id": "a", "dimensions": {"length": "10", "width": "10", "height": "10"}}], + "containers": [{"id": "c", "inner_dimensions": {"length": "20", "width": "20", "height": "20"}}] + }) + .to_string(), + ); + let Err(packvium_core::PackError::InvalidRequest(error)) = refused else { + panic!("a request naming `parallel` must be refused, got {refused:?}"); + }; + assert_eq!( + (error.reason(), error.field()), + ("not_allowed", "/configuration/parallel") + ); } #[test] diff --git a/tests/deadline_and_explanations.rs b/tests/deadline_and_explanations.rs new file mode 100644 index 0000000..fc0823f --- /dev/null +++ b/tests/deadline_and_explanations.rs @@ -0,0 +1,74 @@ +//! Two small public surfaces a caller reads directly: a `Deadline` driven by an injected +//! clock, and the human-readable explanation of why an item was left unpacked. + +mod support; + +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use packvium_core::{ + Clock, Deadline, ItemInstance, ReasonProof, UnpackedItem, explain_reason, explain_unpacked_item, +}; + +/// A clock that stands still until a test moves it. +#[derive(Debug, Default)] +struct ManualClock(AtomicU64); + +impl Clock for ManualClock { + fn now_ns(&self) -> u64 { + self.0.load(Ordering::SeqCst) + } +} + +#[test] +fn a_deadline_reports_elapsed_and_remaining_time_from_its_clock() { + let clock = Arc::new(ManualClock::default()); + let deadline = Deadline::with_clock(10, clock.clone()); + assert_eq!(deadline.remaining_ns(), 10_000_000); + clock.0.store(4_000_000, Ordering::SeqCst); + assert_eq!(deadline.elapsed_ms(), 4); + assert_eq!(deadline.remaining_ns(), 6_000_000); + clock.0.store(25_000_000, Ordering::SeqCst); + assert_eq!(deadline.remaining_ns(), 0); + assert!(deadline.expired()); + let rendered = format!("{deadline:?}"); + assert!(rendered.starts_with("Deadline {"), "{rendered}"); + assert!(rendered.contains("limit_ns: 10000000"), "{rendered}"); +} + +fn unpacked(reason: &str, details: Vec) -> UnpackedItem { + UnpackedItem::new( + ItemInstance { + item: support::item("vase"), + sequence: 1, + }, + reason.into(), + details, + ) +} + +#[test] +fn an_unknown_reason_is_refused_with_its_code() { + let error = explain_reason("gremlins").expect_err("no such reason"); + assert_eq!( + error.to_string(), + "no explanation registered for reason code \"gremlins\"" + ); +} + +#[test] +fn an_explanation_carries_its_proof_level_and_details() { + let observed = + explain_unpacked_item(&unpacked("search_exhausted", Vec::new())).expect("a known reason"); + assert!(observed.contains("Observed: "), "{observed}"); + assert!(!observed.contains('('), "{observed}"); + + let mut unlabelled = unpacked("payload_exceeded", vec!["over by 2 kg".into()]); + unlabelled.proof = ReasonProof { + level: "hearsay".into(), + observations: Vec::new(), + }; + let rendered = explain_unpacked_item(&unlabelled).expect("a known reason"); + assert!(!rendered.contains("Proven"), "{rendered}"); + assert!(rendered.ends_with(" (over by 2 kg)"), "{rendered}"); +} diff --git a/tests/deadline_cutoffs.rs b/tests/deadline_cutoffs.rs new file mode 100644 index 0000000..9aee06e --- /dev/null +++ b/tests/deadline_cutoffs.rs @@ -0,0 +1,147 @@ +//! A search cut off by its deadline at any point still returns a valid result that accounts +//! for every item. +//! +//! The deadline is driven by a clock that advances one millisecond per observation, so the +//! cut-off lands after a fixed number of deadline checks rather than after a wall-clock +//! interval: the same limit stops the same search at the same place on every host. Sweeping +//! the limit walks the cut-off through every deadline check a solver makes, which is how the +//! time-limit branches -- unreachable on a fast host with a real clock -- are exercised. +//! `parallel` is off so the observation order is the program order. + +mod support; + +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use packvium_core::{ + Clock, Container, Deadline, IndependentValidator, Item, PackingConfig, PackingRequest, + PackingStatus, SolverProfile, SolverRegistry, Weight, +}; +use support::{SIDE, container, cube, item}; + +#[derive(Debug, Default)] +struct StepClock(AtomicU64); + +impl Clock for StepClock { + fn now_ns(&self) -> u64 { + self.0.fetch_add(1_000_000, Ordering::SeqCst) + } +} + +/// The scene every sweep cuts off. The group is optional because the maximal-space walk +/// stands down for grouped items, so a grouped scene would never run it. +fn items(grouped: bool) -> Vec { + let mut bricks = item("brick"); + bricks.quantity = 6; + let mut set = item("set"); + set.quantity = 3; + if grouped { + set.group = Some("kit".into()); + } + set.dimensions = cube(SIDE / 2); + let mut heavy = item("heavy"); + heavy.quantity = 2; + heavy.weight = Weight(40 * Weight::TICKS_PER_G); + let mut giant = item("giant"); + giant.dimensions = cube(10 * SIDE); + vec![bricks, set, heavy, giant] +} + +fn containers() -> Vec { + let mut small = container(); + small.id = "small".into(); + small.inner_dimensions = cube(2 * SIDE); + small.max_payload = Some(Weight(50 * Weight::TICKS_PER_G)); + small.quantity = Some(2); + let mut large = container(); + large.id = "large".into(); + large.max_payload = Some(Weight(100 * Weight::TICKS_PER_G)); + vec![small, large] +} + +fn request(profile: SolverProfile, solvers: &[&str]) -> PackingRequest { + PackingRequest { + items: items(solvers.is_empty()), + containers: containers(), + config: PackingConfig { + profile, + parallel: false, + solvers: solvers.iter().map(|name| (*name).to_owned()).collect(), + container_plan_beam_width: if profile == SolverProfile::Quality { + 4 + } else { + 1 + }, + container_plan_node_limit: if profile == SolverProfile::Quality { + 64 + } else { + 1 + }, + // Every instance in the scene, so the exact-small profile's search is admitted + // rather than refused; the scene is grouped there, which keeps it small. + exact_item_limit: 12, + max_containers: Some(3), + ..PackingConfig::default() + }, + output_length_unit: "mm".into(), + output_weight_unit: "g".into(), + catalog_versions_used: Vec::new(), + fixed_placements: Vec::new(), + fixed_containers: Vec::new(), + } +} + +/// How many deadline observations the search makes when nothing cuts it off. +fn observations_to_finish(request: &PackingRequest) -> u64 { + let clock = Arc::new(StepClock::default()); + let deadline = Deadline::with_clock(u64::MAX / 1_000_000, clock.clone()); + SolverRegistry::default() + .solve_with_deadline(request, &deadline) + .expect("the uncut search finishes"); + clock.0.load(Ordering::SeqCst) / 1_000_000 +} + +/// Cut the search off at evenly spaced points across its whole run. +fn sweep(profile: SolverProfile, solvers: &[&str]) { + const CUTS: u64 = 60; + let request = request(profile, solvers); + let total = observations_to_finish(&request); + let mut cut_off = 0; + for step in 1..=CUTS { + let limit_ms = (total * step / CUTS).max(1); + let deadline = Deadline::with_clock(limit_ms, Arc::new(StepClock::default())); + let result = SolverRegistry::default() + .solve_with_deadline(&request, &deadline) + .unwrap_or_else(|error| panic!("{solvers:?} at {limit_ms} ms: {error}")); + let report = IndependentValidator.validate(&request, &result); + assert!( + report.valid, + "{solvers:?} at {limit_ms} ms: {:?}", + report.issues + ); + if result.status == PackingStatus::TimeLimit { + cut_off += 1; + } + } + assert!(cut_off > 0, "{solvers:?}: no limit cut the search off"); +} + +#[test] +fn each_solver_cut_off_by_its_deadline_still_returns_a_valid_result() { + for solver in [ + "extreme_points", + "maximal_spaces", + "homogeneous_blocks", + "grid", + "layer", + ] { + sweep(SolverProfile::Balanced, &[solver]); + } +} + +#[test] +fn the_quality_portfolio_cut_off_by_its_deadline_still_returns_a_valid_result() { + sweep(SolverProfile::Quality, &[]); + sweep(SolverProfile::Fast, &[]); + sweep(SolverProfile::ExactSmall, &[]); +} diff --git a/tests/error_codes.rs b/tests/error_codes.rs new file mode 100644 index 0000000..a245429 --- /dev/null +++ b/tests/error_codes.rs @@ -0,0 +1,47 @@ +//! Every `PackError` names a closed code, so a transport maps codes rather than messages. +//! +//! The hosted API turns these codes into HTTP statuses; a renamed code would silently change a +//! status, so each variant's code is pinned here. + +use packvium_core::{PackError, pack_json}; +use serde_json::json; + +#[test] +fn every_variant_names_its_closed_code() { + let malformed = serde_json::from_str::("{").unwrap_err(); + let cases = [ + (PackError::InvalidInput("x".into()), "invalid_input"), + (PackError::Serialization(malformed), "invalid_input"), + ( + PackError::UnsupportedFeature("x".into()), + "unsupported_feature", + ), + (PackError::UnsupportedUnit("x".into()), "unsupported_unit"), + (PackError::InvalidNumber("x".into()), "invalid_number"), + ( + PackError::InvalidSolution("x".into()), + "solution_failed_validation", + ), + (PackError::TimeLimit, "time_limit"), + ]; + for (error, code) in cases { + assert_eq!(error.code(), code, "{error}"); + assert!(error.request_error().is_none(), "{error}"); + } +} + +#[test] +fn a_named_refusal_carries_its_own_code_reason_and_field() { + let request = json!({ + "items": [{ "id": "cube", "quantity": 0, + "dimensions": { "length": "1", "width": "1", "height": "1" } }], + "containers": [{ "id": "box", + "inner_dimensions": { "length": "2", "width": "2", "height": "2" } }] + }); + let error = pack_json(&request.to_string()).unwrap_err(); + let refusal = error.request_error().expect("a named refusal"); + assert_eq!(error.code(), "invalid_request"); + assert_eq!(error.code(), refusal.code()); + assert_eq!(refusal.field(), "/items/0/quantity"); + assert!(!refusal.reason().is_empty()); +} diff --git a/tests/fixed_placements.rs b/tests/fixed_placements.rs index b3ad622..bd03cc9 100644 --- a/tests/fixed_placements.rs +++ b/tests/fixed_placements.rs @@ -232,7 +232,7 @@ type Mutation = Box; fn a_fixed_set_that_cannot_hold_is_refused_before_search() { let cases: Vec<(&str, Mutation)> = vec![ ( - "overlap", + "collision", Box::new(|d| { d["fixed_placements"] .as_array_mut() @@ -500,7 +500,7 @@ fn a_fixed_placement_that_is_not_the_schema_shape_is_refused_by_name() { (json!([5]), "fixed_placements[0] is an object"), ( json!([with("zone", json!("a")),]), - r#"fixed_placements[0] does not carry ["zone"]"#, + r#"fixed_placements[0] cannot carry ["zone"]"#, ), ( json!([no_orientation]), @@ -528,7 +528,7 @@ fn a_fixed_placement_that_is_not_the_schema_shape_is_refused_by_name() { ), ( json!([with("position", json!({"x": "100", "w": "5", "a": "1"}))]), - r#"fixed_placements[0].position does not carry ["a","w"]"#, + r#"fixed_placements[0].position cannot carry ["a","w"]"#, ), ( json!([with("position", json!({"y": true}))]), diff --git a/tests/independent_validation.rs b/tests/independent_validation.rs new file mode 100644 index 0000000..0e57c1d --- /dev/null +++ b/tests/independent_validation.rs @@ -0,0 +1,267 @@ +//! The independent validator judges a struct-level result, not a JSON one, so the rules a +//! solver never breaks -- and `pack_json` therefore never shows it breaking -- are only +//! reachable by handing it a deliberately broken result. Each test builds the smallest +//! arrangement that breaks exactly one rule and checks the validator names it. +//! +//! Measured from a test crate rather than an in-file module so the tests do not count +//! towards their own file's coverage (see `registry_and_nested.rs`). + +mod support; + +use std::collections::{BTreeMap, BTreeSet}; + +use packvium_core::{ + AlgorithmReport, Container, IndependentValidator, Item, ItemInstance, PackedContainer, + PackingConfig, PackingRequest, PackingResult, PackingStatus, Placement, Rotation, ShapeType, + UnpackedItem, ValidationReport, +}; +use support::{SIDE, container, item, placed}; + +fn packed(container: &Container, sequence: usize, placements: Vec) -> PackedContainer { + PackedContainer { + container: container.clone(), + sequence, + placements, + lattice_summary: None, + lattice_items: Vec::new(), + } +} + +fn request(items: Vec, container: Container) -> PackingRequest { + PackingRequest { + items, + containers: vec![container], + config: PackingConfig::default(), + output_length_unit: "mm".into(), + output_weight_unit: "g".into(), + catalog_versions_used: Vec::new(), + fixed_placements: Vec::new(), + fixed_containers: Vec::new(), + } +} + +fn result(containers: Vec, unpacked: Vec) -> PackingResult { + PackingResult { + status: PackingStatus::Feasible, + containers, + unpacked, + algorithm: AlgorithmReport::default(), + score: Vec::new(), + warnings: Vec::new(), + alternatives: Vec::new(), + feasibility: None, + termination: None, + optimality: None, + objective: "default".into(), + catalog_versions_used: Vec::new(), + } +} + +fn codes(report: &ValidationReport) -> Vec<&str> { + report + .issues + .iter() + .map(|issue| issue.code.as_str()) + .collect() +} + +/// Validate one container holding `placements` of `items`, and return the issue codes. +fn judge(items: Vec, container: Container, placements: Vec) -> Vec { + let request = request(items, container.clone()); + let report = IndependentValidator.validate( + &request, + &result(vec![packed(&container, 1, placements)], Vec::new()), + ); + codes(&report).into_iter().map(str::to_owned).collect() +} + +fn stacked_pair(lower: &Item, upper: &Item) -> Vec { + vec![placed(lower, 1, 0, 0), placed(upper, 1, 0, SIDE)] +} + +#[test] +fn a_sound_arrangement_has_no_issues() { + let a = item("a"); + assert_eq!( + judge(vec![a.clone()], container(), vec![placed(&a, 1, 0, 0)]), + Vec::::new() + ); +} + +#[test] +fn an_item_both_placed_and_unpacked_is_double_accounted() { + let a = item("a"); + let request = request(vec![a.clone()], container()); + let report = IndependentValidator.validate( + &request, + &result( + vec![packed(&container(), 1, vec![placed(&a, 1, 0, 0)])], + vec![UnpackedItem::new( + ItemInstance { + item: a, + sequence: 1, + }, + "search_exhausted".into(), + Vec::new(), + )], + ), + ); + assert_eq!(codes(&report), ["duplicate_accounting"]); +} + +#[test] +fn opening_more_containers_than_the_inventory_holds_is_refused() { + let mut a = item("a"); + a.quantity = 2; + let mut limited = container(); + limited.quantity = Some(1); + let request = request(vec![a.clone()], limited.clone()); + let report = IndependentValidator.validate_containers( + &request, + &[ + packed(&limited, 1, vec![placed(&a, 1, 0, 0)]), + packed(&limited, 2, vec![placed(&a, 2, 0, 0)]), + ], + ); + assert_eq!(codes(&report), ["container_inventory"]); +} + +#[test] +fn one_instance_placed_twice_is_a_duplicate() { + let a = item("a"); + let issues = judge( + vec![a.clone()], + container(), + vec![placed(&a, 1, 0, 0), placed(&a, 1, SIDE, 0)], + ); + assert_eq!(issues, ["duplicate_item"]); +} + +#[test] +fn a_group_split_across_containers_is_refused() { + let mut a = item("a"); + a.quantity = 2; + a.group = Some("pair".into()); + let request = request(vec![a.clone()], container()); + let report = IndependentValidator.validate( + &request, + &result( + vec![ + packed(&container(), 1, vec![placed(&a, 1, 0, 0)]), + packed(&container(), 2, vec![placed(&a, 2, 0, 0)]), + ], + Vec::new(), + ), + ); + assert_eq!(codes(&report), ["group_split"]); +} + +#[test] +fn an_item_in_a_container_it_is_not_eligible_for_is_refused() { + let mut a = item("a"); + a.eligible_container_tags = BTreeSet::from(["cold".to_owned()]); + assert_eq!( + judge(vec![a.clone()], container(), vec![placed(&a, 1, 0, 0)]), + ["container_ineligible"] + ); +} + +#[test] +fn a_rotation_the_item_forbids_is_refused() { + let a = item("a"); + let mut turned = placed(&a, 1, 0, 0); + turned.rotation = Rotation::Wlh; + assert_eq!( + judge(vec![a], container(), vec![turned]), + ["rotation_forbidden"] + ); +} + +#[test] +fn a_floor_item_off_the_floor_is_refused() { + let base = item("base"); + let mut floor = item("floor"); + floor.must_be_on_floor = true; + assert_eq!( + judge( + vec![base.clone(), floor.clone()], + container(), + stacked_pair(&base, &floor) + ), + ["floor_required"] + ); +} + +#[test] +fn container_level_limits_are_each_named() { + let mut a = item("a"); + a.quantity = 2; + a.tags = BTreeSet::from(["fragile".to_owned()]); + let two = vec![placed(&a, 1, 0, 0), placed(&a, 2, SIDE, 0)]; + + let mut counted = container(); + counted.max_items = Some(1); + assert_eq!(judge(vec![a.clone()], counted, two.clone()), ["max_items"]); + + let mut tagged = container(); + tagged.tag_limits = BTreeMap::from([("fragile".to_owned(), 1)]); + assert_eq!( + judge(vec![a.clone()], tagged, two.clone()), + ["tag_count_exceeded"] + ); + + let mut reserved = container(); + reserved.void_fill_reserve_ppm = 1_000_000; + assert_eq!( + judge(vec![a], reserved, two), + ["void_fill_reserve_exceeded"] + ); +} + +#[test] +fn a_crushed_compressible_item_is_refused() { + let mut soft = item("soft"); + soft.shape_type = ShapeType::Compressible; + soft.compression_ratio_ppm = Some(0); + soft.max_compression_pressure_kpa = Some(0); + let heavy = item("heavy"); + assert_eq!( + judge( + vec![soft.clone(), heavy.clone()], + container(), + stacked_pair(&soft, &heavy) + ), + ["crush_violation"] + ); +} + +#[test] +fn an_unknown_ground_contact_rule_does_not_invent_a_violation() { + let base = item("base"); + let mut upper = item("upper"); + upper.ground_contact_rule = Some("levitating".into()); + assert_eq!( + judge( + vec![base.clone(), upper.clone()], + container(), + stacked_pair(&base, &upper) + ), + Vec::::new() + ); +} + +#[test] +fn a_later_stop_resting_on_an_earlier_one_breaks_unloading_order() { + let mut early = item("early"); + early.stop_index = Some(1); + let mut late = item("late"); + late.stop_index = Some(2); + assert_eq!( + judge( + vec![early.clone(), late.clone()], + container(), + stacked_pair(&early, &late) + ), + ["unloading_order_violation"] + ); +} diff --git a/tests/measure_parsing.rs b/tests/measure_parsing.rs new file mode 100644 index 0000000..3ec641b --- /dev/null +++ b/tests/measure_parsing.rs @@ -0,0 +1,99 @@ +//! `Length::parse` and `Weight::parse` from outside: every scalar spelling the parser +//! accepts, the ones it refuses, and ties rounding to even at the tick boundary. + +use packvium_core::{Length, PackError, Weight}; +use serde_json::{Value, json}; + +fn ticks(value: Value) -> i64 { + Length::parse(&value, "mm") + .unwrap_or_else(|error| panic!("{value}: {error}")) + .0 +} + +fn refused(value: Value) -> String { + match Length::parse(&value, "mm") { + Err(PackError::InvalidNumber(text)) => text, + other => panic!("{value}: expected an invalid number, got {other:?}"), + } +} + +#[test] +fn a_bare_json_number_takes_the_default_unit() { + assert_eq!(ticks(json!(12)), 12 * Length::TICKS_PER_MM); + assert_eq!( + Weight::parse(&json!(3), "g").expect("grams").0, + 3 * Weight::TICKS_PER_G + ); +} + +#[test] +fn a_value_that_is_not_a_scalar_is_refused() { + assert_eq!(refused(json!(true)), "true"); + assert_eq!(refused(json!({"value": [1]})), "[1]"); +} + +#[test] +fn a_fraction_over_zero_is_refused() { + assert_eq!(refused(json!("1 1/0")), "1 1/0"); + assert_eq!(refused(json!("1/0")), "1/0"); +} + +#[test] +fn a_part_tick_rounds_to_nearest_and_ties_to_even() { + // One tick is 1/16000 mm. + assert_eq!(ticks(json!("1/20000")), 1, "0.8 of a tick rounds up"); + assert_eq!(ticks(json!("1/32000")), 0, "half a tick ties to even zero"); + assert_eq!( + ticks(json!("3/32000")), + 2, + "one and a half ties to even two" + ); +} + +#[test] +fn every_malformed_rational_spelling_is_refused() { + for text in [ + "x 1/2", + "1 x/2", + "1 1/x", + "x/2", + "1/x", + "x.5", + "1.x", + "1.000000000000000000000000000000000000000001", + ] { + assert_eq!(refused(json!(text)), text); + } + assert_eq!(refused(json!({"unit": "mm"})), "missing value"); + assert!(matches!( + Length::parse(&json!({"value": "1", "unit": "furlong"}), "mm"), + Err(PackError::UnsupportedUnit(unit)) if unit == "furlong" + )); + assert!(matches!( + Length::parse(&json!("170141183460469231731687303715884105727 m"), "mm"), + Err(PackError::InvalidNumber(_)) + )); +} + +#[test] +fn negative_whole_and_decimal_spellings_keep_their_sign_until_the_range_check() { + assert!(Length::parse(&json!("-1 1/2"), "mm").is_err()); + assert!(Length::parse(&json!("-1.5"), "mm").is_err()); +} + +#[test] +fn every_unit_spelling_reads_and_writes_exactly() { + assert_eq!(ticks(json!("3 ticks")), 3); + for (unit, per) in [ + ("tick", 1), + ("mg", Weight::TICKS_PER_MG), + ("oz", Weight::TICKS_PER_OZ), + ("lb", Weight::TICKS_PER_LB), + ] { + let weight = Weight::parse(&json!({"value": "2", "unit": unit}), "g").expect(unit); + assert_eq!(weight.0, 2 * per); + assert_eq!(weight.to_json(unit)["value"], "2"); + } + assert_eq!(Length(5).to_json("ticks")["value"], "5"); + assert_eq!(Length(-8_000).to_json("mm")["value"], "-0.5"); +} diff --git a/tests/rebalance_input.rs b/tests/rebalance_input.rs new file mode 100644 index 0000000..b62185b --- /dev/null +++ b/tests/rebalance_input.rs @@ -0,0 +1,309 @@ +//! `rebalance_json` reads a result document the caller hands back, so every malformed +//! shape of that document is refused with an input error naming what is wrong, and a +//! well-formed one round-trips through the reader without losing any item. + +use packvium_core::{PackError, pack_json, rebalance_json}; +use serde_json::{Value, json}; + +fn request() -> Value { + json!({ + "items": [{ "id": "brick", "quantity": 2, "weight": "1000", + "dimensions": { "length": "100", "width": "100", "height": "100" } }], + "containers": [{ "id": "box", + "inner_dimensions": { "length": "200", "width": "100", "height": "100" } }], + "configuration": { + "time_limit_ms": 60000, + "effort_budget": { "max_candidates_evaluated": 100000, + "max_placement_attempts": 100000, + "max_search_nodes": 100000 } + } + }) +} + +fn packed() -> Value { + serde_json::from_str(&pack_json(&request().to_string()).expect("the request packs")) + .expect("result JSON") +} + +fn refusal(result: &Value) -> String { + match rebalance_json(&request().to_string(), &result.to_string(), 4) { + Err(PackError::InvalidInput(message)) => message, + Err(other) => panic!("refused, but not as invalid input: {other}"), + Ok(output) => panic!("{result} was accepted: {output}"), + } +} + +fn placement(result: &mut Value) -> &mut Value { + &mut result["containers"][0]["placements"][0] +} + +#[test] +fn a_packed_result_rebalances_and_keeps_its_containers() { + let mut result = packed(); + result["status"] = json!("optimal"); + placement(&mut result)["position"]["x"] = json!({ "ticks": 0 }); + let output: Value = serde_json::from_str( + &rebalance_json(&request().to_string(), &result.to_string(), 4).expect("rebalances"), + ) + .expect("rebalance JSON"); + assert_eq!(output["containers"].as_array().map(Vec::len), Some(1)); + assert_eq!(output["improved"], json!(false)); +} + +#[test] +fn every_status_spelling_is_read_back() { + for status in [ + "optimal", + "best_found", + "time_limit", + "infeasible", + "invalid_result", + ] { + let mut result = packed(); + result["status"] = json!(status); + rebalance_json(&request().to_string(), &result.to_string(), 0) + .unwrap_or_else(|error| panic!("{status}: {error}")); + } +} + +#[test] +fn the_result_and_its_containers_must_be_objects() { + assert_eq!(refusal(&json!([])), "result must be an object"); + assert_eq!( + refusal(&json!({ "containers": {} })), + "result.containers must be an array" + ); + assert_eq!( + refusal(&json!({ "containers": [1] })), + "result.containers[0] must be an object" + ); +} + +#[test] +fn a_container_must_name_a_known_type_and_list_materialized_placements() { + let mut lattice = packed(); + lattice["containers"][0]["lattice_summary"] = json!({}); + assert_eq!( + refusal(&lattice), + "rebalance requires materialized placement coordinates" + ); + + let mut untyped = packed(); + untyped["containers"][0] + .as_object_mut() + .expect("container object") + .remove("container_type"); + assert_eq!( + refusal(&untyped), + "result.containers[0].container_type is required" + ); + + let mut unknown = packed(); + unknown["containers"][0]["container_type"] = json!("crate"); + assert_eq!(refusal(&unknown), "unknown result container type \"crate\""); + + let mut unlisted = packed(); + unlisted["containers"][0]["placements"] = json!({}); + assert_eq!( + refusal(&unlisted), + "result.containers[0].placements must be an array" + ); + + let mut scalar = packed(); + scalar["containers"][0]["placements"][0] = json!(7); + assert_eq!( + refusal(&scalar), + "result.containers[0].placements[0] must be an object" + ); +} + +#[test] +fn a_placement_must_reference_each_requested_instance_once() { + let mut anonymous = packed(); + placement(&mut anonymous) + .as_object_mut() + .expect("placement object") + .remove("item_id"); + assert_eq!(refusal(&anonymous), "placement.item_id is required"); + + let mut duplicated = packed(); + let first = duplicated["containers"][0]["placements"][0]["item_id"].clone(); + duplicated["containers"][0]["placements"][1]["item_id"] = first.clone(); + assert_eq!( + refusal(&duplicated), + format!("result duplicates or references unknown item instance {first}") + ); + + let mut missing = packed(); + missing["containers"][0]["placements"] + .as_array_mut() + .expect("placements array") + .pop(); + assert_eq!( + refusal(&missing), + "result does not account for every requested item instance" + ); +} + +#[test] +fn a_placement_position_must_be_exact_integer_ticks() { + for (edit, expected) in [ + (json!(null), "placement.position is required"), + (json!(3), "placement.position must be an object"), + ( + json!({ "y": 0, "z": 0 }), + "placement.position.x is required", + ), + ( + json!({ "x": 0, "z": 0 }), + "placement.position.y is required", + ), + ( + json!({ "x": 0, "y": 0 }), + "placement.position.z is required", + ), + ( + json!({ "x": 0.5, "y": 0, "z": 0 }), + "placement.position.x must contain exact integer ticks", + ), + ( + json!({ "x": "half", "y": 0, "z": 0 }), + "placement.position.x must contain exact integer ticks", + ), + ( + json!({ "x": true, "y": 0, "z": 0 }), + "placement.position.x must contain exact integer ticks", + ), + ( + json!({ "x": 0, "y": [], "z": 0 }), + "placement.position.y must contain exact integer ticks", + ), + ( + json!({ "x": 0, "y": 0, "z": [] }), + "placement.position.z must contain exact integer ticks", + ), + ] { + let mut result = packed(); + if edit.is_null() { + placement(&mut result) + .as_object_mut() + .expect("placement object") + .remove("position"); + } else { + placement(&mut result)["position"] = edit; + } + assert_eq!(refusal(&result), expected); + } +} + +#[test] +fn a_placement_needs_dimensions_an_orientation_and_an_exact_top_load() { + for (edit, expected) in [ + (json!(null), "placement.dimensions is required"), + (json!(3), "placement.dimensions must be an object"), + ( + json!({ "width": 1, "height": 1 }), + "placement.dimensions.length is required", + ), + ( + json!({ "length": 1, "height": 1 }), + "placement.dimensions.width is required", + ), + ( + json!({ "length": 1, "width": 1 }), + "placement.dimensions.height is required", + ), + ( + json!({ "length": [], "width": 1, "height": 1 }), + "placement.dimensions.length must contain exact integer ticks", + ), + ( + json!({ "length": 1, "width": [], "height": 1 }), + "placement.dimensions.width must contain exact integer ticks", + ), + ( + json!({ "length": 1, "width": 1, "height": [] }), + "placement.dimensions.height must contain exact integer ticks", + ), + ] { + let mut result = packed(); + if edit.is_null() { + placement(&mut result) + .as_object_mut() + .expect("placement object") + .remove("dimensions"); + } else { + placement(&mut result)["dimensions"] = edit; + } + assert_eq!(refusal(&result), expected); + } + + let mut unoriented = packed(); + placement(&mut unoriented)["orientation"] = json!("diagonal"); + assert_eq!(refusal(&unoriented), "placement.orientation is invalid"); + + let mut fractional_load = packed(); + placement(&mut fractional_load)["top_load"] = json!([]); + assert_eq!( + refusal(&fractional_load), + "placement.top_load must contain exact integer ticks" + ); +} + +#[test] +fn unpacked_items_are_read_back_with_their_reason_and_details() { + let mut result = packed(); + let moved = result["containers"][0]["placements"] + .as_array_mut() + .expect("placements array") + .pop() + .expect("two placements"); + result["unpacked_items"] = json!([{ + "item_id": moved["item_id"], + "details": ["kept aside", 3], + }]); + let output: Value = serde_json::from_str( + &rebalance_json(&request().to_string(), &result.to_string(), 4).expect("rebalances"), + ) + .expect("rebalance JSON"); + assert_eq!(output["improved"], json!(false)); +} + +#[test] +fn a_malformed_unpacked_item_is_refused() { + let mut scalar = packed(); + scalar["unpacked_items"] = json!([1]); + assert_eq!(refusal(&scalar), "unpacked item must be an object"); + + let mut anonymous = packed(); + anonymous["unpacked_items"] = json!([{ "reason": "search_exhausted" }]); + assert_eq!(refusal(&anonymous), "unpacked item_id is required"); + + let mut unknown = packed(); + unknown["unpacked_items"] = json!([{ "item_id": "ghost#1" }]); + assert_eq!( + refusal(&unknown), + "result duplicates or references unknown item instance \"ghost#1\"" + ); +} + +#[test] +fn either_document_that_is_not_json_is_refused() { + let result = packed().to_string(); + for (request, result) in [("{", result.as_str()), (&request().to_string(), "{")] { + assert!(matches!( + rebalance_json(request, result, 4), + Err(PackError::Serialization(_)) + )); + } + let mut empty = request(); + empty["items"] = json!([]); + assert!(rebalance_json(&empty.to_string(), &result, 4).is_err()); +} + +#[test] +fn a_support_ratio_written_as_text_is_read_back() { + let mut result = packed(); + placement(&mut result)["support_ratio"] = json!("0.5"); + rebalance_json(&request().to_string(), &result.to_string(), 4).expect("rebalances"); +} diff --git a/tests/registry_and_nested.rs b/tests/registry_and_nested.rs index 84f35f3..452e9ed 100644 --- a/tests/registry_and_nested.rs +++ b/tests/registry_and_nested.rs @@ -204,6 +204,88 @@ fn a_run_with_no_levels_succeeds_and_packs_nothing() { assert!(result.levels.is_empty()); } +#[test] +fn nested_levels_automatically_chain_containers_into_items_and_honour_beam_width() { + let nested = NestedPackingRequest { + levels: vec![ + NestedLevel { + name: "cartons".into(), + request: request(vec![item("cup", 50)], vec![container("box", 100)]), + }, + NestedLevel { + name: "pallet".into(), + // Empty items: chains from "cartons" level + request: request(vec![], vec![container("pallet", 500)]), + }, + ], + beam_width: 3, + }; + + let result = pack_nested(&nested).expect("chained levels pack"); + assert_eq!(result.levels.len(), 2); + assert_eq!(result.levels[0].0, "cartons"); + assert_eq!(result.levels[1].0, "pallet"); + assert_eq!(result.levels[0].1.containers.len(), 1); + assert_eq!(result.levels[1].1.containers.len(), 1); + assert_eq!(result.levels[1].1.packed_item_count(), 1); +} + +#[test] +fn an_incomplete_level_ends_the_chain_as_pythons_nested_packer_does() { + let nested = NestedPackingRequest { + levels: vec![ + NestedLevel { + name: "cartons".into(), + // The second cup does not fit: this level cannot complete. + request: request( + vec![item("cup", 50), item("urn", 200)], + vec![container("box", 100)], + ), + }, + NestedLevel { + name: "pallet".into(), + request: request(vec![], vec![container("pallet", 500)]), + }, + NestedLevel { + name: "truck".into(), + request: request(vec![], vec![container("truck", 900)]), + }, + ], + beam_width: 0, + }; + + let result = pack_nested(&nested).expect("an unfittable item is a result, not an error"); + let names: Vec<&str> = result + .levels + .iter() + .map(|(name, _)| name.as_str()) + .collect(); + assert_eq!(names, ["cartons"]); + assert!(!result.levels[0].1.complete()); +} + +#[test] +fn a_level_with_its_own_items_still_runs_after_an_incomplete_one() { + let nested = NestedPackingRequest { + levels: vec![ + NestedLevel { + name: "cartons".into(), + request: request(vec![item("urn", 200)], vec![container("box", 100)]), + }, + NestedLevel { + name: "pallet".into(), + request: request(vec![item("crate", 50)], vec![container("pallet", 500)]), + }, + ], + beam_width: 0, + }; + + let result = pack_nested(&nested).expect("each level is a valid request"); + assert_eq!(result.levels.len(), 2); + assert!(!result.levels[0].1.complete()); + assert!(result.levels[1].1.complete()); +} + // ------------------------------------------------------------------ SolverRegistry #[derive(Debug)] diff --git a/tests/request_errors.rs b/tests/request_errors.rs index 15fba88..cc10c46 100644 --- a/tests/request_errors.rs +++ b/tests/request_errors.rs @@ -101,6 +101,21 @@ fn representative_reasons_name_the_value_at_fault() { "/items/0/dimensions/length", "must be a measure", ), + ( + |r| { + r["configuration"]["top_k"] = json!(2); + r["configuration"]["profile"] = json!("balanced"); + }, + "not_allowed", + "/configuration/profile", + "is not a known field", + ), + ( + |r| r["configuration"]["effort_budget"] = json!({"max_nodes": 1}), + "not_allowed", + "/configuration/effort_budget/max_nodes", + "is not a known field", + ), ( |r| r["configuration"]["solver_profile"] = json!("fastest"), "not_allowed", @@ -213,15 +228,47 @@ fn a_fixed_placement_refusal_keeps_its_message_and_gains_reason_and_field() { #[test] fn a_parse_failure_the_rules_do_not_name_is_an_invalid_value_without_a_field() { let mut request = base(); - request["configuration"]["objective"] = json!(17); + request["items"][0]["shape_type"] = json!("sphere"); let error = refused(&request); assert_eq!( (error.code(), error.reason(), error.field()), ("invalid_request", "invalid_value", "") ); - assert!( - error.detail().contains("configuration.objective"), - "{error}" + assert!(error.detail().contains("item.shape_type"), "{error}"); +} + +#[test] +fn an_unknown_objective_or_access_direction_is_refused_with_not_allowed_and_pointer() { + let mut request = base(); + request["configuration"]["objective"] = json!("cheapest"); + let error = refused(&request); + assert_eq!( + (error.code(), error.reason(), error.field()), + ("invalid_request", "not_allowed", "/configuration/objective") + ); + + let mut request = base(); + request["containers"][0]["access_directions"] = json!(["+w"]); + let error = refused(&request); + assert_eq!( + (error.code(), error.reason(), error.field()), + ( + "invalid_request", + "not_allowed", + "/containers/0/access_directions/0" + ) + ); + + let mut request = base(); + request["containers"][0]["access_directions"] = json!("+x"); + let error = refused(&request); + assert_eq!( + (error.code(), error.reason(), error.field()), + ( + "invalid_request", + "wrong_type", + "/containers/0/access_directions" + ) ); } diff --git a/tests/result_serialization.rs b/tests/result_serialization.rs new file mode 100644 index 0000000..03b168b --- /dev/null +++ b/tests/result_serialization.rs @@ -0,0 +1,133 @@ +//! How a result is written out, for the statuses and shapes a default solve does not +//! produce: the closed-form lattice centre of mass, every status spelling and its derived +//! facts, a score past the `i64` range, and a hand-built result with no solver name. + +mod support; + +use packvium_core::{ + AlgorithmReport, PackedContainer, PackingResult, PackingStatus, StartRecord, + aggregate_termination, pack_json, +}; +use serde_json::{Value, json}; +use support::{container, item, placed}; + +fn solve(coordinates: bool) -> Value { + let request = json!({ + "items": [{ "id": "brick", "quantity": 7, "weight": "250", + "dimensions": { "length": "100", "width": "100", "height": "100" } }], + "containers": [{ "id": "crate", + "inner_dimensions": { "length": "300", "width": "300", "height": "300" } }], + "configuration": { + "solver_profile": "fast", + "require_placement_coordinates": coordinates, + "time_limit_ms": 60000, + "effort_budget": { "max_candidates_evaluated": 100000, + "max_placement_attempts": 100000, + "max_search_nodes": 100000 } + } + }); + serde_json::from_str(&pack_json(&request.to_string()).expect("the request packs")) + .expect("result JSON") +} + +#[test] +fn a_weighted_lattice_reports_the_same_centre_of_mass_as_its_placements() { + let compact = solve(false); + let full = solve(true); + assert!( + compact["containers"][0].get("lattice_summary").is_some(), + "{compact}" + ); + let offset = &compact["containers"][0]["centre_of_mass_offset_ppm"]; + assert!(offset.as_i64().is_some_and(|ppm| ppm > 0), "{compact}"); + assert_eq!(offset, &full["containers"][0]["centre_of_mass_offset_ppm"]); +} + +fn hand_built(status: PackingStatus) -> PackingResult { + let brick = item("brick"); + PackingResult { + status, + containers: vec![PackedContainer { + container: container(), + sequence: 1, + placements: vec![placed(&brick, 1, 0, 0)], + lattice_summary: None, + lattice_items: Vec::new(), + }], + unpacked: Vec::new(), + algorithm: AlgorithmReport::default(), + score: vec![i128::MIN, i128::MAX, 7], + warnings: Vec::new(), + alternatives: Vec::new(), + feasibility: None, + termination: None, + optimality: None, + objective: "default".into(), + catalog_versions_used: Vec::new(), + } +} + +#[test] +fn every_status_is_written_with_the_facts_it_implies() { + for (status, spelling, feasibility, termination, optimality) in [ + ( + PackingStatus::Optimal, + "optimal", + "feasible", + "complete", + "proven_optimal", + ), + ( + PackingStatus::Infeasible, + "infeasible", + "infeasible", + "complete", + "proven_infeasible", + ), + ( + PackingStatus::InvalidResult, + "invalid_result", + "unknown", + "error", + "not_proven", + ), + ] { + let written = hand_built(status).to_json("mm", "g", false); + assert_eq!(written["status"], spelling); + assert_eq!(written["feasibility"]["code"], feasibility, "{written}"); + assert_eq!(written["termination"]["code"], termination, "{written}"); + assert_eq!(written["optimality"]["code"], optimality, "{written}"); + } +} + +#[test] +fn a_score_past_the_i64_range_saturates_and_a_nameless_solver_reads_unknown() { + let written = hand_built(PackingStatus::Feasible).to_json("mm", "g", false); + assert_eq!(written["score"], json!([i64::MIN, i64::MAX, 7])); + assert_eq!( + written["termination"]["starts"][0]["id"], "unknown", + "{written}" + ); +} + +#[test] +fn a_placement_box_is_its_physical_extent() { + let brick = item("brick"); + let placement = placed(&brick, 1, 5, 0); + let box_ = placement.box_(); + assert_eq!(box_.origin, placement.position); + assert_eq!(box_.dimensions, placement.dimensions); +} + +#[test] +fn an_errored_run_terminates_as_an_error() { + let start = StartRecord { + id: "grid".into(), + started: true, + completed: true, + truncated: false, + selected: true, + global_deadline_reached: false, + }; + assert_eq!(aggregate_termination(&[start], true).code, "error"); +} diff --git a/tests/revisions.rs b/tests/revisions.rs index be4f3e7..6562d65 100644 --- a/tests/revisions.rs +++ b/tests/revisions.rs @@ -562,7 +562,7 @@ fn a_refusal_quotes_values_by_their_canonical_json() { ), ( json!([with_placement(|p| p["position"] = json!({"w": "5"}))]), - r#"placement.position does not carry ["w"]"#, + r#"placement.position cannot carry ["w"]"#, ), ( json!([with_placement(|p| p["position"] = json!({"x": true}))]), diff --git a/tests/scene_sequencing.rs b/tests/scene_sequencing.rs new file mode 100644 index 0000000..876ff79 --- /dev/null +++ b/tests/scene_sequencing.rs @@ -0,0 +1,198 @@ +//! Loading and removal sequencing over bare boxes and over placements, from outside the +//! module: the dependency graphs, the replay refusals a finished solve never produces, and +//! the placement-level entry point that also replays business rules. + +mod support; + +use packvium_core::{ + ALL_DIRECTIONS, Aabb, Dimensions, Length, LoadingDependencyGraph, Point, SequenceError, + UnloadingDependencyGraph, placement_reachability, replay_removal_order, + safe_loading_order_for_placements, safe_removal_order_with_evidence, + verify_loading_prefix_business_rules, +}; +use support::{SIDE, container, item, placed}; + +fn dimensions(length: i64, width: i64, height: i64) -> Dimensions { + Dimensions { + length: Length(length), + width: Length(width), + height: Length(height), + } +} + +fn box_at(x: i64, z: i64, height: i64) -> Aabb { + Aabb { + origin: Point { x, y: 0, z }, + dimensions: dimensions(10, 10, height), + } +} + +fn replay_reason(result: Result<(), SequenceError>) -> &'static str { + match result { + Err(SequenceError::Replay { reason, .. }) => reason, + other => panic!("expected a replay refusal, got {other:?}"), + } +} + +#[test] +fn a_stack_is_acyclic_in_both_directions() { + let boxes = [box_at(0, 0, 10), box_at(0, 10, 10)]; + assert!(LoadingDependencyGraph::build(&boxes).is_acyclic()); + assert!(UnloadingDependencyGraph::build(&boxes).is_acyclic()); +} + +#[test] +fn two_flat_boxes_on_one_plane_support_each_other_in_a_cycle() { + // A zero-height box's top face is its bottom face, so two of them overlapping on the + // same plane each rest on the other -- the one geometry that closes a cycle. + let boxes = [box_at(0, 5, 0), box_at(5, 5, 0)]; + assert!(!LoadingDependencyGraph::build(&boxes).is_acyclic()); + assert!(!UnloadingDependencyGraph::build(&boxes).is_acyclic()); +} + +#[test] +fn removal_replay_refuses_what_a_safe_order_never_contains() { + let container = dimensions(20, 10, 20); + let stack = [box_at(0, 0, 10), box_at(0, 10, 10)]; + assert_eq!( + replay_reason(replay_removal_order( + &stack, + container, + &[0], + &ALL_DIRECTIONS + )), + "order is not a permutation of every placement index exactly once" + ); + assert_eq!( + replay_reason(replay_removal_order( + &stack, + container, + &[0, 1], + &ALL_DIRECTIONS + )), + "something still resting on it has not been removed yet" + ); + let row = [box_at(0, 0, 10), box_at(10, 0, 10)]; + assert_eq!( + replay_reason(replay_removal_order( + &row, + dimensions(20, 10, 10), + &[1, 0], + &["-x"] + )), + "no allowed direction is clear of the remaining placements" + ); + let steps = safe_removal_order_with_evidence(&stack, container, &ALL_DIRECTIONS) + .expect("a stack unloads top first"); + assert_eq!( + steps.iter().map(|step| step.index).collect::>(), + [1, 0] + ); +} + +#[test] +fn loading_replay_refuses_a_box_walled_in_by_what_is_already_loaded() { + // With only the -x door, the far box must go in first; loading the near one first + // leaves the far one no clear path. + let row = [box_at(0, 0, 10), box_at(10, 0, 10)]; + let error = packvium_core::replay_loading_order(&row, dimensions(20, 10, 10), &[0, 1], &["-x"]); + assert_eq!( + replay_reason(error), + "no allowed direction is clear of what has already been loaded" + ); +} + +#[test] +fn reachability_needs_one_stop_per_placement() { + let boxes = [box_at(0, 0, 10)]; + let error = placement_reachability( + &boxes, + dimensions(10, 10, 10), + Some(&[Some(1), Some(2)]), + &ALL_DIRECTIONS, + ) + .expect_err("two stops for one placement"); + assert!(matches!( + error, + SequenceError::Replay { + reason: "stops must contain exactly one entry per placement", + .. + } + )); +} + +#[test] +fn placements_load_in_a_safe_order_that_also_keeps_business_rules() { + let base = item("base"); + let upper = item("upper"); + let placements = [placed(&upper, 1, 0, SIDE), placed(&base, 1, 0, 0)]; + let order = safe_loading_order_for_placements(&placements, &container(), &ALL_DIRECTIONS) + .expect("a stack of two loads bottom first"); + assert_eq!(order, [1, 0]); + assert!(matches!( + verify_loading_prefix_business_rules(&placements, &[0], &container()), + Err(SequenceError::Replay { index: -1, .. }) + )); +} + +#[test] +fn every_entry_point_refuses_an_unknown_door() { + let boxes = [box_at(0, 0, 10)]; + let container = dimensions(10, 10, 10); + for error in [ + placement_reachability(&boxes, container, None, &["sideways"]).map(|_| ()), + replay_removal_order(&boxes, container, &[0], &["sideways"]), + packvium_core::replay_loading_order(&boxes, container, &[0], &["sideways"]), + safe_removal_order_with_evidence(&boxes, container, &["sideways"]).map(|_| ()), + packvium_core::safe_loading_order_with_evidence(&boxes, container, &["sideways"]) + .map(|_| ()), + ] { + assert!(matches!(error, Err(SequenceError::InvalidDirection(_)))); + } +} + +#[test] +fn replays_refuse_a_box_outside_the_container_or_a_partial_order() { + let outside = [box_at(15, 0, 10)]; + let container = dimensions(20, 10, 10); + assert_eq!( + replay_reason(replay_removal_order( + &outside, + container, + &[0], + &ALL_DIRECTIONS + )), + "placement is outside the container" + ); + let stack = [box_at(0, 0, 10), box_at(0, 10, 10)]; + assert_eq!( + replay_reason(packvium_core::replay_loading_order( + &stack, + dimensions(20, 10, 20), + &[1], + &ALL_DIRECTIONS + )), + "order is not a permutation of every placement index exactly once" + ); +} + +#[test] +fn a_placement_order_refuses_geometry_and_business_rule_violations() { + let base = item("base"); + let floating = [placed(&base, 1, 10 * SIDE, 0)]; + assert!(safe_loading_order_for_placements(&floating, &container(), &ALL_DIRECTIONS).is_err()); + + let mut soft = item("soft"); + soft.shape_type = packvium_core::ShapeType::Compressible; + soft.compression_ratio_ppm = Some(0); + soft.max_compression_pressure_kpa = Some(0); + let heavy = item("heavy"); + let crushed = [placed(&soft, 1, 0, 0), placed(&heavy, 1, 0, SIDE)]; + assert!(matches!( + safe_loading_order_for_placements(&crushed, &container(), &ALL_DIRECTIONS), + Err(SequenceError::Replay { + reason: "business rule violated", + .. + }) + )); +} diff --git a/tests/search_scenarios.rs b/tests/search_scenarios.rs new file mode 100644 index 0000000..d1d5c81 --- /dev/null +++ b/tests/search_scenarios.rs @@ -0,0 +1,182 @@ +//! Small scenes that steer the extreme-point search into branches the golden corpus never +//! reaches: route stops mixed with items that ride the whole route, covered ground contact, +//! a candidate-point budget smaller than the scene, an axle container whose floor fills up, +//! a hull beside an obstacle, grouped items under the beam, and dimensional weight in feet. +//! +//! Every scene goes through `pack_json`, which refuses any result its independent validator +//! rejects, so "it solved" already asserts the answer is valid; each test adds the property +//! its scene exists for. Counted work bounds every search and the time limit is only a fuse. + +use packvium_core::pack_json; +use serde_json::{Value, json}; + +fn solve(mut request: Value) -> Value { + let configuration = request + .as_object_mut() + .expect("request object") + .entry("configuration") + .or_insert_with(|| json!({})) + .as_object_mut() + .expect("configuration object"); + configuration.insert("time_limit_ms".into(), json!(60_000)); + configuration.entry("effort_budget").or_insert_with(|| { + json!({ + "max_candidates_evaluated": 200_000, + "max_placement_attempts": 200_000, + "max_search_nodes": 200_000 + }) + }); + let output = + pack_json(&request.to_string()).unwrap_or_else(|error| panic!("{request}: {error}")); + serde_json::from_str(&output).expect("result JSON") +} + +fn cube(id: &str, side: u32, quantity: u32) -> Value { + json!({ "id": id, "quantity": quantity, "weight": "100", + "dimensions": { "length": side.to_string(), "width": side.to_string(), + "height": side.to_string() } }) +} + +fn placed_count(result: &Value) -> usize { + result["containers"] + .as_array() + .expect("containers") + .iter() + .map(|container| container["placements"].as_array().map_or(0, Vec::len)) + .sum() +} + +#[test] +fn stops_share_a_van_with_items_that_ride_the_whole_route() { + let mut first = cube("first", 50, 2); + first["stop_index"] = json!(1); + let mut second = cube("second", 50, 2); + second["stop_index"] = json!(2); + let result = solve(json!({ + "items": [first, second, cube("rider", 50, 2)], + "containers": [{ "id": "van", "access_directions": ["-x"], + "inner_dimensions": { "length": "200", "width": "50", "height": "100" } }] + })); + assert_eq!(placed_count(&result), 6, "{result}"); +} + +#[test] +fn a_covered_item_stands_only_on_full_corner_support() { + let mut lid = cube("lid", 100, 1); + lid["ground_contact_rule"] = json!("covered"); + lid["dimensions"]["height"] = json!("10"); + let result = solve(json!({ + "items": [cube("base", 100, 1), lid], + "containers": [{ "id": "box", + "inner_dimensions": { "length": "100", "width": "100", "height": "110" } }] + })); + assert_eq!(placed_count(&result), 2, "{result}"); +} + +#[test] +fn a_candidate_budget_smaller_than_the_scene_still_packs() { + let items = (1..=8) + .map(|index| cube(&format!("c{index}"), 10 + index * 3, 1)) + .collect::>(); + let result = solve(json!({ + "items": items, + "containers": [{ "id": "box", + "inner_dimensions": { "length": "120", "width": "120", "height": "120" } }], + "configuration": { "max_candidate_points": 65 } + })); + assert_eq!(placed_count(&result), 8, "{result}"); +} + +#[test] +fn an_axle_container_keeps_packing_once_its_floor_is_full() { + let result = solve(json!({ + "items": [cube("crate", 50, 8)], + "containers": [{ "id": "trailer", + "inner_dimensions": { "length": "100", "width": "100", "height": "100" }, + "axles": [{ "position": "10", "max_load": "100000" }, + { "position": "90", "max_load": "100000" }] }] + })); + assert_eq!(placed_count(&result), 8, "{result}"); +} + +#[test] +fn a_hull_is_kept_clear_of_an_obstacle() { + let hull = json!({ + "id": "wedge", "quantity": 2, "shape_type": "convex_hull", + "dimensions": { "length": "40", "width": "40", "height": "40" }, + "hull_vertices": [ + { "x": "0", "y": "0", "z": "0" }, { "x": "40", "y": "0", "z": "0" }, + { "x": "0", "y": "40", "z": "0" }, { "x": "0", "y": "0", "z": "40" } + ] + }); + let result = solve(json!({ + "items": [hull], + "containers": [{ "id": "box", + "inner_dimensions": { "length": "100", "width": "40", "height": "40" }, + "obstacles": [{ "id": "pillar", "origin": { "x": "35" }, + "dimensions": { "length": "10", "width": "10", "height": "40" } }] }] + })); + assert_eq!(placed_count(&result), 2, "{result}"); +} + +#[test] +fn a_group_is_packed_together_under_the_beam_or_not_at_all() { + let mut kit = cube("kit", 50, 3); + kit["group"] = json!("set"); + let result = solve(json!({ + "items": [kit, cube("filler", 50, 1)], + "containers": [{ "id": "box", + "inner_dimensions": { "length": "100", "width": "50", "height": "50" } }], + "configuration": { "solver_profile": "quality", "max_containers": 1 } + })); + let unpacked = result["unpacked_items"].as_array().expect("unpacked"); + assert!( + unpacked.iter().all(|item| item["item_type"] == "kit"), + "{result}" + ); +} + +#[test] +fn quality_container_plans_respect_payload_node_limits_and_empty_trials() { + let mut heavy = cube("heavy", 40, 4); + heavy["weight"] = json!("30000"); + let blocked = json!({ + "id": "blocked", "inner_dimensions": { "length": "100", "width": "100", "height": "100" }, + "max_payload": "1000000", + "obstacles": [{ "id": "fill", + "dimensions": { "length": "100", "width": "100", "height": "100" } }] + }); + let open = json!({ + "id": "open", "inner_dimensions": { "length": "100", "width": "100", "height": "100" }, + "max_payload": "70000" + }); + for node_limit in [1, 100] { + let result = solve(json!({ + "items": [heavy], + "containers": [blocked, open], + "configuration": { "solver_profile": "quality", + "container_plan_node_limit": node_limit } + })); + assert!( + result["containers"] + .as_array() + .expect("containers") + .iter() + .all(|container| container["container_type"] == "open"), + "{result}" + ); + } +} + +#[test] +fn dimensional_weight_can_be_measured_in_feet() { + let result = solve(json!({ + "items": [cube("parcel", 100, 1)], + "containers": [{ "id": "carton", + "inner_dimensions": { "length": "200", "width": "200", "height": "200" }, + "rate_table": { "weight_brackets_g": [1000000], "prices_minor": [500] } }], + "configuration": { "objective": "shipping_cost", "dimensional_weight_divisor": 139, + "dimensional_weight_length_unit": "ft" } + })); + assert_eq!(result["objective"], "shipping_cost"); +} diff --git a/tests/support/mod.rs b/tests/support/mod.rs new file mode 100644 index 0000000..d875304 --- /dev/null +++ b/tests/support/mod.rs @@ -0,0 +1,90 @@ +//! Struct-level builders shared by the test crates that hand the core objects directly +//! rather than JSON. Each test crate compiles its own copy and uses a subset. +#![allow(dead_code)] + +use std::collections::{BTreeMap, BTreeSet}; + +use packvium_core::{ + Container, Dimensions, Item, ItemInstance, Length, Placement, Point, Rotation, ShapeType, + Weight, +}; + +pub const SIDE: i64 = 10 * Length::TICKS_PER_MM; + +pub fn cube(side: i64) -> Dimensions { + Dimensions { + length: Length(side), + width: Length(side), + height: Length(side), + } +} + +pub fn item(id: &str) -> Item { + Item { + id: id.into(), + dimensions: cube(SIDE), + weight: Weight(Weight::TICKS_PER_G), + quantity: 1, + allowed_rotations: vec![Rotation::Lwh], + stackable: true, + must_be_on_floor: false, + max_top_load: None, + minimum_support_ratio: 0.0, + group: None, + tags: BTreeSet::new(), + incompatible_tags: BTreeSet::new(), + priority: 0, + metadata: BTreeMap::new(), + nesting_height: None, + max_stacked_items: None, + ground_contact_rule: None, + stop_index: None, + eligible_container_tags: BTreeSet::new(), + value: None, + shape_type: ShapeType::RigidCuboid, + hull_vertices: None, + compression_ratio_ppm: None, + max_compression_pressure_kpa: None, + } +} + +pub fn container() -> Container { + Container { + id: "box".into(), + inner_dimensions: cube(4 * SIDE), + outer_dimensions: None, + tare_weight: Weight(0), + max_payload: None, + cost_minor: 0, + quantity: None, + obstacles: Vec::new(), + tags: BTreeSet::new(), + max_items: None, + metadata: BTreeMap::new(), + axles: None, + void_fill_reserve_ppm: 0, + tag_limits: BTreeMap::new(), + max_stack_density: None, + rate_table: None, + access_directions: Vec::new(), + preloaded: Vec::new(), + } +} + +pub fn placed(item: &Item, sequence: usize, x: i64, z: i64) -> Placement { + let position = Point { x, y: 0, z }; + Placement { + instance: ItemInstance { + item: item.clone(), + sequence, + }, + position, + rotation: Rotation::Lwh, + dimensions: item.dimensions, + envelope_origin: position, + envelope_dimensions: item.dimensions, + support_ratio: 1.0, + top_load: Weight(0), + fixed: false, + } +}