diff --git a/CHANGELOG.md b/CHANGELOG.md index 26ce644..8e53419 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,49 @@ What changed in `packvium/packvium` on Packagist, release by release. The format [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.7.0] + +The reference validator ships in the package, `quality` looks ahead in its block solver, and a +request built from objects is refused as its JSON would be. No request or result field changes. + +### Added + +- **`Packvium\Validation\validate(array $request, array $result)`**, with `ResultIssue` (`code`, + `detail`) and `MalformedResult` (an `InvalidArgumentException` carrying `kind`). The reference + validator over the decoded JSON documents, returning an empty list for a valid result; it is + loaded like the `Packvium\Commerce` functions and shares no code with the engine it checks. A + document integer past 64 bits is refused rather than judged. Available on PHP 7.3+ through + `src-legacy/` as well. +- **`StopAccessibilityConstraint::directionsFor()`**, which `ConstraintActivity` now asks instead + of reading the configured doors. + +### Changed + +- **A request built from objects is refused as JSON is.** A model constructor that + refuses a value throws `InvalidRequestException` (code, reason, field `""`), a subclass of the + `InvalidArgumentException` it threw before. `Packer::pack()` checks the objects with the JSON + rules before solving. `FixedPlacement` with a `containerInstance` below 1 is now refused by + `pack()` as `invalid_fixed_placement`, not by its constructor. +- **Every schema enum value is refused as `not_allowed`.** A value outside its list in + `allowed_rotations`, the output and dimensional-weight units, `shape_type`, + `ground_contact_rule` or `configuration.solvers` is `invalid_request` with reason `not_allowed` + at its JSON Pointer. **`ticks` as an output unit is now refused**; the schema never listed it. +- **`quality` looks ahead in the block solver.** Each round completes its leading + blocks greedily and commits the best, so the answer is never worse than the greedy pass. On + our 22 pinned benchmark requests every answer improved, at 3% more CPU. Under a tight effort + budget the block start can now report `truncated` / `effort_limit`. `fast` and `balanced` are + unchanged. +- **A `nesting_height` not below the item's height is refused as `invalid_value`** at its + pointer, and with no `output` block the result is written in `units.length`'s schema code. + +### Fixed + +- **The load rules walk a stack iteratively**, and the dependency-cycle check no longer recurses. +- **The covered ground-contact rule counts only supporters with positive area**, so an item no + longer rests on a box it touches only at an edge. +- **A quantity past 2^53 − 1 on the object path is refused** instead of exhausting memory. +- **A route violation names its violators in sorted order.** + ## [1.6.0] Boxes cut to measure, flat bags, stacking groups and a volume-first objective, all additive. A diff --git a/CITATION.cff b/CITATION.cff index 5ca759e..b6be0a5 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,7 +5,7 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.6.0" +version: "1.7.0" license: MIT url: "https://packvium.com" repository-code: "https://github.com/toxakara/packvium-php" diff --git a/README.md b/README.md index 24c3f2e..21d9da0 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ coordinates and rotations for each item, with a reason for anything that did not Full documentation, the constraint reference and benchmarks live at [packvium.com](https://packvium.com). -> **Version 1.6.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.7.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](https://github.com/toxakara/packvium-php/blob/main/docs/GUARANTEES.md) @@ -123,9 +123,8 @@ $result['termination']['code']; // "complete", "effort_limit" or ``` `termination` says which one stopped the search; only `time_limit` is a result you cannot -replay. In the object API the budget is `new PackingConfig(effortBudget: new EffortBudget(...))`; -`EffortBudget` lives in `Packvium\Algorithm`, the one namespace outside the frozen API, so -prefer the array form where you can. +replay. In the object API the budget is `new PackingConfig(effortBudget: new EffortBudget(...))`, +with `Packvium\Config\EffortBudget`, part of the frozen API since 1.6.0. [`reproducibility.php`](https://github.com/toxakara/packvium-php/blob/main/examples/reproducibility.php) shows all three outcomes. @@ -170,6 +169,29 @@ was left out, and why, in `unpacked_items`. [`errors.php`](https://github.com/toxakara/packvium-php/blob/main/examples/errors.php) turns each kind of refusal into the answer a web handler would send. +## Checking a result + +*New in 1.7.0.* + +`Packvium\Validation\validate` checks a result against the request it answers, from the decoded +JSON alone: geometry, support and load, accounting, the result's facts and its score. It is the +same reference validator every Packvium package exports, so it returns the same issues, code and +detail: + +```php +use Packvium\Serialization\ArrayCodec; +use function Packvium\Validation\validate; + +$issues = validate($request, ArrayCodec::pack($request)); // [] -- valid +foreach ($issues as $issue) { + echo "{$issue->code}: {$issue->detail}\n"; // e.g. collision: cube#1 with cube#2 in box#1 +} +``` + +It shares no code with the engine, so it judges any engine's result, not only this package's. A +result without the documented shape throws `Packvium\Validation\MalformedResult`, whose `kind` +is `contract` or `shape`. + ## Examples Runnable, in [`examples/`](https://github.com/toxakara/packvium-php/tree/main/examples). Each @@ -185,7 +207,7 @@ surprise people. | File | What it shows | | --- | --- | | [`basic.php`](https://github.com/toxakara/packvium-php/blob/main/examples/basic.php) | The smallest useful call: items in, placements out — and the three details in it that are easy to miss. | -| [`objectives.php`](https://github.com/toxakara/packvium-php/blob/main/examples/objectives.php) | All six objectives on scenes where they genuinely disagree, including the rate card that makes the heavier shipment the cheaper one. | +| [`objectives.php`](https://github.com/toxakara/packvium-php/blob/main/examples/objectives.php) | Six of the seven objectives (all but `maximum_volume`) on scenes where they genuinely disagree, including the rate card that makes the heavier shipment the cheaper one. | | [`constraints.php`](https://github.com/toxakara/packvium-php/blob/main/examples/constraints.php) | Upright-only, floor-only, non-stackable, top-load limits, and tags that keep two items out of the same box — plus how to read the reason an item was refused. | | [`limits.php`](https://github.com/toxakara/packvium-php/blob/main/examples/limits.php) | A courier's refrigerated van and cargo bikes: obstacles built from `additional_boxes`, `max_items`, `tag_limits`, `eligible_container_tags` and `max_containers`, and what each one costs. | | [`units.php`](https://github.com/toxakara/packvium-php/blob/main/examples/units.php) | Why there are no floats anywhere: fractional inches, exact ticks, and the one-tick difference between a fit and a refusal. | @@ -305,7 +327,9 @@ code and are not meant to run below it. ## 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. Python and +PHP are held to byte-identical canonical results; Rust and the JavaScript fallback are held +to independent validity and a per-fixture objective floor. Pick the package for your stack; mixing them in one system is safe. Documentation, the constraint reference and the benchmarks are at @@ -315,7 +339,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.7"` | [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) | @@ -339,7 +363,7 @@ CodeMeta form. @software{packvium_php, author = {{Packvium contributors}}, title = {Packvium for PHP}, - version = {1.6.0}, + version = {1.7.0}, license = {MIT}, url = {https://packvium.com} } diff --git a/autoload.php b/autoload.php index 41da364..7c5688d 100644 --- a/autoload.php +++ b/autoload.php @@ -38,3 +38,4 @@ // (Packvium\Commerce\quote and friends). `require_once` makes a second include -- through // Composer's `files` and again by a consumer wiring this up by hand -- harmless. require_once $packviumTree . '/Commerce/functions.php'; +require_once $packviumTree . '/Validation/functions.php'; diff --git a/codemeta.json b/codemeta.json index e998cd9..6c6174b 100644 --- a/codemeta.json +++ b/codemeta.json @@ -3,7 +3,7 @@ "@type": "SoftwareSourceCode", "name": "Packvium for PHP", "description": "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", - "version": "1.6.0", + "version": "1.7.0", "license": "https://spdx.org/licenses/MIT", "author": [ { diff --git a/docs/COMMERCE-API.md b/docs/COMMERCE-API.md index 6237164..7fcc53d 100644 --- a/docs/COMMERCE-API.md +++ b/docs/COMMERCE-API.md @@ -160,9 +160,11 @@ may carry only `tariffs`. Field-level rules: than leaving it to be inferred from which fields the payload happens to carry. - An omitted optional field and an explicit JSON `null` mean the same thing: absent. Writing `"minimum_charge_minor": null` is exactly writing nothing. -- Every integer is exact and, except where a model explicitly allows zero, positive. - The per-field bounds are the ones the models already enforce — see - CATALOG-VERSIONING.md and POLICY-RULES.md. +- Every integer is exact. Dimensions, an item's `weight_g`, `max_payload_g`, + `max_stack_height_mm` and `dimensional_weight_divisor` must be positive; `effective_at`, + `published_at`, `cost_minor`, `minimum_charge_minor`, `fuel_surcharge_permille`, + `flat_charge_minor`, `permille_of_base` and each zone rate in + `cost_per_dimensional_kg_minor` may be zero but not negative. ### Input errors versus rejections @@ -322,13 +324,12 @@ original paths and re-export the relocated definitions, so every workspace test, against the exact same objects. There is one definition of `rate_tariff` in the Python tree, and the installed wheel contains it. `commerce/rating/objective.py` — the solver adapter — is untouched and stays a workspace module: it registers in-process scorer and -selector objects, which EXTENDING.md explains are deliberately not -cross-language features. +selector objects, which are deliberately not cross-language features: an in-process +object cannot cross the JSON boundary every other engine is driven through. ## Conformance standard -Held to the standard every other capability in this project is held to, per -TESTING-AND-RELEASE.md: +Held to the standard every other capability in this project is held to: - **Python and PHP: byte-identical.** Both are ports of one contract; canonical JSON (sorted keys, `,`/`:` separators, no trailing whitespace) of the result document must @@ -364,15 +365,15 @@ TESTING-AND-RELEASE.md: | `catalog_version_info` | `O(h + e log e)` | `O(e)` | The `e log e` term is sorting the three id lists; every other bound is a linear scan of -the relevant history. These match the bounds already published for the underlying -models in ALGORITHMS-AND-COMPLEXITY.md — the wrapper -adds parsing and serialization, both linear in the payload, and nothing else. +the relevant history. These are the bounds of the underlying models; the wrapper adds +parsing and serialization, both linear in the payload, and nothing else. ## Limitations - The document is supplied by the caller. Nothing here fetches, scrapes or embeds any - real carrier's published rates; live rate-card ingestion is still out of scope and - still tracked in LIMITATIONS-AND-ROADMAP.md. + real carrier's published rates. Live rate-card ingestion exists, but in the carrier + connectors, not here: CARRIER-RATE-INGESTION.md builds a + table from a feed, and this API is handed the result like any other document. - `catalog_version_info` returns metadata and id lists, not the resolved master-data records. Exporting the full snapshot is a larger surface with its own wire-format question and is not part of this epic. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 1ee0c28..e0949d9 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -52,7 +52,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.6.0` freezes the public API. Field names, status codes, the objective +Version `1.7.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. @@ -61,7 +61,7 @@ What the freeze does not cover: which of several equally valid packings a solver returns. That is bounded by the objective vector, not by the placement list, and a minor release may return a different arrangement with the same or a better score. -The algorithm complexities documented in `ALGORITHMS-AND-COMPLEXITY.md` are asymptotic +The algorithm complexities Packvium states, in these docs and in the source, are asymptotic design bounds held by review, not per-release measurements. They are not a wall-clock performance contract either: constants, input shape and host all move the real number. Use them to choose a solver profile, not to predict a duration. diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md index df8fd8c..a784f42 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -15,8 +15,7 @@ false` dominates. The engines expose the same two fields on their item type: Python `Item.stacking_group` / `Item.accepts_stacking_groups`, PHP trailing constructor parameters `$stackingGroup` / `$acceptsStackingGroups`, Rust `Item::stacking_group` / - `Item::accepts_stacking_groups`, and the TypeScript request type. See - STACKING-GROUPS.md. + `Item::accepts_stacking_groups`, and the TypeScript request type. - **Item geometry beyond the box.** `shape_type` is an enum — `rigid_cuboid` (the default), `convex_hull`, `compressible` — accompanied by `hull_vertices`, `compression_ratio` and `max_compression_pressure_kpa`. **A request that @@ -26,11 +25,12 @@ The two other values are rolling out one engine at a time, which is what the fields were reserved before the freeze for, and the rollout is finished: **all four engines implement - both**, and are held to byte-identical results on the shared fixtures. The one - recorded difference is the JavaScript fallback on a scene whose answer depends on item - ordering -- it makes a single ordering pass where the other three run a portfolio, so it can - pack validly but less densely; that is pinned in `conformance/native-quality-budget.json` - rather than left to drift. + both**. On the shared fixtures Python and PHP are held to byte-identical results, + Rust and JavaScript to valid results no worse than the native quality budget. The + JavaScript fallback runs its own, smaller portfolio (eight item orderings, one under `fast`, + and four solvers under `quality`), so on a scene whose answer depends on item ordering it can + pack validly but less densely; any such difference is pinned in + `conformance/native-quality-budget.json` rather than left to drift. Where they are implemented: a `convex_hull` item's collisions are decided by an exact integer separating-axis test rather than by its box, and its occupied volume is the hull's @@ -42,7 +42,6 @@ fast path. Hull coordinates are non-negative offsets from the corner of the item's own bounding box and are capped at 10^8 length ticks -- 6.25 m, beyond ordinary parcel sizes, and the bound that keeps the exact geometry inside a 64-bit integer everywhere it can be. - IRREGULAR-ITEMS.md is the model and states why. - `Container`: id, inner/outer dimensions, tare/payload, cost, inventory quantity, obstacles (each a union of one or more exact boxes — `additional_boxes` approximates a non-rectangular zone such as a wheel arch or tapered roof without @@ -75,7 +74,7 @@ parameter `$deformableBoundary` with `PackedContainer::achievedDimensions()` / `billedDimensions()`, Rust `Container::deformable_boundary: Option` with `PackedContainer::achieved_dimensions()` / `billed_dimensions()`, and the TypeScript request - type. See DEFORMABLE-CONTAINERS.md. + type. - **Made-to-measure containers.** `made_to_measure` (absent or `null`: a stock container) makes the container an on-demand box machine whose largest box is `inner_dimensions`: `minimum` and `increment` per axis (required; `minimum` equal to @@ -93,8 +92,7 @@ `invalid_value`. The engines expose it as Python `Container.made_to_measure` (a `packvium.MadeToMeasure`, last field), PHP the trailing constructor parameter `?MadeToMeasure $madeToMeasure` (`Packvium\Domain\MadeToMeasure`), Rust - `Container::made_to_measure: Option`, and the TypeScript request type. See - MADE-TO-MEASURE-CONTAINERS.md. + `Container::made_to_measure: Option`, and the TypeScript request type. - `PackingConfig`: solver profile, deadline, alternatives, deterministic seed, clearance, support threshold (`minimum_support_ratio`, default 0: support is not required, and an item may rest on nothing above the floor; set it above 0 to require that share of the @@ -104,7 +102,7 @@ that bounds all four stable implementations by counted work instead of wall-clock time. In code it is Python `packvium.EffortBudget`, PHP `Packvium\Config\EffortBudget` and Rust `packvium_core::EffortBudget`. `solvers` is an ordered list: every named strategy is run, stable ties prefer - the earlier name, and an unknown name is a structured error. The optional + the earlier name, and an unknown name is a structured error. The stable solver names are `grid`, `extreme_points`, `homogeneous_blocks`, `layer`, `maximal_spaces` and `exact_small`. `homogeneous_blocks` is the unrestricted solid-lattice quality strategy and safely delegates to `extreme_points` when a scene @@ -114,8 +112,7 @@ example, for multiple declared item types or a custom hard constraint); it does not silently return an empty lattice result. The optional `shipping_cost` objective accepts exact dimensional-weight divisor/unit inputs and ranks billable weight from the shipped container's outer dimensions. These fields - have identical semantics in all four implementations — see - ALGORITHMS-AND-COMPLEXITY.md. + have identical semantics in all four implementations. `require_placement_coordinates` (Python/PHP/Rust/JavaScript, default `true`) lets a caller trade per-item coordinates for speed and memory on a bulk single-item-type order: when `false` and `GridSolver`'s regular-lattice preconditions already hold (see the @@ -138,18 +135,18 @@ search with `invalid_fixed_placement`. Python `Packer.pack(items, containers, fixed_placements)` and PHP `Packer::pack($items, $containers, $fixedPlacements)` take `FixedPlacement` values; Rust takes them in `PackingRequest.fixed_placements`, and every - JSON entry point reads the field. PLAN-REVISIONS.md is the contract; - all four engines implement it. + JSON entry point reads the field; all four engines implement it. - `catalog_versions_used`: optional immutable catalog references resolved before packing. Each reference has exactly `catalog_id`, positive `version`, non-negative `published_at_epoch_ms`, and `content_digest`; catalog IDs are unique. Production packing uses a monotonic system clock. Test harnesses and deterministic simulations may inject a monotonic clock into Python `Packer(..., clock=...)`, PHP -`Packer(..., clock: ...)`, Rust `Deadline::with_clock(...)` with -`SolverRegistry::solve_with_deadline(...)`, or the JavaScript fallback's optional clock -argument. The callable returns an implementation-native monotonic value; it must never -move backwards. This is a testing seam, not a serialized request field. +`Packer(..., clock: ...)`, or Rust `Deadline::with_clock(...)` with +`SolverRegistry::solve_with_deadline(...)`. `@packvium/engine` exposes no clock: its +`pack(request)` takes the request alone. The callable returns an implementation-native +monotonic value; it must never move backwards. This is a testing seam, not a serialized +request field. ## Core output @@ -161,8 +158,7 @@ move backwards. This is a testing seam, not a serialized request field. alongside it. The pre-1.1.0 extension point remains open: closing the object would make a previously valid producer fail a 1.1.0 validator, which is a breaking change and therefore not legal in this minor release. No engine emits the reserved fields - yet, so `code` is still the only key any Packvium result carries. See - OPTIMALITY-CERTIFICATES.md; + yet, so `code` is still the only key any Packvium result carries; - legacy `status`: `optimal`, `feasible`, `best_found`, `time_limit`, `infeasible`, or `invalid_result`; - packed containers with exact coordinates, dimensions, rotations, and a `centre_of_mass_offset_ppm` — the weighted centre of mass's exact-integer Chebyshev @@ -174,7 +170,7 @@ move backwards. This is a testing seam, not a serialized request field. share the positive `denominator`; signed numerators intentionally expose a centre of mass outside the axle span instead of clipping it; - unpacked instances with reason codes, proof levels and rejection observations; -- objective score — a five-key lexicographic vector of exact integers, identical across every implementation (OBJECTIVE.md) — and solver statistics; +- objective score — a five-key lexicographic vector of exact integers, lower is better, computed by the same formula in every implementation — and solver statistics. Under the default objective the keys are `unpacked_count`, `container_count`, `total_cost_minor`, `unused_volume_ppm` (per container `floor((V - used) x 10^6 / V)` of inner volume `V`) and `stack_height_ppm` (per container `floor(top x 10^6 / H)` of inner height `H`); `configuration.objective` selects one of seven orderings (`default`, `lowest_cost`, `shipping_cost`, `lowest_landed_cost`, `open_dimension_height`, `maximum_value`, `maximum_volume`), and the result echoes it in `objective`; - the exact `catalog_versions_used` lineage from the request (an empty array when no catalog was involved), preserved by Python, PHP, Rust and JavaScript; - warnings and top-K alternatives. With `minimum_support_ratio` at its default 0, a result @@ -285,8 +281,7 @@ own `code` property): {"code": "invalid_direction", "direction": "sideways"} ``` -`conformance/scene/sequence-fixtures.json` pins this shape across all four languages; -see `docs/SERIALIZATION.md`. +A shared fixture pins this shape across all four languages. Sequence diagnostics use a separate canonical `SequenceWarning` DTO instead of putting caller-facing prose into an untyped string. Its four fields are stable in @@ -409,6 +404,12 @@ without turning a minor release into a parsing break. `status` remains for one compatibility cycle and is checked against the three facts. The alpha release emits no `proven_optimal` claim without a future proof/certificate. +`status: infeasible`, with `feasibility: infeasible` and `optimality: proven_infeasible`, is +emitted only when the portfolio ranks no result at all. A request whose every item is proven +unpackable is not that case: every engine answers `status: best_found`, `feasibility: +unknown` and `optimality: best_found`, with each item and its `proven` reason in +`unpacked_items`. Read `unpacked_items`, not `status`, to learn that nothing fits. + ## Portfolio termination `termination` describes the whole solver portfolio instead of copying one ambiguous @@ -457,8 +458,9 @@ The aggregate fields are derived only from `starts`. Exactly one record is selec clock, and `effort_limit` when the selected start stopped at a counted-work boundary. A truncated loser alone leaves the selected answer's code `complete`, while still making `all_required_starts_completed` false. The two algorithm limit flags preserve -the exact cause. -`winning_start_truncated || global_deadline_reached`. +the exact cause: one of `algorithm.time_limit_reached` and `algorithm.effort_limit_reached` +is true exactly when `winning_start_truncated || global_deadline_reached`, and +`global_deadline_reached` requires `time_limit_reached`. ## Rejection proof @@ -489,7 +491,7 @@ The four levels have deliberately different meanings: | Level | Meaning | | --- | --- | | `proven` | A request-level bound proves rejection without relying on search completeness. Currently `no_compatible_container_dimensions`, `payload_exceeded`, `rotation_restricted` and `no_eligible_container` — each a pure geometry or tag check across every container, none dependent on how far the search got. | -| `observed` | The engine exhausted or rejected the candidates it actually examined; this is not a global impossibility proof. | +| `observed` | The engine exhausted or rejected the candidates it actually examined; this is not a global impossibility proof. Currently `no_feasible_placement`, `search_exhausted`, `exact_search_incomplete` and `insufficient_support` — the last when replaying the finished layout finds a place the item fits once the support rules are set aside, and none with them, in every engine. | | `inferred` | The reason follows from solver state or a compound rule but has no complete certificate. | | `unknown_due_to_limit` | A deadline stopped the search, so no negative conclusion is claimed. | @@ -510,6 +512,28 @@ load can only refuse an item a fresh container would take, so they all end there relieve the front one -- and both rank after the structural proofs, the deadline, the effort budget and `group_cannot_fit_together`. +## Result validation + +Every package can check a result against the request it answers with the same reference +validator, and gets the same issue list back: geometry, support and load, accounting, the +result's facts and its score, each issue a `code` and a `detail`, an empty list meaning +valid. A result without the documented shape is refused as `MalformedResult`, whose `kind` is +`contract` or `shape`. + +- Python: `packvium.validate(request, result)`, `packvium.MalformedResult`. +- Rust: `packvium_core::validate_json(request, result)` over JSON text, returning + `Vec` or `MalformedResult { kind, message }`; `validate_json_outcome` returns the + same as one JSON document for a binding. +- PyO3 (`packvium_native_rust`): `validate_json(request, result)` over JSON text, a list of + `{"code", "detail"}` dicts, `MalformedResult` (a `ValueError`) with `kind`. +- `@packvium/engine`: `validate(request, result)`, `MalformedResult`, and + `ValidatorUnavailableError` (`code: 'validator_unavailable'`) when the compiled addon is + absent, until the JavaScript fallback's port. +- `@packvium/browser`: `validate(request, result)`, a promise, `MalformedResult`. + +- PHP: `Packvium\Validation\validate(array $request, array $result)`, a `list` + (`code`, `detail`), `MalformedResult` with `kind`. + ## Commercial and control-plane API Three deterministic functions over one canonical JSON document -- a carrier quote, an @@ -546,8 +570,7 @@ request returns a result with a status rather than raising. A document derived from an already validated packing result: what to do first, why this carton, and what was not packed. It is a view, not a decision — it calls no solver and no -validator, and a test in each language asserts that. The contract is -EXECUTION-PLAN.md. +validator, and a test in each language asserts that. | Language | Entry point | | --- | --- | @@ -609,8 +632,7 @@ One portable document built from a validated result. It carries: of the solver record, and an honest replay level. It is exported as JSON, RFC 4180 CSV, or a self-contained printable HTML work order. Like the -plan it is a view, not a decision: no solver, validator, renderer or clock is called. The -contract is OPERATIONAL-ARTIFACTS.md. +plan it is a view, not a decision: no solver, validator, renderer or clock is called. | Language | Builder | Exports | | --- | --- | --- | @@ -645,8 +667,7 @@ An append-only, hash-chained record of what differed from an approved plan: a mi a substituted carton, an operator lock or a verified placement. Each revision derives the request the next plan solves; a replan is an ordinary solve of it, with locks and verified placements carried as `fixed_placements`. A revision is a pure function of its parent, the -approved operational artifact and its events, and calls no solver or clock. The contract is -PLAN-REVISIONS.md. +approved operational artifact and its events, and calls no solver or clock. | Language | Surface | | --- | --- | @@ -663,9 +684,8 @@ stopping at the first. Refusals use `invalid_revision`, `invalid_event`, `event_ ## Scenario and recommendation API Scenario what-if comparison and catalog/rule recommendation publication, exported as -`packvium.simulation` and `packvium.recommendations`. The full contract is -INTELLIGENCE-API.md; what belongs here is the surface and its two -limits, both of which are part of the API rather than notes about it. +`packvium.simulation` and `packvium.recommendations`. This section is the surface and its +two limits, both of which are part of the API rather than notes about it. | Language | Entry point | | --- | --- | @@ -677,7 +697,7 @@ document is proved by driving four engines as subprocesses over JSON. `run_scena an `OrderEvaluator` *callback* as its central argument, and a callback does not cross a pipe -- so the harness that proves the packing and commerce contracts cannot express a scenario at all. Whether the data-in/data-out half ever crosses runtimes is an open -question, not an omission; INTELLIGENCE-API.md scopes it. +question, not an omission. **Historical replay ships with the ledger it reads.** `evaluate_on_history` scores a recommendation against decisions held out by an explicit `split_at`, and could not be @@ -700,10 +720,10 @@ importing the submodule, which puts them outside the frozen API snapshot the pac commerce surfaces are held to. They work, they are tested, and they will not be withdrawn inside 1.x — but a parameter may be renamed or a returned value gain a field in a minor release, announced in the changelog rather than blocked by a gate. Pin the version if you -depend on the exact shape. COMPATIBILITY.md states why this one surface -is held that way and what would change it. +depend on the exact shape. ## JSON API Python, PHP, Rust and the JavaScript fallback accept the same top-level keys: `units`, -`configuration`, `items`, `containers`, `catalog_versions_used`, and `output`. +`configuration`, `items`, `containers`, `catalog_versions_used`, `policy`, `output` and +`fixed_placements`. diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index 272c4ee..fd1e6e6 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -20,7 +20,7 @@ Conversion supports floor, ceiling and ties-to-even nearest rounding. Applicatio ## Geometry versus scores -Feasibility checks are integer-only, including the support ratio: the requested fraction is converted once to parts per million and compared as `supported_area >= floor(base_area x ratio_ppm / 10^6)`, never as a float division against an epsilon. The independent validator rechecks boundaries and intersections using exact integers. +Feasibility checks are integer-only, including the support ratio: the requested fraction is converted once to parts per million, `ratio_ppm = floor(ratio x 10^6 + 0.5)` on the IEEE double the request carries (each step correctly rounded, so every language gets the same integer; on about one in a hundred seven-decimal halves it differs from rounding the exact decimal, `0.0001245` giving 124), and compared as `supported_area >= floor(base_area x ratio_ppm / 10^6)`, never as a float division against an epsilon. Every result validator applies this same rule rather than the exact rational. `void_fill_reserve_ratio` goes through the same conversion and reserves `floor(inner_volume x ratio_ppm / 10^6)` cubic ticks, which the validators recompute the same way. The independent validator rechecks boundaries and intersections using exact integers. The Rust solver and validator were the exception until 2026-09-02: both compared `area / base_area + 1e-12 < ratio` in `f64`. On a real-sized base (a square centimetre is `2.56 x 10^10` square ticks) an area one square tick short of the requirement sits well inside that epsilon, so Rust admitted a placement the shared validator refused. Both now go through `support_area_sufficient`, the rule above; the `f64` ratio survives only as the reported `support_ratio` on the placement record. @@ -33,7 +33,7 @@ Coordinates remain 64-bit integers. Values that exceed that range are handled wi | Quantity | Why it overflows | How it is handled | | --- | --- | --- | | Volume, for output and ordering | A one-metre cube is `4.096 x 10^21` cubic ticks | `BigInt::multiply`/`add`, compared as decimal integers; this includes exact-small's equal-count physical-volume tie-break | -| Objective keys 3 and 4 | Ratio of two volumes | `BigInt::subtract` / `BigInt::divide`, see OBJECTIVE.md | +| Objective keys 3 and 4 | `unused_volume_ppm`, per container `floor((V - used) x 10^6 / V)`, scales a volume by 10^6; `stack_height_ppm` is `floor(top x 10^6 / H)` | `BigInt::subtract` / `BigInt::divide` | | Load shares, `weight x area / total_area` | Eighth-microgram counts times squared ticks | `Arithmetic::mulDiv`, exact and overflow-free | | Serialized decimals | Ticks beyond `2^53` do not survive a `double` | long division on digits, rounded ties-to-even | @@ -46,7 +46,7 @@ converted back to a number only at the existing JSON boundary. ## The bound path's declared ceiling -`docs/OPTIMALITY-CERTIFICATES.md` defines lower bounds on the objective. Their arithmetic is +The engines compute lower bounds on the objective during search. Their arithmetic is integer-only, and the limit at which they refuse is **declared rather than inherited from the language**: every sum in that path must stay below `10^30`, and exceeding it is a structured refusal in all four engines rather than a number. diff --git a/src-legacy/Algorithm/CandidateFinder.php b/src-legacy/Algorithm/CandidateFinder.php index 9db5145..89aef49 100644 --- a/src-legacy/Algorithm/CandidateFinder.php +++ b/src-legacy/Algorithm/CandidateFinder.php @@ -68,9 +68,13 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf // reaches it. $active=[]; foreach($constraints as $constraint){ - if(ConstraintActivity::isInert($constraint,$container,$item,$stackSensitive,$routeSensitive,$config->accessDirections))continue; - $active[]=[$constraint,$constraint instanceof SupportConstraint]; + if(ConstraintActivity::isInert($constraint,$container,$item,$stackSensitive,$routeSensitive))continue; + $active[]=[$constraint,$constraint instanceof SupportConstraint,ConstraintActivity::isPositionIndependent($constraint)]; } + // A rule that reads no position answers the same at every (point, rotation) of this + // search, so it is asked once, by the first position that reaches it. + // Keyed by chain position; the stored value is the verdict's `allowed`. + $fixedVerdicts=[]; if($points===null){ if($item->item->nestingHeight===null)$scan=array_slice($state->orderedPoints,0,$config->maxCandidatePoints); else{ @@ -83,7 +87,7 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf }); $scan=array_slice($scan,0,$config->maxCandidatePoints); } - if($container->axles!==null)$scan=array_merge($scan, self::axleBalancedPoints($state,$item,$forms,$limitX)); + if($container->axles!==null)$scan=self::appendUnseen($scan,self::axleBalancedPoints($state,$item,$forms,$limitX)); }else{$scan=$points;usort($scan,static function (Point $a, Point $b): int { return [$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]; });} @@ -128,9 +132,12 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf } if($blocked)continue; $ctx=new ConstraintContext($container,$placed,$item,$point,$rotation,$physical,$envelope,$stackSensitive,$routeSensitive); - foreach($active as [$constraint,$countsSupport]){ + foreach($active as $link=>[$constraint,$countsSupport,$positionIndependent]){ if($countsSupport)$stats->supportChecks++; - if(!$constraint->evaluate($ctx)->allowed){$blocked=true;break;} + $allowed=$positionIndependent + ?($fixedVerdicts[$link] = $fixedVerdicts[$link] ?? $constraint->evaluate($ctx)->allowed) + :$constraint->evaluate($ctx)->allowed; + if(!$allowed){$blocked=true;break;} } if($blocked)continue; $score=$scorer->score($state,$point,$envelope); @@ -200,6 +207,30 @@ private static function nestingPoints(ContainerState $state,ItemInstance $item): return $points; } + /** + * `$points` then the `$extra` points not already offered, keeping their order (S20). + * + * A repeated point is the same candidate scanned twice: it can change nothing but the + * counted effort. O(k + a) for k offered and a extra points. + * + * @param list $points + * @param list $extra + * @return list + */ + private static function appendUnseen(array $points, array $extra): array + { + $fresh=[]; + foreach($extra as $point)$fresh["{$point->x}:{$point->y}:{$point->z}"]=true; + foreach($points as $point)unset($fresh["{$point->x}:{$point->y}:{$point->z}"]); + foreach($extra as $point){ + $key="{$point->x}:{$point->y}:{$point->z}"; + if(!isset($fresh[$key]))continue; + unset($fresh[$key]); + $points[]=$point; + } + return $points; + } + /** * Extra floor-level candidates that seat this item on an axle's own limit. * @@ -223,6 +254,9 @@ private static function axleBalancedPoints(ContainerState $state, ItemInstance $ $floorYs=[]; foreach($state->points as $point)if($point->z===0)$floorYs[$point->y]=true; $floorYs=$floorYs===[]?[0]:array_keys($floorYs); + // Ascending, as Python and Rust scan them: insertion order moved which point a + // counted stop landed on (S12). + sort($floorYs); $points=[]; foreach($forms as [, , , $dx, , , ]){ foreach(AxleLoad::axleBalancedOrigins($container->axles,$otherUnits,$tareTicks,$tareDoubledX,$item->weight()->ticks,$dx) as $x1){ diff --git a/src-legacy/Algorithm/DeterministicRandom.php b/src-legacy/Algorithm/DeterministicRandom.php index 99cdfc6..ab9835f 100644 --- a/src-legacy/Algorithm/DeterministicRandom.php +++ b/src-legacy/Algorithm/DeterministicRandom.php @@ -20,7 +20,8 @@ final class DeterministicRandom */ private $state; - public function __construct(int $seed){$this->state=$seed%self::MODULUS;} + /** PHP's % keeps the dividend's sign; Python's does not, and the shuffle indexes by the draw. */ + public function __construct(int $seed){$this->state=(($seed%self::MODULUS)+self::MODULUS)%self::MODULUS;} private function bits():int { diff --git a/src-legacy/Algorithm/EffortBudget.php b/src-legacy/Algorithm/EffortBudget.php index c705623..2a5ce28 100644 --- a/src-legacy/Algorithm/EffortBudget.php +++ b/src-legacy/Algorithm/EffortBudget.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Packvium\Algorithm; -use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; /** * Counted-work limits, checked alongside (never instead of) the wall clock. @@ -51,7 +51,7 @@ public function __construct( // caller means; the schema's floor for each is 1. foreach (['maxCandidatesEvaluated'=>$maxCandidatesEvaluated,'maxPlacementAttempts'=>$maxPlacementAttempts,'maxSearchNodes'=>$maxSearchNodes,'maxRestarts'=>$maxRestarts] as $name=>$limit) { if ($limit!==null && $limit<1) { - throw new InvalidArgumentException("effortBudget.{$name} must be at least 1"); + throw new ObjectRefusal('below_minimum',"effortBudget.{$name} must be at least 1"); } } } diff --git a/src-legacy/Algorithm/ExactSmallSolver.php b/src-legacy/Algorithm/ExactSmallSolver.php index 2485744..9b62337 100644 --- a/src-legacy/Algorithm/ExactSmallSolver.php +++ b/src-legacy/Algorithm/ExactSmallSolver.php @@ -122,7 +122,6 @@ public function packOne(Container $container,int $sequence,array $items,PackingC if($deadline->expired())return; $stats->searchNodesExpanded++; $stateCount=count($state->placements); - $bestCount=count($best->placements); if(self::isBetterForObjective($state,$stateVolume,$best,$bestVolume,$config)){ $best=$state; $bestVolume=$stateVolume; diff --git a/src-legacy/Algorithm/HomogeneousBlockSolver.php b/src-legacy/Algorithm/HomogeneousBlockSolver.php index bff67ab..46b1280 100644 --- a/src-legacy/Algorithm/HomogeneousBlockSolver.php +++ b/src-legacy/Algorithm/HomogeneousBlockSolver.php @@ -3,6 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; +use Packvium\Config\SolverProfile; use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Constraint\PlacementConstraint; use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Placement,Point,ShapeType}; @@ -42,6 +43,10 @@ final class HomogeneousBlockSolver implements SingleContainerSolver /** Lattice nodes between two clock reads are a power of two: 1 << CLOCK_SHIFT. */ private const CLOCK_SHIFT=6; private const CLOCK_STRIDE=(1<modes as $mode){ if($deadline->expired()){$reached=true;break;} $solution=$this->packMode($container,$sequence,$items,$config,$stats,$deadline,$mode,$nodeLimit); + if($config->profile===SolverProfile::Quality&&!$deadline->expired()) + $solution=$this->lookahead($container,$sequence,$items,$config,$stats,$deadline,$mode,$nodeLimit*self::LOOKAHEAD_NODE_FACTOR,$solution); $reached=$reached||$solution->timeLimitReached; $byVolume=$config->objective==='maximum_volume'; if($best===null||$this->solutionKey($solution,$byVolume)<$this->solutionKey($best,$byVolume))$best=$solution; @@ -248,25 +255,26 @@ private static function largestBlock(int $maximumX,int $maximumY,int $maximumZ,i } /** - * The round's leading block over every (space, type, rotation) group, or null. + * The round's `$leaders` leading blocks over every (space, type, rotation) group, best first. * * Every group's nodes count toward the limits before any is ranked, and a stop inside a * group lands on the node the per-node loop stopped at: a stopped round places nothing, * so which node led it is never read. Inside one group every key field except the * count-derived lead is equal, and fill and volume grow with the count, so the group's * first largest count is the only node that can lead. No node exceeds the capacity or - * the whole lattice, and a group whose bound already trails the incumbent cannot lead: - * the cheap lead is monotone in the count, since a float product is. + * the whole lattice, and once `$leaders` blocks are kept a group whose bound already + * trails the last of them cannot lead: the cheap lead is monotone in the count, since a + * float product is. * * @param list $spaces * @param array $capacities * @param array>> $rotations - * @return array|null + * @return list> */ - private static function leadingBlock(array $spaces,array $capacities,array $rotations,string $mode,int &$nodes,int $stopAt,SearchStats $stats,Deadline $deadline,bool &$reached):?array + private static function leadingBlocks(array $spaces,array $capacities,array $rotations,string $mode,int $leaders,int &$nodes,int $stopAt,SearchStats $stats,Deadline $deadline,bool &$reached):array { - $best=null;$byCount=$mode==='count'; - // The incumbent's cheap lead as scalars: its count, and its float volume less the margin. + $leading=[];$byCount=$mode==='count'; + // The last kept block's cheap lead as scalars: its count, and its float volume less the margin. $leadCount=0;$leadFloor=-INF; foreach($spaces as $space){ $spaceLength=$space->dimensions->length->ticks;$spaceWidth=$space->dimensions->width->ticks;$spaceHeight=$space->dimensions->height->ticks; @@ -281,7 +289,7 @@ private static function leadingBlock(array $spaces,array $capacities,array $rota if($nodes+$groupNodes>$stopAt||(($nodes+$groupNodes-1)>>self::CLOCK_SHIFT)!==(($nodes-1)>>self::CLOCK_SHIFT)){ $expanded=self::expandable($nodes,$groupNodes,$stopAt,$deadline); $nodes+=$expanded;$stats->searchNodesExpanded+=$expanded; - if($expanded<$groupNodes){$reached=true;return null;} + if($expanded<$groupNodes){$reached=true;return [];} }else{$nodes+=$groupNodes;$stats->searchNodesExpanded+=$groupNodes;} if($envelopeHeight>$spaceHeight)continue; $maximumZ=intdiv($spaceHeight,$envelopeHeight); @@ -293,55 +301,169 @@ private static function leadingBlock(array $spaces,array $capacities,array $rota $approximateUsed=$count*$volume; if($byCount?$count<$leadCount:$approximateUsed<$leadFloor)continue; $candidate=['space'=>$space,'itemId'=>$itemId,'rotation'=>$lattice['rotation'],'rotationName'=>$lattice['rotationName'],'physical'=>$lattice['physical'],'envelope'=>$lattice['envelope'],'volume'=>$lattice['volume'],'approximateUsed'=>$approximateUsed,'nx'=>$nx,'ny'=>$ny,'nz'=>$nz,'count'=>$count]; - if($best!==null&&!self::leads($candidate,$best,$mode))continue; - $best=$candidate;$leadCount=$count;$leadFloor=$approximateUsed*(1-self::FLOAT_MARGIN); + $full=count($leading)===$leaders; + if($full&&!self::leads($candidate,$leading[$leaders-1],$mode))continue; + $position=count($leading); + while($position>0&&self::leads($candidate,$leading[$position-1],$mode))$position--; + array_splice($leading,$position,0,[$candidate]); + if(count($leading)>$leaders)array_pop($leading); + if(count($leading)===$leaders){$last=$leading[$leaders-1];$leadCount=$last['count'];$leadFloor=$last['approximateUsed']*(1-self::FLOAT_MARGIN);} } } } - return $best; + return $leading; } - private function packMode(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit):SingleContainerSolution + /** @param list $items @return array> */ + private static function byType(array $items):array { - $state=new ContainerState($container,$sequence); - $spaces=[new Space(new Point(0,0,0),$container->innerDimensions)]; $remaining=[]; foreach($items as $instance)$remaining[$instance->item->id][]=$instance; ksort($remaining,SORT_STRING); - $nodes=0;$reached=false;$rotations=[]; + return $remaining; + } + + /** + * Each type's distinct rotations with what every lattice of them shares. + * + * @param array> $remaining + * @return array>> + */ + private static function rotationsOf(array $remaining,PackingConfig $config):array + { + $rotations=[]; + foreach($remaining as $itemId=>$available)$rotations[$itemId]=self::lattices($available[0],$config); + return $rotations; + } + + private function packMode(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit):SingleContainerSolution + { + $remaining=self::byType($items); + $nodes=0;$reached=false; + $solution=$this->complete($container,new ContainerState($container,$sequence),[new Space(new Point(0,0,0),$container->innerDimensions)],$remaining,self::rotationsOf($remaining,$config),$config,$stats,$deadline,$mode,$nodeLimit,$nodes,$reached); + return new SingleContainerSolution($solution->state,$solution->unpacked,false,$reached||$deadline->expired()); + } + + /** + * How many of each type one block may still take, for the types that may take any. + * + * @param array> $remaining + * @return array + */ + private static function capacities(Container $container,ContainerState $state,array $remaining):array + { + $capacities=[]; + foreach($remaining as $itemId=>$available){ + if($available===[])continue; + $prototype=$available[0];$capacity=count($available); + if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems-$state->placementCount()); + if($container->maxPayload!==null&&$prototype->weight()->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks-$state->payloadTicks,$prototype->weight()->ticks)); + if($capacity<=0)continue; + $capacities[$itemId]=$capacity; + } + return $capacities; + } + + /** + * One round's leading blocks under the mode's node limit and the effort budget. + * + * @param list $spaces + * @param array> $remaining + * @param array>> $rotations + * @return list> + */ + private static function round(Container $container,ContainerState $state,array $spaces,array $remaining,array $rotations,string $mode,int $leaders,int $nodeLimit,int &$nodes,SearchStats $stats,Deadline $deadline,bool &$reached):array + { + // Only the node count moves a counted limit inside one round: candidates and + // placements are counted when a block is placed, after it. + $stopAt=$nodes+max(0,min($nodeLimit-$nodes,$deadline->searchNodesLeft($stats))); + return self::leadingBlocks($spaces,self::capacities($container,$state,$remaining),$rotations,$mode,$leaders,$nodes,$stopAt,$stats,$deadline,$reached); + } + + /** + * Commit each round's leading block until nothing more fits. + * + * @param list $spaces + * @param array> $remaining + * @param array>> $rotations + */ + private function complete(Container $container,ContainerState $state,array $spaces,array $remaining,array $rotations,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit,int &$nodes,bool &$reached):SingleContainerSolution + { while($spaces!==[]&&array_sum(array_map('count',$remaining))>0){ - // Only the node count moves a counted limit inside one round: candidates and - // placements are counted when a block is placed, after it. - $stopAt=$nodes+max(0,min($nodeLimit-$nodes,$deadline->searchNodesLeft($stats))); - // A type's capacity and lattices do not depend on the space they are tried in. - $capacities=[]; - foreach($remaining as $itemId=>$available){ - if($available===[])continue; - $prototype=$available[0];$capacity=count($available); - if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems-$state->placementCount()); - if($container->maxPayload!==null&&$prototype->weight()->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks-$state->payloadTicks,$prototype->weight()->ticks)); - if($capacity<=0)continue; - $capacities[$itemId]=$capacity; - $rotations[$itemId] = $rotations[$itemId] ?? self::lattices($prototype,$config); - } - $best=self::leadingBlock($spaces,$capacities,$rotations,$mode,$nodes,$stopAt,$stats,$deadline,$reached); - if($best===null||$reached)break; - $chosen=array_slice($remaining[$best['itemId']],0,$best['count']); - $remaining[$best['itemId']]=array_slice($remaining[$best['itemId']],$best['count']); - $clearance=$config->clearance->ticks;$index=0; - for($z=0;$z<$best['nz'];$z++)for($y=0;$y<$best['ny'];$y++)for($x=0;$x<$best['nx'];$x++){ - $point=new Point($best['space']->origin->x+$x*$best['envelope']->length->ticks,$best['space']->origin->y+$y*$best['envelope']->width->ticks,$best['space']->origin->z+$z*$best['envelope']->height->ticks); - $position=new Point($point->x+$clearance,$point->y+$clearance,$point->z+$clearance); - // Above its bottom layer a member rests on an identical footprint; the - // bottom layer rests on whatever is there. - $support=$z===0?self::memberSupport($state,$chosen[$index],$point,$best['envelope']):1.0; - $state->addDirect(new Placement($chosen[$index++],$position,$best['rotation'],$best['physical'],$point,$best['envelope'],$support)); - $stats->candidatesEvaluated++;$stats->placementsAttempted++; - } - $blockDimensions=new Dimensions(new Length($best['nx']*$best['envelope']->length->ticks),new Length($best['ny']*$best['envelope']->width->ticks),new Length($best['nz']*$best['envelope']->height->ticks)); - $spaces=MaximalSpaceSolver::subtractAll($spaces,[new AxisAlignedBox($best['space']->origin,$blockDimensions)],$stats); + $leading=self::round($container,$state,$spaces,$remaining,$rotations,$mode,1,$nodeLimit,$nodes,$stats,$deadline,$reached); + if($leading===[]||$reached)break; + $spaces=self::commit($state,$spaces,$remaining,$leading[0],$config,$stats); } $unpacked=[];foreach($remaining as $available)foreach($available as $instance)$unpacked[]=$instance; - return new SingleContainerSolution($state,$unpacked,false,$reached||$deadline->expired()); + return new SingleContainerSolution($state,$unpacked,false,$reached); + } + + /** + * `$greedy`, or a better answer from completing each round's leading blocks. + * + * Each round ranks its LOOKAHEAD_WIDTH leading blocks, completes each one greedily on a + * copy, and commits the block whose completion ranks best. The greedy answer is the first + * completion, so the result is never worse than it. The round's first block is the greedy + * choice after the block committed last, so its completion is the one already known -- + * unless the greedy pass was stopped by the node limit, when the first round completes it + * under the lookahead's larger budget. When that budget runs out the best completion so + * far stands; only the deadline or the effort budget marks the answer as stopped. + * + * @param list $items + */ + private function lookahead(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit,SingleContainerSolution $greedy):SingleContainerSolution + { + $byVolume=$config->objective==='maximum_volume'; + $state=new ContainerState($container,$sequence); + $spaces=[new Space(new Point(0,0,0),$container->innerDimensions)]; + $remaining=self::byType($items); + $rotations=self::rotationsOf($remaining,$config); + $best=$greedy;$bestKey=$this->solutionKey($greedy,$byVolume); + $known=$greedy->timeLimitReached?null:$greedy; + $nodes=0;$reached=false; + while($spaces!==[]&&array_sum(array_map('count',$remaining))>0){ + $leading=self::round($container,$state,$spaces,$remaining,$rotations,$mode,self::LOOKAHEAD_WIDTH,$nodeLimit,$nodes,$stats,$deadline,$reached); + if($leading===[]||$reached)break; + $chosen=$known===null?null:[$this->solutionKey($known,$byVolume),$known,$leading[0]]; + foreach($known===null?$leading:array_slice($leading,1) as $block){ + $trialState=$state->copy();$trialRemaining=$remaining; + $trialSpaces=self::commit($trialState,$spaces,$trialRemaining,$block,$config,$stats); + $trial=$this->complete($container,$trialState,$trialSpaces,$trialRemaining,$rotations,$config,$stats,$deadline,$mode,$nodeLimit,$nodes,$reached); + if($reached)break; + $trialKey=$this->solutionKey($trial,$byVolume); + if($chosen===null||$trialKey<$chosen[0])$chosen=[$trialKey,$trial,$block]; + } + if($reached||$chosen===null)break; + [$chosenKey,$known,$block]=$chosen; + if($chosenKey<$bestKey){$best=$known;$bestKey=$chosenKey;} + $spaces=self::commit($state,$spaces,$remaining,$block,$config,$stats); + } + return new SingleContainerSolution($best->state,$best->unpacked,false,$best->timeLimitReached||$deadline->expired()); + } + + /** + * Place every member of the block, bottom layer first, and return the spaces left. + * + * @param list $spaces + * @param array> $remaining + * @param array $best + * @return list + */ + private static function commit(ContainerState $state,array $spaces,array &$remaining,array $best,PackingConfig $config,SearchStats $stats):array + { + $chosen=array_slice($remaining[$best['itemId']],0,$best['count']); + $remaining[$best['itemId']]=array_slice($remaining[$best['itemId']],$best['count']); + $clearance=$config->clearance->ticks;$index=0; + for($z=0;$z<$best['nz'];$z++)for($y=0;$y<$best['ny'];$y++)for($x=0;$x<$best['nx'];$x++){ + $point=new Point($best['space']->origin->x+$x*$best['envelope']->length->ticks,$best['space']->origin->y+$y*$best['envelope']->width->ticks,$best['space']->origin->z+$z*$best['envelope']->height->ticks); + $position=new Point($point->x+$clearance,$point->y+$clearance,$point->z+$clearance); + // Above its bottom layer a member rests on an identical footprint; the + // bottom layer rests on whatever is there. + $support=$z===0?self::memberSupport($state,$chosen[$index],$point,$best['envelope']):1.0; + $state->addDirect(new Placement($chosen[$index++],$position,$best['rotation'],$best['physical'],$point,$best['envelope'],$support)); + $stats->candidatesEvaluated++;$stats->placementsAttempted++; + } + $blockDimensions=new Dimensions(new Length($best['nx']*$best['envelope']->length->ticks),new Length($best['ny']*$best['envelope']->width->ticks),new Length($best['nz']*$best['envelope']->height->ticks)); + return MaximalSpaceSolver::subtractAll($spaces,[new AxisAlignedBox($best['space']->origin,$blockDimensions)],$stats); } } diff --git a/src-legacy/Artifacts/OperationalArtifact.php b/src-legacy/Artifacts/OperationalArtifact.php index 3c778f3..4eeef69 100644 --- a/src-legacy/Artifacts/OperationalArtifact.php +++ b/src-legacy/Artifacts/OperationalArtifact.php @@ -36,7 +36,7 @@ final class OperationalArtifact * The engine's own name is deliberately not recorded: four correct builders naming * themselves would emit four different documents. */ - public const SUITE_VERSION = '1.6.0'; + public const SUITE_VERSION = '1.7.0'; /** The deterministic part of `result.algorithm`; `duration_ms` is wall-clock time. */ private const SOLVER_FIELDS = ['profile', 'solver', 'seed', 'time_limit_reached', 'effort_limit_reached']; diff --git a/src-legacy/Config/PackingConfig.php b/src-legacy/Config/PackingConfig.php index dbda469..128b7cd 100644 --- a/src-legacy/Config/PackingConfig.php +++ b/src-legacy/Config/PackingConfig.php @@ -1,7 +1,8 @@ containerPlanBeamWidth = $containerPlanBeamWidth; $this->containerPlanNodeLimit = $containerPlanNodeLimit; $this->accessDirections = $accessDirections; - if($timeLimitMs<=0||$topK<=0||$exactItemLimit<=0||$multiStartOrders<=0||$maxCandidatesPerItem<=0||$parallelStarts<=0||$containerPlanBeamWidth<=0||$containerPlanNodeLimit<=0)throw new InvalidArgumentException('Positive configuration values required');if($maxContainers!==null&&$maxContainers<1)throw new InvalidArgumentException('maxContainers must be at least 1');if($maxCandidatePoints<16)throw new InvalidArgumentException('maxCandidatePoints must be at least 16');if($minimumSupportRatio<0||$minimumSupportRatio>1)throw new InvalidArgumentException('Minimum support ratio must be between 0 and 1');if($dimensionalWeightDivisor!==null&&$dimensionalWeightDivisor<=0)throw new InvalidArgumentException('dimensionalWeightDivisor must be positive');$this->clearance=$clearance??new Length(0);} + if($timeLimitMs<=0||$topK<=0||$exactItemLimit<=0||$multiStartOrders<=0||$maxCandidatesPerItem<=0||$parallelStarts<=0||$containerPlanBeamWidth<=0||$containerPlanNodeLimit<=0)throw new ObjectRefusal('below_minimum','Positive configuration values required');if($maxContainers!==null&&$maxContainers<1)throw new ObjectRefusal('below_minimum','maxContainers must be at least 1');if($maxCandidatePoints<16)throw new ObjectRefusal('below_minimum','maxCandidatePoints must be at least 16');if(!($minimumSupportRatio>=0&&$minimumSupportRatio<=1))throw ObjectRefusal::ratio($minimumSupportRatio,'Minimum support ratio must be between 0 and 1');if($dimensionalWeightDivisor!==null&&$dimensionalWeightDivisor<=0)throw new ObjectRefusal('below_minimum','dimensionalWeightDivisor must be positive');if(!in_array($dimensionalWeightLengthUnit,RequestRules::LENGTH_UNITS,true))throw new ObjectRefusal('not_allowed','dimensionalWeightLengthUnit must be one of '.implode(', ',RequestRules::LENGTH_UNITS));if(!in_array($dimensionalWeightWeightUnit,RequestRules::WEIGHT_UNITS,true))throw new ObjectRefusal('not_allowed','dimensionalWeightWeightUnit must be one of '.implode(', ',RequestRules::WEIGHT_UNITS));$this->clearance=$clearance??new Length(0);} public static function fast(int $timeLimitMs=200,?Length $clearance=null,bool $requirePlacementCoordinates=true,bool $validateResult=true):self{return new self(SolverProfile::Fast, $timeLimitMs, 1, 42, null, $clearance, 0.0, 7, 1, $validateResult, 1, 4096, [], 'default', null, null, 'in', 'lb', $requirePlacementCoordinates);} public static function balanced(int $timeLimitMs=1000,int $topK=3,?Length $clearance=null):self{return new self(SolverProfile::Balanced,$timeLimitMs,$topK,42,null,$clearance);} public static function quality(int $timeLimitMs=5000,int $topK=5,?Length $clearance=null):self{return new self(SolverProfile::Quality, $timeLimitMs, $topK, 42, null, $clearance, 0.0, 7, 24, true, 16, 4096, [], 'default', null, null, 'in', 'lb', true, 1, 16, 100000);} diff --git a/src-legacy/Constraint/Internal/ConstraintActivity.php b/src-legacy/Constraint/Internal/ConstraintActivity.php index 668900c..3126334 100644 --- a/src-legacy/Constraint/Internal/ConstraintActivity.php +++ b/src-legacy/Constraint/Internal/ConstraintActivity.php @@ -23,14 +23,24 @@ */ final class ConstraintActivity { - /** @param list $defaultAccessDirections */ + /** + * Whether a built-in rule's verdict for an item never reads the candidate's position. + * + * Compatibility and tag counts look only at the item, the container and what is + * already placed, all fixed for one candidate search, so one verdict serves every + * (point, rotation) of it -- as Rust and JavaScript already compute them once per item. + */ + public static function isPositionIndependent(PlacementConstraint $constraint): bool + { + return $constraint instanceof CompatibilityConstraint || $constraint instanceof TagCountConstraint; + } + public static function isInert( PlacementConstraint $constraint, Container $container, ItemInstance $item, bool $stackSensitive, - bool $routeSensitive, - array $defaultAccessDirections + bool $routeSensitive ): bool { if ($constraint instanceof FloorConstraint) { return !$item->item->mustBeOnFloor; @@ -53,9 +63,9 @@ public static function isInert( return !$routeSensitive; } if ($constraint instanceof StopAccessibilityConstraint) { - // A flat bag has no walls, so it inherits no doors either. - return !$routeSensitive || $container->isFlatBag() - || ($container->accessDirections === [] && $defaultAccessDirections === []); + // The instance, not the configuration: a caller-supplied constraint carries + // its own default doors (S17). + return !$routeSensitive || $constraint->directionsFor($container) === []; } if ($constraint instanceof AxleLoadConstraint) { return $container->axles === null; diff --git a/src-legacy/Constraint/Internal/DirectSupportView.php b/src-legacy/Constraint/Internal/DirectSupportView.php index 70906b7..97ff3f4 100644 --- a/src-legacy/Constraint/Internal/DirectSupportView.php +++ b/src-legacy/Constraint/Internal/DirectSupportView.php @@ -3,14 +3,9 @@ namespace Packvium\Constraint\Internal; use Packvium\Domain\AxisAlignedBox; -/** Candidate support surfaces plus canonical positive-area direct supporters. */ +/** Positive-area direct supporters of one candidate, in placement-index order. */ final class DirectSupportView { - /** - * @var list - * @readonly - */ - public $surfaces; /** * @var list * @readonly @@ -32,14 +27,12 @@ final class DirectSupportView */ public $supportingArea; /** - * @param list $surfaces * @param list $supporterIndexes * @param list $supporterBoxes * @param list $supporterAreas */ - public function __construct(array $surfaces, array $supporterIndexes, array $supporterBoxes, array $supporterAreas, int $supportingArea) + public function __construct(array $supporterIndexes, array $supporterBoxes, array $supporterAreas, int $supportingArea) { - $this->surfaces = $surfaces; $this->supporterIndexes = $supporterIndexes; $this->supporterBoxes = $supporterBoxes; $this->supporterAreas = $supporterAreas; diff --git a/src-legacy/Constraint/Internal/LoadAnalysis.php b/src-legacy/Constraint/Internal/LoadAnalysis.php index 64f3f15..35f8707 100644 --- a/src-legacy/Constraint/Internal/LoadAnalysis.php +++ b/src-legacy/Constraint/Internal/LoadAnalysis.php @@ -98,25 +98,58 @@ public function crushed():?array return null; } - /** @return list> */ + /** + * Walked iteratively in the load order topLoads uses: a child's top is above its + * supporter's, so every child's set is complete before its supporter reads it. The + * recursive walk spent one frame per stack level. Set keys are in no + * promised order; a caller that names a member sorts first. + * + * @return list> + */ public function restingAbove():array { if($this->restingAbove!==null)return $this->restingAbove; - $memo=[]; - $aboveSet=function(int $index) use (&$aboveSet,&$memo):array{ - if(isset($memo[$index]))return $memo[$index]; + $count=count($this->units); + $sets=$count===0?[]:array_fill(0,$count,[]); + foreach($this->graph->descendingIndices() as $index){ $result=[]; - foreach($this->graph->children($index) as $child){ - $result[$child]=true; - foreach($aboveSet($child) as $ancestor=>$_)$result[$ancestor]=true; - } - return $memo[$index]=$result; - }; - $sets=[]; - for($index=0,$count=count($this->units);$index<$count;$index++)$sets[]=$aboveSet($index); + foreach($this->graph->children($index) as $child)$result+=[$child=>true]+$sets[$child]; + $sets[$index]=$result; + } return $this->restingAbove=$sets; } + /** + * Whether any stop is a real one. A scene where everything rides the whole route has + * no order to violate, so callers ask this before building a graph at all. + * + * @param list $stops + */ + public static function routed(array $stops):bool + { + foreach($stops as $stop)if($stop!==INF)return true; + return false; + } + + /** + * First unit due at an earlier stop with a later-stop unit resting above it, as + * [code, detail]. `$stops` is parallel to the units; INF rides the whole route. + * + * @param list $stops @return array{0:string,1:string}|null + */ + public function routeOrderViolated(array $stops):?array + { + foreach($this->restingAbove() as $index=>$above){ + // Ascending, as Python iterates: the detail names the first violator (S16). + $uppers=array_keys($above); + sort($uppers); + foreach($uppers as $upper) + if($stops[$upper]>$stops[$index]) + return ['unloading_order_violation',$this->units[$index]->label.' blocked by '.$this->units[$upper]->label]; + } + return null; + } + /** @return list */ public function stackedCounts():array { diff --git a/src-legacy/Constraint/Internal/LoadSupportGraph.php b/src-legacy/Constraint/Internal/LoadSupportGraph.php index 9fdc08f..e04051e 100644 --- a/src-legacy/Constraint/Internal/LoadSupportGraph.php +++ b/src-legacy/Constraint/Internal/LoadSupportGraph.php @@ -222,21 +222,21 @@ private static function sameNestingColumn(Placement $placement,ItemInstance $ite /** * Direct support for one active candidate: O(m) time and O(m) output space. * - * Ordinary face semantics are retained exactly. With an exact adjacent nesting - * predecessor, shadowed same-column face surfaces are removed and that predecessor - * becomes one full-area supporter. Every returned list stays in placement-index - * order, so remainder and traversal decisions remain canonical. + * A box whose top is on the candidate's base plane supports it when the two overlap + * with positive area. With an exact adjacent nesting predecessor, shadowed + * same-column face supporters are removed and that predecessor becomes one full-area + * supporter. Every returned list stays in placement-index order, so remainder and + * traversal decisions remain canonical. * * @param list $placements */ public static function candidateView(array $placements,ItemInstance $item,AxisAlignedBox $box):DirectSupportView { - $surfaceEntries=[];$supporterEntries=[];$nearestLower=null; + $supporterEntries=[];$nearestLower=null; $nesting=$item->item->nestingHeight; foreach($placements as $index=>$placement){ $other=$placement->envelopeBox(); if($other->z2()===$box->origin->z){ - $surfaceEntries[]=['index'=>$index,'box'=>$other]; $area=$other->overlapAreaXY($box); if($area>0)$supporterEntries[]=['index'=>$index,'box'=>$other,'area'=>$area]; } @@ -251,21 +251,12 @@ public static function candidateView(array $placements,ItemInstance $item,AxisAl &&$nearestLower['box']->z2()-$box->origin->z===$nesting->ticks ?$nearestLower:null; if($predecessor!==null){ - $surfaceEntries=array_values(array_filter( - $surfaceEntries, - static function (array $entry) use ($placements, $item, $box): bool { - return !self::sameNestingColumn($placements[$entry['index']],$item,$box); - }, - )); $supporterEntries=array_values(array_filter( $supporterEntries, static function (array $entry) use ($placements, $item, $box): bool { return !self::sameNestingColumn($placements[$entry['index']],$item,$box); }, )); - $surfaceAt=0; - while($surfaceAt|null */ + private $placements; + /** + * @var \Packvium\Constraint\Internal\LoadSupportGraph|null + */ + private $base; + /** @var list */ + private $baseUnits=[]; + /** + * @var int + */ + private $hint=1; + + /** + * `$placements`' units and graph with `$unit` appended at the last index. + * + * @param list $placements + * @return array{0:list,1:LoadSupportGraph} + */ + public function withCandidate(array $placements,LoadUnit $unit):array + { + $box=$unit->box; + $base=$this->baseFor($placements,max($box->x2()-$box->origin->x,$box->y2()-$box->origin->y)); + $units=$this->baseUnits; + $units[]=$unit; + return [$units,$base->withUnit($unit,$this->hint)]; + } + + /** + * The support graph over `$placements` alone, rebuilt only when it cannot serve. + * + * The cell hint has to cover every candidate that will be appended to this base, and + * the widest of them is not known in advance -- a candidate is a *new* item and may + * be the widest in the request. So the hint grows to fit the first candidate that + * needs it and the base is rebuilt that once; after that the run is served from + * cache. Sizing it from the container instead would always be safe and always + * coarse, and a cell far larger than the boxes collapses the spatial hash back into + * the all-pairs scan it exists to avoid. + * + * @param list $placements + */ + private function baseFor(array $placements,int $footprint):LoadSupportGraph + { + $same=$this->base!==null&&$this->placements===$placements; + if($same&&$footprint<=$this->hint)return $this->base; + $this->hint=max($same?$this->hint:1,$footprint); + $this->placements=$placements; + $this->baseUnits=LoadCalculator::units($placements); + $this->base=new LoadSupportGraph($this->baseUnits,$this->hint); + return $this->base; + } +} diff --git a/src-legacy/Constraint/LoadCalculator.php b/src-legacy/Constraint/LoadCalculator.php index dbce0d3..1e0e47a 100644 --- a/src-legacy/Constraint/LoadCalculator.php +++ b/src-legacy/Constraint/LoadCalculator.php @@ -100,14 +100,8 @@ public static function stackedCounts(array $units):array */ public static function routeOrderViolated(array $units,array $stops):?array { - $routed=false; - foreach($stops as $stop)if($stop!==INF){$routed=true;break;} - if(!$routed)return null; - foreach(self::restingAbove($units) as $index=>$above) - foreach(array_keys($above) as $upper) - if($stops[$upper]>$stops[$index]) - return ['unloading_order_violation',$units[$index]->label.' blocked by '.$units[$upper]->label]; - return null; + if(!LoadAnalysis::routed($stops))return null; + return (new LoadAnalysis($units,new LoadSupportGraph($units)))->routeOrderViolated($stops); } /** First unit whose stacked-item limit is exceeded, as [code, detail]. @param list $units @return array{0:string,1:string}|null */ diff --git a/src-legacy/Constraint/RouteOrderConstraint.php b/src-legacy/Constraint/RouteOrderConstraint.php index b9ecbbf..617fb95 100644 --- a/src-legacy/Constraint/RouteOrderConstraint.php +++ b/src-legacy/Constraint/RouteOrderConstraint.php @@ -1,6 +1,7 @@ routeSensitive)return ConstraintResult::allow(); - $units=LoadCalculator::units( - $c->placements, - new LoadUnit( - $c->envelopeBox(),$c->item->weight()->ticks,null,null,$c->item->id(), - $c->item->item->nestingHeight===null?null:$c->item->item->id,($nullsafeVariable1 = $c->item->item->nestingHeight) ? $nullsafeVariable1->ticks : null, - ), + $candidate=new LoadUnit( + $c->envelopeBox(),$c->item->weight()->ticks,null,null,$c->item->id(), + $c->item->item->nestingHeight===null?null:$c->item->item->id,($nullsafeVariable1 = $c->item->item->nestingHeight) ? $nullsafeVariable1->ticks : null, ); $stops=[]; foreach($c->placements as $p)$stops[]=$p->instance->item->stopIndex===null?INF:(float)$p->instance->item->stopIndex; $stops[]=$c->item->item->stopIndex===null?INF:(float)$c->item->item->stopIndex; - $failure=LoadCalculator::routeOrderViolated($units,$stops); + if(!LoadAnalysis::routed($stops))return ConstraintResult::allow(); + [$units,$graph]=($this->support = $this->support ?? new PlacedSupportBase())->withCandidate($c->placements,$candidate); + $failure=(new LoadAnalysis($units,$graph))->routeOrderViolated($stops); return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); } } diff --git a/src-legacy/Constraint/StopAccessibilityConstraint.php b/src-legacy/Constraint/StopAccessibilityConstraint.php index 4199165..39c3ee2 100644 --- a/src-legacy/Constraint/StopAccessibilityConstraint.php +++ b/src-legacy/Constraint/StopAccessibilityConstraint.php @@ -127,12 +127,26 @@ private function baseFor(array $placements,Dimensions $container,array $directio return [$clear,$stops]; } + /** + * The doors this constraint enforces in `$container`; empty means it is inert there. + * + * The container's own doors win; this instance's configured list is what a container + * that states none inherits. A flat bag has no walls, so it inherits none. + * Public so the candidate sweep asks the instance, as Python's `directions_for` + * does, rather than the configuration a custom instance may not have been built from. + * + * @return list + */ + public function directionsFor(\Packvium\Domain\Container $container):array + { + if($container->isFlatBag())return []; + return $container->accessDirections!==[]?$container->accessDirections:$this->defaultDirections; + } + public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->routeSensitive)return ConstraintResult::allow(); - // The container's own doors win; the configured list is what a container that - // states none inherits. A flat bag has no walls, so it inherits none. - $directions=$c->container->isFlatBag()?[]:($c->container->accessDirections!==[]?$c->container->accessDirections:$this->defaultDirections); + $directions=$this->directionsFor($c->container); if($directions===[])return ConstraintResult::allow(); $candidateStop=$c->item->item->stopIndex??INF; $inner=$c->container->innerDimensions; diff --git a/src-legacy/Constraint/SupportConstraint.php b/src-legacy/Constraint/SupportConstraint.php index 5878a34..b8bd567 100644 --- a/src-legacy/Constraint/SupportConstraint.php +++ b/src-legacy/Constraint/SupportConstraint.php @@ -45,12 +45,11 @@ public function evaluate(ConstraintContext $c):ConstraintResult if(!$this->canReject($c->item))return ConstraintResult::allow(); $box=$c->envelopeBox(); $support=LoadSupportGraph::candidateView($c->placements,$c->item,$box); - $surfaces=$support->surfaces; $supporters=$support->supporterBoxes; $rule=$c->item->item->groundContactRule; if($rule!==null&&$rule!=='free'){ $count=count($supporters); - if($rule==='covered'&&!self::touchesCorners($box,$surfaces)) + if($rule==='covered'&&!self::touchesCorners($box,$supporters)) return ConstraintResult::reject('ground_contact_violation',"covered: {$count} supporter(s), not all four corners touched"); if($rule==='single'&&$count!==1) return ConstraintResult::reject('ground_contact_violation',"single: rests on {$count} item(s)"); @@ -75,18 +74,18 @@ public function evaluate(ConstraintContext $c):ConstraintResult } /** - * Whether every one of the candidate's four base corners rests on some surface. + * Whether every one of the candidate's four base corners rests on some supporter. * * A ratio cannot express this: 90% of the footprint concentrated in the middle - * passes any ratio below that but leaves every corner hanging. + * passes any ratio below that but leaves every corner hanging. Only positive-area + * supporters count: a neighbour touching a corner along an edge carries nothing, + * and Rust, JS and every validator ignore it. * - * @param list<\Packvium\Domain\AxisAlignedBox> $surfaces - */ - /** * Public, not private: `Sequence\LoadingDependencyGraph::verifyLoadingPrefixBusinessRules` * reuses this exact corner-touch calculation against every loading - * prefix, not only the finished scene -- widened visibility only, no behaviour - * change, so every existing caller of this constraint is unaffected. + * prefix, not only the finished scene. + * + * @param list<\Packvium\Domain\AxisAlignedBox> $surfaces the candidate's positive-area supporters */ public static function touchesCorners(\Packvium\Domain\AxisAlignedBox $box,array $surfaces):bool { diff --git a/src-legacy/Constraint/TopLoadConstraint.php b/src-legacy/Constraint/TopLoadConstraint.php index 812af9d..4e9deab 100644 --- a/src-legacy/Constraint/TopLoadConstraint.php +++ b/src-legacy/Constraint/TopLoadConstraint.php @@ -1,74 +1,33 @@ |null */ - private $placements; - /** - * @var \Packvium\Constraint\Internal\LoadSupportGraph|null - */ - private $base; - /** @var list */ - private $baseUnits=[]; - /** - * @var int - */ - private $hint=1; - + // Created on first use rather than in a constructor, which would widen the frozen + // public surface (spec/api/php.json) for an internal cache. /** - * The support graph over `$placements` alone, rebuilt only when it cannot serve. - * - * The cell hint has to cover every candidate that will be appended to this base, and - * the widest of them is not known in advance -- a candidate is a *new* item and may - * be the widest in the request. So the hint grows to fit the first candidate that - * needs it and the base is rebuilt that once; after that the run is served from - * cache. Sizing it from the container instead would always be safe and always - * coarse, and a cell far larger than the boxes collapses the spatial hash back into - * the all-pairs scan it exists to avoid. - * - * @param list $placements + * @var \Packvium\Constraint\Internal\PlacedSupportBase|null */ - private function baseFor(array $placements,int $footprint):LoadSupportGraph - { - $same=$this->base!==null&&$this->placements===$placements; - if($same&&$footprint<=$this->hint)return $this->base; - $this->hint=max($same?$this->hint:1,$footprint); - $this->placements=$placements; - $this->baseUnits=LoadCalculator::units($placements); - $this->base=new LoadSupportGraph($this->baseUnits,$this->hint); - return $this->base; - } + private $support; public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->stackSensitive)return ConstraintResult::allow(); - $candidate=$c->envelopeBox(); $item=$c->item->item; $unit=new LoadUnit( - $candidate,$c->item->weight()->ticks,($nullsafeVariable1 = $item->maxTopLoad) ? $nullsafeVariable1->ticks : null,$item->maxStackedItems,$c->item->id(), + $c->envelopeBox(),$c->item->weight()->ticks,($nullsafeVariable1 = $item->maxTopLoad) ? $nullsafeVariable1->ticks : null,$item->maxStackedItems,$c->item->id(), $item->nestingHeight===null?null:$item->id,($nullsafeVariable2 = $item->nestingHeight) ? $nullsafeVariable2->ticks : null, $item->compressionRatioPpm,$item->maxCompressionPressureKpa, ); - $footprint=max($candidate->x2()-$candidate->origin->x,$candidate->y2()-$candidate->origin->y); - $base=$this->baseFor($c->placements,$footprint); - $units=$this->baseUnits; - $units[]=$unit; - $graph=$base->withUnit($unit,$this->hint); + [$units,$graph]=($this->support = $this->support ?? new PlacedSupportBase())->withCandidate($c->placements,$unit); $nonStackable=$graph->nonStackableFailure($c->placements,$c->item,count($units)-1); if($nonStackable!==null)return ConstraintResult::reject($nonStackable[0],$nonStackable[1]); $densityLimit=($nullsafeVariable3 = $c->container->maxStackDensity) ? $nullsafeVariable3->ticks : null; diff --git a/src-legacy/Domain/Compression.php b/src-legacy/Domain/Compression.php index 2e214bc..ad69314 100644 --- a/src-legacy/Domain/Compression.php +++ b/src-legacy/Domain/Compression.php @@ -3,6 +3,7 @@ namespace Packvium\Domain; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Unit\Length; use Packvium\Unit\Weight; @@ -127,7 +128,9 @@ public static function effectiveHeight( public static function ratioToPpm(float $ratio): int { if ($ratio < 0.0 || $ratio > 1.0) { - throw new InvalidArgumentException('compression_ratio must be between zero and one'); + // Below zero is the schema's floor; the schema sets no ceiling, so above one stays + // the catch-all `invalid_value` every engine answers. + throw new ObjectRefusal($ratio < 0.0 ? 'below_minimum' : 'invalid_value', 'compression_ratio must be between zero and one'); } return (int)($ratio * self::PPM + 0.5); } diff --git a/src-legacy/Domain/Container.php b/src-legacy/Domain/Container.php index cdba94c..59bd207 100644 --- a/src-legacy/Domain/Container.php +++ b/src-legacy/Domain/Container.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Unit\Length; use Packvium\Unit\Weight; final class Container @@ -152,8 +153,8 @@ public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $ $this->preloaded = $preloaded; $this->deformableBoundary = $deformableBoundary; $this->madeToMeasure = $madeToMeasure; - if($id==='')throw new InvalidArgumentException('Container id is required');($nullsafeVariable1 = $madeToMeasure) ? $nullsafeVariable1->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]) : null;if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio);if($quantity!==null&&$quantity<=0)throw new InvalidArgumentException('Container quantity must be positive');if($costMinor<0)throw new InvalidArgumentException('Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new InvalidArgumentException('Container max_items must be at least 1');if($voidFillReserveRatio<0||$voidFillReserveRatio>1)throw new InvalidArgumentException('void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new InvalidArgumentException('tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new InvalidArgumentException('Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new InvalidArgumentException("Obstacle {$o->id} lies outside container"); - if($axles!==null){[$front,$rear]=$axles;if($front->position->ticks>=$rear->position->ticks)throw new InvalidArgumentException('The front axle must be strictly nearer the origin than the rear axle');if($front->position->ticks<0||$rear->position->ticks>$innerDimensions->length->ticks)throw new InvalidArgumentException("Axle positions must lie within the container's length");} + if($id==='')throw new ObjectRefusal('invalid_value','Container id is required');($nullsafeVariable1 = $madeToMeasure) ? $nullsafeVariable1->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]) : null;if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio);if($quantity!==null&&$quantity<=0)throw new ObjectRefusal('below_minimum','Container quantity must be positive');if($costMinor<0)throw new ObjectRefusal('below_minimum','Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new ObjectRefusal('below_minimum','Container max_items must be at least 1');if(!($voidFillReserveRatio>=0&&$voidFillReserveRatio<=1))throw ObjectRefusal::ratio($voidFillReserveRatio,'void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new ObjectRefusal('below_minimum','tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new ObjectRefusal('invalid_value','Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new ObjectRefusal('invalid_value',"Obstacle {$o->id} lies outside container"); + if($axles!==null){[$front,$rear]=$axles;if($front->position->ticks>=$rear->position->ticks)throw new ObjectRefusal('invalid_value','The front axle must be strictly nearer the origin than the rear axle');if($front->position->ticks<0||$rear->position->ticks>$innerDimensions->length->ticks)throw new ObjectRefusal('invalid_value',"Axle positions must lie within the container's length");} foreach($accessDirections as $direction)if(!in_array($direction,SweptRegion::ALL_DIRECTIONS,true))throw new InvalidArgumentException("unknown movement direction {$direction}"); // Deduplicated into the canonical order rather than kept as given: two callers // naming the same doors in a different order must search identically. @@ -197,9 +198,9 @@ private static function dimensionsOf(array $sides):Dimensions{return new Dimensi */ private static function requireBagFields(string $kind,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio):void { - if(!in_array($kind,FlatBag::KINDS,true))throw new InvalidArgumentException("unknown deformable_boundary kind {$kind}"); + if(!in_array($kind,FlatBag::KINDS,true))throw new ObjectRefusal('not_allowed',"unknown deformable_boundary kind {$kind}"); $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'max_stack_density'=>$maxStackDensity!==null,'outer_dimensions'=>$outerDimensions!==null,'void_fill_reserve_ratio'=>$voidFillReserveRatio>0]; - foreach($present as $name=>$set)if($set)throw new InvalidArgumentException("{$name} cannot be combined with deformable_boundary"); + foreach($present as $name=>$set)if($set)throw new ObjectRefusal('not_allowed',"{$name} cannot be combined with deformable_boundary"); } /** * @param \Packvium\Unit\Weight|int|string|mixed[] $tareWeight diff --git a/src-legacy/Domain/Dimensions.php b/src-legacy/Domain/Dimensions.php index f0bd010..ff8b533 100644 --- a/src-legacy/Domain/Dimensions.php +++ b/src-legacy/Domain/Dimensions.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Support\BigInt; use Packvium\Unit\Length; use Packvium\Unit\Rounding; @@ -32,7 +33,7 @@ public function __construct(Length $length,Length $width,Length $height){$this-> * @param int|string $w * @param int|string $h */ - public static function of($l,$w,$h,string $unit='mm',string $rounding=Rounding::Nearest):self{return new self(Length::of($l,$unit,$rounding),Length::of($w,$unit,$rounding),Length::of($h,$unit,$rounding));} + public static function of($l,$w,$h,string $unit='mm',string $rounding=Rounding::Nearest):self{return self::read(Length::of($l,$unit,$rounding),Length::of($w,$unit,$rounding),Length::of($h,$unit,$rounding));} /** * @param int|string $l * @param int|string $w @@ -45,7 +46,9 @@ public static function mm($l,$w,$h,string $rounding=Rounding::Nearest):self{retu * @param int|string $h */ public static function inches($l,$w,$h,string $rounding=Rounding::Nearest):self{return self::of($l,$w,$h,'in',$rounding);} - /** @param array{length:mixed,width:mixed,height:mixed} $data */ public static function fromArray(array $data,string $unit='mm',string $rounding=Rounding::Nearest):self{return new self(Length::parse($data['length'],$unit,$rounding),Length::parse($data['width'],$unit,$rounding),Length::parse($data['height'],$unit,$rounding));} + /** @param array{length:mixed,width:mixed,height:mixed} $data */ public static function fromArray(array $data,string $unit='mm',string $rounding=Rounding::Nearest):self{return self::read(Length::parse($data['length'],$unit,$rounding),Length::parse($data['width'],$unit,$rounding),Length::parse($data['height'],$unit,$rounding));} + /** Sides read from the caller's input, where a zero side is a request refusal; the constructor still guards the arithmetic. */ + private static function read(Length $length,Length $width,Length $height):self{if(min($length->ticks,$width->ticks,$height->ticks)<=0)throw new ObjectRefusal('invalid_value','All dimensions must be positive');return new self($length,$width,$height);} public function rotated(string $r):self{switch ($r) { case Rotation::LWH: return new self($this->length,$this->width,$this->height); diff --git a/src-legacy/Domain/FixedPlacement.php b/src-legacy/Domain/FixedPlacement.php index 55c19d1..c225683 100644 --- a/src-legacy/Domain/FixedPlacement.php +++ b/src-legacy/Domain/FixedPlacement.php @@ -1,7 +1,6 @@ itemId = $itemId; $this->containerId = $containerId; $this->position = $position; $this->rotation = $rotation; $this->containerInstance = $containerInstance; - if($containerInstance<1)throw new InvalidArgumentException('container_instance counts from 1'); } public function packedContainerId():string{return "{$this->containerId}#{$this->containerInstance}";} diff --git a/src-legacy/Domain/Item.php b/src-legacy/Domain/Item.php index e020a75..472ef2e 100644 --- a/src-legacy/Domain/Item.php +++ b/src-legacy/Domain/Item.php @@ -1,7 +1,7 @@ 1)throw new InvalidArgumentException('Minimum support ratio must be between 0 and 1');if($maxStackedItems!==null&&$maxStackedItems<1)throw new InvalidArgumentException('max_stacked_items must be at least 1');if($groundContactRule!==null&&!in_array($groundContactRule,self::GROUND_CONTACT_RULES,true))throw new InvalidArgumentException('ground_contact_rule must be one of '.implode(', ',self::GROUND_CONTACT_RULES)); - if($nestingHeight!==null&&!($nestingHeight->ticks>=0&&$nestingHeight->ticks<$dimensions->height->ticks))throw new InvalidArgumentException("nesting_height must be at least zero and strictly less than the item's own height"); - if($stopIndex!==null&&($stopIndex<0||$stopIndex>self::MAX_EXACT_STOP_INDEX))throw new InvalidArgumentException('stop_index must be a non-negative safe integer'); - if($value!==null&&$value<0)throw new InvalidArgumentException('value must be non-negative'); + if($id==='')throw new ObjectRefusal('invalid_value','Item id is required');if($quantity<=0)throw new ObjectRefusal('below_minimum','Item quantity must be positive');if(!($minimumSupportRatio>=0&&$minimumSupportRatio<=1))throw ObjectRefusal::ratio($minimumSupportRatio,'Minimum support ratio must be between 0 and 1');if($maxStackedItems!==null&&$maxStackedItems<1)throw new ObjectRefusal('below_minimum','max_stacked_items must be at least 1');if($groundContactRule!==null&&!in_array($groundContactRule,self::GROUND_CONTACT_RULES,true))throw new ObjectRefusal('not_allowed','ground_contact_rule must be one of '.implode(', ',self::GROUND_CONTACT_RULES)); + if($nestingHeight!==null&&!($nestingHeight->ticks>=0&&$nestingHeight->ticks<$dimensions->height->ticks))throw new ObjectRefusal('invalid_value',"nesting_height must be at least zero and strictly less than the item's own height"); + if($stopIndex!==null&&($stopIndex<0||$stopIndex>self::MAX_EXACT_STOP_INDEX))throw new ObjectRefusal($stopIndex<0?'below_minimum':'above_maximum','stop_index must be a non-negative safe integer'); + if($value!==null&&$value<0)throw new ObjectRefusal('below_minimum','value must be non-negative'); if($keepUpright)$allowedRotations=array_values(array_filter($allowedRotations,static function (string $r) { return in_array($r,Rotation::upright(),true); - }));if($allowedRotations===[])throw new InvalidArgumentException('At least one rotation must be allowed'); + }));if($allowedRotations===[])throw new ObjectRefusal('invalid_value','At least one rotation must be allowed'); $this->id=$id;$this->dimensions=$dimensions;$this->weight=$weight??new Weight(0);$this->quantity=$quantity;$this->allowedRotations=$allowedRotations;$this->keepUpright=$keepUpright;$this->stackable=$stackable;$this->mustBeOnFloor=$mustBeOnFloor;$this->maxTopLoad=$maxTopLoad;$this->minimumSupportRatio=$minimumSupportRatio;$this->groundContactRule=$groundContactRule;$this->group=$group;$this->tags=array_values(array_unique($tags));$this->incompatibleTags=array_values(array_unique($incompatibleTags));$this->priority=$priority;$this->metadata=$metadata;$this->maxStackedItems=$maxStackedItems;$this->eligibleContainerTags=array_values(array_unique($eligibleContainerTags));$this->nestingHeight=$nestingHeight;$this->stopIndex=$stopIndex;$this->value=$value; $this->shapeType=$shapeType; $this->hullVertices=self::admitShape($shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa,$dimensions,$nestingHeight); @@ -186,15 +186,18 @@ private static function admitShape(string $shapeType,?array $hullVertices,?int $ $foreign = ['hull_vertices'=>$hullVertices,'compression_ratio'=>$ratioPpm,'max_compression_pressure_kpa'=>$limitKpa]; break; } + // The value's own floor first, as the JSON rules check it before the shape. + if($limitKpa!==null&&$limitKpa<0) + throw new ObjectRefusal('below_minimum','max_compression_pressure_kpa cannot be negative'); foreach($foreign as $name=>$value){ - if($value!==null)throw new InvalidArgumentException("{$name} is not part of a {$shapeType} item"); + if($value!==null)throw new ObjectRefusal('invalid_value',"{$name} is not part of a {$shapeType} item"); } // Both rewrite occupied height. Choosing an order silently would give four engines // four contracts, so the interaction is refused until a task defines it. if($nestingHeight!==null&&$shapeType!==ShapeType::RIGID_CUBOID) - throw new InvalidArgumentException("nesting_height with shape_type {$shapeType} is not supported yet"); + throw new ObjectRefusal('invalid_value',"nesting_height with shape_type {$shapeType} is not supported yet"); if($shapeType===ShapeType::CONVEX_HULL){ - if($hullVertices===null)throw new InvalidArgumentException('a convex_hull item requires hull_vertices'); + if($hullVertices===null)throw new ObjectRefusal('invalid_value','a convex_hull item requires hull_vertices'); $hullVertices=HullShape::validate($hullVertices); [$low,$high]=HullShape::boundingExtent($hullVertices); $declared=[$dimensions->length->ticks,$dimensions->width->ticks,$dimensions->height->ticks]; @@ -203,17 +206,15 @@ private static function admitShape(string $shapeType,?array $hullVertices,?int $ // a hull poking out of it would be collision-tested against space the solver // never reserved. if($high[$axis]-$low[$axis]>$declared[$axis]) - throw new InvalidArgumentException('hull_vertices span does not fit inside dimensions'); + throw new ObjectRefusal('invalid_value','hull_vertices span does not fit inside dimensions'); } return $hullVertices; } if($shapeType===ShapeType::COMPRESSIBLE){ if($ratioPpm===null||$limitKpa===null) - throw new InvalidArgumentException('a compressible item requires both compression_ratio and max_compression_pressure_kpa'); + throw new ObjectRefusal('invalid_value','a compressible item requires both compression_ratio and max_compression_pressure_kpa'); if($ratioPpm<0||$ratioPpm>Compression::PPM) - throw new InvalidArgumentException('compression_ratio must be between zero and one'); - if($limitKpa<0) - throw new InvalidArgumentException('max_compression_pressure_kpa cannot be negative'); + throw new ObjectRefusal('invalid_value','compression_ratio must be between zero and one'); } return $hullVertices; } diff --git a/src-legacy/Domain/MadeToMeasure.php b/src-legacy/Domain/MadeToMeasure.php index b1bccf5..ed1149b 100644 --- a/src-legacy/Domain/MadeToMeasure.php +++ b/src-legacy/Domain/MadeToMeasure.php @@ -1,7 +1,7 @@ costPerSquareMetreMinor = $costPerSquareMetreMinor; $this->tarePerSquareMetre = $tarePerSquareMetre; $this->outerAllowance = $outerAllowance; - if(min($minimum)<=0)throw new InvalidArgumentException('made_to_measure minimum must be positive'); - if(min($increment)<=0)throw new InvalidArgumentException('made_to_measure increment must be positive'); - if($costPerSquareMetreMinor<0||$tarePerSquareMetre<0)throw new InvalidArgumentException('made_to_measure prices cannot be negative'); - if(min($outerAllowance)<0)throw new InvalidArgumentException('made_to_measure outer_allowance cannot be negative'); + if(min($minimum)<=0)throw new ObjectRefusal('invalid_value','made_to_measure minimum must be positive'); + if(min($increment)<=0)throw new ObjectRefusal('invalid_value','made_to_measure increment must be positive'); + if($costPerSquareMetreMinor<0||$tarePerSquareMetre<0)throw new ObjectRefusal('below_minimum','made_to_measure prices cannot be negative'); + if(min($outerAllowance)<0)throw new ObjectRefusal('negative_measure','made_to_measure outer_allowance cannot be negative'); } /** @@ -76,8 +76,8 @@ public function __construct(array $minimum,array $increment,int $costPerSquareMe public function admits(array $maximum):void { foreach(['length','width','height'] as $axis=>$name){ - if($this->minimum[$axis]>$maximum[$axis])throw new InvalidArgumentException("made_to_measure minimum {$name} exceeds inner_dimensions"); - if(($maximum[$axis]-$this->minimum[$axis])%$this->increment[$axis]!==0)throw new InvalidArgumentException("made_to_measure increment {$name} does not divide inner_dimensions minus minimum"); + if($this->minimum[$axis]>$maximum[$axis])throw new ObjectRefusal('invalid_value',"made_to_measure minimum {$name} exceeds inner_dimensions"); + if(($maximum[$axis]-$this->minimum[$axis])%$this->increment[$axis]!==0)throw new ObjectRefusal('invalid_value',"made_to_measure increment {$name} does not divide inner_dimensions minus minimum"); } } diff --git a/src-legacy/Domain/PackingRequest.php b/src-legacy/Domain/PackingRequest.php index 9e7e77c..5dc32d3 100644 --- a/src-legacy/Domain/PackingRequest.php +++ b/src-legacy/Domain/PackingRequest.php @@ -1,7 +1,7 @@ $items @param list $containers @param list $fixedPlacements */ public function __construct(array $items,array $containers,array $fixedPlacements=[]){$this->items = $items; $this->containers = $containers; $this->fixedPlacements = $fixedPlacements; - if($items===[])throw new InvalidArgumentException('At least one item is required');if($containers===[])throw new InvalidArgumentException('At least one container is required');self::unique(array_map(function (Item $i) { + if($items===[])throw new ObjectRefusal('invalid_value','At least one item is required');if($containers===[])throw new ObjectRefusal('invalid_value','At least one container is required');self::unique(array_map(function (Item $i) { return $i->id; },$items),'item');self::unique(array_map(function (Container $c) { return $c->id; },$containers),'container');} /** @return list */ public function instances():array{$out=[];foreach($this->items as $i)array_push($out,...$i->instances());return $out;} - private static function unique(array $ids,string $kind):void{if(count($ids)!==count(array_unique($ids)))throw new InvalidArgumentException(ucfirst($kind).' ids must be unique');} + private static function unique(array $ids,string $kind):void{if(count($ids)!==count(array_unique($ids)))throw new ObjectRefusal('duplicate_id',ucfirst($kind).' ids must be unique');} } diff --git a/src-legacy/Domain/RateTable.php b/src-legacy/Domain/RateTable.php index 82249eb..003a836 100644 --- a/src-legacy/Domain/RateTable.php +++ b/src-legacy/Domain/RateTable.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; -use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; /** * A carrier rate card carried by the request rather than by a code plugin. @@ -54,31 +54,31 @@ public function __construct( $this->minimumChargeMinor = $minimumChargeMinor; $this->fuelSurchargePermille = $fuelSurchargePermille; if ($weightBracketsG === []) { - throw new InvalidArgumentException('rate_table requires at least one weight bracket'); + throw new ObjectRefusal('invalid_value', 'rate_table requires at least one weight bracket'); } if (count($weightBracketsG) !== count($pricesMinor)) { - throw new InvalidArgumentException('rate_table weight_brackets_g and prices_minor must be the same length'); + throw new ObjectRefusal('invalid_value', 'rate_table weight_brackets_g and prices_minor must be the same length'); } $previous = 0; foreach ($weightBracketsG as $bound) { if ($bound <= 0) { - throw new InvalidArgumentException('rate_table weight brackets must be positive'); + throw new ObjectRefusal('below_minimum', 'rate_table weight brackets must be positive'); } if ($bound <= $previous) { - throw new InvalidArgumentException('rate_table weight brackets must be strictly ascending'); + throw new ObjectRefusal('invalid_value', 'rate_table weight brackets must be strictly ascending'); } $previous = $bound; } foreach ($pricesMinor as $price) { if ($price < 0) { - throw new InvalidArgumentException('rate_table prices cannot be negative'); + throw new ObjectRefusal('below_minimum', 'rate_table prices cannot be negative'); } } if ($minimumChargeMinor < 0) { - throw new InvalidArgumentException('rate_table minimum_charge_minor cannot be negative'); + throw new ObjectRefusal('below_minimum', 'rate_table minimum_charge_minor cannot be negative'); } if ($fuelSurchargePermille < 0) { - throw new InvalidArgumentException('rate_table fuel_surcharge_permille cannot be negative'); + throw new ObjectRefusal('below_minimum', 'rate_table fuel_surcharge_permille cannot be negative'); } } diff --git a/src-legacy/Packer.php b/src-legacy/Packer.php index 8b14be4..64df02a 100644 --- a/src-legacy/Packer.php +++ b/src-legacy/Packer.php @@ -4,7 +4,7 @@ namespace Packvium; use Packvium\Algorithm\{Deadline, FixedPlacementAdmission, SolverOrchestrator}; -use Packvium\Support\{StableSorter, UnsupportedPlacements}; +use Packvium\Support\{RequestObjects, StableSorter, UnsupportedPlacements}; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, UnratedWeightException}; use Packvium\Extension\ExtensionRegistry; @@ -52,6 +52,9 @@ public function __construct(?PackingConfig $config = null, ?ExtensionRegistry $e /** @param list $items @param list $containers @param list $fixedPlacements */ public function pack(array $items, array $containers, array $fixedPlacements = []): PackingResult { + // The JSON path's rules, with the JSON path's reason and field: a request + // built from objects is refused exactly where the same request as JSON would be. + RequestObjects::check($items, $containers, $this->config, $fixedPlacements); $request = new PackingRequest($items, $containers, $fixedPlacements); // Both cost objectives price the same billed weight, so both need the divisor. // There is no library-chosen default: a wrong guess would silently misprice diff --git a/src-legacy/Revisions/PlanRevision.php b/src-legacy/Revisions/PlanRevision.php index e46e9da..8708a46 100644 --- a/src-legacy/Revisions/PlanRevision.php +++ b/src-legacy/Revisions/PlanRevision.php @@ -364,7 +364,7 @@ private static function validatePlacement(stdClass $event): void self::requireName(JsonValue::get($placement, 'item_type'), 'placement.item_type'); self::requireName(JsonValue::get($placement, 'container_type'), 'placement.container_type'); if (!\in_array(JsonValue::get($placement, 'orientation'), FixedPlacementShape::ORIENTATIONS, true)) { - throw new PlanRevisionException('invalid_event', 'placement.orientation is one of the six codes'); + throw new PlanRevisionException('invalid_event', 'placement.orientation must be one of ' . CanonicalJson::spelling(FixedPlacementShape::ORIENTATIONS)); } $instance = JsonValue::has($placement, 'container_instance') ? JsonValue::integer($placement->container_instance) : 1; if ($instance === null || $instance < 1) { diff --git a/src-legacy/Sequence/LoadingDependencyGraph.php b/src-legacy/Sequence/LoadingDependencyGraph.php index 94818d3..4cdba1a 100644 --- a/src-legacy/Sequence/LoadingDependencyGraph.php +++ b/src-legacy/Sequence/LoadingDependencyGraph.php @@ -255,7 +255,7 @@ public static function verifyLoadingPrefixBusinessRules(array $placements, array array_slice($present, 0, -1), $candidate->instance, $candidateBox, ); $count = count($support->supporterBoxes); - $violated = ($rule === 'covered' && !\Packvium\Constraint\SupportConstraint::touchesCorners($candidateBox, $support->surfaces)) + $violated = ($rule === 'covered' && !\Packvium\Constraint\SupportConstraint::touchesCorners($candidateBox, $support->supporterBoxes)) || ($rule === 'single' && $count !== 1) || ($rule === 'multiple' && $count < 2); if ($violated) { diff --git a/src-legacy/Sequence/SequenceGeometry.php b/src-legacy/Sequence/SequenceGeometry.php index 3b777fe..4369726 100644 --- a/src-legacy/Sequence/SequenceGeometry.php +++ b/src-legacy/Sequence/SequenceGeometry.php @@ -102,25 +102,34 @@ public static function validateBoxAtStep(int $index, int $step, array $boxes, ar } } - /** @param array> $dependsOn */ + /** + * Kahn's algorithm: acyclic exactly when every node can be released. O(V + E). + * + * Iterative, not a depth-first walk: a stack of sheets is a dependency chain as long + * as the stack, and recursion spent one frame per level. + * + * @param array> $dependsOn + */ public static function isAcyclic(array $dependsOn): bool { - $visiting = []; - $visited = []; - $visit = function (int $node) use (&$visit, &$visiting, &$visited, $dependsOn): bool { - if (isset($visited[$node])) { return true; } - if (isset($visiting[$node])) { return false; } - $visiting[$node] = true; + $waiting = []; + foreach ($dependsOn as $node => $dependencies) { + $waiting[$node] = $waiting[$node] ?? 0; + foreach (array_keys($dependencies) as $dependency) { + $waiting[$dependency] = ($waiting[$dependency] ?? 0) + 1; + } + } + $ready = array_keys(array_filter($waiting, static function (int $count): bool { + return $count === 0; + })); + $released = 0; + while ($ready !== []) { + $node = array_pop($ready); + $released++; foreach (array_keys($dependsOn[$node] ?? []) as $dependency) { - if (!$visit($dependency)) { return false; } + if (--$waiting[$dependency] === 0) { $ready[] = $dependency; } } - unset($visiting[$node]); - $visited[$node] = true; - return true; - }; - foreach (array_keys($dependsOn) as $node) { - if (!$visit($node)) { return false; } } - return true; + return $released === count($waiting); } } diff --git a/src-legacy/Serialization/ArrayCodec.php b/src-legacy/Serialization/ArrayCodec.php index 9b5268b..d0c6735 100644 --- a/src-legacy/Serialization/ArrayCodec.php +++ b/src-legacy/Serialization/ArrayCodec.php @@ -9,7 +9,7 @@ use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; use Packvium\Policy\PolicyRuleSet; -use Packvium\Support\{FixedPlacementShape,JsonValue,MeasureReading,RequestRules}; +use Packvium\Support\{FixedPlacementShape,JsonValue,MeasureReading,ObjectRefusal,RequestRules}; use Packvium\Unit\{Length,Weight}; use Throwable; use TypeError; @@ -150,6 +150,17 @@ public static function madeToMeasureCombinations(array $data):array } /** @return array a collection to scan, or nothing when it is not one */ + /** + * The output unit a request without `output.length_unit` is written in: the + * request's own `units.length`, spelt as the schema's output code, so `Inches` is `in`. + * A unit no output code names -- the internal `tick` -- gives `mm`, the default of both blocks. + */ + private static function outputLengthCode(string $requestUnit):string + { + $multiplier=Length::multiplier($requestUnit); + foreach(['mm','cm','m','in','ft'] as $code)if(Length::multiplier($code)===$multiplier)return $code; + return 'mm'; + } private static function entries(array $data,string $collection):array{$entries=$data[$collection]??[];return is_array($entries)?$entries:[];} /** @@ -172,7 +183,7 @@ public static function pack($data):array catch(InvalidArgumentException|TypeError|ValueError|ArithmeticError $error){throw self::asRequestError($error);} $unit=(string)($data['units']['length']??'mm'); $out=$data['output']??[]; - $result=(new Packer($config,$extensions))->pack($items,$containers,$fixed)->toArray($out['length_unit']??$unit,$out['weight_unit']??'g'); + $result=(new Packer($config,$extensions))->pack($items,$containers,$fixed)->toArray($out['length_unit']??self::outputLengthCode($unit),$out['weight_unit']??'g'); $result['catalog_versions_used']=$references; return $result; } @@ -215,6 +226,9 @@ private static function model(array $data):array */ private static function asRequestError(Throwable $error):Throwable { + // A model's own refusal names a reason for the object API; these rules did not name + // this value, and every engine reports that as `invalid_value` with no field. + if($error instanceof ObjectRefusal)return new InvalidRequestException('invalid_value','',$error->detail(),$error); if($error instanceof InvalidRequestException||$error instanceof UnsupportedFeatureException||method_exists($error,'errorCode'))return $error; return new InvalidRequestException('invalid_value','',$error->getMessage(),$error); } diff --git a/src-legacy/Support/FixedPlacementShape.php b/src-legacy/Support/FixedPlacementShape.php index b6701a0..a561abc 100644 --- a/src-legacy/Support/FixedPlacementShape.php +++ b/src-legacy/Support/FixedPlacementShape.php @@ -95,7 +95,7 @@ private static function requireEntry($entry, string $where, string $field, strin } } if (!\in_array(JsonValue::get($entry, 'orientation'), self::ORIENTATIONS, true)) { - throw self::malformed("{$where}.orientation is one of the six codes", "{$field}/orientation"); + throw self::malformed("{$where}.orientation must be one of " . CanonicalJson::spelling(self::ORIENTATIONS), "{$field}/orientation"); } $instance = JsonValue::has($entry, 'container_instance') ? JsonValue::integer(JsonValue::get($entry, 'container_instance')) : 1; if ($instance === null || $instance < 1) { diff --git a/src-legacy/Support/ObjectRefusal.php b/src-legacy/Support/ObjectRefusal.php new file mode 100644 index 0000000..674ebb9 --- /dev/null +++ b/src-legacy/Support/ObjectRefusal.php @@ -0,0 +1,40 @@ + 1 ? 'above_maximum' : 'invalid_value'); + return new self($reason, $detail); + } + + /** + * The text a model has always thrown, so a wrapper that quotes it (a commerce document, + * a measure verdict, cross-engine conformance) reads exactly what it read before. + */ + protected function composeMessage(): string + { + return $this->detail(); + } +} diff --git a/src-legacy/Support/RationalParser.php b/src-legacy/Support/RationalParser.php index 312f3cf..545dd49 100644 --- a/src-legacy/Support/RationalParser.php +++ b/src-legacy/Support/RationalParser.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Support; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Unit\Rounding; final class RationalParser { @@ -31,13 +32,13 @@ public static function parse($value): array if (preg_match('/^([+-]?\d+)\s*\/\s*(\d+)$/', $text, $m)) { $n = self::parseWhole($m[1]); $d = self::parseWhole($m[2]); self::assertDenominator($d); return [$n, $d]; } - if (!preg_match('/^([+-]?)(\d+)(?:\.(\d+))?$/', $text, $m)) { throw new InvalidArgumentException("Invalid decimal or fraction: {$text}"); } + if (!preg_match('/^([+-]?)(\d+)(?:\.(\d+))?$/', $text, $m)) { throw new ObjectRefusal('wrong_type', "Invalid decimal or fraction: {$text}"); } $fraction = $m[3] ?? ''; if ($fraction === '') { $num = self::parseWhole($m[2]); return [$negative ? -$num : $num, 1]; } - if (strlen($fraction) > 18) { throw new InvalidArgumentException('Decimal has more fractional digits than a tick can distinguish'); } + if (strlen($fraction) > 18) { throw new ObjectRefusal('wrong_type', 'Decimal has more fractional digits than a tick can distinguish'); } $den = 10 ** strlen($fraction); $intPart = self::parseWhole($m[2]); if ($intPart !== 0 && $intPart > intdiv(PHP_INT_MAX - (int)$fraction, $den)) { diff --git a/src-legacy/Support/RequestObjects.php b/src-legacy/Support/RequestObjects.php new file mode 100644 index 0000000..45af6e2 --- /dev/null +++ b/src-legacy/Support/RequestObjects.php @@ -0,0 +1,231 @@ + `PackingConfig` property, for each of `RequestRules::CONFIGURATION_INTEGERS`. */ + private const CONFIGURATION_PROPERTIES = [ + 'time_limit_ms' => 'timeLimitMs', 'alternatives' => 'topK', 'max_containers' => 'maxContainers', + 'exact_item_limit' => 'exactItemLimit', 'multi_start_orders' => 'multiStartOrders', + 'max_candidates_per_item' => 'maxCandidatesPerItem', 'max_candidate_points' => 'maxCandidatePoints', + 'container_plan_beam_width' => 'containerPlanBeamWidth', 'container_plan_node_limit' => 'containerPlanNodeLimit', + 'dimensional_weight_divisor' => 'dimensionalWeightDivisor', + ]; + /** JSON name => `EffortBudget` property, for each of `RequestRules::EFFORT_LIMITS`. */ + private const EFFORT_PROPERTIES = [ + 'max_candidates_evaluated' => 'maxCandidatesEvaluated', 'max_placement_attempts' => 'maxPlacementAttempts', + 'max_search_nodes' => 'maxSearchNodes', 'max_restarts' => 'maxRestarts', + ]; + + /** + * Refuse the request with its first violation, or return. + * + * @param list $items + * @param list $containers + * @param list $fixedPlacements + * @throws InvalidRequestException + */ + public static function check(array $items, array $containers, PackingConfig $config, array $fixedPlacements = []): void + { + self::configuration($config); + foreach ($items as $index => $item) { + self::item($item, "/items/{$index}"); + } + RequestRules::requireUniqueIds(\array_map(static function (Item $item): string { + return $item->id; + }, $items), 'items'); + foreach ($containers as $index => $container) { + self::container($container, "/containers/{$index}"); + } + RequestRules::requireUniqueIds(\array_map(static function (Container $container): string { + return $container->id; + }, $containers), 'containers'); + foreach ($fixedPlacements as $index => $placement) { + self::fixedPlacement($placement, "fixed_placements[{$index}]", "/fixed_placements/{$index}"); + } + } + + /** + * `FixedPlacementShape`'s rules that an object can break, in its order and with its refusal; + * the types hold the orientation and the position, and `Point` refuses a negative + * coordinate. Whether the set can hold is `FixedPlacementAdmission`'s to say. + */ + private static function fixedPlacement(FixedPlacement $placement, string $where, string $field): void + { + foreach (['item_type' => $placement->itemId, 'container_type' => $placement->containerId] as $name => $value) { + if ($value === '') { + throw new FixedPlacementException("{$where}.{$name} is a non-empty string", 'malformed', "{$field}/{$name}"); + } + } + $instance = JsonValue::integer($placement->containerInstance); + if ($instance === null || $instance < 1) { + throw new FixedPlacementException("{$where}.container_instance counts from 1", 'malformed', "{$field}/container_instance"); + } + } + + /** + * `objective` is not checked here: an unknown one keeps its own, older error on this path, + * `UnknownObjectiveException`, thrown when the objective is resolved. + */ + private static function configuration(PackingConfig $config): void + { + $where = '/configuration'; + foreach (RequestRules::CONFIGURATION_INTEGERS as $name => $minimum) { + $property = self::CONFIGURATION_PROPERTIES[$name]; + self::optionalInteger($config->{$property}, "{$where}/{$name}", $minimum); + } + RequestRules::ratio($config->minimumSupportRatio, "{$where}/minimum_support_ratio", 1); + $budget = $config->effortBudget; + if ($budget === null) { + return; + } + foreach (RequestRules::EFFORT_LIMITS as $name) { + $property = self::EFFORT_PROPERTIES[$name]; + self::optionalInteger($budget->{$property}, "{$where}/effort_budget/{$name}", 1); + } + } + + private static function item(Item $item, string $where): void + { + RequestRules::integer($item->quantity, "{$where}/quantity", 1); + self::optionalInteger($item->maxStackedItems, "{$where}/max_stacked_items", 1); + self::optionalInteger($item->stopIndex, "{$where}/stop_index", 0); + self::optionalInteger($item->value, "{$where}/value", 0); + self::optionalInteger($item->maxCompressionPressureKpa, "{$where}/max_compression_pressure_kpa", 0); + RequestRules::ratio($item->minimumSupportRatio, "{$where}/minimum_support_ratio", 1); + if ($item->stackingGroup !== null) { + RequestRules::stackingGroupName($item->stackingGroup, "{$where}/stacking_group"); + } + foreach (self::codePointOrder($item->acceptsStackingGroups) as $index => $name) { + RequestRules::stackingGroupName($name, "{$where}/accepts_stacking_groups/{$index}"); + } + } + + private static function container(Container $container, string $where): void + { + self::optionalInteger($container->quantity, "{$where}/quantity", 1); + self::optionalInteger($container->maxItems, "{$where}/max_items", 1); + RequestRules::integer($container->costMinor, "{$where}/cost_minor", 0); + RequestRules::ratio($container->voidFillReserveRatio, "{$where}/void_fill_reserve_ratio", 1); + self::tagLimits($container->tagLimits, "{$where}/tag_limits"); + if ($container->rateTable !== null) { + self::rateTable($container->rateTable, "{$where}/rate_table"); + } + if ($container->deformableBoundary !== null) { + self::flatBag($container, $where); + } + if ($container->madeToMeasure !== null) { + self::madeToMeasure($container, $container->madeToMeasure, $where); + } + } + + /** + * `strcmp` on the tags' strings -- PHP made `"10"` the key 10 -- is UTF-8 byte order, + * which is code-point order. O(t log t) for t tags. + * + * @param array $limits + */ + private static function tagLimits(array $limits, string $where): void + { + $tags = \array_map('strval', \array_keys($limits)); + \usort($tags, 'strcmp'); + foreach ($tags as $tag) { + RequestRules::integer($limits[$tag], RequestRules::pointer($where, $tag), 1); + } + } + + private static function rateTable(RateTable $table, string $where): void + { + foreach (['weight_brackets_g' => [$table->weightBracketsG, 1], 'prices_minor' => [$table->pricesMinor, 0]] as $name => [$values, $minimum]) { + foreach ($values as $index => $value) { + RequestRules::integer($value, "{$where}/{$name}/{$index}", $minimum); + } + } + RequestRules::integer($table->minimumChargeMinor, "{$where}/minimum_charge_minor", 0); + RequestRules::integer($table->fuelSurchargePermille, "{$where}/fuel_surcharge_permille", 0); + } + + /** + * The fields a flat bag refuses, in the JSON rules' order. The container's constructor + * already refused an unknown kind and every field but `made_to_measure`, with no field + * named; walking them all keeps the order the JSON path reports in. An empty list is how + * an object leaves a list field out; JSON leaves it absent. + */ + private static function flatBag(Container $container, string $where): void + { + $fields = [ + 'obstacles' => $container->obstacles, 'axles' => $container->axles, + 'access_directions' => $container->accessDirections, 'max_stack_density' => $container->maxStackDensity, + 'outer_dimensions' => $container->outerDimensions, 'void_fill_reserve_ratio' => $container->voidFillReserveRatio, + 'made_to_measure' => $container->madeToMeasure, + ]; + foreach (RequestRules::BAG_EXCLUSIONS as $name) { + $value = $fields[$name] === [] ? null : $fields[$name]; + if (RequestRules::setBesideABag($name, $value)) { + throw new InvalidRequestException('not_allowed', "{$where}/{$name}", 'cannot be combined with deformable_boundary'); + } + } + } + + private static function madeToMeasure(Container $container, MadeToMeasure $machine, string $where): void + { + $price = "{$where}/made_to_measure/cost_per_square_metre_minor"; + RequestRules::integer($machine->costPerSquareMetreMinor, $price, 0); + if ($container->outerDimensions !== null) { + throw new InvalidRequestException('not_allowed', "{$where}/outer_dimensions", 'cannot be combined with made_to_measure'); + } + $inner = $container->innerDimensions; + $largest = MadeToMeasure::boxCostFor($machine->costPerSquareMetreMinor, $container->costMinor, + [$inner->length->ticks, $inner->width->ticks, $inner->height->ticks]); + if (BigInt::compare($largest, MadeToMeasure::MAX_EXACT_INTEGER) > 0) { + throw new InvalidRequestException('invalid_value', $price, 'prices the largest box above ' . CanonicalJson::MAX_EXACT_MAGNITUDE); + } + } + + private static function optionalInteger(?int $value, string $field, int $minimum): void + { + if ($value !== null) { + RequestRules::integer($value, $field, $minimum); + } + } + + /** + * Strings in code-point order; anything mistyped after them, so it is still checked. + * + * @param list $values + * @return list + */ + private static function codePointOrder(array $values): array + { + \usort($values, static function ($left, $right): int { + return (\is_string($right) <=> \is_string($left)) + ?: (\is_string($left) && \is_string($right) ? \strcmp($left, $right) : 0); + }); + return $values; + } +} diff --git a/src-legacy/Support/RequestRules.php b/src-legacy/Support/RequestRules.php index fcb3af3..c46bff5 100644 --- a/src-legacy/Support/RequestRules.php +++ b/src-legacy/Support/RequestRules.php @@ -13,7 +13,7 @@ * The request schema's rules, walked over the decoded JSON before any model is built. * * Held to `packvium.request_errors.check_request`: the first violation wins, in the order every - * engine follows -- units, configuration, items, containers -- and is refused with the same + * engine follows -- units, output, configuration, items, containers -- and is refused with the same * reason, JSON Pointer and message the reference raises. * * The request arrives from `json_decode(..., true)`, where `{}` and `[]` are the same empty @@ -25,13 +25,21 @@ final class RequestRules public const SOLVER_PROFILES = ['fast', 'balanced', 'quality', 'exact_small']; public const OBJECTIVES = ['default', 'lowest_cost', 'shipping_cost', 'lowest_landed_cost', 'open_dimension_height', 'maximum_value', 'maximum_volume']; public const ACCESS_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; - - private const CONFIGURATION_INTEGERS = [ + /** The schema's closed vocabularies, each refused as `not_allowed` like the two above. */ + public const SOLVERS = ['grid', 'extreme_points', 'homogeneous_blocks', 'layer', 'maximal_spaces', 'exact_small']; + public const ROTATIONS = ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']; + public const LENGTH_UNITS = ['mm', 'cm', 'm', 'in', 'ft']; + public const WEIGHT_UNITS = ['mg', 'g', 'kg', 'oz', 'lb']; + public const GROUND_CONTACT_RULES = ['free', 'covered', 'single', 'multiple']; + public const SHAPE_TYPES = ['rigid_cuboid', 'convex_hull', 'compressible']; + + /** Shared with `RequestObjects`, which walks the same fields over a request of objects. */ + public const CONFIGURATION_INTEGERS = [ 'time_limit_ms' => 1, 'alternatives' => 1, 'max_containers' => 1, 'exact_item_limit' => 1, 'multi_start_orders' => 1, 'max_candidates_per_item' => 1, 'max_candidate_points' => 16, 'container_plan_beam_width' => 1, 'container_plan_node_limit' => 1, 'dimensional_weight_divisor' => 1, ]; - private const EFFORT_LIMITS = ['max_candidates_evaluated', 'max_placement_attempts', 'max_search_nodes', 'max_restarts']; + public const EFFORT_LIMITS = ['max_candidates_evaluated', 'max_placement_attempts', 'max_search_nodes', 'max_restarts']; /** Every key the request schema's `configuration` declares; it sets `additionalProperties: false`. */ private const CONFIGURATION_FIELDS = [ 'alternatives', 'clearance', 'container_plan_beam_width', 'container_plan_node_limit', @@ -42,7 +50,7 @@ final class RequestRules ]; private const SIDES = ['length', 'width', 'height']; /** Container fields a flat bag refuses, in reporting order (docs/DEFORMABLE-CONTAINERS.md). */ - private const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', + public const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure']; /** Every key the request schema's `made_to_measure` declares; it sets `additionalProperties: false`. */ private const MADE_TO_MEASURE_FIELDS = ['cost_per_square_metre_minor', 'increment', 'minimum', 'outer_allowance', @@ -59,21 +67,22 @@ public static function check($data): void { $request = self::objectAt($data, ''); $unit = self::units(JsonValue::get($request, 'units')); + self::output(JsonValue::get($request, 'output')); self::configuration(JsonValue::get($request, 'configuration'), $unit); $items = self::requiredList($request, 'items', ''); foreach ($items as $index => $raw) { self::item($raw, "/items/{$index}", $unit); } - self::requireUniqueIds($items, 'items'); + self::requireUniqueIds(self::identifiers($items), 'items'); $containers = self::requiredList($request, 'containers', ''); foreach ($containers as $index => $raw) { self::container($raw, "/containers/{$index}", $unit); } - self::requireUniqueIds($containers, 'containers'); + self::requireUniqueIds(self::identifiers($containers), 'containers'); } /** The RFC 6901 pointer to one member, escaping `~` and `/` in its name. */ - private static function pointer(string $base, string $name): string + public static function pointer(string $base, string $name): string { return $base . '/' . \str_replace(['~', '/'], ['~0', '~1'], $name); } @@ -96,6 +105,17 @@ private static function units($raw): string return $length; } + /** @param mixed $raw */ + private static function output($raw): void + { + if ($raw === null) { + return; + } + $output = self::objectAt($raw, '/output'); + self::optionalOneOf($output, 'length_unit', '/output', self::LENGTH_UNITS); + self::optionalOneOf($output, 'weight_unit', '/output', self::WEIGHT_UNITS); + } + /** @param mixed $raw */ private static function configuration($raw, string $unit): void { @@ -105,16 +125,11 @@ private static function configuration($raw, string $unit): void $where = '/configuration'; $configuration = self::objectAt($raw, $where); self::knownFields($configuration, $where, self::CONFIGURATION_FIELDS); - $profile = JsonValue::get($configuration, 'solver_profile'); - if ($profile !== null && !\in_array($profile, self::SOLVER_PROFILES, true)) { - throw self::refuse('not_allowed', "{$where}/solver_profile", - 'must be one of ' . CanonicalJson::spelling(self::SOLVER_PROFILES)); - } - $objective = JsonValue::get($configuration, 'objective'); - if ($objective !== null && !\in_array($objective, self::OBJECTIVES, true)) { - throw self::refuse('not_allowed', "{$where}/objective", - 'must be one of ' . CanonicalJson::spelling(self::OBJECTIVES)); - } + self::optionalOneOf($configuration, 'solver_profile', $where, self::SOLVER_PROFILES); + self::optionalOneOf($configuration, 'objective', $where, self::OBJECTIVES); + self::optionalEachOneOf($configuration, 'solvers', $where, self::SOLVERS); + self::optionalOneOf($configuration, 'dimensional_weight_length_unit', $where, self::LENGTH_UNITS); + self::optionalOneOf($configuration, 'dimensional_weight_weight_unit', $where, self::WEIGHT_UNITS); foreach (self::CONFIGURATION_INTEGERS as $name => $minimum) { self::optionalInteger($configuration, $name, $where, $minimum); } @@ -130,6 +145,24 @@ private static function configuration($raw, string $unit): void } } + /** + * A nested copy sinks by less than its own height, or it would vanish into the one below + *. Both measures have passed their own rules already. O(1). + * + * @param stdClass|array $item + */ + private static function nestingBelowHeight($item, string $where, string $unit): void + { + $nesting = JsonValue::get($item, 'nesting_height'); + if ($nesting === null) { + return; + } + $height = JsonValue::get(JsonValue::get($item, 'dimensions'), 'height'); + if (MeasureReading::ticks($nesting, Length::class, $unit) >= MeasureReading::ticks($height, Length::class, $unit)) { + throw self::refuse('invalid_value', "{$where}/nesting_height", "must be less than the item's height"); + } + } + /** @param mixed $raw */ private static function item($raw, string $where, string $unit): void { @@ -140,6 +173,7 @@ private static function item($raw, string $where, string $unit): void self::optionalMeasure($item, 'weight', $where, Weight::class, self::WEIGHT_UNIT); self::optionalMeasure($item, 'max_top_load', $where, Weight::class, self::WEIGHT_UNIT); self::optionalMeasure($item, 'nesting_height', $where, Length::class, $unit); + self::nestingBelowHeight($item, $where, $unit); self::optionalInteger($item, 'max_stacked_items', $where, 1); self::optionalInteger($item, 'stop_index', $where, 0); self::optionalInteger($item, 'value', $where, 0); @@ -156,10 +190,13 @@ private static function item($raw, string $where, string $unit): void self::stackingGroupName($name, "{$where}/accepts_stacking_groups/{$index}"); } } + self::optionalEachOneOf($item, 'allowed_rotations', $where, self::ROTATIONS); + self::optionalOneOf($item, 'ground_contact_rule', $where, self::GROUND_CONTACT_RULES); + self::optionalOneOf($item, 'shape_type', $where, self::SHAPE_TYPES); } /** @param mixed $value */ - private static function stackingGroupName($value, string $field): void + public static function stackingGroupName($value, string $field): void { if (!\is_string($value)) { throw self::refuse('wrong_type', $field, 'must be a string'); @@ -303,7 +340,7 @@ private static function deformableBoundary($container, $raw, string $where): voi * * @param mixed $value */ - private static function setBesideABag(string $name, $value): bool + public static function setBesideABag(string $name, $value): bool { if ($name === 'obstacles') { return $value !== null && $value !== []; @@ -317,12 +354,52 @@ private static function setBesideABag(string $name, $value): bool /** @param mixed $raw */ private static function accessDirections($raw, string $where): void { - $list = self::listAt($raw, $where); - foreach ($list as $index => $direction) { - if (!\in_array($direction, self::ACCESS_DIRECTIONS, true)) { - throw self::refuse('not_allowed', "{$where}/{$index}", - 'must be one of ' . CanonicalJson::spelling(self::ACCESS_DIRECTIONS)); - } + self::eachOneOf($raw, $where, self::ACCESS_DIRECTIONS); + } + + /** + * @param stdClass|array $object + * @param list $allowed + */ + private static function optionalOneOf($object, string $name, string $where, array $allowed): void + { + $value = JsonValue::get($object, $name); + if ($value !== null) { + self::oneOf($value, "{$where}/{$name}", $allowed); + } + } + + /** + * @param stdClass|array $object + * @param list $allowed + */ + private static function optionalEachOneOf($object, string $name, string $where, array $allowed): void + { + $value = JsonValue::get($object, $name); + if ($value !== null) { + self::eachOneOf($value, "{$where}/{$name}", $allowed); + } + } + + /** + * @param mixed $raw + * @param list $allowed + */ + private static function eachOneOf($raw, string $where, array $allowed): void + { + foreach (self::listAt($raw, $where) as $index => $value) { + self::oneOf($value, "{$where}/{$index}", $allowed); + } + } + + /** + * @param mixed $value + * @param list $allowed + */ + private static function oneOf($value, string $field, array $allowed): void + { + if (!\in_array($value, $allowed, true)) { + throw self::refuse('not_allowed', $field, 'must be one of ' . CanonicalJson::spelling($allowed)); } } @@ -391,7 +468,7 @@ private static function obstacles($raw, string $where, string $unit): void // ------------------------------------------------------------------------- primitives /** @param mixed $value */ - private static function integer($value, string $field, int $minimum): void + public static function integer($value, string $field, int $minimum): void { $number = JsonValue::integer($value); if ($number === null) { @@ -423,7 +500,7 @@ private static function refuseNonInteger($value, string $field, int $minimum): v } /** @param mixed $value */ - private static function ratio($value, string $field, ?int $maximum): void + public static function ratio($value, string $field, ?int $maximum): void { if (!\is_int($value) && !\is_float($value)) { throw self::refuse('wrong_type', $field, 'must be a number'); @@ -585,13 +662,12 @@ private static function requiredString($object, string $name, string $where): vo /** * Checked once every entry is well formed, so the later of two equal ids is named. * - * @param list $entries + * @param list $identifiers */ - private static function requireUniqueIds(array $entries, string $key): void + public static function requireUniqueIds(array $identifiers, string $key): void { $seen = []; - foreach ($entries as $index => $entry) { - $identifier = (string) JsonValue::get($entry, 'id'); + foreach ($identifiers as $index => $identifier) { if (isset($seen[$identifier])) { throw self::refuse('duplicate_id', "/{$key}/{$index}/id", 'repeats the id ' . CanonicalJson::spelling($identifier)); } @@ -599,6 +675,17 @@ private static function requireUniqueIds(array $entries, string $key): void } } + /** + * @param list $entries + * @return list + */ + private static function identifiers(array $entries): array + { + return \array_map(static function ($entry): string { + return (string) JsonValue::get($entry, 'id'); + }, $entries); + } + private static function refuse(string $reason, string $field, string $detail): InvalidRequestException { return new InvalidRequestException($reason, $field, $detail); diff --git a/src-legacy/Support/ResultValidation/Accounting.php b/src-legacy/Support/ResultValidation/Accounting.php new file mode 100644 index 0000000..a94048f --- /dev/null +++ b/src-legacy/Support/ResultValidation/Accounting.php @@ -0,0 +1,329 @@ + $issues */ + public static function checkStructure($result, array &$issues): void + { + $summary = Json::at($result, 'summary'); + $containers = Json::items(Json::at($result, 'containers'), 'result.containers'); + $packed = 0; + foreach ($containers as $container) { + $packed += \count(Json::items(Json::at($container, 'placements'), 'placements')); + } + $unpacked = \count(Json::items(Json::at($result, 'unpacked_items'), 'result.unpacked_items')); + foreach (['container_count' => \count($containers), 'packed_item_count' => $packed, 'unpacked_item_count' => $unpacked] as $field => $actual) { + $reported = Json::at($summary, $field); + if (!Json::equalsInt($reported, $actual)) { + $issues[] = new ResultIssue('summary_mismatch', "{$field} " . PyFormat::str($reported) . " != {$actual}"); + } + } + $complete = Json::at($result, 'complete'); + if (!Json::equalsInt($complete, $unpacked === 0 ? 1 : 0)) { + $issues[] = new ResultIssue('complete_mismatch', 'complete=' . PyFormat::str($complete) . " with {$unpacked} unpacked"); + } + } + + /** + * Participating `require_container_tag` rules, resolved from the request alone -- a second + * implementation of docs/POLICY-RULES.md, so a resolution bug shared with an engine cannot + * hide behind agreement with it. + * + * @param mixed $request @return list + */ + public static function containerTagRules($request): array + { + $policy = Json::get($request, 'policy'); + if (!Json::isDict($policy)) { + return []; + } + $declared = Json::get($policy, 'rules'); + if (!Json::isList($declared) || $declared === []) { + return []; + } + $asOf = Json::intInstance(Json::get($policy, 'as_of')); + if ($asOf === null) { + return []; + } + $shipment = Json::get($policy, 'shipment'); + $shipment = Json::truthy($shipment) ? $shipment : []; + $latest = new Ordered(); + foreach ($declared as $rule) { + if (!Json::isDict($rule) || !Json::has($rule, 'require_container_tag')) { + continue; + } + $appliesTo = Json::get($rule, 'applies_to'); + $appliesTo = Json::truthy($appliesTo) ? $appliesTo : []; + if (!Json::isDict($appliesTo)) { + throw MalformedResult::shape('applies_to must be an object'); + } + foreach ($appliesTo as $fact => $value) { + if (!Json::equals(Json::get($shipment, (string)$fact), $value)) { + continue 2; + } + } + if (Json::compare(Json::get($rule, 'effective_at', 0), $asOf) > 0) { + continue; + } + $id = Json::get($rule, 'id'); + $current = $latest->get($id); + $newer = $current === null || Json::compare( + [Json::get($rule, 'effective_at', 0), Json::get($rule, 'version', 0)], + [Json::get($current, 'effective_at', 0), Json::get($current, 'version', 0)] + ) > 0; + if ($newer) { + $latest->set($id, $rule); + } + } + return $latest->values(); + } + + /** @param mixed $result @param list $issues */ + public static function checkAccounting($result, Context $context, array &$issues): void + { + $seen = new Ordered(); + $perType = new Ordered(); + foreach (Json::items(Json::at($result, 'containers'), 'result.containers') as $container) { + foreach (Json::items(Json::at($container, 'placements'), 'placements') as $placement) { + $itemId = Json::at($placement, 'item_id'); + if ($seen->has($itemId)) { + $issues[] = new ResultIssue('duplicate_item', PyFormat::str($itemId)); + } + $seen->set($itemId, true); + $itemType = Json::at($placement, 'item_type'); + $perType->set($itemType, $perType->get($itemType, 0) + 1); + } + } + $algorithm = Json::at($result, 'algorithm'); + $timedOut = Json::truthy(Json::at($algorithm, 'time_limit_reached')); + $effortLimited = Json::truthy(Json::at($algorithm, 'effort_limit_reached')); + foreach (Json::items(Json::at($result, 'unpacked_items'), 'result.unpacked_items') as $unpacked) { + $itemId = Json::at($unpacked, 'item_id'); + if ($seen->has($itemId)) { + $issues[] = new ResultIssue('duplicate_item', PyFormat::str($itemId) . ' is both packed and unpacked'); + } + $seen->set($itemId, true); + $itemType = Json::at($unpacked, 'item_type'); + $perType->set($itemType, $perType->get($itemType, 0) + 1); + if (!Json::truthy(Json::get($unpacked, 'reason'))) { + $issues[] = new ResultIssue('missing_reason', PyFormat::str($itemId)); + } + self::checkReasonProof($unpacked, $context->items->get($itemType), $context, $timedOut, $effortLimited, $issues); + } + foreach ($perType->entries() as [$itemType, $count]) { + $spec = $context->items->get($itemType); + if ($spec === null) { + $issues[] = new ResultIssue('unknown_item', PyFormat::str($itemType)); + } elseif (!Json::equalsInt($spec->quantity, $count)) { + $issues[] = new ResultIssue('quantity_mismatch', PyFormat::str($itemType) . ": {$count} accounted for, " . PyFormat::str($spec->quantity) . ' requested'); + } + } + foreach ($context->items->entries() as [$itemType, $spec]) { + if (!$perType->has($itemType)) { + $issues[] = new ResultIssue('quantity_mismatch', PyFormat::str($itemType) . ': 0 accounted for, ' . PyFormat::str($spec->quantity) . ' requested'); + } + } + } + + /** + * Whether one envelope of this size fits the empty container: its frame and, for a flat bag, + * both girth sums with the envelope alone at the origin. + * + * @param array $size + */ + public static function fitsEmpty(ContainerSpec $container, array $size): bool + { + for ($axis = 0; $axis < 3; ++$axis) { + if (Exact::compare($size[$axis], $container->inner[$axis]) > 0) { + return false; + } + } + return !$container->flatBag + || (Exact::compare(Exact::add($size[0], $size[2]), $container->inner[0]) <= 0 + && Exact::compare(Exact::add($size[1], $size[2]), $container->inner[1]) <= 0); + } + + /** + * `any(fits_empty(container, rotated envelope) for container ... for rotation ...)`, stopping + * at the first fit as Python's generator does, so an unknown rotation is only an error when + * the search reaches it. + * + * @param list $rotations + */ + private static function fitsSome(ItemSpec $spec, Context $context, array $rotations): bool + { + $margin = Exact::mul(2, $context->clearance); + foreach ($context->containers->values() as $container) { + foreach ($rotations as $rotation) { + $axes = Geometry::axes(Json::text($rotation, 'a rotation')); + $size = [ + Exact::add($spec->dimensions[$axes[0]], $margin), + Exact::add($spec->dimensions[$axes[1]], $margin), + Exact::add($spec->dimensions[$axes[2]], $margin), + ]; + if (self::fitsEmpty($container, $size)) { + return true; + } + } + } + return false; + } + + /** `value in tags` for a frozenset of strings; an unhashable value is Python's `TypeError`. @param array $tags @param mixed $value */ + public static function holds(array $tags, $value): bool + { + Json::hashKey($value); + return \is_string($value) && isset($tags[$value]); + } + + /** @param mixed $unpacked @param list $issues */ + private static function checkReasonProof($unpacked, ?ItemSpec $spec, Context $context, bool $timedOut, bool $effortLimited, array &$issues): void + { + $itemId = PyFormat::str(Json::get($unpacked, 'item_id', '?')); + $reason = Json::get($unpacked, 'reason', ''); + $proof = Json::get($unpacked, 'proof'); + if (!Json::isDict($proof)) { + $issues[] = new ResultIssue('missing_reason_proof', $itemId); + return; + } + Json::hashKey($reason); + $is = static function (array $names) use ($reason): bool { return \is_string($reason) && \in_array($reason, $names, true); }; + $expected = $is(self::PROVEN) ? 'proven' : ($is(self::LIMITED) ? 'unknown_due_to_limit' : ($is(self::OBSERVED) ? 'observed' : 'inferred')); + $level = Json::get($proof, 'level'); + if (!Json::isText($level, $expected)) { + $issues[] = new ResultIssue('reason_proof_mismatch', "{$itemId}: " . PyFormat::repr($reason) . ' has proof ' . PyFormat::repr($level) . ', expected ' . PyFormat::stringRepr($expected)); + } + if (Json::isText($reason, 'time_limit') && !$timedOut) { + $issues[] = new ResultIssue('reason_limit_mismatch', "{$itemId}: time_limit reason without a reached time limit"); + } + if (Json::isText($reason, 'effort_limit') && !$effortLimited) { + $issues[] = new ResultIssue('reason_limit_mismatch', "{$itemId}: effort_limit reason without a reached effort limit"); + } + if ($spec !== null) { + self::checkProvenReason($unpacked, $reason, $spec, $context, $itemId, $issues); + } + self::checkObservations($proof, $reason, $itemId, $issues); + } + + /** @param mixed $unpacked @param mixed $reason @param list $issues */ + private static function checkProvenReason($unpacked, $reason, ItemSpec $spec, Context $context, string $itemId, array &$issues): void + { + $every = \array_keys(Geometry::ROTATIONS); + if (Json::isText($reason, 'no_compatible_container_dimensions')) { + if (self::fitsSome($spec, $context, $spec->allowedRotations)) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: at least one allowed orientation fits a container"); + } + if (self::fitsSome($spec, $context, $every)) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: fits at least one container once every rotation is tried, not only its own allowed set -- should be rotation_restricted"); + } + } + if (Json::isText($reason, 'rotation_restricted')) { + if (self::fitsSome($spec, $context, $spec->allowedRotations)) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: already fits a container within its own allowed rotations"); + } + if (!self::fitsSome($spec, $context, $every)) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: does not fit any container even with every rotation tried -- should be no_compatible_container_dimensions"); + } + } + if (Json::isText($reason, 'payload_exceeded')) { + foreach ($context->containers->values() as $container) { + if ($container->maxPayload === null || Exact::compare($spec->weight, $container->maxPayload) <= 0) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: its weight is within at least one container payload limit"); + break; + } + } + } + if (Json::isText($reason, 'no_eligible_container')) { + foreach ($context->containers->values() as $container) { + if ($spec->eligibleContainerTags === [] || \array_intersect_key($spec->eligibleContainerTags, $container->tags) !== []) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: at least one container satisfies its eligible tags"); + break; + } + } + } + if (Json::isText($reason, 'policy_rule')) { + self::checkPolicyCitation($unpacked, $spec, $context, $itemId, $issues); + } + } + + /** + * Two claims, both checked: that some rule rules this item out of every container, and that + * the rule the result *names* is that rule. + * + * @param mixed $unpacked @param list $issues + */ + private static function checkPolicyCitation($unpacked, ItemSpec $spec, Context $context, string $itemId, array &$issues): void + { + $blocking = []; + foreach ($context->rules as $rule) { + if (!self::holds($spec->tags, Json::get(Json::at($rule, 'require_container_tag'), 'item_tag'))) { + continue; + } + $admitted = false; + foreach ($context->containers->values() as $container) { + if (self::holds($container->tags, Json::get(Json::at($rule, 'require_container_tag'), 'container_tag'))) { + $admitted = true; + break; + } + } + if (!$admitted) { + $blocking[] = $rule; + } + } + if ($blocking === []) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: no participating policy rule rules it out of every container"); + return; + } + $details = Json::get($unpacked, 'details'); + $cited = Json::truthy($details) + ? \implode(' ', \array_map(static function ($detail): string { return Json::text($detail, 'details'); }, Json::items($details, 'details'))) + : ''; + foreach ($blocking as $rule) { + $name = PyFormat::str(Json::at($rule, 'id')) . '@' . PyFormat::str(Json::at($rule, 'version')); + if (\strpos($cited, $name) !== false) { + return; + } + } + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: cites " . PyFormat::stringRepr($cited) . ', which names no rule that actually blocks it'); + } + + /** @param mixed $proof @param mixed $reason @param list $issues */ + private static function checkObservations($proof, $reason, string $itemId, array &$issues): void + { + $observations = Json::get($proof, 'observations'); + if (!Json::isList($observations) || $observations === []) { + $issues[] = new ResultIssue('missing_reason_observations', $itemId); + return; + } + $observedReason = false; + foreach ($observations as $observation) { + if (!Json::isDict($observation)) { + $issues[] = new ResultIssue('malformed_reason_observation', $itemId); + continue; + } + $code = Json::get($observation, 'code'); + $count = Json::intInstance(Json::get($observation, 'count')); + $details = Json::get($observation, 'details'); + if (!\is_string($code) || $code === '' || $count === null || $count < 1 || !Json::isList($details)) { + $issues[] = new ResultIssue('malformed_reason_observation', $itemId); + continue; + } + if (Json::equals($code, $reason)) { + $observedReason = true; + } + } + if (!$observedReason) { + $issues[] = new ResultIssue('reason_observation_mismatch', "{$itemId}: " . PyFormat::str($reason)); + } + } +} diff --git a/src-legacy/Support/ResultValidation/ContainerCheck.php b/src-legacy/Support/ResultValidation/ContainerCheck.php new file mode 100644 index 0000000..c12aa7a --- /dev/null +++ b/src-legacy/Support/ResultValidation/ContainerCheck.php @@ -0,0 +1,477 @@ +getMessage()); + } + } + + /** The largest envelope x2, y2 and z2 over a container's placements. @param mixed $packed @param int|string $clearance @return array{0:int|string,1:int|string,2:int|string} */ + public static function achievedExtent($packed, $clearance): array + { + $extent = null; + foreach (Json::items(Json::at($packed, 'placements'), 'placements') as $placement) { + $envelope = self::envelope($placement, $clearance); + $extent = $extent === null + ? [$envelope->x2, $envelope->y2, $envelope->z2] + : [Exact::max($extent[0], $envelope->x2), Exact::max($extent[1], $envelope->y2), Exact::max($extent[2], $envelope->z2)]; + } + return $extent ?? [0, 0, 0]; + } + + /** + * `achieved_dimensions` is present exactly when the container declares a soft size, and equals + * the tight extent; a flat bag's extent must pass the girth rule. + * + * @param mixed $packed @param int|string $clearance @param list $issues + */ + public static function checkAchievedExtent($packed, ContainerSpec $spec, $clearance, array &$issues): void + { + $reported = Json::get($packed, 'achieved_dimensions'); + $packedId = new Label($packed); + if (!$spec->reportsAchievedExtent) { + if ($reported !== null) { + $issues[] = new ResultIssue('achieved_dimensions_mismatch', "{$packedId}: reported for a container of fixed size"); + } + $packedId->verify(); + return; + } + [$a, $b, $c] = self::achievedExtent($packed, $clearance); + $stated = null; + if (Json::isDict($reported)) { + $stated = []; + foreach (self::SIDES as $side) { + $stated[] = Json::get(Json::get($reported, $side, []), 'ticks'); + } + } + if (!self::matches($stated, [$a, $b, $c])) { + $issues[] = new ResultIssue('achieved_dimensions_mismatch', "{$packedId}: reported " . self::optionalTuple($stated) . ', computed ' . PyFormat::intTuple([$a, $b, $c])); + } + if ($spec->flatBag && (Exact::compare(Exact::add($a, $c), $spec->inner[0]) > 0 || Exact::compare(Exact::add($b, $c), $spec->inner[1]) > 0)) { + $issues[] = new ResultIssue('bag_girth_exceeded', "{$packedId}: a + c = " . Exact::add($a, $c) . ', b + c = ' . Exact::add($b, $c) . ", flat size {$spec->inner[0]} x {$spec->inner[1]}"); + } + $packedId->verify(); + } + + /** @param list|null $stated @param list $expected */ + private static function matches(?array $stated, array $expected): bool + { + if ($stated === null) { + return false; + } + foreach ($expected as $index => $value) { + if (!Json::equalsInt($stated[$index], $value)) { + return false; + } + } + return true; + } + + /** @param list|null $values */ + private static function optionalTuple(?array $values): string + { + return $values === null ? 'None' : PyFormat::valueTuple($values); + } + + /** `(value.get(key) or {}).get("ticks")` per side, or null when `value` is not an object. @param mixed $value @return list|null */ + private static function reportedTicks($value): ?array + { + if (!Json::isDict($value)) { + return null; + } + $ticks = []; + foreach (self::SIDES as $side) { + $ticks[] = self::nestedTicks($value, $side); + } + return $ticks; + } + + /** `(block.get(key) or {}).get("ticks")`. @param mixed $block @return mixed */ + private static function nestedTicks($block, string $key) + { + $value = Json::get($block, $key); + return Json::truthy($value) ? Json::get($value, 'ticks') : null; + } + + /** + * Recompute a made-to-measure container's box from its placements alone and return the spec + * every later check uses: the recomputed box, never the reported one. + * + * @param mixed $packed @param Ordered $items @param int|string $clearance @param list $issues + */ + public static function checkMadeToMeasure($packed, bool $compact, ContainerSpec $spec, Ordered $items, $clearance, array &$issues): ContainerSpec + { + $containerId = PyFormat::str(Json::get($packed, 'id', '?')); + $block = Json::get($packed, 'made_to_measure'); + $machine = $spec->madeToMeasure; + if ($machine === null) { + if ($block !== null) { + $issues[] = new ResultIssue('made_to_measure_unexpected', $containerId); + } + return $spec; + } + if (!Json::isDict($block)) { + $issues[] = new ResultIssue('made_to_measure_missing', $containerId); + $block = []; + } + if ($compact) { + $issues[] = new ResultIssue('lattice_summary_on_made_to_measure', $containerId); + } + $achieved = self::achievedExtent($packed, $clearance); + $fabricated = []; + for ($axis = 0; $axis < 3; ++$axis) { + $minimum = $machine->minimum[$axis]; + $increment = $machine->increment[$axis]; + $steps = Exact::ceilDiv(Exact::sub(Exact::max($achieved[$axis], $minimum), $minimum), $increment); + $fabricated[] = Exact::add($minimum, Exact::mul($steps, $increment)); + } + for ($axis = 0; $axis < 3; ++$axis) { + if (Exact::compare($fabricated[$axis], $spec->inner[$axis]) > 0) { + $issues[] = new ResultIssue('fabricated_dimensions_exceed_machine', "{$containerId}: " . PyFormat::intTuple($fabricated) . ' beyond ' . PyFormat::intTuple($spec->inner)); + break; + } + } + $reportedInner = self::reportedTicks(Json::get($packed, 'inner_dimensions')); + if (!self::matches($reportedInner, $fabricated)) { + $issues[] = new ResultIssue('fabricated_dimensions_mismatch', "{$containerId}: reported " . self::optionalTuple($reportedInner) . ', computed ' . PyFormat::intTuple($fabricated)); + } + $outer = []; + for ($axis = 0; $axis < 3; ++$axis) { + $outer[] = Exact::add($fabricated[$axis], $machine->allowance[$axis]); + } + $reportedOuter = self::reportedTicks(Json::get($packed, 'outer_dimensions')); + if (!self::matches($reportedOuter, $outer)) { + $issues[] = new ResultIssue('outer_dimensions_mismatch', "{$containerId}: reported " . self::optionalTuple($reportedOuter) . ', computed ' . PyFormat::intTuple($outer)); + } + $cost = Exact::add($spec->costMinor, self::perSquareMetreCeiling($machine->pricePerSquareMetreMinor, $fabricated)); + $reportedCost = Json::get($block, 'cost_minor'); + if (!Json::equalsInt($reportedCost, $cost)) { + $issues[] = new ResultIssue('made_to_measure_cost_mismatch', "{$containerId}: reported " . PyFormat::str($reportedCost) . ", computed {$cost}"); + } + $tare = Exact::add($spec->tareWeight, self::perSquareMetreCeiling($machine->tarePerSquareMetre, $fabricated)); + $reportedTare = self::nestedTicks($block, 'tare_weight'); + if (!Json::equalsInt($reportedTare, $tare)) { + $issues[] = new ResultIssue('made_to_measure_tare_mismatch', "{$containerId}: reported " . PyFormat::str($reportedTare) . ", computed {$tare}"); + } + $gross = Exact::add($tare, self::payloadOf($packed, $items)); + $reportedGross = self::nestedTicks($packed, 'gross_weight'); + if (!Json::equalsInt($reportedGross, $gross)) { + $issues[] = new ResultIssue('gross_weight_mismatch', "{$containerId}: reported " . PyFormat::str($reportedGross) . ", computed {$gross}"); + } + $recomputed = clone $spec; + $recomputed->inner = $fabricated; + $recomputed->outer = $outer; + $recomputed->costMinor = $cost; + $recomputed->tareWeight = $tare; + return $recomputed; + } + + /** `ceil(rate * 2(LW + LH + WH) / 1 m^2)`. @param int|string $rate @param array $sides @return int|string */ + private static function perSquareMetreCeiling($rate, array $sides) + { + [$length, $width, $height] = $sides; + $area = Exact::mul(2, Exact::add(Exact::add(Exact::mul($length, $width), Exact::mul($length, $height)), Exact::mul($width, $height))); + return Exact::ceilDiv(Exact::mul($rate, $area), Stacking::SQUARE_METRE_TICKS); + } + + /** The summed weight of every placement whose type the request declares. @param mixed $packed @param Ordered $items @return int|string */ + public static function payloadOf($packed, Ordered $items) + { + $payload = 0; + foreach (Json::items(Json::at($packed, 'placements'), 'placements') as $placement) { + $spec = $items->get(Json::at($placement, 'item_type')); + if ($spec !== null) { + $payload = Exact::add($payload, $spec->weight); + } + } + return $payload; + } + + /** @param mixed $packed @param Ordered $items @param int|string $clearance @param list $issues */ + public static function check($packed, ContainerSpec $spec, Ordered $items, $clearance, Ratio $globalSupport, array &$issues): void + { + $packedId = new Label($packed); + $placements = Json::items(Json::at($packed, 'placements'), 'placements'); + $boundary = new Cuboid(0, 0, 0, $spec->inner[0], $spec->inner[1], $spec->inner[2]); + $byId = new Ordered(); + $payload = 0; + foreach ($placements as $placement) { + $itemId = Json::at($placement, 'item_id'); + $itemSpec = $items->get(Json::at($placement, 'item_type')); + $envelope = self::envelope($placement, $clearance); + $byId->set($itemId, new Entry($itemId, $envelope, $placement, $itemSpec)); + $label = PyFormat::str($itemId); + if (!$boundary->contains($envelope)) { + $issues[] = new ResultIssue('outside_container', "{$label} in {$packedId}"); + } + foreach ($spec->obstacles as $obstacle) { + if ($envelope->intersects($obstacle) && Geometry::solidsOverlap(Stacking::placedHull($envelope, $placement, $itemSpec), $obstacle->vertices())) { + $issues[] = new ResultIssue('obstacle_collision', "{$label} in {$packedId}"); + } + } + if ($itemSpec === null) { + continue; + } + $payload = Exact::add($payload, $itemSpec->weight); + self::checkRotation($placement, $itemSpec, $label, $issues); + if ($itemSpec->eligibleContainerTags !== [] && \array_intersect_key($itemSpec->eligibleContainerTags, $spec->tags) === []) { + $tags = \array_map('strval', \array_keys($itemSpec->eligibleContainerTags)); + \sort($tags, SORT_STRING); + $issues[] = new ResultIssue('container_ineligible', "{$label}: " . PyFormat::str(Json::at($packed, 'container_type')) . ' has none of ' . PyFormat::listOf(\array_map([PyFormat::class, 'stringRepr'], $tags))); + } + if ($itemSpec->mustBeOnFloor && Exact::sign($envelope->z) !== 0) { + $issues[] = new ResultIssue('floor_violation', "{$label} at z={$envelope->z}"); + } + } + $entries = $byId->values(); + self::checkPairs($entries, $packedId, $issues); + [$supporters, $directAbove] = Stacking::supportGraph($entries); + Stacking::checkSupportAndLoad($entries, $supporters, $directAbove, $globalSupport, $issues); + $loads = Stacking::propagateLoad($entries, $supporters); + if ($spec->maxStackDensity !== null) { + Stacking::checkStackDensity($packedId, $entries, $loads, $spec->maxStackDensity, $issues); + } + Stacking::checkCrush($packedId, $entries, $loads, $issues); + Stacking::checkRouteRemovalOrder($packedId, $entries, $directAbove, $spec->inner, $spec->accessDirections, $issues); + self::checkLimits($packed, $packedId, $placements, $spec, $items, $payload, $issues); + self::checkVolumes($packed, $packedId, $placements, $spec, $items, $byId, $loads, $issues); + $totalWeight = self::payloadOf($packed, $items); + self::checkCentreOfMass($packed, $packedId, $placements, $spec, $items, $totalWeight, $issues); + self::checkAxles($packed, $packedId, $placements, $spec, $items, $totalWeight, $issues); + $packedId->verify(); + } + + /** @param mixed $placement @param list $issues */ + private static function checkRotation($placement, ItemSpec $spec, string $itemId, array &$issues): void + { + $orientation = Json::at($placement, 'orientation'); + if (!Geometry::isRotation($orientation)) { + $issues[] = new ResultIssue('unknown_orientation', "{$itemId}: " . PyFormat::str($orientation)); + return; + } + if (!$spec->allows($orientation)) { + $issues[] = new ResultIssue('forbidden_rotation', "{$itemId}: {$orientation}"); + } + $expected = $spec->rotated($orientation); + $dimensions = Json::at($placement, 'dimensions'); + $actual = []; + foreach (self::SIDES as $side) { + $actual[] = Json::at(Json::at($dimensions, $side), 'ticks'); + } + if (!self::matches($actual, $expected)) { + $issues[] = new ResultIssue('dimension_mismatch', "{$itemId}: {$orientation} of " . PyFormat::intTuple($spec->dimensions) . ' is ' . PyFormat::intTuple($expected) . ', got ' . PyFormat::valueTuple($actual)); + } + } + + /** @param list $entries @param list $issues */ + private static function checkPairs(array $entries, Label $packedId, array &$issues): void + { + $count = \count($entries); + for ($first = 0; $first < $count; ++$first) { + $left = $entries[$first]; + for ($second = $first + 1; $second < $count; ++$second) { + $right = $entries[$second]; + if ($left->envelope->intersects($right->envelope) + && Geometry::solidsOverlap(Stacking::placedHull($left->envelope, $left->placement, $left->spec), Stacking::placedHull($right->envelope, $right->placement, $right->spec)) + && !Stacking::validNesting($left, $right)) { + $issues[] = new ResultIssue('collision', PyFormat::str($left->id) . ' with ' . PyFormat::str($right->id) . " in {$packedId}"); + } + if ($left->spec !== null && $right->spec !== null + && (\array_intersect_key($left->spec->incompatibleTags, $right->spec->tags) !== [] + || \array_intersect_key($right->spec->incompatibleTags, $left->spec->tags) !== [])) { + $issues[] = new ResultIssue('incompatible_items', PyFormat::str($left->id) . ' is incompatible with ' . PyFormat::str($right->id) . " in {$packedId}"); + } + } + } + } + + /** @param mixed $packed @param list $placements @param Ordered $items @param int|string $payload @param list $issues */ + private static function checkLimits($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, $payload, array &$issues): void + { + if ($spec->maxPayload !== null && Exact::compare($payload, $spec->maxPayload) > 0) { + $issues[] = new ResultIssue('payload_exceeded', "{$packedId}: {$payload} > {$spec->maxPayload} ticks"); + } + $reported = Json::get(Json::get($packed, 'payload_weight', []), 'ticks'); + if ($reported !== null && !Json::equalsInt($reported, $payload)) { + $issues[] = new ResultIssue('payload_weight_mismatch', "{$packedId}: reported " . PyFormat::str($reported) . ", computed {$payload}"); + } + if ($spec->maxItems !== null && \count($placements) > $spec->maxItems) { + $issues[] = new ResultIssue('max_items_exceeded', "{$packedId}: " . \count($placements) . " > {$spec->maxItems}"); + } + foreach ($spec->tagLimits as [$tag, $limit]) { + $count = 0; + foreach ($placements as $placement) { + $item = $items->get(Json::at($placement, 'item_type')); + if ($item !== null && isset($item->tags[$tag])) { + ++$count; + } + } + if (Exact::compare($count, $limit) > 0) { + $issues[] = new ResultIssue('tag_count_exceeded', "{$packedId}: {$tag} count {$count} > limit {$limit}"); + } + } + } + + /** + * @param mixed $packed @param list $placements @param Ordered $items + * @param Ordered $byId @param list $loads @param list $issues + */ + private static function checkVolumes($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, Ordered $byId, array $loads, array &$issues): void + { + // Every placement counts, through the envelope its item id resolves to -- a repeated id + // resolves to its last placement, as the reference's dict does. + $used = 0; + foreach ($placements as $placement) { + $index = $byId->position(Json::at($placement, 'item_id')); + $entry = $byId->get(Json::at($placement, 'item_id')); + $used = Exact::add($used, Stacking::occupiedVolume($entry->envelope, $placement, $items->get(Json::at($placement, 'item_type')), $loads[$index])); + } + $entries = $byId->values(); + for ($first = 0, $count = \count($entries); $first < $count; ++$first) { + for ($second = $first + 1; $second < $count; ++$second) { + if (Stacking::validNesting($entries[$first], $entries[$second])) { + $left = $entries[$first]; + $used = Exact::sub($used, Exact::mul(Exact::mul($left->spec->nestingHeight, $left->envelope->length), $left->envelope->width)); + } + } + } + $reportedVolume = Json::get($packed, 'used_volume_ticks3'); + if ($reportedVolume !== null && Exact::compare(Json::pyInt($reportedVolume, 'used_volume_ticks3'), $used) !== 0) { + $issues[] = new ResultIssue('used_volume_mismatch', "{$packedId}: reported " . PyFormat::str($reportedVolume) . ", computed {$used}"); + } + $volume = $spec->volume(); + $scaledReserve = self::ratioPpm($spec->voidFillReserveRatio); + $reserved = Exact::add( + Exact::mul(Exact::floorDiv($volume, self::SCORE_SCALE), $scaledReserve), + Exact::floorDiv(Exact::mul(Exact::mod($volume, self::SCORE_SCALE), $scaledReserve), self::SCORE_SCALE) + ); + $reportedReserve = Json::get($packed, 'void_fill_reserve_ticks3'); + if ($reportedReserve !== null && Exact::compare(Json::pyInt($reportedReserve, 'void_fill_reserve_ticks3'), $reserved) !== 0) { + $issues[] = new ResultIssue('void_fill_reserve_mismatch', "{$packedId}: reported " . PyFormat::str($reportedReserve) . ", computed {$reserved}"); + } elseif (Exact::sign($reserved) !== 0 && $reportedReserve === null) { + $issues[] = new ResultIssue('void_fill_reserve_mismatch', "{$packedId}: non-zero reserve {$reserved} is not reported"); + } + $usable = Exact::sub($volume, $reserved); + if (Exact::compare($used, $usable) > 0) { + $issues[] = new ResultIssue('void_fill_reserve_exceeded', "{$packedId}: used {$used} > usable {$usable}"); + } + } + + /** + * A support, void-fill reserve or compression ratio in parts per million exactly as every solver + * converts it: the IEEE double `floor(ratio * 10^6 + 0.5)` of docs/UNITS-AND-NUMERICS.md. + * Rounding the exact rational instead disagrees on about one in a hundred seven-decimal + * halves and would refuse placements, and reported reserves, every solver produces. + */ + public static function ratioPpm(Ratio $ratio): int + { + return (int)($ratio->toFloat() * self::SCORE_SCALE + 0.5); + } + + /** `sum(weight * (2 * position + extent))` along one axis, over declared item types. @param list $placements @param Ordered $items @return int|string */ + private static function doubledMoment(array $placements, Ordered $items, string $axis, string $side) + { + $moment = 0; + foreach ($placements as $placement) { + $spec = $items->get(Json::at($placement, 'item_type')); + if ($spec === null) { + continue; + } + $position = Json::int(Json::at(Json::at(Json::at($placement, 'position'), $axis), 'ticks'), 'placement ticks'); + $extent = Json::int(Json::at(Json::at(Json::at($placement, 'dimensions'), $side), 'ticks'), 'placement ticks'); + $moment = Exact::add($moment, Exact::mul($spec->weight, Exact::add(Exact::mul(2, $position), $extent))); + } + return $moment; + } + + /** @param mixed $packed @param list $placements @param Ordered $items @param int|string $totalWeight @param list $issues */ + private static function checkCentreOfMass($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, $totalWeight, array &$issues): void + { + $expected = 0; + if (Exact::sign($totalWeight) !== 0) { + $offset = static function ($doubled, $side) use ($totalWeight) { + $centred = Exact::mul($totalWeight, $side); + return Exact::floorDiv(Exact::mul(Exact::abs(Exact::sub($doubled, $centred)), self::SCORE_SCALE), $centred); + }; + $expected = Exact::max( + $offset(self::doubledMoment($placements, $items, 'x', 'length'), $spec->inner[0]), + $offset(self::doubledMoment($placements, $items, 'y', 'width'), $spec->inner[1]) + ); + } + $reported = Json::get($packed, 'centre_of_mass_offset_ppm'); + if (!Json::equalsInt($reported, $expected)) { + $issues[] = new ResultIssue('centre_of_mass_mismatch', "{$packedId}: reported " . PyFormat::str($reported) . ", computed {$expected}"); + } + } + + /** @param mixed $packed @param list $placements @param Ordered $items @param int|string $totalWeight @param list $issues */ + private static function checkAxles($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, $totalWeight, array &$issues): void + { + if ($spec->axles === null) { + if (Json::has($packed, 'axle_reactions')) { + $issues[] = new ResultIssue('axle_reaction_mismatch', "{$packedId}: reactions reported without configured axles"); + } + return; + } + if (\count($spec->axles) !== 2) { + throw MalformedResult::shape("{$packedId}: axles must name exactly a front and a rear axle"); + } + [[$frontX, $frontLimit], [$rearX, $rearLimit]] = $spec->axles; + $denominator = Exact::mul(2, Exact::sub($rearX, $frontX)); + $gross = Exact::add($spec->tareWeight, $totalWeight); + $doubledWeightedX = Exact::add(Exact::mul($spec->tareWeight, $spec->inner[0]), self::doubledMoment($placements, $items, 'x', 'length')); + $frontNumerator = Exact::sub(Exact::mul(Exact::mul(2, $gross), $rearX), $doubledWeightedX); + $rearNumerator = Exact::sub($doubledWeightedX, Exact::mul(Exact::mul(2, $gross), $frontX)); + $expected = [ + 'basis' => 'gross', + 'denominator' => (string)$denominator, + 'front_numerator' => (string)$frontNumerator, + 'rear_numerator' => (string)$rearNumerator, + ]; + $reported = Json::get($packed, 'axle_reactions'); + if (!Json::equals($reported, $expected)) { + $issues[] = new ResultIssue('axle_reaction_mismatch', "{$packedId}: reported " . PyFormat::str($reported) . ', computed ' . PyFormat::repr($expected)); + } + $over = static function ($limit, $numerator) use ($denominator): bool { + return $limit !== null && Exact::compare($numerator, Exact::mul($limit, $denominator)) > 0; + }; + if ($over($frontLimit, $frontNumerator) || $over($rearLimit, $rearNumerator)) { + $issues[] = new ResultIssue('axle_overloaded', (string)$packedId); + } + } +} diff --git a/src-legacy/Support/ResultValidation/ContainerSpec.php b/src-legacy/Support/ResultValidation/ContainerSpec.php new file mode 100644 index 0000000..9357724 --- /dev/null +++ b/src-legacy/Support/ResultValidation/ContainerSpec.php @@ -0,0 +1,52 @@ + */ + public $obstacles; + /** @var array */ + public $tags; + /** @var list sorted by tag, the order the reference walks it in */ + public $tagLimits; + /** @var Ratio */ + public $voidFillReserveRatio; + /** @var int|string */ + public $tareWeight; + /** @var list|null each axle's position and load limit */ + public $axles; + /** @var int|string|null */ + public $maxStackDensity; + /** @var mixed */ + public $rateTable; + /** @var list */ + public $accessDirections; + /** @var bool */ + public $flatBag; + /** @var bool */ + public $reportsAchievedExtent; + /** @var MachineSpec|null */ + public $madeToMeasure; + + /** @return int|string */ + public function volume() + { + return Exact::mul(Exact::mul($this->inner[0], $this->inner[1]), $this->inner[2]); + } +} diff --git a/src-legacy/Support/ResultValidation/Context.php b/src-legacy/Support/ResultValidation/Context.php new file mode 100644 index 0000000..96823a6 --- /dev/null +++ b/src-legacy/Support/ResultValidation/Context.php @@ -0,0 +1,25 @@ + */ + public $items; + /** @var Ordered */ + public $containers; + /** @var int|string */ + public $clearance; + /** @var list the participating `require_container_tag` rules */ + public $rules; + + /** @param Ordered $items @param Ordered $containers @param int|string $clearance @param list $rules */ + public function __construct(Ordered $items, Ordered $containers, $clearance, array $rules) + { + $this->items = $items; + $this->containers = $containers; + $this->clearance = $clearance; + $this->rules = $rules; + } +} diff --git a/src-legacy/Support/ResultValidation/Cuboid.php b/src-legacy/Support/ResultValidation/Cuboid.php new file mode 100644 index 0000000..b1edbbf --- /dev/null +++ b/src-legacy/Support/ResultValidation/Cuboid.php @@ -0,0 +1,85 @@ +x = $x; + $this->y = $y; + $this->z = $z; + $this->length = $length; + $this->width = $width; + $this->height = $height; + $this->x2 = Exact::add($x, $length); + $this->y2 = Exact::add($y, $width); + $this->z2 = Exact::add($z, $height); + $this->baseArea = Exact::mul($length, $width); + } + + public function intersects(self $other): bool + { + return Exact::compare($this->x, $other->x2) < 0 && Exact::compare($other->x, $this->x2) < 0 + && Exact::compare($this->y, $other->y2) < 0 && Exact::compare($other->y, $this->y2) < 0 + && Exact::compare($this->z, $other->z2) < 0 && Exact::compare($other->z, $this->z2) < 0; + } + + public function contains(self $other): bool + { + return Exact::compare($this->x, $other->x) <= 0 && Exact::compare($this->y, $other->y) <= 0 + && Exact::compare($this->z, $other->z) <= 0 && Exact::compare($other->x2, $this->x2) <= 0 + && Exact::compare($other->y2, $this->y2) <= 0 && Exact::compare($other->z2, $this->z2) <= 0; + } + + /** @return int|string */ + public function overlapAreaXy(self $other) + { + $dx = Exact::max(0, Exact::sub(self::min($this->x2, $other->x2), Exact::max($this->x, $other->x))); + $dy = Exact::max(0, Exact::sub(self::min($this->y2, $other->y2), Exact::max($this->y, $other->y))); + return Exact::mul($dx, $dy); + } + + /** @return list the eight corners, in the reference's order */ + public function vertices(): array + { + $corners = []; + foreach ([false, true] as $farX) { + foreach ([false, true] as $farY) { + foreach ([false, true] as $farZ) { + $corners[] = [$farX ? $this->x2 : $this->x, $farY ? $this->y2 : $this->y, $farZ ? $this->z2 : $this->z]; + } + } + } + return $corners; + } + + /** @param int|string $a @param int|string $b @return int|string */ + private static function min($a, $b) + { + return Exact::compare($a, $b) <= 0 ? $a : $b; + } +} diff --git a/src-legacy/Support/ResultValidation/Entry.php b/src-legacy/Support/ResultValidation/Entry.php new file mode 100644 index 0000000..ce65a50 --- /dev/null +++ b/src-legacy/Support/ResultValidation/Entry.php @@ -0,0 +1,25 @@ +id = $id; + $this->envelope = $envelope; + $this->placement = $placement; + $this->spec = $spec; + } +} diff --git a/src-legacy/Support/ResultValidation/Exact.php b/src-legacy/Support/ResultValidation/Exact.php new file mode 100644 index 0000000..57c267c --- /dev/null +++ b/src-legacy/Support/ResultValidation/Exact.php @@ -0,0 +1,169 @@ + $b; + } + return SignedBigInt::compare($a, $b); + } + + /** @param int|string $value */ + public static function sign($value): int + { + return self::compare($value, 0); + } + + /** @param int|string $value @return int|string */ + public static function negate($value) + { + if (\is_int($value) && $value !== PHP_INT_MIN) { + return -$value; + } + return self::normalize(SignedBigInt::negate($value)); + } + + /** @param int|string $value @return int|string */ + public static function abs($value) + { + return self::sign($value) < 0 ? self::negate($value) : $value; + } + + /** @param int|string $a @param int|string $b @return int|string */ + public static function max($a, $b) + { + return self::compare($a, $b) >= 0 ? $a : $b; + } + + /** + * Python's `a // b`. + * + * @param int|string $a @param int|string $b @return int|string + */ + public static function floorDiv($a, $b) + { + if (self::sign($b) === 0) { + throw MalformedResult::shape('division by zero'); + } + if (\is_int($a) && \is_int($b) && !($a === PHP_INT_MIN && $b === -1)) { + $quotient = \intdiv($a, $b); + return ($a % $b !== 0 && (($a < 0) !== ($b < 0))) ? $quotient - 1 : $quotient; + } + $magnitude = BigInt::divide((string)self::abs($a), (string)self::abs($b)); + $negative = (self::sign($a) < 0) !== (self::sign($b) < 0); + if (!$negative) { + return self::normalize($magnitude); + } + $exact = self::compare(self::mul($magnitude, self::abs($b)), self::abs($a)) === 0; + return self::negate($exact ? self::normalize($magnitude) : self::add($magnitude, 1)); + } + + /** Python's `a % b`, which takes the divisor's sign. @param int|string $a @param int|string $b @return int|string */ + public static function mod($a, $b) + { + return self::sub($a, self::mul(self::floorDiv($a, $b), $b)); + } + + /** `-(-a // b)`. @param int|string $a @param int|string $b @return int|string */ + public static function ceilDiv($a, $b) + { + return self::negate(self::floorDiv(self::negate($a), $b)); + } + + /** @param int|string $a @param int|string $b @return int|string */ + public static function gcd($a, $b) + { + $a = self::abs($a); + $b = self::abs($b); + while (self::sign($b) !== 0) { + [$a, $b] = [$b, self::mod($a, $b)]; + } + return $a; + } + + /** @param list $values @return int|string */ + public static function sum(array $values) + { + $total = 0; + foreach ($values as $value) { + $total = self::add($total, $value); + } + return $total; + } + + /** `2 ** $power`, exactly. @return int|string */ + public static function powerOfTwo(int $power) + { + if ($power < 62) { + return 1 << $power; + } + $value = 1 << 61; + for ($i = 61; $i < $power; ++$i) { + $value = self::mul($value, 2); + } + return $value; + } +} diff --git a/src-legacy/Support/ResultValidation/Facts.php b/src-legacy/Support/ResultValidation/Facts.php new file mode 100644 index 0000000..17c439f --- /dev/null +++ b/src-legacy/Support/ResultValidation/Facts.php @@ -0,0 +1,243 @@ + $issues */ + public static function checkAlgorithmMetrics($result, array &$issues): void + { + $algorithm = self::algorithm($result); + $metrics = Json::get($algorithm, 'metrics'); + $wellFormed = Json::isDict($metrics); + foreach (self::METRICS as $field) { + $count = $wellFormed ? Json::strictInt(Json::get($metrics, $field)) : null; + $wellFormed = $wellFormed && $count !== null && $count >= 0; + } + if (!$wellFormed) { + $issues[] = new ResultIssue('solver_metrics_mismatch', 'algorithm.metrics must contain every non-negative integer counter'); + return; + } + $candidates = Json::strictInt(Json::get($algorithm, 'candidates_evaluated')); + $attempts = Json::strictInt(Json::get($algorithm, 'placements_attempted')); + if ($candidates === null || $attempts === null || $candidates !== $metrics['feasible_candidates'] || $attempts !== $metrics['orientations_considered']) { + $issues[] = new ResultIssue('solver_metrics_mismatch', 'legacy candidate counters must mirror algorithm.metrics'); + } + } + + /** Counted-work limits are respected, and the stop flag is evidenced by one. @param mixed $request @param mixed $result @param list $issues */ + public static function checkEffortBudget($request, $result, array &$issues): void + { + $algorithm = Json::at($result, 'algorithm'); + $effortLimited = Json::get($algorithm, 'effort_limit_reached'); + if (!\is_bool($effortLimited)) { + throw MalformedResult::contract('algorithm.effort_limit_reached must be a boolean'); + } + $budget = Json::get(Json::get($request, 'configuration', []), 'effort_budget'); + if ($budget === null) { + if ($effortLimited) { + $issues[] = new ResultIssue('effort_budget_mismatch', 'effort_limit_reached is true but the request has no effort_budget'); + } + return; + } + if (!Json::isDict($budget)) { + throw MalformedResult::contract('config.effort_budget must be an object'); + } + $metrics = Json::get($algorithm, 'metrics'); + if (!Json::isDict($metrics)) { + return; + } + $reached = false; + foreach (['max_candidates_evaluated' => 'feasible_candidates', 'max_placement_attempts' => 'orientations_considered', 'max_search_nodes' => 'search_nodes_expanded'] as $budgetName => $metricName) { + $limit = Json::get($budget, $budgetName); + $value = Json::strictInt(Json::get($metrics, $metricName)); + if ($limit === null || $value === null) { + continue; + } + $order = Json::compare($value, $limit); + if ($order > 0) { + $issues[] = new ResultIssue('effort_budget_exceeded', "{$metricName} is {$value}, above {$budgetName}=" . PyFormat::str($limit)); + } + $reached = $reached || $order >= 0; + } + $restartLimit = Json::get($budget, 'max_restarts'); + $starts = Json::get(Json::get($result, 'termination', []), 'starts', []); + $limit = Json::intInstance($restartLimit); + if ($limit !== null && Json::isList($starts)) { + $started = 0; + foreach ($starts as $start) { + if (Json::isDict($start) && Json::get($start, 'started') === true) { + ++$started; + } + } + if ($started > $limit) { + $issues[] = new ResultIssue('effort_budget_exceeded', "started {$started} solver runs, above max_restarts=" . PyFormat::str($restartLimit)); + } + $reached = $reached || $started >= $limit; + } + if ($effortLimited && !$reached) { + $issues[] = new ResultIssue('effort_budget_mismatch', 'effort_limit_reached is true but no configured counted-work boundary was reached'); + } + } + + /** @param mixed $algorithm */ + private static function flag($algorithm, string $name): bool + { + $value = Json::get($algorithm, $name); + if (!\is_bool($value)) { + throw MalformedResult::contract("algorithm.{$name} must be a boolean"); + } + return $value; + } + + /** @param mixed $result */ + private static function factCode($result, string $name): string + { + $fact = Json::at($result, $name); + if (!Json::isDict($fact)) { + throw MalformedResult::contract("{$name} must be an object"); + } + $code = Json::get($fact, 'code'); + if (!\is_string($code) || $code === '') { + throw MalformedResult::contract("{$name}.code must be a non-empty string"); + } + return $code; + } + + /** @param mixed $result @param list $issues */ + public static function checkResultFacts($result, array &$issues): void + { + $algorithm = self::algorithm($result); + $timedOut = self::flag($algorithm, 'time_limit_reached'); + $effortLimited = self::flag($algorithm, 'effort_limit_reached'); + if ($timedOut && $effortLimited) { + $issues[] = new ResultIssue('result_fact_mismatch', 'time_limit_reached and effort_limit_reached cannot both be true'); + } + $termination = Json::at($result, 'termination'); + if (!Json::isDict($termination)) { + throw MalformedResult::contract('termination must be an object'); + } + self::checkStarts($termination, $algorithm, $timedOut, $effortLimited, $issues); + + $status = Json::at($result, 'status'); + $complete = Json::truthy(Json::at($result, 'complete')); + $invalid = Json::isText($status, 'invalid_result'); + $expected = [ + 'feasibility' => Json::isText($status, 'infeasible') ? 'infeasible' : (($complete && !$invalid) ? 'feasible' : 'unknown'), + 'termination' => $invalid ? 'error' : ($timedOut ? 'time_limit' : ($effortLimited ? 'effort_limit' : 'complete')), + 'optimality' => Json::isText($status, 'optimal') ? 'proven_optimal' + : (Json::isText($status, 'infeasible') ? 'proven_infeasible' : ((!$complete && !$invalid) ? 'best_found' : 'not_proven')), + ]; + foreach ($expected as $name => $code) { + $actual = self::factCode($result, $name); + if ($actual !== $code) { + $issues[] = new ResultIssue('result_fact_mismatch', "{$name}.code is " . PyFormat::stringRepr($actual) . ', expected ' . PyFormat::stringRepr($code)); + } + } + } + + /** @param mixed $termination @param mixed $algorithm @param list $issues */ + private static function checkStarts($termination, $algorithm, bool $timedOut, bool $effortLimited, array &$issues): void + { + $starts = Json::get($termination, 'starts'); + if (!Json::isList($starts) || $starts === []) { + $issues[] = new ResultIssue('termination_aggregate_mismatch', 'termination.starts must contain at least one start'); + return; + } + $malformed = false; + foreach ($starts as $start) { + if (!Json::isDict($start) || !\is_string(Json::get($start, 'id'))) { + $malformed = true; + continue; + } + $flags = []; + foreach (['started', 'completed', 'truncated', 'selected', 'global_deadline_reached'] as $name) { + $flags[] = Json::get($start, $name); + } + if (\count(\array_filter($flags, 'is_bool')) !== 5) { + $malformed = true; + continue; + } + [$started, $completed, $truncated] = $flags; + if (($completed && (!$started || $truncated)) || ($truncated && (!$started || $completed)) || (!$started && ($completed || $truncated))) { + $issues[] = new ResultIssue('start_record_mismatch', Json::at($start, 'id') . ': inconsistent lifecycle flags'); + } + } + if ($malformed) { + $issues[] = new ResultIssue('start_record_mismatch', 'a start record is missing its id or boolean lifecycle fields'); + } + $isTrue = static function ($start, string $name): bool { + return Json::isDict($start) && Json::get($start, $name) === true; + }; + $selected = \array_values(\array_filter($starts, static function ($start) use ($isTrue): bool { return $isTrue($start, 'selected'); })); + if (\count($selected) !== 1) { + $issues[] = new ResultIssue('termination_aggregate_mismatch', 'expected one selected start, found ' . \count($selected)); + return; + } + foreach ($starts as $start) { + if (!Json::isDict($start)) { + return; + } + } + $winner = $selected[0]; + $any = static function (string $name) use ($starts, $isTrue): bool { + foreach ($starts as $start) { + if ($isTrue($start, $name)) { + return true; + } + } + return false; + }; + $all = static function (string $name) use ($starts, $isTrue): bool { + foreach ($starts as $start) { + if (!$isTrue($start, $name)) { + return false; + } + } + return true; + }; + $aggregate = [ + 'any_start_truncated' => $any('truncated'), + 'all_required_starts_completed' => $all('completed'), + 'winning_start_truncated' => $isTrue($winner, 'truncated'), + 'global_deadline_reached' => $any('global_deadline_reached'), + ]; + foreach ($aggregate as $name => $expected) { + $reported = Json::get($termination, $name); + if ($reported !== $expected) { + $issues[] = new ResultIssue('termination_aggregate_mismatch', "{$name} is " . PyFormat::repr($reported) . ', expected ' . PyFormat::boolRepr($expected)); + } + } + $solver = Json::get($algorithm, 'solver'); + $selectedId = Json::get($winner, 'id', ''); + if (\is_string($solver) && !Json::isText($selectedId, $solver) + && \strncmp(Json::text($selectedId, 'a start id'), "{$solver}#", \strlen($solver) + 1) !== 0) { + $issues[] = new ResultIssue('winning_start_mismatch', 'selected start ' . PyFormat::repr($selectedId) . ' does not identify solver ' . PyFormat::stringRepr($solver)); + } + if ($aggregate['global_deadline_reached'] && !$timedOut) { + $issues[] = new ResultIssue('legacy_time_limit_mismatch', 'global_deadline_reached requires time_limit_reached'); + } + if (($aggregate['global_deadline_reached'] || $aggregate['winning_start_truncated']) !== ($timedOut || $effortLimited)) { + $issues[] = new ResultIssue('termination_limit_mismatch', 'selected-start truncation must identify exactly one reached limit'); + } + } +} diff --git a/src-legacy/Support/ResultValidation/Geometry.php b/src-legacy/Support/ResultValidation/Geometry.php new file mode 100644 index 0000000..ed76d9d --- /dev/null +++ b/src-legacy/Support/ResultValidation/Geometry.php @@ -0,0 +1,278 @@ + [0, 1, 2], 'LHW' => [0, 2, 1], 'WLH' => [1, 0, 2], + 'WHL' => [1, 2, 0], 'HLW' => [2, 0, 1], 'HWL' => [2, 1, 0], + ]; + + /** `ROTATIONS[orientation]`. @return array{0:int,1:int,2:int} */ + public static function axes(string $orientation): array + { + if (!\array_key_exists($orientation, self::ROTATIONS)) { + throw MalformedResult::shape(\sprintf('unknown orientation "%s"', $orientation)); + } + return self::ROTATIONS[$orientation]; + } + + /** `orientation in ROTATIONS`, for any JSON value; an unhashable one is Python's `TypeError`. @param mixed $orientation */ + public static function isRotation($orientation): bool + { + Json::hashKey($orientation); + return \is_string($orientation) && \array_key_exists($orientation, self::ROTATIONS); + } + + /** @param array $left @param array $right @return array{0:int|string,1:int|string,2:int|string} */ + public static function difference(array $left, array $right): array + { + return [Exact::sub($left[0], $right[0]), Exact::sub($left[1], $right[1]), Exact::sub($left[2], $right[2])]; + } + + /** @param array $left @param array $right @return array{0:int|string,1:int|string,2:int|string} */ + public static function cross(array $left, array $right): array + { + return [ + Exact::sub(Exact::mul($left[1], $right[2]), Exact::mul($left[2], $right[1])), + Exact::sub(Exact::mul($left[2], $right[0]), Exact::mul($left[0], $right[2])), + Exact::sub(Exact::mul($left[0], $right[1]), Exact::mul($left[1], $right[0])), + ]; + } + + /** @param array $left @param array $right @return int|string */ + public static function dot(array $left, array $right) + { + return Exact::add(Exact::add(Exact::mul($left[0], $right[0]), Exact::mul($left[1], $right[1])), Exact::mul($left[2], $right[2])); + } + + /** The axis reduced by its gcd and signed so its first non-zero component is positive. @param array $axis @return array{0:int|string,1:int|string,2:int|string} */ + public static function primitiveAxis(array $axis): array + { + $divisor = Exact::gcd(Exact::gcd($axis[0], $axis[1]), $axis[2]); + if (Exact::sign($divisor) === 0) { + return [0, 0, 0]; + } + $reduced = [Exact::floorDiv($axis[0], $divisor), Exact::floorDiv($axis[1], $divisor), Exact::floorDiv($axis[2], $divisor)]; + foreach ($reduced as $value) { + if (Exact::sign($value) !== 0) { + return Exact::sign($value) < 0 ? [Exact::negate($reduced[0]), Exact::negate($reduced[1]), Exact::negate($reduced[2])] : $reduced; + } + } + return [0, 0, 0]; + } + + /** + * Reorient a hull the way `ROTATIONS` reorients its box, flipping one axis on an odd + * permutation so it stays a proper rotation, then translated so its bounds start at 0. + * + * @param list $vertices + * @param array{0:int,1:int,2:int} $axes + * @return list + */ + public static function rotateHull(array $vertices, array $axes): array + { + $inversions = 0; + for ($first = 0; $first < 3; ++$first) { + for ($second = $first + 1; $second < 3; ++$second) { + if ($axes[$first] > $axes[$second]) { + ++$inversions; + } + } + } + $turned = []; + foreach ($vertices as $vertex) { + $x = $vertex[$axes[0]]; + $turned[] = [$inversions % 2 === 1 ? Exact::negate($x) : $x, $vertex[$axes[1]], $vertex[$axes[2]]]; + } + if ($turned === []) { + throw MalformedResult::shape('a hull without vertices'); + } + $low = []; + for ($axis = 0; $axis < 3; ++$axis) { + $low[$axis] = $turned[0][$axis]; + foreach ($turned as $vertex) { + if (Exact::compare($vertex[$axis], $low[$axis]) < 0) { + $low[$axis] = $vertex[$axis]; + } + } + } + return \array_map(static function (array $vertex) use ($low): array { return self::difference($vertex, $low); }, $turned); + } + + /** Whether two convex solids share interior volume; touching is contact, not collision. @param list $left @param list $right */ + public static function solidsOverlap(array $left, array $right): bool + { + foreach (self::hullAxes($left, $right) as $axis) { + [$leftLow, $leftHigh] = self::extent($left, $axis); + [$rightLow, $rightHigh] = self::extent($right, $axis); + if (Exact::compare($leftHigh, $rightLow) <= 0 || Exact::compare($rightHigh, $leftLow) <= 0) { + return false; + } + } + return true; + } + + /** Exact volume of a convex hull, `6V = sum of a . (b x c)` over its outward faces. @param list $vertices @return int|string */ + public static function hullVolume(array $vertices) + { + $normals = []; + foreach (self::triples($vertices) as [$first, $second, $third]) { + $axis = self::primitiveAxis(self::cross(self::difference($second, $first), self::difference($third, $first))); + if (Exact::sign($axis[0]) !== 0 || Exact::sign($axis[1]) !== 0 || Exact::sign($axis[2]) !== 0) { + $normals[self::axisKey($axis)] = $axis; + } + } + $sixVolumes = 0; + foreach ($normals as $axis) { + foreach ([$axis, [Exact::negate($axis[0]), Exact::negate($axis[1]), Exact::negate($axis[2])]] as $outward) { + [, $highest] = self::extent($vertices, $outward); + $face = []; + foreach ($vertices as $vertex) { + if (Exact::compare(self::dot($vertex, $outward), $highest) === 0) { + $face[] = $vertex; + } + } + if (\count($face) < 3) { + continue; + } + $ordered = self::windFace($face, $outward); + for ($index = 1; $index + 1 < \count($ordered); ++$index) { + $sixVolumes = Exact::add($sixVolumes, self::dot($ordered[0], self::cross($ordered[$index], $ordered[$index + 1]))); + } + } + } + return Exact::floorDiv(Exact::abs($sixVolumes), 6); + } + + /** + * Corners of one planar convex face in cyclic order seen from outside, by gift-wrapping from + * the lexicographically smallest vertex; collinear candidates resolve to the farthest. + * + * @param list $face @param array $outward @return list + */ + private static function windFace(array $face, array $outward): array + { + $start = $face[0]; + foreach ($face as $vertex) { + if (self::compareVertices($vertex, $start) < 0) { + $start = $vertex; + } + } + $ordered = [$start]; + $current = $start; + for ($step = 0, $count = \count($face); $step < $count; ++$step) { + $following = null; + foreach ($face as $candidate) { + if (self::compareVertices($candidate, $current) === 0) { + continue; + } + if ($following === null) { + $following = $candidate; + continue; + } + $turn = self::dot(self::cross(self::difference($following, $current), self::difference($candidate, $current)), $outward); + $reachVector = self::difference($candidate, $current); + $heldVector = self::difference($following, $current); + $reach = self::dot($reachVector, $reachVector); + $held = self::dot($heldVector, $heldVector); + if (Exact::sign($turn) < 0 || (Exact::sign($turn) === 0 && Exact::compare($reach, $held) > 0)) { + $following = $candidate; + } + } + if ($following === null || self::compareVertices($following, $start) === 0) { + break; + } + $ordered[] = $following; + $current = $following; + } + return $ordered; + } + + /** The complete separating-axis superset: face normals of each hull and cross products of their edges. @param list $left @param list $right @return list */ + private static function hullAxes(array $left, array $right): array + { + $axes = []; + foreach ([$left, $right] as $hull) { + foreach (self::triples($hull) as [$first, $second, $third]) { + $axis = self::primitiveAxis(self::cross(self::difference($second, $first), self::difference($third, $first))); + $axes[self::axisKey($axis)] = $axis; + } + } + $rightDirections = self::pairDirections($right); + foreach (self::pairDirections($left) as $one) { + foreach ($rightDirections as $other) { + $axis = self::primitiveAxis(self::cross($one, $other)); + $axes[self::axisKey($axis)] = $axis; + } + } + unset($axes[self::axisKey([0, 0, 0])]); + return \array_values($axes); + } + + /** @param list $points @return list */ + private static function pairDirections(array $points): array + { + $directions = []; + for ($first = 0, $count = \count($points); $first < $count; ++$first) { + for ($second = $first + 1; $second < $count; ++$second) { + $directions[] = self::difference($points[$second], $points[$first]); + } + } + return $directions; + } + + /** Every 3-combination, in `itertools.combinations` order. @param list $points @return \Generator> */ + private static function triples(array $points): \Generator + { + for ($first = 0, $count = \count($points); $first < $count; ++$first) { + for ($second = $first + 1; $second < $count; ++$second) { + for ($third = $second + 1; $third < $count; ++$third) { + yield [$points[$first], $points[$second], $points[$third]]; + } + } + } + } + + /** @param list $points @param array $axis @return array{0:int|string,1:int|string} */ + private static function extent(array $points, array $axis): array + { + $low = $high = null; + foreach ($points as $point) { + $value = self::dot($point, $axis); + if ($low === null || Exact::compare($value, $low) < 0) { + $low = $value; + } + if ($high === null || Exact::compare($value, $high) > 0) { + $high = $value; + } + } + return [$low, $high]; + } + + /** @param array $axis */ + private static function axisKey(array $axis): string + { + return $axis[0] . ',' . $axis[1] . ',' . $axis[2]; + } + + /** @param array $left @param array $right */ + private static function compareVertices(array $left, array $right): int + { + for ($axis = 0; $axis < 3; ++$axis) { + $order = Exact::compare($left[$axis], $right[$axis]); + if ($order !== 0) { + return $order; + } + } + return 0; + } +} diff --git a/src-legacy/Support/ResultValidation/ItemSpec.php b/src-legacy/Support/ResultValidation/ItemSpec.php new file mode 100644 index 0000000..b1ca228 --- /dev/null +++ b/src-legacy/Support/ResultValidation/ItemSpec.php @@ -0,0 +1,77 @@ + */ + public $allowedRotations; + /** @var bool */ + public $stackable; + /** @var bool */ + public $mustBeOnFloor; + /** @var int|string|null */ + public $maxTopLoad; + /** @var Ratio */ + public $minimumSupportRatio; + /** @var array */ + public $tags; + /** @var array */ + public $eligibleContainerTags; + /** @var int|null */ + public $maxStackedItems; + /** @var mixed */ + public $groundContactRule; + /** @var int|string|null */ + public $nestingHeight; + /** @var array */ + public $incompatibleTags; + /** @var int|null */ + public $stopIndex; + /** @var mixed */ + public $value; + /** @var mixed */ + public $shapeType; + /** @var list|null */ + public $hullVertices; + /** @var int|string|null */ + public $compressionRatioPpm; + /** @var int|null */ + public $maxCompressionPressureKpa; + /** @var mixed */ + public $stackingGroup; + /** @var array */ + public $acceptsStackingGroups; + + /** `orientation in allowed_rotations`. @param mixed $orientation */ + public function allows($orientation): bool + { + foreach ($this->allowedRotations as $allowed) { + if (Json::equals($allowed, $orientation)) { + return true; + } + } + return false; + } + + public function isConvexHull(): bool + { + return Json::isText($this->shapeType, 'convex_hull'); + } + + /** @return array{0:int|string,1:int|string,2:int|string} */ + public function rotated(string $orientation): array + { + $axes = Geometry::axes($orientation); + return [$this->dimensions[$axes[0]], $this->dimensions[$axes[1]], $this->dimensions[$axes[2]]]; + } +} diff --git a/src-legacy/Support/ResultValidation/Json.php b/src-legacy/Support/ResultValidation/Json.php new file mode 100644 index 0000000..1517c34 --- /dev/null +++ b/src-legacy/Support/ResultValidation/Json.php @@ -0,0 +1,318 @@ + */ + public static function items($value, string $what): array + { + if (!self::isList($value)) { + throw MalformedResult::shape(\sprintf('%s must be a list, got %s', $what, self::kind($value))); + } + return $value; + } + + /** @param mixed $value */ + public static function text($value, string $what): string + { + if (!\is_string($value)) { + throw MalformedResult::shape(\sprintf('%s must be a string, got %s', $what, self::kind($value))); + } + return $value; + } + + /** + * An integer the reference does arithmetic on. A boolean is Python's `int`; a float would + * carry the reference into float arithmetic this port does not follow, so it is refused. + * + * @param mixed $value + */ + public static function int($value, string $what): int + { + if (\is_int($value)) { + return $value; + } + if (\is_bool($value)) { + return (int)$value; + } + throw MalformedResult::shape(\sprintf('%s must be an integer, got %s', $what, self::kind($value))); + } + + /** @param mixed $value */ + public static function optionalInt($value, string $what): ?int + { + return $value === null ? null : self::int($value, $what); + } + + /** `isinstance(value, int)`, which a boolean satisfies. @param mixed $value */ + public static function intInstance($value): ?int + { + if (\is_int($value)) { + return $value; + } + return \is_bool($value) ? (int)$value : null; + } + + /** `isinstance(value, int) and not isinstance(value, bool)`. @param mixed $value */ + public static function strictInt($value): ?int + { + return \is_int($value) ? $value : null; + } + + /** Python's `int(value)`: a number truncates, a string parses as a base-10 integer. @param mixed $value @return int|string */ + public static function pyInt($value, string $what) + { + if (\is_int($value) || \is_bool($value)) { + return (int)$value; + } + if (\is_float($value) && \is_finite($value)) { + $truncated = $value < 0 ? \ceil($value) : \floor($value); + if (\abs($truncated) < 9.0e18) { + return (int)$truncated; + } + return Exact::normalize(\sprintf('%.0f', $truncated)); + } + if (\is_string($value) && \preg_match('/^\s*([+-]?)(\d+(?:_\d+)*)\s*$/', $value, $parts) === 1) { + $digits = \ltrim(\str_replace('_', '', $parts[2]), '0'); + $magnitude = Exact::normalize($digits === '' ? '0' : $digits); + return $parts[1] === '-' ? Exact::negate($magnitude) : $magnitude; + } + throw MalformedResult::shape(\sprintf('%s: int() cannot convert %s', $what, self::kind($value))); + } + + /** Python truthiness. @param mixed $value */ + public static function truthy($value): bool + { + if ($value === null) { + return false; + } + if (\is_bool($value)) { + return $value; + } + if (\is_int($value) || \is_float($value)) { + return $value != 0; + } + if (\is_string($value)) { + return $value !== ''; + } + return $value !== []; + } + + /** + * Python `==`: a boolean equals its integer, an integer equals the float of the same value, + * containers compare element-wise and objects regardless of key order. + * + * @param mixed $left @param mixed $right + */ + public static function equals($left, $right): bool + { + $leftNumber = self::number($left); + $rightNumber = self::number($right); + if ($leftNumber !== null || $rightNumber !== null) { + return $leftNumber !== null && $rightNumber !== null && self::compareNumbers($leftNumber, $rightNumber) === 0; + } + if ($left === null || $right === null) { + return $left === $right; + } + if (\is_string($left) || \is_string($right)) { + return \is_string($left) && \is_string($right) && $left === $right; + } + if (\count($left) !== \count($right)) { + return false; + } + if (self::isList($left) && self::isList($right)) { + foreach ($left as $index => $element) { + if (!self::equals($element, $right[$index])) { + return false; + } + } + return true; + } + foreach ($left as $key => $element) { + if (!\array_key_exists($key, $right) || !self::equals($element, $right[$key])) { + return false; + } + } + return true; + } + + /** `value == number` for an exact integer. @param mixed $value @param int|string $number */ + public static function equalsInt($value, $number): bool + { + $read = self::number($value); + return $read !== null && self::compareNumbers($read, $number) === 0; + } + + /** `value == text`. @param mixed $value */ + public static function isText($value, string $text): bool + { + return \is_string($value) && $value === $text; + } + + /** + * Python's ordering for what the reference sorts or compares: numbers with numbers, strings + * with strings, lists element-wise. Anything else is Python's `TypeError`. + * + * @param mixed $left @param mixed $right + */ + public static function compare($left, $right): int + { + $leftNumber = self::number($left); + $rightNumber = self::number($right); + if ($leftNumber !== null && $rightNumber !== null) { + return self::compareNumbers($leftNumber, $rightNumber); + } + if (\is_string($left) && \is_string($right)) { + return \strcmp($left, $right) <=> 0; + } + if (self::isList($left) && self::isList($right)) { + foreach ($left as $index => $element) { + if (!\array_key_exists($index, $right)) { + return 1; + } + if (!self::equals($element, $right[$index])) { + return self::compare($element, $right[$index]); + } + } + return \count($left) <=> \count($right); + } + throw MalformedResult::shape(\sprintf('cannot order %s against %s', self::kind($left), self::kind($right))); + } + + /** + * The identity Python hashes a set member or dict key by, so `1`, `1.0` and `True` share one. + * A list or an object is unhashable. + * + * @param mixed $value + */ + public static function hashKey($value): string + { + $number = self::number($value); + if ($number !== null) { + return 'n' . (\is_float($number) ? \sprintf('%.17e', $number) : (string)$number); + } + if ($value === null) { + return 'null'; + } + if (\is_string($value)) { + return 's' . $value; + } + throw MalformedResult::shape(self::kind($value) . ' is unhashable'); + } + + /** Sort values in place by Python's ordering. @param list $values */ + public static function sort(array &$values): void + { + \usort($values, [self::class, 'compare']); + } + + /** @param mixed $value */ + public static function kind($value): string + { + if ($value === null) { + return 'null'; + } + if (\is_bool($value)) { + return 'a boolean'; + } + if (\is_int($value)) { + return 'an integer'; + } + if (\is_float($value)) { + return 'a number'; + } + if (\is_string($value)) { + return 'a string'; + } + return self::isList($value) && $value !== [] ? 'a list' : 'an object'; + } + + /** + * A JSON number as an exact integer when it is one (an integral float within range reads as + * that integer, as Python compares it), else the float. + * + * @param mixed $value @return int|float|null + */ + private static function number($value) + { + if (\is_bool($value)) { + return (int)$value; + } + if (\is_int($value)) { + return $value; + } + if (\is_float($value)) { + return (\floor($value) === $value && \abs($value) < 9.0e18) ? (int)$value : $value; + } + return null; + } + + /** @param int|float|string $left @param int|float|string $right */ + private static function compareNumbers($left, $right): int + { + if (\is_float($left) || \is_float($right)) { + return (float)$left <=> (float)$right; + } + return Exact::compare($left, $right); + } +} diff --git a/src-legacy/Support/ResultValidation/Label.php b/src-legacy/Support/ResultValidation/Label.php new file mode 100644 index 0000000..60a0320 --- /dev/null +++ b/src-legacy/Support/ResultValidation/Label.php @@ -0,0 +1,41 @@ +text = $id === $this ? null : PyFormat::str($id); + } + + public function __toString(): string + { + if ($this->text === null) { + $this->missingUsed = true; + return '?'; + } + return $this->text; + } + + public function verify(): void + { + if ($this->missingUsed) { + throw MalformedResult::shape('a packed container with an issue has no id'); + } + } +} diff --git a/src-legacy/Support/ResultValidation/Lattice.php b/src-legacy/Support/ResultValidation/Lattice.php new file mode 100644 index 0000000..8e80ed0 --- /dev/null +++ b/src-legacy/Support/ResultValidation/Lattice.php @@ -0,0 +1,212 @@ + $items @param Ordered $containers + * @param int|string $clearance @param list $issues + * @return mixed the result with every valid summary expanded into placements + */ + public static function materialize($request, $result, Ordered $items, Ordered $containers, $clearance, array &$issues) + { + $packedContainers = Json::items(Json::at($result, 'containers'), 'result.containers'); + $summarized = false; + foreach ($packedContainers as $packed) { + $summarized = $summarized || Json::has($packed, 'lattice_summary'); + } + if (!$summarized) { + return $result; + } + $optional = Json::get(Json::get($request, 'configuration', []), 'require_placement_coordinates') === false; + foreach ($packedContainers as $index => $packed) { + $placements = self::expand($packed, $optional, $items, $containers, $clearance, $issues); + if ($placements !== null) { + $packedContainers[$index]['placements'] = $placements; + } + } + $result['containers'] = $packedContainers; + return $result; + } + + /** + * @param mixed $packed @param Ordered $items @param Ordered $containers + * @param int|string $clearance @param list $issues + * @return list|null the placements to write into the container, or null to leave it + */ + private static function expand($packed, bool $optional, Ordered $items, Ordered $containers, $clearance, array &$issues): ?array + { + $summary = Json::get($packed, 'lattice_summary'); + if ($summary === null) { + return null; + } + $containerId = PyFormat::str(Json::get($packed, 'id', '?')); + if (!$optional) { + $issues[] = new ResultIssue('unexpected_lattice_summary', "{$containerId}: request requires explicit placement coordinates"); + } + if (Json::truthy(Json::get($packed, 'placements'))) { + $issues[] = new ResultIssue('lattice_placements_conflict', "{$containerId}: compact summary and explicit placements are mutually exclusive"); + } + $itemType = Json::get($summary, 'item_type'); + $item = $items->get($itemType); + $container = $containers->get(Json::get($packed, 'container_type')); + if ($item === null || $container === null) { + // The ordinary accounting and container checks report the unknown reference. + return null; + } + $fields = self::fields($summary, $containerId); + $problems = self::problems($fields, $item, $itemType, $container, $clearance); + if ($problems !== []) { + foreach ($problems as $problem) { + $issues[] = new ResultIssue('lattice_summary_mismatch', "{$containerId}: {$problem}"); + } + return []; + } + return self::synthesize($fields, $summary, $itemType, $containerId, $clearance); + } + + /** @param mixed $summary @return array */ + private static function fields($summary, string $containerId): array + { + try { + $sides = static function (string $key) use ($summary): array { + $block = Json::at($summary, $key); + return \array_map(static function (string $side) use ($block) { + return Json::at(Json::at($block, $side), 'ticks'); + }, self::SIDES); + }; + return [ + 'orientation' => Json::at($summary, 'orientation'), + 'physical' => $sides('physical_dimensions'), + 'envelope' => $sides('envelope_dimensions'), + 'nx' => Json::at($summary, 'nx'), + 'ny' => Json::at($summary, 'ny'), + 'layers_used' => Json::at($summary, 'layers_used'), + 'layer_step' => Json::at(Json::at($summary, 'layer_step'), 'ticks'), + 'count' => Json::at($summary, 'count'), + ]; + } catch (MalformedResult $missing) { + // The reference reports a missing field as a contract break, naming the container. + throw MalformedResult::contract("{$containerId}: lattice_summary is missing a canonical field: {$missing->getMessage()}"); + } + } + + /** @param array $fields @param mixed $itemType @param int|string $clearance @return list */ + private static function problems(array $fields, ItemSpec $item, $itemType, ContainerSpec $container, $clearance): array + { + $problems = []; + $orientation = $fields['orientation']; + if (!Geometry::isRotation($orientation)) { + $problems[] = 'unknown orientation ' . PyFormat::repr($orientation); + } else { + $expected = $item->rotated($orientation); + if (!self::matches($fields['physical'], $expected)) { + $problems[] = 'physical dimensions ' . PyFormat::valueTuple($fields['physical']) . ' != rotated item ' . PyFormat::intTuple($expected); + } + if (!$item->allows($orientation)) { + $problems[] = "orientation {$orientation} is forbidden for " . PyFormat::str($itemType); + } + } + $margin = Exact::mul(2, $clearance); + $expectedEnvelope = []; + foreach ($fields['physical'] as $side) { + $expectedEnvelope[] = Exact::add(Json::int($side, 'physical dimension'), $margin); + } + if (!self::matches($fields['envelope'], $expectedEnvelope)) { + $problems[] = 'envelope dimensions ' . PyFormat::valueTuple($fields['envelope']) . ' != physical+clearance ' . PyFormat::intTuple($expectedEnvelope); + } + if ($item->nestingHeight !== null) { + $problems[] = 'compact lattice form is not valid for nesting items'; + } + if (!Json::equals($fields['layer_step'], $fields['envelope'][2])) { + $problems[] = 'layer_step ' . PyFormat::str($fields['layer_step']) . ' != envelope height ' . PyFormat::str($fields['envelope'][2]); + } + foreach (['nx', 'ny', 'layers_used', 'layer_step', 'count'] as $name) { + $value = Json::strictInt($fields[$name]); + if ($value === null || $value < 1) { + $problems[] = "{$name} must be a positive integer, got " . PyFormat::repr($fields[$name]); + } + } + if ($problems === []) { + self::independentCounts($fields, $item, $container, $problems); + } + return $problems; + } + + /** Reached only once every field is a positive integer and the envelope is the expected one. @param array $fields @param list $problems */ + private static function independentCounts(array $fields, ItemSpec $item, ContainerSpec $container, array &$problems): void + { + $nx = $fields['nx']; + $ny = $fields['ny']; + $layersUsed = $fields['layers_used']; + $layerStep = $fields['layer_step']; + $count = $fields['count']; + $expectedNx = Exact::floorDiv($container->inner[0], $fields['envelope'][0]); + $expectedNy = Exact::floorDiv($container->inner[1], $fields['envelope'][1]); + $expectedLayers = Exact::ceilDiv($count, Exact::mul($nx, $ny)); + if (Exact::compare($nx, $expectedNx) !== 0) { + $problems[] = "nx {$nx} != independently computed {$expectedNx}"; + } + if (Exact::compare($ny, $expectedNy) !== 0) { + $problems[] = "ny {$ny} != independently computed {$expectedNy}"; + } + if (Exact::compare($layersUsed, $expectedLayers) !== 0) { + $problems[] = "layers_used {$layersUsed} != independently computed {$expectedLayers}"; + } + if ($count > Json::int($item->quantity, 'quantity')) { + $problems[] = "count {$count} exceeds requested quantity " . PyFormat::str($item->quantity); + } + $capacity = Exact::floorDiv($container->inner[2], $layerStep); + if (Exact::compare($layersUsed, $capacity) > 0) { + $problems[] = "layers_used {$layersUsed} exceeds vertical capacity {$capacity}"; + } + } + + /** @param array $fields @param mixed $summary @param mixed $itemType @param int|string $clearance @return list */ + private static function synthesize(array $fields, $summary, $itemType, string $containerId, $clearance): array + { + $nx = $fields['nx']; + $ny = $fields['ny']; + $perLayer = $nx * $ny; + $physical = Json::at($summary, 'physical_dimensions'); + $tick = static function ($value): array { return ['ticks' => $value]; }; + $placements = []; + for ($index = 0; $index < $fields['count']; ++$index) { + $placements[] = [ + 'item_id' => PyFormat::str($itemType) . "#lattice:{$containerId}:" . ($index + 1), + 'item_type' => $itemType, + 'orientation' => $fields['orientation'], + 'position' => [ + 'x' => $tick(Exact::add(Exact::mul($index % $nx, $fields['envelope'][0]), $clearance)), + 'y' => $tick(Exact::add(Exact::mul(\intdiv($index, $nx) % $ny, $fields['envelope'][1]), $clearance)), + 'z' => $tick(Exact::add(Exact::mul(\intdiv($index, $perLayer), $fields['layer_step']), $clearance)), + ], + 'dimensions' => $physical, + ]; + } + return $placements; + } + + /** Element-wise `reported == expected` for a tuple of JSON values. @param list $reported @param list $expected */ + private static function matches(array $reported, array $expected): bool + { + foreach ($expected as $index => $value) { + if (!Json::equalsInt($reported[$index], $value)) { + return false; + } + } + return true; + } +} diff --git a/src-legacy/Support/ResultValidation/MachineSpec.php b/src-legacy/Support/ResultValidation/MachineSpec.php new file mode 100644 index 0000000..96690ea --- /dev/null +++ b/src-legacy/Support/ResultValidation/MachineSpec.php @@ -0,0 +1,18 @@ + $last) { + $low = $middle + 1; + } else { + return true; + } + } + return false; + } +} diff --git a/src-legacy/Support/ResultValidation/ObjectiveCheck.php b/src-legacy/Support/ResultValidation/ObjectiveCheck.php new file mode 100644 index 0000000..90fc817 --- /dev/null +++ b/src-legacy/Support/ResultValidation/ObjectiveCheck.php @@ -0,0 +1,314 @@ + $fabricated @param list $issues */ + public static function check($request, $result, Context $context, Ordered $fabricated, array &$issues): void + { + $configuration = Json::get($request, 'configuration', []); + $selected = Json::get($configuration, 'objective', 'default'); + $reportedName = Json::get($result, 'objective'); + if ((Json::has($configuration, 'objective') || $reportedName !== null) && !Json::equals($reportedName, $selected)) { + $issues[] = new ResultIssue('objective_mismatch', 'reported ' . PyFormat::repr($reportedName) . ', requested ' . PyFormat::repr($selected)); + } + $reported = \array_map(static function ($component) { return Json::pyInt($component, 'score'); }, Json::items(Json::at($result, 'score'), 'score')); + $billing = [ + 'divisor' => Json::get($configuration, 'dimensional_weight_divisor'), + 'length_unit' => Json::get($configuration, 'dimensional_weight_length_unit', 'in'), + 'weight_unit' => Json::get($configuration, 'dimensional_weight_weight_unit', 'lb'), + ]; + $recomputed = self::objective($result, $context, $fabricated, $selected, $billing); + $same = \count($reported) === \count($recomputed); + foreach ($recomputed as $index => $value) { + $same = $same && Exact::compare($reported[$index], $value) === 0; + } + if (!$same) { + $issues[] = new ResultIssue('score_mismatch', 'reported ' . PyFormat::intList($reported) . ', recomputed ' . PyFormat::intList($recomputed)); + } + } + + /** + * @param mixed $result @param Ordered $fabricated @param mixed $name + * @param array{divisor:mixed,length_unit:mixed,weight_unit:mixed} $billing + * @return list + */ + private static function objective($result, Context $context, Ordered $fabricated, $name, array $billing): array + { + $cost = $unused = $height = $billable = $achievedHeight = $landed = 0; + $billed = Json::isText($name, 'shipping_cost') || Json::isText($name, 'lowest_landed_cost'); + $containers = Json::items(Json::at($result, 'containers'), 'result.containers'); + foreach ($containers as $packed) { + $spec = $fabricated->get(Json::get($packed, 'id')) ?? $context->containers->get(Json::at($packed, 'container_type')); + if ($spec === null) { + continue; + } + $cost = Exact::add($cost, $spec->costMinor); + $volume = $spec->volume(); + if (Exact::sign($volume) === 0) { + continue; + } + $used = Json::pyInt(Json::at($packed, 'used_volume_ticks3'), 'used_volume_ticks3'); + $unused = Exact::add($unused, Exact::floorDiv(Exact::mul(Exact::sub($volume, $used), ContainerCheck::SCORE_SCALE), $volume)); + $top = null; + foreach (Json::items(Json::at($packed, 'placements'), 'placements') as $placement) { + $z = Json::int(Json::at(Json::at(Json::at($placement, 'position'), 'z'), 'ticks'), 'placement ticks'); + $extent = Json::int(Json::at(Json::at(Json::at($placement, 'dimensions'), 'height'), 'ticks'), 'placement ticks'); + $reach = Exact::add(Exact::add($z, $extent), $context->clearance); + $top = $top === null ? $reach : Exact::max($top, $reach); + } + $top = $top ?? 0; + $height = Exact::add($height, Exact::floorDiv(Exact::mul($top, ContainerCheck::SCORE_SCALE), $spec->inner[2])); + $achievedHeight = Exact::add($achievedHeight, $top); + if ($billed && $billing['divisor'] !== null) { + $gross = Json::pyInt(Json::get(Json::get($packed, 'gross_weight', []), 'ticks', 0), 'gross_weight'); + $size = $spec->flatBag ? ContainerCheck::achievedExtent($packed, $context->clearance) : ($spec->outer ?? $spec->inner); + $dimensional = self::dimensionalWeight( + $size, + Json::int($billing['divisor'], 'dimensional_weight_divisor'), + Json::text($billing['length_unit'], 'dimensional_weight_length_unit'), + Json::text($billing['weight_unit'], 'dimensional_weight_weight_unit') + ); + $charged = Exact::max($gross, $dimensional); + $billable = Exact::add($billable, $charged); + if (Json::isText($name, 'lowest_landed_cost')) { + $landed = Exact::add($landed, self::landedCharge($spec, $charged)); + } + } + } + $unpackedItems = Json::items(Json::at($result, 'unpacked_items'), 'result.unpacked_items'); + $unpacked = \count($unpackedItems); + $opened = \count($containers); + $requiresDivisor = static function (string $objective): MalformedResult { + return MalformedResult::contract("{$objective} objective requires configuration.dimensional_weight_divisor"); + }; + if (!\is_string($name)) { + throw MalformedResult::contract('unknown requested objective ' . PyFormat::repr($name)); + } + switch ($name) { + case 'default': + return [$unpacked, $opened, $cost, $unused, $height]; + case 'lowest_cost': + return [$unpacked, $cost, $opened, $unused, $height]; + case 'shipping_cost': + if ($billing['divisor'] === null) { + throw $requiresDivisor('shipping_cost'); + } + return [$unpacked, $billable, $opened, $unused, $height]; + case 'lowest_landed_cost': + if ($billing['divisor'] === null) { + throw $requiresDivisor('lowest_landed_cost'); + } + return [$unpacked, $landed, $opened, $unused, $height]; + case 'open_dimension_height': + return [$unpacked, $achievedHeight, $opened, $cost, $unused]; + case 'maximum_value': + $forgone = 0; + foreach ($unpackedItems as $item) { + $spec = $context->items->get(Json::at($item, 'item_type')); + if ($spec !== null && Json::truthy($spec->value)) { + $forgone = Exact::add($forgone, Json::int($spec->value, 'value')); + } + } + return [$unpacked, $forgone, $opened, $cost, $unused]; + case 'maximum_volume': + $nominal = static function (ItemSpec $spec) { + return Exact::mul(Exact::mul($spec->dimensions[0], $spec->dimensions[1]), $spec->dimensions[2]); + }; + $unpackedVolume = 0; + foreach ($unpackedItems as $item) { + $spec = $context->items->get(Json::at($item, 'item_type')); + if ($spec !== null) { + $unpackedVolume = Exact::add($unpackedVolume, $nominal($spec)); + } + } + $requested = 0; + foreach ($context->items->values() as $spec) { + $requested = Exact::add($requested, Exact::mul($nominal($spec), Json::int($spec->quantity, 'quantity'))); + } + $unpackedPpm = Exact::sign($requested) === 0 ? 0 : Exact::ceilDiv(Exact::mul($unpackedVolume, ContainerCheck::SCORE_SCALE), $requested); + return [$unpackedPpm, $unpacked, $opened, $cost, $unused]; + } + throw MalformedResult::contract('unknown requested objective ' . PyFormat::repr($name)); + } + + /** `floor(volume * weight ticks per unit / (length ticks per unit ^ 3 * divisor))`. @param array $size @return int|string */ + private static function dimensionalWeight(array $size, int $divisor, string $lengthUnit, string $weightUnit) + { + $length = Units::perUnit(Units::LENGTH, $lengthUnit); + $weight = Units::perUnit(Units::WEIGHT, $weightUnit); + $volume = Exact::mul(Exact::mul($size[0], $size[1]), $size[2]); + return Exact::floorDiv(Exact::mul($volume, $weight), Exact::mul(Exact::mul(Exact::mul($length, $length), $length), $divisor)); + } + + /** + * One container's carrier charge from the request's own rate card: billed weight up to whole + * grams, the minimum charge, then the fuel surcharge rounded up. + * + * @param int|string $billedTicks @return int|string + */ + private static function landedCharge(ContainerSpec $spec, $billedTicks) + { + if ($spec->rateTable === null) { + throw MalformedResult::contract('container ' . PyFormat::repr($spec->id) . ' has no rate_table, so lowest_landed_cost cannot price it'); + } + $table = $spec->rateTable; + $read = static function ($value, string $what) { return Json::pyInt($value, $what); }; + $brackets = \array_map(static function ($bound) use ($read) { return $read($bound, 'bracket'); }, Json::items(Json::at($table, 'weight_brackets_g'), 'weight_brackets_g')); + $prices = \array_map(static function ($price) use ($read) { return $read($price, 'price'); }, Json::items(Json::at($table, 'prices_minor'), 'prices_minor')); + $grams = Exact::ceilDiv($billedTicks, Units::TICKS_PER_GRAM); + foreach ($brackets as $index => $bound) { + if (!\array_key_exists($index, $prices)) { + break; + } + if (Exact::compare($grams, $bound) <= 0) { + $base = Exact::max($prices[$index], $read(Json::get($table, 'minimum_charge_minor', 0), 'minimum_charge_minor')); + $permille = $read(Json::get($table, 'fuel_surcharge_permille', 0), 'fuel_surcharge_permille'); + return Exact::add($base, Exact::ceilDiv(Exact::mul($base, $permille), 1000)); + } + } + if ($brackets === []) { + throw MalformedResult::shape('an empty rate table'); + } + $last = $brackets[\count($brackets) - 1]; + throw MalformedResult::contract('container ' . PyFormat::repr($spec->id) . " bills at {$grams} g, above its rate table's last bracket ({$last} g); the shipment has no published price"); + } + + /** @param mixed $request @param mixed $result @param list $issues */ + public static function checkSolverSelection($request, $result, array &$issues): void + { + $selected = Json::get(Json::get($request, 'configuration', []), 'solvers', []); + if (!Json::truthy($selected)) { + return; + } + $listed = Json::items($selected, 'configuration.solvers'); + $reported = Json::get(Json::at($result, 'algorithm'), 'solver'); + $base = \is_string($reported) ? \explode(':', $reported, 2)[0] : $reported; + foreach ($listed as $solver) { + if (Json::equals($solver, $base)) { + return; + } + } + $issues[] = new ResultIssue('solver_selection_mismatch', 'reported ' . PyFormat::repr($reported) . ', requested one of ' . PyFormat::repr($selected)); + } + + /** A group travels together or not at all: one container, and never half-packed. @param mixed $request @param mixed $result @param list $issues */ + public static function checkGroups($request, $result, array &$issues): void + { + $rawItems = Json::items(Json::at($request, 'items'), 'request.items'); + $groups = new Ordered(); + foreach ($rawItems as $raw) { + if (Json::get($raw, 'group') !== null) { + $groups->set(Json::at($raw, 'id'), Json::at($raw, 'group')); + } + } + if ($groups->count() === 0) { + return; + } + $located = new Ordered(); + $packed = new Ordered(); + foreach (Json::items(Json::at($result, 'containers'), 'result.containers') as $container) { + foreach (Json::items(Json::at($container, 'placements'), 'placements') as $placement) { + $group = $groups->get(Json::at($placement, 'item_type')); + if ($group === null) { + continue; + } + $places = $located->get($group) ?? new Ordered(); + $places->set(Json::at($container, 'id'), true); + $located->set($group, $places); + $packed->set($group, $packed->get($group, 0) + 1); + } + } + $expected = new Ordered(); + foreach ($rawItems as $raw) { + $group = Json::get($raw, 'group'); + if ($group !== null) { + $expected->set($group, Exact::add($expected->get($group, 0), Json::int(Json::get($raw, 'quantity', 1), 'quantity'))); + } + } + $names = $located->keys(); + Json::sort($names); + foreach ($names as $group) { + $places = $located->get($group); + if ($places->count() > 1) { + $where = \array_map(static function ($place): string { return Json::text($place, 'a container id'); }, $places->keys()); + \sort($where, SORT_STRING); + $issues[] = new ResultIssue('group_split', PyFormat::str($group) . ': ' . \implode(', ', $where)); + } + $placed = $packed->get($group, 0); + $wanted = $expected->get($group, 0); + if (Exact::compare($placed, $wanted) !== 0) { + $issues[] = new ResultIssue('group_partially_packed', PyFormat::str($group) . ": {$placed} of {$wanted} placed"); + } + } + } + + /** Every fixed placement is reported where the request put it, and nothing else claims to be. @param mixed $request @param mixed $result @param list $issues */ + public static function checkFixedPlacements($request, $result, string $unit, array &$issues): void + { + $requested = []; + foreach (Json::items(Json::get($request, 'fixed_placements', []), 'fixed_placements') as $entry) { + $containerId = PyFormat::str(Json::at($entry, 'container_type')) . '#' . PyFormat::str(Json::get($entry, 'container_instance', 1)); + $position = Json::get($entry, 'position', []); + $key = [$containerId, Json::at($entry, 'item_type')]; + foreach (['x', 'y', 'z'] as $axis) { + $key[] = Units::toTicks(Json::get($position, $axis, 0), $unit, Units::LENGTH); + } + $key[] = Json::at($entry, 'orientation'); + $requested[self::keyHash($key)] = $key; + } + $reported = []; + $containerTypes = new Ordered(); + foreach (Json::items(Json::at($result, 'containers'), 'result.containers') as $container) { + $containerId = Json::get($container, 'id', ''); + $containerTypes->set($containerId, Json::at($container, 'container_type')); + foreach (Json::items(Json::at($container, 'placements'), 'placements') as $placement) { + if (Json::get($placement, 'fixed') !== true) { + continue; + } + $position = Json::at($placement, 'position'); + $key = [$containerId, Json::at($placement, 'item_type')]; + foreach (['x', 'y', 'z'] as $axis) { + $key[] = Json::at(Json::at($position, $axis), 'ticks'); + } + $key[] = Json::at($placement, 'orientation'); + $reported[self::keyHash($key)] = $key; + } + } + foreach (self::sorted(\array_values($requested)) as $key) { + $containerId = $key[0]; + $hash = \strrpos($containerId, '#'); + $declaredType = $hash === false ? $containerId : (string) \substr($containerId, 0, $hash); + if (!Json::isText($containerTypes->get($containerId), $declaredType)) { + $issues[] = new ResultIssue('fixed_container_missing', $containerId); + } elseif (!\array_key_exists(self::keyHash($key), $reported)) { + $issues[] = new ResultIssue('fixed_placement_moved', PyFormat::str($key[1]) . " fixed in {$containerId} at " . PyFormat::valueTuple([$key[2], $key[3], $key[4]]) . ' ' . PyFormat::str($key[5])); + } + } + $unexpected = \array_values(\array_diff_key($reported, $requested)); + foreach (self::sorted($unexpected) as $key) { + $issues[] = new ResultIssue('unexpected_fixed_placement', PyFormat::str($key[1]) . ' in ' . PyFormat::str($key[0]) . ' at ' . PyFormat::valueTuple([$key[2], $key[3], $key[4]]) . ' ' . PyFormat::str($key[5])); + } + } + + /** @param list $key */ + private static function keyHash(array $key): string + { + return \implode("\0", \array_map([Json::class, 'hashKey'], $key)); + } + + /** @param list> $keys @return list> */ + private static function sorted(array $keys): array + { + Json::sort($keys); + return $keys; + } +} diff --git a/src-legacy/Support/ResultValidation/Ordered.php b/src-legacy/Support/ResultValidation/Ordered.php new file mode 100644 index 0000000..7fdc30b --- /dev/null +++ b/src-legacy/Support/ResultValidation/Ordered.php @@ -0,0 +1,72 @@ + */ + private $entries = []; + /** @var array */ + private $index = []; + + /** @param mixed $key @param T $value */ + public function set($key, $value): void + { + $hashed = Json::hashKey($key); + if (isset($this->index[$hashed])) { + $this->entries[$this->index[$hashed]][1] = $value; + return; + } + $this->index[$hashed] = \count($this->entries); + $this->entries[] = [$key, $value]; + } + + /** @param mixed $key @param T|null $default @return T|null */ + public function get($key, $default = null) + { + $position = $this->position($key); + return $position === null ? $default : $this->entries[$position][1]; + } + + /** @param mixed $key */ + public function has($key): bool + { + return $this->position($key) !== null; + } + + /** The entry's place in insertion order. @param mixed $key */ + public function position($key): ?int + { + return $this->index[Json::hashKey($key)] ?? null; + } + + /** @return list key and value, in insertion order */ + public function entries(): array + { + return $this->entries; + } + + /** @return list */ + public function values(): array + { + return \array_map(static function (array $entry) { return $entry[1]; }, $this->entries); + } + + /** @return list */ + public function keys(): array + { + return \array_map(static function (array $entry) { return $entry[0]; }, $this->entries); + } + + public function count(): int + { + return \count($this->entries); + } +} diff --git a/src-legacy/Support/ResultValidation/PyFormat.php b/src-legacy/Support/ResultValidation/PyFormat.php new file mode 100644 index 0000000..dc130f6 --- /dev/null +++ b/src-legacy/Support/ResultValidation/PyFormat.php @@ -0,0 +1,188 @@ + $element) { + $pairs[] = self::stringRepr((string)$key) . ': ' . self::repr($element); + } + return $value === [] ? '[]' : '{' . \implode(', ', $pairs) . '}'; + } + + /** `[a, b]` from already-formatted elements. @param list $elements */ + public static function listOf(array $elements): string + { + return '[' . \implode(', ', $elements) . ']'; + } + + /** `(a, b)`; a one-element tuple keeps its trailing comma. @param list $elements */ + public static function tupleOf(array $elements): string + { + return \count($elements) === 1 ? '(' . $elements[0] . ',)' : '(' . \implode(', ', $elements) . ')'; + } + + /** @param list $values */ + public static function intTuple(array $values): string + { + return self::tupleOf(\array_map('strval', $values)); + } + + /** @param list $values */ + public static function intList(array $values): string + { + return self::listOf(\array_map('strval', $values)); + } + + /** @param list $values */ + public static function valueTuple(array $values): string + { + return self::tupleOf(\array_map([self::class, 'repr'], $values)); + } + + public static function boolRepr(bool $flag): string + { + return $flag ? 'True' : 'False'; + } + + /** `f"{value:.6f}"`; PHP's `%f` and Python's both round the exact binary value half to even. */ + public static function fixed6(float $value): string + { + return \sprintf('%.6f', $value); + } + + /** + * `repr(float)`: the shortest digits that round-trip, in fixed notation for decimal exponents + * from -4 to 15 and scientific (`1e-05`, `1e+16`) outside that. + */ + public static function floatRepr(float $value): string + { + if (\is_nan($value)) { + return 'nan'; + } + if (\is_infinite($value)) { + return $value > 0 ? 'inf' : '-inf'; + } + // `atan2` is the one portable reading of negative zero's sign: -pi for -0.0, pi for 0.0. + $sign = ($value < 0 || ($value == 0.0 && \atan2($value, -1.0) < 0)) ? '-' : ''; + if ($value == 0.0) { + return $sign . '0.0'; + } + [$digits, $point] = ShortestFloat::digits(\abs($value)); + $exponent = $point - 1; + $count = \strlen($digits); + if ($exponent >= -4 && $exponent < 16) { + if ($point <= 0) { + return $sign . '0.' . \str_repeat('0', -$point) . $digits; + } + if ($count <= $point) { + return $sign . $digits . \str_repeat('0', $point - $count) . '.0'; + } + return $sign . \substr($digits, 0, $point) . '.' . \substr($digits, $point); + } + $fraction = $count > 1 ? '.' . \substr($digits, 1) : ''; + return \sprintf('%s%s%se%s%02d', $sign, $digits[0], $fraction, $exponent < 0 ? '-' : '+', \abs($exponent)); + } + + /** + * `repr(str)`: single quotes unless the text holds a single quote and no double quote, + * Python's escapes for the backslash, the quote, `\t`, `\n`, `\r` and other non-printables. + */ + public static function stringRepr(string $text): string + { + $quote = (\strpos($text, "'") !== false && \strpos($text, '"') === false) ? '"' : "'"; + $out = $quote; + foreach (self::codePoints($text) as [$character, $code]) { + if ($character === '\\') { + $out .= '\\\\'; + } elseif ($character === "\t") { + $out .= '\\t'; + } elseif ($character === "\n") { + $out .= '\\n'; + } elseif ($character === "\r") { + $out .= '\\r'; + } elseif ($character === $quote) { + $out .= '\\' . $character; + } elseif ($code < 0x20 || $code === 0x7f) { + $out .= \sprintf('\\x%02x', $code); + } elseif ($code < 0x7f || self::printable($code)) { + $out .= $character; + } elseif ($code <= 0xff) { + $out .= \sprintf('\\x%02x', $code); + } elseif ($code <= 0xffff) { + $out .= \sprintf('\\u%04x', $code); + } else { + $out .= \sprintf('\\U%08x', $code); + } + } + return $out . $quote; + } + + /** @return list each UTF-8 character and its code point */ + private static function codePoints(string $text): array + { + $characters = \preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY); + if ($characters === false) { + $characters = \str_split($text); + } + $points = []; + foreach ($characters as $character) { + $bytes = \array_values(\unpack('C*', $character)); + $length = \count($bytes); + if ($length === 1) { + $code = $bytes[0]; + } elseif ($length === 2) { + $code = (($bytes[0] & 0x1f) << 6) | ($bytes[1] & 0x3f); + } elseif ($length === 3) { + $code = (($bytes[0] & 0x0f) << 12) | (($bytes[1] & 0x3f) << 6) | ($bytes[2] & 0x3f); + } else { + $code = (($bytes[0] & 0x07) << 18) | (($bytes[1] & 0x3f) << 12) | (($bytes[2] & 0x3f) << 6) | ($bytes[3] & 0x3f); + } + $points[] = [$character, $code]; + } + return $points; + } + + /** Python's `str.isprintable` for a code point at or above U+007F, from the generated table. */ + private static function printable(int $code): bool + { + return !NonPrintable::contains($code); + } +} diff --git a/src-legacy/Support/ResultValidation/Ratio.php b/src-legacy/Support/ResultValidation/Ratio.php new file mode 100644 index 0000000..383221d --- /dev/null +++ b/src-legacy/Support/ResultValidation/Ratio.php @@ -0,0 +1,144 @@ +numerator = $numerator; + $this->denominator = $denominator; + } + + /** @param int|string $numerator @param int|string $denominator */ + public static function of($numerator, $denominator): self + { + if (Exact::sign($denominator) === 0) { + throw MalformedResult::shape('Fraction with a zero denominator'); + } + $divisor = Exact::gcd($numerator, $denominator); + if (Exact::sign($divisor) === 0) { + $divisor = 1; + } + $numerator = Exact::floorDiv($numerator, $divisor); + $denominator = Exact::floorDiv($denominator, $divisor); + if (Exact::sign($denominator) < 0) { + return new self(Exact::negate($numerator), Exact::negate($denominator)); + } + return new self($numerator, $denominator); + } + + /** @param int|string $value */ + public static function integer($value): self + { + return new self($value, 1); + } + + public function add(self $other): self + { + return self::of( + Exact::add(Exact::mul($this->numerator, $other->denominator), Exact::mul($other->numerator, $this->denominator)), + Exact::mul($this->denominator, $other->denominator) + ); + } + + public function mul(self $other): self + { + return self::of(Exact::mul($this->numerator, $other->numerator), Exact::mul($this->denominator, $other->denominator)); + } + + /** @param int|string $value */ + public function mulInt($value): self + { + return $this->mul(self::integer($value)); + } + + public function negate(): self + { + return new self(Exact::negate($this->numerator), $this->denominator); + } + + public function compare(self $other): int + { + return Exact::compare( + Exact::mul($this->numerator, $other->denominator), + Exact::mul($other->numerator, $this->denominator) + ); + } + + /** @param int|string $value */ + public function compareInt($value): int + { + return $this->compare(self::integer($value)); + } + + /** `numerator // denominator`. @return int|string */ + public function floor() + { + return Exact::floorDiv($this->numerator, $this->denominator); + } + + /** + * Python's `float(fraction)`: the nearest double, ties to even. The quotient is taken to 53 + * significant bits exactly and the remainder decides the last one. + */ + public function toFloat(): float + { + $numerator = Exact::abs($this->numerator); + if (Exact::sign($numerator) === 0) { + return 0.0; + } + $denominator = $this->denominator; + $limit = 1 << 53; + if (\is_int($numerator) && \is_int($denominator) && $numerator <= $limit && $denominator <= $limit) { + $value = $numerator / $denominator; + } else { + $value = self::nearestDouble($numerator, $denominator); + } + return Exact::sign($this->numerator) < 0 ? -$value : $value; + } + + /** @param int|string $numerator @param int|string $denominator */ + private static function nearestDouble($numerator, $denominator): float + { + // Scale so the quotient has exactly 53 bits; the float estimate only picks the start. + $shift = 52 - (int)\floor(\log((float)$numerator, 2) - \log((float)$denominator, 2)); + for (;;) { + [$scaledNumerator, $scaledDenominator] = $shift >= 0 + ? [Exact::mul($numerator, Exact::powerOfTwo($shift)), $denominator] + : [$numerator, Exact::mul($denominator, Exact::powerOfTwo(-$shift))]; + $quotient = Exact::floorDiv($scaledNumerator, $scaledDenominator); + if (Exact::compare($quotient, 1 << 52) < 0) { + ++$shift; + continue; + } + if (Exact::compare($quotient, 1 << 53) >= 0) { + --$shift; + continue; + } + break; + } + $remainder = Exact::sub($scaledNumerator, Exact::mul($quotient, $scaledDenominator)); + $order = Exact::compare(Exact::mul($remainder, 2), $scaledDenominator); + if ($order > 0 || ($order === 0 && $quotient % 2 === 1)) { + ++$quotient; + if ($quotient === 1 << 53) { + $quotient = 1 << 52; + --$shift; + } + } + return (float)$quotient * \pow(2.0, -$shift); + } +} diff --git a/src-legacy/Support/ResultValidation/Spec.php b/src-legacy/Support/ResultValidation/Spec.php new file mode 100644 index 0000000..f255c6a --- /dev/null +++ b/src-legacy/Support/ResultValidation/Spec.php @@ -0,0 +1,215 @@ + */ + public static function items($request, string $unit): Ordered + { + $items = new Ordered(); + foreach (Json::items(Json::at($request, 'items'), 'request.items') as $raw) { + $rotations = Json::get($raw, 'allowed_rotations'); + if ($rotations === null) { + $rotations = Json::truthy(Json::get($raw, 'keep_upright')) ? self::UPRIGHT_ROTATIONS : \array_keys(Geometry::ROTATIONS); + } else { + $rotations = Json::items($rotations, 'allowed_rotations'); + } + $id = Json::at($raw, 'id'); + $spec = new ItemSpec(); + $spec->id = Json::text($id, 'an item id'); + $spec->dimensions = Units::dimensions(Json::at($raw, 'dimensions'), $unit); + $spec->weight = Units::toTicks(Json::get($raw, 'weight', 0), 'g', Units::WEIGHT); + $spec->quantity = Json::get($raw, 'quantity', 1); + $spec->allowedRotations = \array_values($rotations); + $spec->stackable = Json::truthy(Json::get($raw, 'stackable', true)); + $spec->mustBeOnFloor = Json::truthy(Json::get($raw, 'must_be_on_floor')); + $spec->maxTopLoad = self::measured($raw, 'max_top_load', 'g', Units::WEIGHT); + $spec->minimumSupportRatio = Units::ratioOf(Json::get($raw, 'minimum_support_ratio', 0)); + $spec->tags = self::tagSet(Json::get($raw, 'tags', []), 'tags'); + $spec->eligibleContainerTags = self::tagSet(Json::get($raw, 'eligible_container_tags', []), 'eligible_container_tags'); + $spec->maxStackedItems = Json::optionalInt(Json::get($raw, 'max_stacked_items'), 'max_stacked_items'); + $spec->groundContactRule = Json::get($raw, 'ground_contact_rule'); + $spec->nestingHeight = self::measured($raw, 'nesting_height', $unit, Units::LENGTH); + $spec->incompatibleTags = self::tagSet(Json::get($raw, 'incompatible_tags', []), 'incompatible_tags'); + $spec->stopIndex = Json::optionalInt(Json::get($raw, 'stop_index'), 'stop_index'); + $spec->value = Json::get($raw, 'value'); + $spec->shapeType = Json::get($raw, 'shape_type', 'rigid_cuboid'); + $spec->hullVertices = self::hull($raw, $unit); + $ratio = Json::get($raw, 'compression_ratio'); + // The solvers' ratio rule, applied once: floor(ratio * 1000000 + 0.5) on the double. + $spec->compressionRatioPpm = $ratio === null ? null + : ContainerCheck::ratioPpm(Units::ratioOf($ratio)); + $spec->maxCompressionPressureKpa = Json::optionalInt(Json::get($raw, 'max_compression_pressure_kpa'), 'max_compression_pressure_kpa'); + $spec->stackingGroup = Json::get($raw, 'stacking_group'); + $accepted = Json::get($raw, 'accepts_stacking_groups'); + $spec->acceptsStackingGroups = Json::truthy($accepted) ? self::tagSet($accepted, 'accepts_stacking_groups') : []; + $items->set($id, $spec); + } + return $items; + } + + /** @param mixed $request @return Ordered */ + public static function containers($request, string $unit): Ordered + { + $containers = new Ordered(); + foreach (Json::items(Json::at($request, 'containers'), 'request.containers') as $raw) { + $spec = new ContainerSpec(); + $spec->id = Json::at($raw, 'id'); + $spec->inner = Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit); + $spec->accessDirections = self::accessDirections($raw); + $outer = Json::get($raw, 'outer_dimensions'); + $spec->outer = $outer === null ? null : Units::dimensions($outer, $unit); + $spec->costMinor = Json::int(Json::get($raw, 'cost_minor', 0), 'cost_minor'); + $spec->maxPayload = self::measured($raw, 'max_payload', 'g', Units::WEIGHT); + $spec->maxItems = Json::optionalInt(Json::get($raw, 'max_items'), 'max_items'); + $spec->quantity = Json::optionalInt(Json::get($raw, 'quantity'), 'quantity'); + $spec->obstacles = self::obstacles($raw, $unit); + $spec->tags = self::tagSet(Json::get($raw, 'tags', []), 'tags'); + $spec->tagLimits = self::tagLimits($raw); + $spec->voidFillReserveRatio = Units::ratioOf(Json::get($raw, 'void_fill_reserve_ratio', 0)); + $spec->tareWeight = Units::toTicks(Json::get($raw, 'tare_weight', 0), 'g', Units::WEIGHT); + $spec->axles = self::axles($raw, $unit); + $spec->maxStackDensity = self::measured($raw, 'max_stack_density', 'g', Units::WEIGHT); + $spec->rateTable = Json::get($raw, 'rate_table'); + $spec->flatBag = Json::get($raw, 'deformable_boundary') !== null; + $spec->reportsAchievedExtent = $spec->flatBag || Json::get($raw, 'made_to_measure') !== null; + $machine = Json::get($raw, 'made_to_measure'); + $spec->madeToMeasure = $machine === null ? null : self::machine($machine, $unit); + $containers->set($spec->id, $spec); + } + return $containers; + } + + /** `None if raw.get(key) is None else to_ticks(...)`. @param mixed $raw @param array $table @return int|string|null */ + private static function measured($raw, string $key, string $unit, array $table) + { + $value = Json::get($raw, $key); + return $value === null ? null : Units::toTicks($value, $unit, $table); + } + + /** `frozenset(value)` of a request's tag list; the contract's tags are strings. @param mixed $value @return array */ + private static function tagSet($value, string $what): array + { + $tags = []; + foreach (Json::items($value, $what) as $tag) { + $tags[Json::text($tag, $what)] = true; + } + return $tags; + } + + /** @param mixed $raw @return list|null */ + private static function hull($raw, string $unit): ?array + { + $declared = Json::get($raw, 'hull_vertices'); + if ($declared === null) { + return null; + } + $vertices = []; + foreach (Json::items($declared, 'hull_vertices') as $vertex) { + $vertices[] = [ + Units::toTicks(Json::at($vertex, 'x'), $unit, Units::LENGTH), + Units::toTicks(Json::at($vertex, 'y'), $unit, Units::LENGTH), + Units::toTicks(Json::at($vertex, 'z'), $unit, Units::LENGTH), + ]; + } + return $vertices; + } + + /** @param mixed $raw @return list */ + private static function accessDirections($raw): array + { + $declared = Json::items(Json::get($raw, 'access_directions', []), 'access_directions'); + foreach ($declared as $direction) { + Json::hashKey($direction); + } + return \array_values(\array_filter(self::EXIT_DIRECTIONS, static function (string $direction) use ($declared): bool { + foreach ($declared as $named) { + if (Json::isText($named, $direction)) { + return true; + } + } + return false; + })); + } + + /** @param mixed $raw @return list */ + private static function obstacles($raw, string $unit): array + { + $boxes = []; + foreach (Json::items(Json::get($raw, 'obstacles', []), 'obstacles') as $obstacle) { + $additional = Json::items(Json::get($obstacle, 'additional_boxes', []), 'additional_boxes'); + foreach (\array_merge([$obstacle], $additional) as $component) { + $origin = Json::get($component, 'origin', []); + [$length, $width, $height] = Units::dimensions(Json::at($component, 'dimensions'), $unit); + $boxes[] = new Cuboid( + Units::toTicks(Json::get($origin, 'x', 0), $unit, Units::LENGTH), + Units::toTicks(Json::get($origin, 'y', 0), $unit, Units::LENGTH), + Units::toTicks(Json::get($origin, 'z', 0), $unit, Units::LENGTH), + $length, + $width, + $height + ); + } + } + return $boxes; + } + + /** `{str(tag): int(limit)}`, sorted by tag as the reference iterates it. @param mixed $raw @return list */ + private static function tagLimits($raw): array + { + $declared = Json::get($raw, 'tag_limits', []); + if (!Json::isDict($declared)) { + throw MalformedResult::shape('tag_limits must be an object'); + } + $limits = []; + foreach ($declared as $tag => $limit) { + $limits[] = [(string)$tag, Json::pyInt($limit, 'tag_limits')]; + } + \usort($limits, static function (array $a, array $b): int { return \strcmp($a[0], $b[0]); }); + return $limits; + } + + /** @param mixed $raw @return list|null */ + private static function axles($raw, string $unit): ?array + { + $declared = Json::get($raw, 'axles'); + if ($declared === null) { + return null; + } + $axles = []; + foreach (Json::items($declared, 'axles') as $axle) { + $axles[] = [ + Units::toTicks(Json::at($axle, 'position'), $unit, Units::LENGTH), + self::measured($axle, 'max_load', 'g', Units::WEIGHT), + ]; + } + return $axles; + } + + /** @param mixed $raw */ + private static function machine($raw, string $unit): MachineSpec + { + $sides = static function (string $name) use ($raw, $unit): array { + $value = Json::get($raw, $name); + return $value === null ? [0, 0, 0] : Units::dimensions($value, $unit); + }; + $machine = new MachineSpec(); + $machine->minimum = $sides('minimum'); + $machine->increment = $sides('increment'); + $price = Json::get($raw, 'cost_per_square_metre_minor'); + $machine->pricePerSquareMetreMinor = Json::truthy($price) ? Json::int($price, 'cost_per_square_metre_minor') : 0; + $tare = Json::get($raw, 'tare_per_square_metre'); + $machine->tarePerSquareMetre = $tare === null ? 0 : Units::toTicks($tare, 'g', Units::WEIGHT); + $machine->allowance = $sides('outer_allowance'); + return $machine; + } +} diff --git a/src-legacy/Support/ResultValidation/Stacking.php b/src-legacy/Support/ResultValidation/Stacking.php new file mode 100644 index 0000000..ef43d03 --- /dev/null +++ b/src-legacy/Support/ResultValidation/Stacking.php @@ -0,0 +1,455 @@ + $entries + * @return array{0:list>,1:list>} supporters and the items directly above each + */ + public static function supportGraph(array $entries): array + { + $byTop = []; + foreach ($entries as $index => $entry) { + $byTop[(string)$entry->envelope->z2][] = $index; + } + $supporters = \array_fill(0, \count($entries), []); + foreach ($entries as $upper => $entry) { + foreach ($byTop[(string)$entry->envelope->z] ?? [] as $lower) { + if ($lower === $upper) { + continue; + } + $area = $entries[$lower]->envelope->overlapAreaXy($entry->envelope); + if (Exact::sign($area) > 0) { + $supporters[$upper][] = [$lower, $area]; + } + } + } + + $groupKeys = []; + $groups = []; + foreach ($entries as $index => $entry) { + if ($entry->spec === null || $entry->spec->nestingHeight === null) { + continue; + } + $envelope = $entry->envelope; + $key = Json::hashKey(Json::at($entry->placement, 'item_type')) . "\0" . \implode(',', [ + $envelope->x, $envelope->y, $envelope->x2, $envelope->y2, $entry->spec->nestingHeight, + ]); + $groupKeys[$index] = $key; + $groups[$key][] = $index; + } + $predecessors = []; + foreach ($groups as $group) { + \usort($group, static function (int $a, int $b) use ($entries): int { + return Exact::compare($entries[$a]->envelope->z, $entries[$b]->envelope->z) ?: $a <=> $b; + }); + for ($position = 0; $position + 1 < \count($group); ++$position) { + [$lower, $upper] = [$group[$position], $group[$position + 1]]; + $nesting = $entries[$lower]->spec->nestingHeight; + if (Exact::compare(Exact::sub($entries[$lower]->envelope->z2, $entries[$upper]->envelope->z), $nesting) === 0) { + $predecessors[$upper] = $lower; + } + } + } + foreach ($predecessors as $upper => $lower) { + $key = $groupKeys[$upper]; + $edges = \array_values(\array_filter($supporters[$upper], static function (array $edge) use ($groupKeys, $key): bool { + return ($groupKeys[$edge[0]] ?? null) !== $key; + })); + $position = \count($edges); + foreach ($edges as $at => $edge) { + if ($edge[0] > $lower) { + $position = $at; + break; + } + } + \array_splice($edges, $position, 0, [[$lower, $entries[$upper]->envelope->baseArea]]); + $supporters[$upper] = $edges; + } + + $directAbove = \array_fill(0, \count($entries), []); + foreach ($supporters as $upper => $edges) { + foreach ($edges as [$lower]) { + $directAbove[$lower][$upper] = true; + } + } + return [$supporters, $directAbove]; + } + + /** + * @param list $entries @param list> $supporters + * @param list> $directAbove @param list $issues + */ + public static function checkSupportAndLoad(array $entries, array $supporters, array $directAbove, Ratio $globalSupport, array &$issues): void + { + foreach ($entries as $index => $entry) { + $spec = $entry->spec; + if ($spec === null || Exact::sign($entry->envelope->z) === 0) { + continue; + } + $itemId = PyFormat::str($entry->id); + $supporting = $supporters[$index]; + $required = $globalSupport->compare($spec->minimumSupportRatio) < 0 ? $spec->minimumSupportRatio : $globalSupport; + self::checkGroundContact($itemId, $entry->envelope, $supporting, $entries, $spec->groundContactRule, $issues); + if ($required->compareInt(0) > 0) { + $area = Exact::sum(\array_map(static function (array $edge) { return $edge[1]; }, $supporting)); + if (Exact::compare($area, self::requiredSupportArea($entry->envelope->baseArea, ContainerCheck::ratioPpm($required))) < 0) { + $ratio = Ratio::of($area, $entry->envelope->baseArea); + $issues[] = new ResultIssue('insufficient_support', "{$itemId}: " . PyFormat::fixed6($ratio->toFloat()) . ' < ' . PyFormat::fixed6($required->toFloat())); + } + } + foreach ($supporting as [$lower]) { + $lowerSpec = $entries[$lower]->spec; + if ($lowerSpec === null) { + continue; + } + $lowerId = PyFormat::str($entries[$lower]->id); + if (!$lowerSpec->stackable) { + $issues[] = new ResultIssue('non_stackable', "{$itemId} rests on {$lowerId}"); + } elseif ($lowerSpec->acceptsStackingGroups !== [] && !Accounting::holds($lowerSpec->acceptsStackingGroups, $spec->stackingGroup)) { + $issues[] = new ResultIssue('stacking_group_incompatible', "{$itemId} rests on {$lowerId}"); + } + if ($lowerSpec->maxTopLoad !== null && Exact::compare($spec->weight, $lowerSpec->maxTopLoad) > 0) { + $issues[] = new ResultIssue('top_load_exceeded', "{$itemId} ({$spec->weight} ticks) on {$lowerId} (limit {$lowerSpec->maxTopLoad})"); + } + } + } + foreach ($entries as $index => $entry) { + if ($entry->spec === null || $entry->spec->maxStackedItems === null) { + continue; + } + $descendants = []; + $pending = \array_keys($directAbove[$index]); + while ($pending !== []) { + $above = \array_pop($pending); + if (isset($descendants[$above])) { + continue; + } + $descendants[$above] = true; + foreach (\array_keys($directAbove[$above]) as $next) { + $pending[] = $next; + } + } + if (\count($descendants) > $entry->spec->maxStackedItems) { + $issues[] = new ResultIssue('max_stacked_items_exceeded', PyFormat::str($entry->id) . ': ' . \count($descendants) . " above > limit {$entry->spec->maxStackedItems}"); + } + } + } + + /** Exact `floor(baseArea * ppm / 10^6)`, the least supported area the ratio allows. @param int|string $baseArea @return int|string */ + private static function requiredSupportArea($baseArea, int $ppm) + { + return Exact::floorDiv(Exact::mul($baseArea, $ppm), ContainerCheck::SCORE_SCALE); + } + + /** @param list $supporting @param list $entries @param mixed $rule @param list $issues */ + private static function checkGroundContact(string $itemId, Cuboid $envelope, array $supporting, array $entries, $rule, array &$issues): void + { + if ($rule === null || Json::isText($rule, 'free')) { + return; + } + if (Json::isText($rule, 'covered')) { + $corners = [[$envelope->x, $envelope->y], [$envelope->x2, $envelope->y], [$envelope->x, $envelope->y2], [$envelope->x2, $envelope->y2]]; + foreach ($corners as [$x, $y]) { + $covered = false; + foreach ($supporting as [$lower]) { + $surface = $entries[$lower]->envelope; + if (Exact::compare($surface->x, $x) <= 0 && Exact::compare($x, $surface->x2) <= 0 + && Exact::compare($surface->y, $y) <= 0 && Exact::compare($y, $surface->y2) <= 0) { + $covered = true; + break; + } + } + if (!$covered) { + $issues[] = new ResultIssue('ground_contact_violation', "{$itemId}: covered requires all four base corners"); + return; + } + } + } elseif (Json::isText($rule, 'single') && \count($supporting) !== 1) { + $issues[] = new ResultIssue('ground_contact_violation', "{$itemId}: single has " . \count($supporting) . ' supporters'); + } elseif (Json::isText($rule, 'multiple') && \count($supporting) < 2) { + $issues[] = new ResultIssue('ground_contact_violation', "{$itemId}: multiple has " . \count($supporting) . ' supporters'); + } + } + + /** + * Cumulative weight each item bears from everything resting on it, split across supporters by + * contact area and conserved exactly (the remainder goes to the last supporter), top-down. + * + * @param list $entries @param list> $supporters + * @return list + */ + public static function propagateLoad(array $entries, array $supporters): array + { + $order = \array_keys($entries); + \usort($order, static function (int $a, int $b) use ($entries): int { + $left = $entries[$a]->envelope; + $right = $entries[$b]->envelope; + return Exact::compare($right->z2, $left->z2) ?: (Exact::compare($right->z, $left->z) ?: Json::compare($entries[$a]->id, $entries[$b]->id)); + }); + $loads = \array_fill(0, \count($entries), 0); + foreach ($order as $upper) { + $spec = $entries[$upper]->spec; + if ($spec === null) { + continue; + } + $supports = $supporters[$upper]; + $totalArea = Exact::sum(\array_map(static function (array $edge) { return $edge[1]; }, $supports)); + if (Exact::sign($totalArea) === 0) { + continue; + } + $downward = Exact::add($spec->weight, $loads[$upper]); + $assigned = 0; + foreach ($supports as $position => [$lower, $area]) { + $share = $position === \count($supports) - 1 + ? Exact::sub($downward, $assigned) + : Exact::floorDiv(Exact::mul($downward, $area), $totalArea); + $assigned = Exact::add($assigned, $share); + $loads[$lower] = Exact::add($loads[$lower], $share); + } + } + return $loads; + } + + /** + * The pressure a footprint carries, in kPa, exactly: + * `load * g * (ticks per metre)^2 / (ticks per kg * g denominator * Pa per kPa * area)`. + * + * @param int|string $load @param int|string $baseArea + */ + private static function pressure($load, $baseArea): Ratio + { + return Ratio::of( + Exact::mul($load, Exact::mul(980665, self::SQUARE_METRE_TICKS)), + Exact::mul(Exact::mul(Units::TICKS_PER_KG, 100000000), $baseArea) + ); + } + + /**: no `compressible` item may carry more pressure than it declared. @param list $entries @param list $loads @param list $issues */ + public static function checkCrush(Label $packedId, array $entries, array $loads, array &$issues): void + { + foreach ($entries as $index => $entry) { + $limit = $entry->spec === null ? null : $entry->spec->maxCompressionPressureKpa; + if ($limit === null) { + continue; + } + $pressure = self::pressure($loads[$index], $entry->envelope->baseArea); + if ($pressure->compareInt($limit) > 0) { + $issues[] = new ResultIssue('crush_violation', PyFormat::str($entry->id) . " in {$packedId}: " . PyFormat::fixed6($pressure->toFloat()) . " kPa exceeds {$limit} kPa"); + } + } + } + + /** + * Occupied height under load, rounded up, never below one tick. A crushed item keeps its + * height: `checkCrush` already reports it. + * + * @param int|string $load @return int|string + */ + public static function compressedHeight(Cuboid $envelope, ItemSpec $spec, $load) + { + $limit = $spec->maxCompressionPressureKpa; + if ($limit === null) { + return $envelope->height; + } + if ($spec->compressionRatioPpm === null) { + // The reference asserts the pair: a pressure limit without a ratio is not a request it reads. + throw MalformedResult::shape("{$spec->id}: max_compression_pressure_kpa without compression_ratio"); + } + $pressure = self::pressure($load, $envelope->baseArea); + if ($pressure->compareInt($limit) > 0 || $limit === 0) { + return $envelope->height; + } + $divisor = Exact::mul(Exact::mul($limit, 1000000), $pressure->denominator); + $retained = Exact::sub($divisor, Exact::mul($spec->compressionRatioPpm, $pressure->numerator)); + return Exact::max(1, Exact::ceilDiv(Exact::mul($envelope->height, $retained), $divisor)); + } + + /**: weight per square metre of an item's own base, at every level of the stack. @param list $entries @param list $loads @param int|string $maxDensity @param list $issues */ + public static function checkStackDensity(Label $packedId, array $entries, array $loads, $maxDensity, array &$issues): void + { + foreach ($entries as $index => $entry) { + if ($entry->spec === null) { + continue; + } + $total = Exact::add($entry->spec->weight, $loads[$index]); + if (Exact::compare(Exact::mul($total, self::SQUARE_METRE_TICKS), Exact::mul($maxDensity, $entry->envelope->baseArea)) > 0) { + $issues[] = new ResultIssue('stack_density_exceeded', PyFormat::str($entry->id) . " in {$packedId}: {$total} ticks over {$entry->envelope->baseArea} ticks^2 exceeds {$maxDensity} ticks/m^2"); + } + } + } + + /** + * Items due at an earlier stop must all be removable -- unblocked from + * above and slidable out a door (all six walls when the container names none) -- before the + * route moves on. + * + * @param list $entries @param list> $directAbove + * @param array $container @param list $doors @param list $issues + */ + public static function checkRouteRemovalOrder(Label $packedId, array $entries, array $directAbove, array $container, array $doors, array &$issues): void + { + $stops = []; + foreach ($entries as $index => $entry) { + if ($entry->spec !== null && $entry->spec->stopIndex !== null) { + $stops[$index] = $entry->spec->stopIndex; + } + } + if ($stops === []) { + return; + } + $directions = $doors === [] ? Spec::EXIT_DIRECTIONS : $doors; + $present = \array_fill_keys(\array_keys($entries), true); + $distinct = \array_values(\array_unique($stops)); + \sort($distinct); + foreach ($distinct as $stop) { + $due = []; + foreach ($stops as $index => $value) { + if ($value === $stop && isset($present[$index])) { + $due[$index] = true; + } + } + while ($due !== []) { + $chosen = null; + foreach (\array_keys($due) as $item) { + if (\array_intersect_key($directAbove[$item], $present) !== []) { + continue; + } + if (self::hasClearExit($item, $entries, $present, $container, $directions) + && ($chosen === null || Json::compare($entries[$item]->id, $entries[$chosen]->id) < 0)) { + $chosen = $item; + } + } + if ($chosen === null) { + $names = \array_map(static function (int $index) use ($entries) { return $entries[$index]->id; }, \array_keys($due)); + Json::sort($names); + $listed = PyFormat::listOf(\array_map([PyFormat::class, 'repr'], $names)); + $issues[] = new ResultIssue('unloading_order_violation', "{$packedId}: stop {$stop} cannot fully unload {$listed} before the route moves on"); + return; + } + unset($present[$chosen], $due[$chosen]); + } + } + } + + /** @param list $entries @param array $present @param array $container @param list $directions */ + private static function hasClearExit(int $item, array $entries, array $present, array $container, array $directions): bool + { + foreach ($directions as $direction) { + $region = self::sweptRegion($entries[$item]->envelope, $container, $direction); + $blocked = false; + foreach (\array_keys($present) as $other) { + if ($other !== $item && $region->intersects($entries[$other]->envelope)) { + $blocked = true; + break; + } + } + if (!$blocked) { + return true; + } + } + return false; + } + + /** @param array $container */ + private static function sweptRegion(Cuboid $envelope, array $container, string $direction): Cuboid + { + [$x1, $y1, $z1, $x2, $y2, $z2] = [$envelope->x, $envelope->y, $envelope->z, $envelope->x2, $envelope->y2, $envelope->z2]; + if ($direction === '+x') { + [$x1, $x2] = [$x2, $container[0]]; + } elseif ($direction === '-x') { + [$x1, $x2] = [0, $x1]; + } elseif ($direction === '+y') { + [$y1, $y2] = [$y2, $container[1]]; + } elseif ($direction === '-y') { + [$y1, $y2] = [0, $y1]; + } elseif ($direction === '+z') { + [$z1, $z2] = [$z2, $container[2]]; + } else { + [$z1, $z2] = [0, $z1]; + } + return new Cuboid($x1, $y1, $z1, Exact::sub($x2, $x1), Exact::sub($y2, $y1), Exact::sub($z2, $z1)); + } + + /** Whether two stacked instances form a valid nested column. */ + public static function validNesting(Entry $left, Entry $right): bool + { + if ($left->spec === null || $right->spec === null || $left->spec->nestingHeight === null) { + return false; + } + $nesting = $left->spec->nestingHeight; + if ($left->spec->id !== $right->spec->id + || !Json::equals(Json::at($left->placement, 'item_type'), Json::at($right->placement, 'item_type')) + || $right->spec->nestingHeight === null || Exact::compare($right->spec->nestingHeight, $nesting) !== 0) { + return false; + } + $a = $left->envelope; + $b = $right->envelope; + foreach (['x', 'y', 'x2', 'y2'] as $edge) { + if (Exact::compare($a->{$edge}, $b->{$edge}) !== 0) { + return false; + } + } + [$lower, $upper] = Exact::compare($a->z, $b->z) <= 0 ? [$a, $b] : [$b, $a]; + return Exact::compare($lower->z, $upper->z) !== 0 && Exact::compare(Exact::sub($lower->z2, $upper->z), $nesting) === 0; + } + + /** Space a placement actually takes: its compressed box, its hull, or its box. @param mixed $placement @param int|string $load @return int|string */ + public static function occupiedVolume(Cuboid $envelope, $placement, ?ItemSpec $spec, $load) + { + if ($spec !== null && $spec->maxCompressionPressureKpa !== null) { + return Exact::mul($envelope->baseArea, self::compressedHeight($envelope, $spec, $load)); + } + if ($spec !== null && $spec->isConvexHull() && $spec->hullVertices !== null) { + return Geometry::hullVolume(Geometry::rotateHull($spec->hullVertices, Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')))); + } + $solid = self::placedHull($envelope, $placement, $spec); + if ($solid === $envelope->vertices()) { + $dimensions = Json::at($placement, 'dimensions'); + $side = static function (string $name) use ($dimensions): int { + return Json::int(Json::at(Json::at($dimensions, $name), 'ticks'), 'a placement dimension'); + }; + return Exact::mul(Exact::mul($side('length'), $side('width')), $side('height')); + } + return Geometry::hullVolume($solid); + } + + /** + * The solid a placement occupies, as vertices in container coordinates: the exact hull when the + * request allows it and the reported box matches, otherwise the envelope's corners. + * + * @param mixed $placement @return list + */ + public static function placedHull(Cuboid $envelope, $placement, ?ItemSpec $spec): array + { + if ($spec === null || $spec->hullVertices === null || !$spec->isConvexHull() || $spec->stopIndex !== null) { + return $envelope->vertices(); + } + $axes = Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')); + $rotated = [$spec->dimensions[$axes[0]], $spec->dimensions[$axes[1]], $spec->dimensions[$axes[2]]]; + if (Exact::compare($envelope->length, $rotated[0]) !== 0 || Exact::compare($envelope->width, $rotated[1]) !== 0 + || Exact::compare($envelope->height, $rotated[2]) !== 0) { + return $envelope->vertices(); + } + return \array_map(static function (array $vertex) use ($envelope): array { + return [Exact::add($envelope->x, $vertex[0]), Exact::add($envelope->y, $vertex[1]), Exact::add($envelope->z, $vertex[2])]; + }, Geometry::rotateHull($spec->hullVertices, $axes)); + } +} diff --git a/src-legacy/Support/ResultValidation/Units.php b/src-legacy/Support/ResultValidation/Units.php new file mode 100644 index 0000000..cdf6e54 --- /dev/null +++ b/src-legacy/Support/ResultValidation/Units.php @@ -0,0 +1,197 @@ + 16000, 'cm' => 160000, 'm' => 16000000, 'in' => 406400, 'inch' => 406400, + 'inches' => 406400, 'ft' => 4876800, 'tick' => 1, 'ticks' => 1, + ]; + + /** Weight ticks per unit. One tick is 1/8 microgram. */ + public const WEIGHT = [ + 'mg' => 8000, 'g' => 8000000, 'kg' => 8000000000, 'oz' => 226796185, + 'lb' => 3628738960, 'lbs' => 3628738960, 'tick' => 1, 'ticks' => 1, + ]; + + public const TICKS_PER_MM = 16000; + public const TICKS_PER_GRAM = 8000000; + public const TICKS_PER_KG = 8000000000; + + /** `table[unit]`, an exact key. @param array $table */ + public static function perUnit(array $table, string $unit): int + { + if (!\array_key_exists($unit, $table)) { + throw MalformedResult::shape(\sprintf('unknown unit "%s"', $unit)); + } + return $table[$unit]; + } + + /** + * A measure (a number, a string with an optional unit suffix, or `{value, unit}`) to exact + * ticks, rounding halves to even. + * + * @param mixed $measure @param array $table @return int|string + */ + public static function toTicks($measure, string $defaultUnit, array $table) + { + $unit = $defaultUnit; + $raw = $measure; + if (Json::isDict($measure) && $measure !== []) { + $raw = Json::at($measure, 'value'); + if (\array_key_exists('unit', $measure)) { + $unit = Json::text($measure['unit'], "a measure's unit"); + } + } elseif (\is_string($measure)) { + $suffixed = self::unitSuffix(self::strip($measure), $table); + if ($suffixed !== null) { + [$raw, $unit] = $suffixed; + } + } + $scaled = self::parseRational($raw)->mulInt(self::perUnit($table, \strtolower($unit))); + return self::roundHalfEven($scaled); + } + + /** + * The longest unit suffix the text ends with, case-insensitively, that leaves a non-empty + * number before it; ties in length go to the table's earlier entry, as Python's stable sort + * over the table does. + * + * @param array $table @return array{0:string,1:string}|null + */ + private static function unitSuffix(string $stripped, array $table): ?array + { + $suffixes = \array_keys($table); + $order = \array_flip($suffixes); + \usort($suffixes, static function (string $a, string $b) use ($order): int { + return [\strlen($b), $order[$a]] <=> [\strlen($a), $order[$b]]; + }); + $lowered = \strtolower($stripped); + foreach ($suffixes as $suffix) { + $length = \strlen($suffix); + if (\strlen($lowered) < $length || \substr($lowered, -$length) !== $suffix) { + continue; + } + $number = self::strip((string) \substr($stripped, 0, -$length)); + if ($number !== '') { + return [$number, $suffix]; + } + } + return null; + } + + /** @return int|string */ + private static function roundHalfEven(Ratio $scaled) + { + $floor = $scaled->floor(); + $remainder = Ratio::of(Exact::sub($scaled->numerator, Exact::mul($floor, $scaled->denominator)), $scaled->denominator); + $order = $remainder->compare(Ratio::of(1, 2)); + if ($order > 0) { + return Exact::add($floor, 1); + } + if ($order < 0) { + return $floor; + } + return Exact::mod($floor, 2) === 0 ? $floor : Exact::add($floor, 1); + } + + /** + * `parse_rational`: an integer exactly, anything else through its `str()` as a fraction, a + * mixed fraction (`12 3/8`) when the text holds a space. + * + * @param mixed $value + */ + public static function parseRational($value): Ratio + { + $integer = Json::intInstance($value); + if ($integer !== null) { + return Ratio::integer($integer); + } + $stripped = self::strip(PyFormat::str($value)); + if (\strpos($stripped, ' ') === false) { + return self::parseFraction($stripped); + } + $parts = \preg_split('/[\s\p{Z}]+/u', $stripped, 2); + $fraction = self::parseFraction($parts[1] ?? ''); + if (\strncmp($parts[0], '-', 1) === 0) { + $fraction = $fraction->negate(); + } + return self::parseFraction($parts[0])->add($fraction); + } + + /** `Fraction(str(value))`, the reference's reading of a ratio field. @param mixed $value */ + public static function ratioOf($value): Ratio + { + return self::parseFraction(PyFormat::str($value)); + } + + /** + * `Fraction(text)` by the grammar of CPython 3.11's `fractions._RATIONAL_FORMAT`: optional + * whitespace and sign, then `n/d`, or a decimal with an optional exponent; digit groups may + * be split by single underscores. Only ASCII digits are read. + */ + public static function parseFraction(string $text): Ratio + { + $digits = '\d+(?:_\d+)*'; + $pattern = "/^[\\s\\p{Z}]*([-+]?)(?=\\d|\\.\\d)({$digits})?(?:\\/({$digits})|(?:\\.({$digits})?)?(?:[eE]([-+]?{$digits}))?)[\\s\\p{Z}]*$/u"; + if (\preg_match($pattern, $text, $parts) !== 1) { + throw MalformedResult::shape(\sprintf('Invalid literal for Fraction: %s', PyFormat::stringRepr($text))); + } + $clean = static function (string $group) { + return Exact::normalize(\ltrim(\str_replace('_', '', $group), '0') ?: '0'); + }; + $numerator = $clean($parts[2] ?? ''); + $denominator = 1; + if (($parts[3] ?? '') !== '') { + $denominator = $clean($parts[3]); + } else { + $decimals = \str_replace('_', '', $parts[4] ?? ''); + if ($decimals !== '') { + $scale = Exact::normalize('1' . \str_repeat('0', \strlen($decimals))); + $numerator = Exact::add(Exact::mul($numerator, $scale), $clean($decimals)); + $denominator = $scale; + } + $exponent = $parts[5] ?? ''; + if ($exponent !== '') { + $power = (int)\str_replace(['_', '+'], '', $exponent); + if (\abs($power) > 400) { + throw MalformedResult::shape('arithmetic overflow: an exponent beyond what this validator computes'); + } + $factor = Exact::normalize('1' . \str_repeat('0', \abs($power))); + if ($power < 0) { + $denominator = Exact::mul($denominator, $factor); + } else { + $numerator = Exact::mul($numerator, $factor); + } + } + } + if ($parts[1] === '-') { + $numerator = Exact::negate($numerator); + } + return Ratio::of($numerator, $denominator); + } + + /** Python's `str.strip()`: Unicode whitespace from both ends. */ + public static function strip(string $text): string + { + return \preg_replace('/^[\s\p{Z}]+|[\s\p{Z}]+$/u', '', $text) ?? $text; + } + + /** @param mixed $value @return array{0:int|string,1:int|string,2:int|string} */ + public static function dimensions($value, string $unit): array + { + return [ + self::toTicks(Json::at($value, 'length'), $unit, self::LENGTH), + self::toTicks(Json::at($value, 'width'), $unit, self::LENGTH), + self::toTicks(Json::at($value, 'height'), $unit, self::LENGTH), + ]; + } +} diff --git a/src-legacy/Support/ResultValidation/Validator.php b/src-legacy/Support/ResultValidation/Validator.php new file mode 100644 index 0000000..8195a80 --- /dev/null +++ b/src-legacy/Support/ResultValidation/Validator.php @@ -0,0 +1,123 @@ + */ + public static function validate($request, $result): array + { + foreach (self::REQUIRED_KEYS as $key) { + if (!Json::has($result, $key)) { + throw MalformedResult::contract('result is missing ' . PyFormat::stringRepr($key)); + } + } + $unit = Json::text(Json::get(Json::get($request, 'units', []), 'length', 'mm'), 'units.length'); + $configuration = Json::get($request, 'configuration', []); + $clearance = Units::toTicks(Json::get($configuration, 'clearance', 0), $unit, Units::LENGTH); + $globalSupport = Units::ratioOf(Json::get($configuration, 'minimum_support_ratio', 0)); + $items = Spec::items($request, $unit); + $containers = Spec::containers($request, $unit); + + $issues = []; + $validated = Lattice::materialize($request, $result, $items, $containers, $clearance, $issues); + Accounting::checkStructure($validated, $issues); + Facts::checkAlgorithmMetrics($validated, $issues); + Facts::checkEffortBudget($request, $validated, $issues); + Facts::checkResultFacts($validated, $issues); + $context = new Context($items, $containers, $clearance, Accounting::containerTagRules($request)); + Accounting::checkAccounting($validated, $context, $issues); + self::checkInfeasibleProof($validated, $issues); + + $fabricated = self::checkContainers($validated, $result, $context, $globalSupport, $issues); + self::checkContainerCounts($validated, $configuration, $containers, $issues); + + ObjectiveCheck::checkFixedPlacements($request, $validated, $unit, $issues); + ObjectiveCheck::checkGroups($request, $validated, $issues); + ObjectiveCheck::checkSolverSelection($request, $validated, $issues); + ObjectiveCheck::check($request, $validated, $context, $fabricated, $issues); + return $issues; + } + + /** @param mixed $result @param list $issues */ + private static function checkInfeasibleProof($result, array &$issues): void + { + if (!Json::isText(Json::at($result, 'status'), 'infeasible')) { + return; + } + foreach (Json::items(Json::at($result, 'unpacked_items'), 'result.unpacked_items') as $unpacked) { + if (!Json::isText(Json::get(Json::get($unpacked, 'proof', []), 'level'), 'proven')) { + $issues[] = new ResultIssue('unproven_infeasible', 'infeasible status requires a proven rejection for every unpacked item'); + return; + } + } + } + + /** + * Each packed container against its type, recomputing a made-to-measure box first; returns + * those recomputed boxes by container id, for the objective. + * + * @param mixed $validated @param mixed $reported @param list $issues @return Ordered + */ + private static function checkContainers($validated, $reported, Context $context, Ratio $globalSupport, array &$issues): Ordered + { + $fabricated = new Ordered(); + $originals = Json::items(Json::at($reported, 'containers'), 'result.containers'); + foreach (Json::items(Json::at($validated, 'containers'), 'result.containers') as $index => $packed) { + if (!\array_key_exists($index, $originals)) { + break; + } + $containerType = Json::at($packed, 'container_type'); + $spec = $context->containers->get($containerType); + if ($spec === null) { + $issues[] = new ResultIssue('unknown_container_type', PyFormat::str($containerType)); + continue; + } + $spec = ContainerCheck::checkMadeToMeasure($packed, Json::has($originals[$index], 'lattice_summary'), $spec, $context->items, $context->clearance, $issues); + if ($spec->madeToMeasure !== null) { + $fabricated->set(Json::at($packed, 'id'), $spec); + } + ContainerCheck::check($packed, $spec, $context->items, $context->clearance, $globalSupport, $issues); + ContainerCheck::checkAchievedExtent($packed, $spec, $context->clearance, $issues); + } + return $fabricated; + } + + /** @param mixed $validated @param mixed $configuration @param Ordered $containers @param list $issues */ + private static function checkContainerCounts($validated, $configuration, Ordered $containers, array &$issues): void + { + $opened = Json::items(Json::at($validated, 'containers'), 'result.containers'); + $inventory = new Ordered(); + foreach ($opened as $packed) { + $containerType = Json::at($packed, 'container_type'); + if ($containers->has($containerType)) { + $inventory->set($containerType, $inventory->get($containerType, 0) + 1); + } + } + foreach ($inventory->entries() as [$containerType, $count]) { + $quantity = $containers->get($containerType)->quantity; + if ($quantity !== null && $count > $quantity) { + $issues[] = new ResultIssue('container_inventory_exceeded', PyFormat::str($containerType) . ": used {$count}, available {$quantity}"); + } + } + $limit = Json::optionalInt(Json::get($configuration, 'max_containers'), 'max_containers'); + if ($limit !== null && \count($opened) > $limit) { + $issues[] = new ResultIssue('max_containers_exceeded', \count($opened) . " containers opened, limit {$limit}"); + } + } +} diff --git a/src-legacy/Unit/Length.php b/src-legacy/Unit/Length.php index e0f2bc7..5d8cb92 100644 --- a/src-legacy/Unit/Length.php +++ b/src-legacy/Unit/Length.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Unit; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Support\RationalParser; final class Length { @@ -17,7 +18,7 @@ public function __construct(int $ticks){$this->ticks = $ticks; * @param int|string $value */ public static function of($value,string $unit='mm',string $rounding=Rounding::Nearest):self - { return new self(RationalParser::scaled($value,self::multiplier($unit),$rounding)); } + { return self::read(RationalParser::scaled($value,self::multiplier($unit),$rounding)); } /** * @param int|string $value */ @@ -60,6 +61,8 @@ public static function multiplier(string $unit):int{switch (strtolower(trim($uni case 'ft': return self::TICKS_PER_INCH*12; default: - throw new InvalidArgumentException("Unsupported length unit: {$unit}"); + throw new ObjectRefusal('invalid_unit',"Unsupported length unit: {$unit}"); }} + /** A length read from the caller's input; the constructor still guards the arithmetic, where a negative is a defect, not a caller's mistake. */ + private static function read(int $ticks):self{if($ticks<0)throw new ObjectRefusal('negative_measure','Length cannot be negative');return new self($ticks);} } diff --git a/src-legacy/Unit/Weight.php b/src-legacy/Unit/Weight.php index 419dbb6..44c44b3 100644 --- a/src-legacy/Unit/Weight.php +++ b/src-legacy/Unit/Weight.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Unit; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Support\RationalParser; final class Weight { @@ -16,7 +17,7 @@ public function __construct(int $ticks){$this->ticks = $ticks; /** * @param int|string $value */ - public static function of($value,string $unit='g',string $rounding=Rounding::Nearest):self{return new self(RationalParser::scaled($value,self::multiplier($unit),$rounding));} + public static function of($value,string $unit='g',string $rounding=Rounding::Nearest):self{return self::read(RationalParser::scaled($value,self::multiplier($unit),$rounding));} /** * @param $this|int|string|mixed[] $value */ @@ -42,6 +43,8 @@ public static function multiplier(string $unit):int{switch (strtolower(trim($uni case 'lbs': return self::TICKS_PER_LB; default: - throw new InvalidArgumentException("Unsupported weight unit: {$unit}"); + throw new ObjectRefusal('invalid_unit',"Unsupported weight unit: {$unit}"); }} + /** A weight read from the caller's input; the constructor still guards the arithmetic, where a negative is a defect, not a caller's mistake. */ + private static function read(int $ticks):self{if($ticks<0)throw new ObjectRefusal('negative_measure','Weight cannot be negative');return new self($ticks);} } diff --git a/src-legacy/Validation/MalformedResult.php b/src-legacy/Validation/MalformedResult.php new file mode 100644 index 0000000..e80948f --- /dev/null +++ b/src-legacy/Validation/MalformedResult.php @@ -0,0 +1,37 @@ +kind = $kind; + } + + public static function contract(string $message): self + { + return new self($message, self::CONTRACT); + } + + public static function shape(string $message): self + { + return new self($message, self::SHAPE); + } +} diff --git a/src-legacy/Validation/ResultIssue.php b/src-legacy/Validation/ResultIssue.php new file mode 100644 index 0000000..f1c85e8 --- /dev/null +++ b/src-legacy/Validation/ResultIssue.php @@ -0,0 +1,26 @@ +code = $code; + $this->detail = $detail; + } + + public function __toString(): string + { + return "{$this->code}: {$this->detail}"; + } +} diff --git a/src-legacy/Validation/functions.php b/src-legacy/Validation/functions.php new file mode 100644 index 0000000..d631ae7 --- /dev/null +++ b/src-legacy/Validation/functions.php @@ -0,0 +1,33 @@ + $request + * @param array $result + * @return list + * @throws MalformedResult when the result does not have the documented shape at all + */ + function validate(array $request, array $result): array + { + return Validator::validate($request, $result); + } +} diff --git a/src/Algorithm/CandidateFinder.php b/src/Algorithm/CandidateFinder.php index 082e3f8..cbfa625 100644 --- a/src/Algorithm/CandidateFinder.php +++ b/src/Algorithm/CandidateFinder.php @@ -68,9 +68,13 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf // reaches it. $active=[]; foreach($constraints as $constraint){ - if(ConstraintActivity::isInert($constraint,$container,$item,$stackSensitive,$routeSensitive,$config->accessDirections))continue; - $active[]=[$constraint,$constraint instanceof SupportConstraint]; + if(ConstraintActivity::isInert($constraint,$container,$item,$stackSensitive,$routeSensitive))continue; + $active[]=[$constraint,$constraint instanceof SupportConstraint,ConstraintActivity::isPositionIndependent($constraint)]; } + // A rule that reads no position answers the same at every (point, rotation) of this + // search, so it is asked once, by the first position that reaches it. + // Keyed by chain position; the stored value is the verdict's `allowed`. + $fixedVerdicts=[]; if($points===null){ if($item->item->nestingHeight===null)$scan=array_slice($state->orderedPoints,0,$config->maxCandidatePoints); else{ @@ -81,7 +85,7 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf usort($scan,static fn(Point $a,Point $b):int=>[$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]); $scan=array_slice($scan,0,$config->maxCandidatePoints); } - if($container->axles!==null)$scan=[...$scan,...self::axleBalancedPoints($state,$item,$forms,$limitX)]; + if($container->axles!==null)$scan=self::appendUnseen($scan,self::axleBalancedPoints($state,$item,$forms,$limitX)); }else{$scan=$points;usort($scan,static fn(Point $a,Point $b):int=>[$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]);} $out=[];$best=null; $retained=$max!==null&&$max>1?new \SplPriorityQueue():null; @@ -124,9 +128,12 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf } if($blocked)continue; $ctx=new ConstraintContext($container,$placed,$item,$point,$rotation,$physical,$envelope,$stackSensitive,$routeSensitive); - foreach($active as [$constraint,$countsSupport]){ + foreach($active as $link=>[$constraint,$countsSupport,$positionIndependent]){ if($countsSupport)$stats->supportChecks++; - if(!$constraint->evaluate($ctx)->allowed){$blocked=true;break;} + $allowed=$positionIndependent + ?($fixedVerdicts[$link]??=$constraint->evaluate($ctx)->allowed) + :$constraint->evaluate($ctx)->allowed; + if(!$allowed){$blocked=true;break;} } if($blocked)continue; $score=$scorer->score($state,$point,$envelope); @@ -192,6 +199,30 @@ private static function nestingPoints(ContainerState $state,ItemInstance $item): return $points; } + /** + * `$points` then the `$extra` points not already offered, keeping their order (S20). + * + * A repeated point is the same candidate scanned twice: it can change nothing but the + * counted effort. O(k + a) for k offered and a extra points. + * + * @param list $points + * @param list $extra + * @return list + */ + private static function appendUnseen(array $points, array $extra): array + { + $fresh=[]; + foreach($extra as $point)$fresh["{$point->x}:{$point->y}:{$point->z}"]=true; + foreach($points as $point)unset($fresh["{$point->x}:{$point->y}:{$point->z}"]); + foreach($extra as $point){ + $key="{$point->x}:{$point->y}:{$point->z}"; + if(!isset($fresh[$key]))continue; + unset($fresh[$key]); + $points[]=$point; + } + return $points; + } + /** * Extra floor-level candidates that seat this item on an axle's own limit. * @@ -215,6 +246,9 @@ private static function axleBalancedPoints(ContainerState $state, ItemInstance $ $floorYs=[]; foreach($state->points as $point)if($point->z===0)$floorYs[$point->y]=true; $floorYs=$floorYs===[]?[0]:array_keys($floorYs); + // Ascending, as Python and Rust scan them: insertion order moved which point a + // counted stop landed on (S12). + sort($floorYs); $points=[]; foreach($forms as [, , , $dx, , , ]){ foreach(AxleLoad::axleBalancedOrigins($container->axles,$otherUnits,$tareTicks,$tareDoubledX,$item->weight()->ticks,$dx) as $x1){ diff --git a/src/Algorithm/DeterministicRandom.php b/src/Algorithm/DeterministicRandom.php index 41d01cb..88e3386 100644 --- a/src/Algorithm/DeterministicRandom.php +++ b/src/Algorithm/DeterministicRandom.php @@ -17,7 +17,8 @@ final class DeterministicRandom private int $state; - public function __construct(int $seed){$this->state=$seed%self::MODULUS;} + /** PHP's % keeps the dividend's sign; Python's does not, and the shuffle indexes by the draw. */ + public function __construct(int $seed){$this->state=(($seed%self::MODULUS)+self::MODULUS)%self::MODULUS;} private function bits():int { diff --git a/src/Algorithm/EffortBudget.php b/src/Algorithm/EffortBudget.php index 36a693e..d3d7bf3 100644 --- a/src/Algorithm/EffortBudget.php +++ b/src/Algorithm/EffortBudget.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Packvium\Algorithm; -use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; /** * Counted-work limits, checked alongside (never instead of) the wall clock. @@ -27,7 +27,7 @@ public function __construct( // caller means; the schema's floor for each is 1. foreach (['maxCandidatesEvaluated'=>$maxCandidatesEvaluated,'maxPlacementAttempts'=>$maxPlacementAttempts,'maxSearchNodes'=>$maxSearchNodes,'maxRestarts'=>$maxRestarts] as $name=>$limit) { if ($limit!==null && $limit<1) { - throw new InvalidArgumentException("effortBudget.{$name} must be at least 1"); + throw new ObjectRefusal('below_minimum',"effortBudget.{$name} must be at least 1"); } } } diff --git a/src/Algorithm/ExactSmallSolver.php b/src/Algorithm/ExactSmallSolver.php index 439bbab..a8ad960 100644 --- a/src/Algorithm/ExactSmallSolver.php +++ b/src/Algorithm/ExactSmallSolver.php @@ -112,7 +112,6 @@ public function packOne(Container $container,int $sequence,array $items,PackingC if($deadline->expired())return; $stats->searchNodesExpanded++; $stateCount=count($state->placements); - $bestCount=count($best->placements); if(self::isBetterForObjective($state,$stateVolume,$best,$bestVolume,$config)){ $best=$state; $bestVolume=$stateVolume; diff --git a/src/Algorithm/HomogeneousBlockSolver.php b/src/Algorithm/HomogeneousBlockSolver.php index 03bcfb7..4196ae3 100644 --- a/src/Algorithm/HomogeneousBlockSolver.php +++ b/src/Algorithm/HomogeneousBlockSolver.php @@ -3,6 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; +use Packvium\Config\SolverProfile; use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Constraint\PlacementConstraint; use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Placement,Point,ShapeType}; @@ -28,6 +29,10 @@ final class HomogeneousBlockSolver implements SingleContainerSolver /** Lattice nodes between two clock reads are a power of two: 1 << CLOCK_SHIFT. */ private const CLOCK_SHIFT=6; private const CLOCK_STRIDE=(1<modes as $mode){ if($deadline->expired()){$reached=true;break;} $solution=$this->packMode($container,$sequence,$items,$config,$stats,$deadline,$mode,$nodeLimit); + if($config->profile===SolverProfile::Quality&&!$deadline->expired()) + $solution=$this->lookahead($container,$sequence,$items,$config,$stats,$deadline,$mode,$nodeLimit*self::LOOKAHEAD_NODE_FACTOR,$solution); $reached=$reached||$solution->timeLimitReached; $byVolume=$config->objective==='maximum_volume'; if($best===null||$this->solutionKey($solution,$byVolume)<$this->solutionKey($best,$byVolume))$best=$solution; @@ -227,25 +234,26 @@ private static function largestBlock(int $maximumX,int $maximumY,int $maximumZ,i } /** - * The round's leading block over every (space, type, rotation) group, or null. + * The round's `$leaders` leading blocks over every (space, type, rotation) group, best first. * * Every group's nodes count toward the limits before any is ranked, and a stop inside a * group lands on the node the per-node loop stopped at: a stopped round places nothing, * so which node led it is never read. Inside one group every key field except the * count-derived lead is equal, and fill and volume grow with the count, so the group's * first largest count is the only node that can lead. No node exceeds the capacity or - * the whole lattice, and a group whose bound already trails the incumbent cannot lead: - * the cheap lead is monotone in the count, since a float product is. + * the whole lattice, and once `$leaders` blocks are kept a group whose bound already + * trails the last of them cannot lead: the cheap lead is monotone in the count, since a + * float product is. * * @param list $spaces * @param array $capacities * @param array>> $rotations - * @return array|null + * @return list> */ - private static function leadingBlock(array $spaces,array $capacities,array $rotations,string $mode,int &$nodes,int $stopAt,SearchStats $stats,Deadline $deadline,bool &$reached):?array + private static function leadingBlocks(array $spaces,array $capacities,array $rotations,string $mode,int $leaders,int &$nodes,int $stopAt,SearchStats $stats,Deadline $deadline,bool &$reached):array { - $best=null;$byCount=$mode==='count'; - // The incumbent's cheap lead as scalars: its count, and its float volume less the margin. + $leading=[];$byCount=$mode==='count'; + // The last kept block's cheap lead as scalars: its count, and its float volume less the margin. $leadCount=0;$leadFloor=-INF; foreach($spaces as $space){ $spaceLength=$space->dimensions->length->ticks;$spaceWidth=$space->dimensions->width->ticks;$spaceHeight=$space->dimensions->height->ticks; @@ -260,7 +268,7 @@ private static function leadingBlock(array $spaces,array $capacities,array $rota if($nodes+$groupNodes>$stopAt||(($nodes+$groupNodes-1)>>self::CLOCK_SHIFT)!==(($nodes-1)>>self::CLOCK_SHIFT)){ $expanded=self::expandable($nodes,$groupNodes,$stopAt,$deadline); $nodes+=$expanded;$stats->searchNodesExpanded+=$expanded; - if($expanded<$groupNodes){$reached=true;return null;} + if($expanded<$groupNodes){$reached=true;return [];} }else{$nodes+=$groupNodes;$stats->searchNodesExpanded+=$groupNodes;} if($envelopeHeight>$spaceHeight)continue; $maximumZ=intdiv($spaceHeight,$envelopeHeight); @@ -272,55 +280,169 @@ private static function leadingBlock(array $spaces,array $capacities,array $rota $approximateUsed=$count*$volume; if($byCount?$count<$leadCount:$approximateUsed<$leadFloor)continue; $candidate=['space'=>$space,'itemId'=>$itemId,'rotation'=>$lattice['rotation'],'rotationName'=>$lattice['rotationName'],'physical'=>$lattice['physical'],'envelope'=>$lattice['envelope'],'volume'=>$lattice['volume'],'approximateUsed'=>$approximateUsed,'nx'=>$nx,'ny'=>$ny,'nz'=>$nz,'count'=>$count]; - if($best!==null&&!self::leads($candidate,$best,$mode))continue; - $best=$candidate;$leadCount=$count;$leadFloor=$approximateUsed*(1-self::FLOAT_MARGIN); + $full=count($leading)===$leaders; + if($full&&!self::leads($candidate,$leading[$leaders-1],$mode))continue; + $position=count($leading); + while($position>0&&self::leads($candidate,$leading[$position-1],$mode))$position--; + array_splice($leading,$position,0,[$candidate]); + if(count($leading)>$leaders)array_pop($leading); + if(count($leading)===$leaders){$last=$leading[$leaders-1];$leadCount=$last['count'];$leadFloor=$last['approximateUsed']*(1-self::FLOAT_MARGIN);} } } } - return $best; + return $leading; } - private function packMode(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit):SingleContainerSolution + /** @param list $items @return array> */ + private static function byType(array $items):array { - $state=new ContainerState($container,$sequence); - $spaces=[new Space(new Point(0,0,0),$container->innerDimensions)]; $remaining=[]; foreach($items as $instance)$remaining[$instance->item->id][]=$instance; ksort($remaining,SORT_STRING); - $nodes=0;$reached=false;$rotations=[]; + return $remaining; + } + + /** + * Each type's distinct rotations with what every lattice of them shares. + * + * @param array> $remaining + * @return array>> + */ + private static function rotationsOf(array $remaining,PackingConfig $config):array + { + $rotations=[]; + foreach($remaining as $itemId=>$available)$rotations[$itemId]=self::lattices($available[0],$config); + return $rotations; + } + + private function packMode(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit):SingleContainerSolution + { + $remaining=self::byType($items); + $nodes=0;$reached=false; + $solution=$this->complete($container,new ContainerState($container,$sequence),[new Space(new Point(0,0,0),$container->innerDimensions)],$remaining,self::rotationsOf($remaining,$config),$config,$stats,$deadline,$mode,$nodeLimit,$nodes,$reached); + return new SingleContainerSolution($solution->state,$solution->unpacked,false,$reached||$deadline->expired()); + } + + /** + * How many of each type one block may still take, for the types that may take any. + * + * @param array> $remaining + * @return array + */ + private static function capacities(Container $container,ContainerState $state,array $remaining):array + { + $capacities=[]; + foreach($remaining as $itemId=>$available){ + if($available===[])continue; + $prototype=$available[0];$capacity=count($available); + if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems-$state->placementCount()); + if($container->maxPayload!==null&&$prototype->weight()->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks-$state->payloadTicks,$prototype->weight()->ticks)); + if($capacity<=0)continue; + $capacities[$itemId]=$capacity; + } + return $capacities; + } + + /** + * One round's leading blocks under the mode's node limit and the effort budget. + * + * @param list $spaces + * @param array> $remaining + * @param array>> $rotations + * @return list> + */ + private static function round(Container $container,ContainerState $state,array $spaces,array $remaining,array $rotations,string $mode,int $leaders,int $nodeLimit,int &$nodes,SearchStats $stats,Deadline $deadline,bool &$reached):array + { + // Only the node count moves a counted limit inside one round: candidates and + // placements are counted when a block is placed, after it. + $stopAt=$nodes+max(0,min($nodeLimit-$nodes,$deadline->searchNodesLeft($stats))); + return self::leadingBlocks($spaces,self::capacities($container,$state,$remaining),$rotations,$mode,$leaders,$nodes,$stopAt,$stats,$deadline,$reached); + } + + /** + * Commit each round's leading block until nothing more fits. + * + * @param list $spaces + * @param array> $remaining + * @param array>> $rotations + */ + private function complete(Container $container,ContainerState $state,array $spaces,array $remaining,array $rotations,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit,int &$nodes,bool &$reached):SingleContainerSolution + { while($spaces!==[]&&array_sum(array_map('count',$remaining))>0){ - // Only the node count moves a counted limit inside one round: candidates and - // placements are counted when a block is placed, after it. - $stopAt=$nodes+max(0,min($nodeLimit-$nodes,$deadline->searchNodesLeft($stats))); - // A type's capacity and lattices do not depend on the space they are tried in. - $capacities=[]; - foreach($remaining as $itemId=>$available){ - if($available===[])continue; - $prototype=$available[0];$capacity=count($available); - if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems-$state->placementCount()); - if($container->maxPayload!==null&&$prototype->weight()->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks-$state->payloadTicks,$prototype->weight()->ticks)); - if($capacity<=0)continue; - $capacities[$itemId]=$capacity; - $rotations[$itemId]??=self::lattices($prototype,$config); - } - $best=self::leadingBlock($spaces,$capacities,$rotations,$mode,$nodes,$stopAt,$stats,$deadline,$reached); - if($best===null||$reached)break; - $chosen=array_slice($remaining[$best['itemId']],0,$best['count']); - $remaining[$best['itemId']]=array_slice($remaining[$best['itemId']],$best['count']); - $clearance=$config->clearance->ticks;$index=0; - for($z=0;$z<$best['nz'];$z++)for($y=0;$y<$best['ny'];$y++)for($x=0;$x<$best['nx'];$x++){ - $point=new Point($best['space']->origin->x+$x*$best['envelope']->length->ticks,$best['space']->origin->y+$y*$best['envelope']->width->ticks,$best['space']->origin->z+$z*$best['envelope']->height->ticks); - $position=new Point($point->x+$clearance,$point->y+$clearance,$point->z+$clearance); - // Above its bottom layer a member rests on an identical footprint; the - // bottom layer rests on whatever is there. - $support=$z===0?self::memberSupport($state,$chosen[$index],$point,$best['envelope']):1.0; - $state->addDirect(new Placement($chosen[$index++],$position,$best['rotation'],$best['physical'],$point,$best['envelope'],$support)); - $stats->candidatesEvaluated++;$stats->placementsAttempted++; - } - $blockDimensions=new Dimensions(new Length($best['nx']*$best['envelope']->length->ticks),new Length($best['ny']*$best['envelope']->width->ticks),new Length($best['nz']*$best['envelope']->height->ticks)); - $spaces=MaximalSpaceSolver::subtractAll($spaces,[new AxisAlignedBox($best['space']->origin,$blockDimensions)],$stats); + $leading=self::round($container,$state,$spaces,$remaining,$rotations,$mode,1,$nodeLimit,$nodes,$stats,$deadline,$reached); + if($leading===[]||$reached)break; + $spaces=self::commit($state,$spaces,$remaining,$leading[0],$config,$stats); } $unpacked=[];foreach($remaining as $available)foreach($available as $instance)$unpacked[]=$instance; - return new SingleContainerSolution($state,$unpacked,false,$reached||$deadline->expired()); + return new SingleContainerSolution($state,$unpacked,false,$reached); + } + + /** + * `$greedy`, or a better answer from completing each round's leading blocks. + * + * Each round ranks its LOOKAHEAD_WIDTH leading blocks, completes each one greedily on a + * copy, and commits the block whose completion ranks best. The greedy answer is the first + * completion, so the result is never worse than it. The round's first block is the greedy + * choice after the block committed last, so its completion is the one already known -- + * unless the greedy pass was stopped by the node limit, when the first round completes it + * under the lookahead's larger budget. When that budget runs out the best completion so + * far stands; only the deadline or the effort budget marks the answer as stopped. + * + * @param list $items + */ + private function lookahead(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit,SingleContainerSolution $greedy):SingleContainerSolution + { + $byVolume=$config->objective==='maximum_volume'; + $state=new ContainerState($container,$sequence); + $spaces=[new Space(new Point(0,0,0),$container->innerDimensions)]; + $remaining=self::byType($items); + $rotations=self::rotationsOf($remaining,$config); + $best=$greedy;$bestKey=$this->solutionKey($greedy,$byVolume); + $known=$greedy->timeLimitReached?null:$greedy; + $nodes=0;$reached=false; + while($spaces!==[]&&array_sum(array_map('count',$remaining))>0){ + $leading=self::round($container,$state,$spaces,$remaining,$rotations,$mode,self::LOOKAHEAD_WIDTH,$nodeLimit,$nodes,$stats,$deadline,$reached); + if($leading===[]||$reached)break; + $chosen=$known===null?null:[$this->solutionKey($known,$byVolume),$known,$leading[0]]; + foreach($known===null?$leading:array_slice($leading,1) as $block){ + $trialState=$state->copy();$trialRemaining=$remaining; + $trialSpaces=self::commit($trialState,$spaces,$trialRemaining,$block,$config,$stats); + $trial=$this->complete($container,$trialState,$trialSpaces,$trialRemaining,$rotations,$config,$stats,$deadline,$mode,$nodeLimit,$nodes,$reached); + if($reached)break; + $trialKey=$this->solutionKey($trial,$byVolume); + if($chosen===null||$trialKey<$chosen[0])$chosen=[$trialKey,$trial,$block]; + } + if($reached||$chosen===null)break; + [$chosenKey,$known,$block]=$chosen; + if($chosenKey<$bestKey){$best=$known;$bestKey=$chosenKey;} + $spaces=self::commit($state,$spaces,$remaining,$block,$config,$stats); + } + return new SingleContainerSolution($best->state,$best->unpacked,false,$best->timeLimitReached||$deadline->expired()); + } + + /** + * Place every member of the block, bottom layer first, and return the spaces left. + * + * @param list $spaces + * @param array> $remaining + * @param array $best + * @return list + */ + private static function commit(ContainerState $state,array $spaces,array &$remaining,array $best,PackingConfig $config,SearchStats $stats):array + { + $chosen=array_slice($remaining[$best['itemId']],0,$best['count']); + $remaining[$best['itemId']]=array_slice($remaining[$best['itemId']],$best['count']); + $clearance=$config->clearance->ticks;$index=0; + for($z=0;$z<$best['nz'];$z++)for($y=0;$y<$best['ny'];$y++)for($x=0;$x<$best['nx'];$x++){ + $point=new Point($best['space']->origin->x+$x*$best['envelope']->length->ticks,$best['space']->origin->y+$y*$best['envelope']->width->ticks,$best['space']->origin->z+$z*$best['envelope']->height->ticks); + $position=new Point($point->x+$clearance,$point->y+$clearance,$point->z+$clearance); + // Above its bottom layer a member rests on an identical footprint; the + // bottom layer rests on whatever is there. + $support=$z===0?self::memberSupport($state,$chosen[$index],$point,$best['envelope']):1.0; + $state->addDirect(new Placement($chosen[$index++],$position,$best['rotation'],$best['physical'],$point,$best['envelope'],$support)); + $stats->candidatesEvaluated++;$stats->placementsAttempted++; + } + $blockDimensions=new Dimensions(new Length($best['nx']*$best['envelope']->length->ticks),new Length($best['ny']*$best['envelope']->width->ticks),new Length($best['nz']*$best['envelope']->height->ticks)); + return MaximalSpaceSolver::subtractAll($spaces,[new AxisAlignedBox($best['space']->origin,$blockDimensions)],$stats); } } diff --git a/src/Artifacts/OperationalArtifact.php b/src/Artifacts/OperationalArtifact.php index 3c778f3..4eeef69 100644 --- a/src/Artifacts/OperationalArtifact.php +++ b/src/Artifacts/OperationalArtifact.php @@ -36,7 +36,7 @@ final class OperationalArtifact * The engine's own name is deliberately not recorded: four correct builders naming * themselves would emit four different documents. */ - public const SUITE_VERSION = '1.6.0'; + public const SUITE_VERSION = '1.7.0'; /** The deterministic part of `result.algorithm`; `duration_ms` is wall-clock time. */ private const SOLVER_FIELDS = ['profile', 'solver', 'seed', 'time_limit_reached', 'effort_limit_reached']; diff --git a/src/Config/PackingConfig.php b/src/Config/PackingConfig.php index a97ac1a..79b4573 100644 --- a/src/Config/PackingConfig.php +++ b/src/Config/PackingConfig.php @@ -1,14 +1,15 @@ $solvers */ - public function __construct(public SolverProfile $profile=SolverProfile::Balanced,public int $timeLimitMs=1000,public int $topK=3,public int $seed=42,public ?int $maxContainers=null,?Length $clearance=null,public float $minimumSupportRatio=0.0,public int $exactItemLimit=7,public int $multiStartOrders=8,public bool $validateResult=true,public int $maxCandidatesPerItem=1,public int $maxCandidatePoints=4096,public array $solvers=[],public string $objective='default',public ?EffortBudget $effortBudget=null,public ?int $dimensionalWeightDivisor=null,public string $dimensionalWeightLengthUnit='in',public string $dimensionalWeightWeightUnit='lb',public bool $requirePlacementCoordinates=true,public int $parallelStarts=1,public int $containerPlanBeamWidth=1,public int $containerPlanNodeLimit=1,public array $accessDirections=[]){if($timeLimitMs<=0||$topK<=0||$exactItemLimit<=0||$multiStartOrders<=0||$maxCandidatesPerItem<=0||$parallelStarts<=0||$containerPlanBeamWidth<=0||$containerPlanNodeLimit<=0)throw new InvalidArgumentException('Positive configuration values required');if($maxContainers!==null&&$maxContainers<1)throw new InvalidArgumentException('maxContainers must be at least 1');if($maxCandidatePoints<16)throw new InvalidArgumentException('maxCandidatePoints must be at least 16');if($minimumSupportRatio<0||$minimumSupportRatio>1)throw new InvalidArgumentException('Minimum support ratio must be between 0 and 1');if($dimensionalWeightDivisor!==null&&$dimensionalWeightDivisor<=0)throw new InvalidArgumentException('dimensionalWeightDivisor must be positive');$this->clearance=$clearance??new Length(0);} + public function __construct(public SolverProfile $profile=SolverProfile::Balanced,public int $timeLimitMs=1000,public int $topK=3,public int $seed=42,public ?int $maxContainers=null,?Length $clearance=null,public float $minimumSupportRatio=0.0,public int $exactItemLimit=7,public int $multiStartOrders=8,public bool $validateResult=true,public int $maxCandidatesPerItem=1,public int $maxCandidatePoints=4096,public array $solvers=[],public string $objective='default',public ?EffortBudget $effortBudget=null,public ?int $dimensionalWeightDivisor=null,public string $dimensionalWeightLengthUnit='in',public string $dimensionalWeightWeightUnit='lb',public bool $requirePlacementCoordinates=true,public int $parallelStarts=1,public int $containerPlanBeamWidth=1,public int $containerPlanNodeLimit=1,public array $accessDirections=[]){if($timeLimitMs<=0||$topK<=0||$exactItemLimit<=0||$multiStartOrders<=0||$maxCandidatesPerItem<=0||$parallelStarts<=0||$containerPlanBeamWidth<=0||$containerPlanNodeLimit<=0)throw new ObjectRefusal('below_minimum','Positive configuration values required');if($maxContainers!==null&&$maxContainers<1)throw new ObjectRefusal('below_minimum','maxContainers must be at least 1');if($maxCandidatePoints<16)throw new ObjectRefusal('below_minimum','maxCandidatePoints must be at least 16');if(!($minimumSupportRatio>=0&&$minimumSupportRatio<=1))throw ObjectRefusal::ratio($minimumSupportRatio,'Minimum support ratio must be between 0 and 1');if($dimensionalWeightDivisor!==null&&$dimensionalWeightDivisor<=0)throw new ObjectRefusal('below_minimum','dimensionalWeightDivisor must be positive');if(!in_array($dimensionalWeightLengthUnit,RequestRules::LENGTH_UNITS,true))throw new ObjectRefusal('not_allowed','dimensionalWeightLengthUnit must be one of '.implode(', ',RequestRules::LENGTH_UNITS));if(!in_array($dimensionalWeightWeightUnit,RequestRules::WEIGHT_UNITS,true))throw new ObjectRefusal('not_allowed','dimensionalWeightWeightUnit must be one of '.implode(', ',RequestRules::WEIGHT_UNITS));$this->clearance=$clearance??new Length(0);} public static function fast(int $timeLimitMs=200,?Length $clearance=null,bool $requirePlacementCoordinates=true,bool $validateResult=true):self{return new self(SolverProfile::Fast,$timeLimitMs,1,42,null,$clearance,0.0,7,1,$validateResult,1,requirePlacementCoordinates:$requirePlacementCoordinates);} public static function balanced(int $timeLimitMs=1000,int $topK=3,?Length $clearance=null):self{return new self(SolverProfile::Balanced,$timeLimitMs,$topK,42,null,$clearance);} public static function quality(int $timeLimitMs=5000,int $topK=5,?Length $clearance=null):self{return new self(SolverProfile::Quality,$timeLimitMs,$topK,42,null,$clearance,0.0,7,24,true,16,containerPlanBeamWidth:16,containerPlanNodeLimit:100_000);} diff --git a/src/Constraint/Internal/ConstraintActivity.php b/src/Constraint/Internal/ConstraintActivity.php index a0211c4..74a37fe 100644 --- a/src/Constraint/Internal/ConstraintActivity.php +++ b/src/Constraint/Internal/ConstraintActivity.php @@ -23,14 +23,24 @@ */ final class ConstraintActivity { - /** @param list $defaultAccessDirections */ + /** + * Whether a built-in rule's verdict for an item never reads the candidate's position. + * + * Compatibility and tag counts look only at the item, the container and what is + * already placed, all fixed for one candidate search, so one verdict serves every + * (point, rotation) of it -- as Rust and JavaScript already compute them once per item. + */ + public static function isPositionIndependent(PlacementConstraint $constraint): bool + { + return $constraint instanceof CompatibilityConstraint || $constraint instanceof TagCountConstraint; + } + public static function isInert( PlacementConstraint $constraint, Container $container, ItemInstance $item, bool $stackSensitive, bool $routeSensitive, - array $defaultAccessDirections, ): bool { if ($constraint instanceof FloorConstraint) { return !$item->item->mustBeOnFloor; @@ -53,9 +63,9 @@ public static function isInert( return !$routeSensitive; } if ($constraint instanceof StopAccessibilityConstraint) { - // A flat bag has no walls, so it inherits no doors either. - return !$routeSensitive || $container->isFlatBag() - || ($container->accessDirections === [] && $defaultAccessDirections === []); + // The instance, not the configuration: a caller-supplied constraint carries + // its own default doors (S17). + return !$routeSensitive || $constraint->directionsFor($container) === []; } if ($constraint instanceof AxleLoadConstraint) { return $container->axles === null; diff --git a/src/Constraint/Internal/DirectSupportView.php b/src/Constraint/Internal/DirectSupportView.php index 8e821a9..557a7d8 100644 --- a/src/Constraint/Internal/DirectSupportView.php +++ b/src/Constraint/Internal/DirectSupportView.php @@ -3,17 +3,15 @@ namespace Packvium\Constraint\Internal; use Packvium\Domain\AxisAlignedBox; -/** Candidate support surfaces plus canonical positive-area direct supporters. */ +/** Positive-area direct supporters of one candidate, in placement-index order. */ final readonly class DirectSupportView { /** - * @param list $surfaces * @param list $supporterIndexes * @param list $supporterBoxes * @param list $supporterAreas */ public function __construct( - public array $surfaces, public array $supporterIndexes, public array $supporterBoxes, public array $supporterAreas, diff --git a/src/Constraint/Internal/LoadAnalysis.php b/src/Constraint/Internal/LoadAnalysis.php index af0717b..81d39ef 100644 --- a/src/Constraint/Internal/LoadAnalysis.php +++ b/src/Constraint/Internal/LoadAnalysis.php @@ -93,25 +93,58 @@ public function crushed():?array return null; } - /** @return list> */ + /** + * Walked iteratively in the load order topLoads uses: a child's top is above its + * supporter's, so every child's set is complete before its supporter reads it. The + * recursive walk spent one frame per stack level. Set keys are in no + * promised order; a caller that names a member sorts first. + * + * @return list> + */ public function restingAbove():array { if($this->restingAbove!==null)return $this->restingAbove; - $memo=[]; - $aboveSet=function(int $index) use (&$aboveSet,&$memo):array{ - if(isset($memo[$index]))return $memo[$index]; + $count=count($this->units); + $sets=$count===0?[]:array_fill(0,$count,[]); + foreach($this->graph->descendingIndices() as $index){ $result=[]; - foreach($this->graph->children($index) as $child){ - $result[$child]=true; - foreach($aboveSet($child) as $ancestor=>$_)$result[$ancestor]=true; - } - return $memo[$index]=$result; - }; - $sets=[]; - for($index=0,$count=count($this->units);$index<$count;$index++)$sets[]=$aboveSet($index); + foreach($this->graph->children($index) as $child)$result+=[$child=>true]+$sets[$child]; + $sets[$index]=$result; + } return $this->restingAbove=$sets; } + /** + * Whether any stop is a real one. A scene where everything rides the whole route has + * no order to violate, so callers ask this before building a graph at all. + * + * @param list $stops + */ + public static function routed(array $stops):bool + { + foreach($stops as $stop)if($stop!==INF)return true; + return false; + } + + /** + * First unit due at an earlier stop with a later-stop unit resting above it, as + * [code, detail]. `$stops` is parallel to the units; INF rides the whole route. + * + * @param list $stops @return array{0:string,1:string}|null + */ + public function routeOrderViolated(array $stops):?array + { + foreach($this->restingAbove() as $index=>$above){ + // Ascending, as Python iterates: the detail names the first violator (S16). + $uppers=array_keys($above); + sort($uppers); + foreach($uppers as $upper) + if($stops[$upper]>$stops[$index]) + return ['unloading_order_violation',$this->units[$index]->label.' blocked by '.$this->units[$upper]->label]; + } + return null; + } + /** @return list */ public function stackedCounts():array { diff --git a/src/Constraint/Internal/LoadSupportGraph.php b/src/Constraint/Internal/LoadSupportGraph.php index 6948318..3b5b520 100644 --- a/src/Constraint/Internal/LoadSupportGraph.php +++ b/src/Constraint/Internal/LoadSupportGraph.php @@ -212,21 +212,21 @@ private static function sameNestingColumn(Placement $placement,ItemInstance $ite /** * Direct support for one active candidate: O(m) time and O(m) output space. * - * Ordinary face semantics are retained exactly. With an exact adjacent nesting - * predecessor, shadowed same-column face surfaces are removed and that predecessor - * becomes one full-area supporter. Every returned list stays in placement-index - * order, so remainder and traversal decisions remain canonical. + * A box whose top is on the candidate's base plane supports it when the two overlap + * with positive area. With an exact adjacent nesting predecessor, shadowed + * same-column face supporters are removed and that predecessor becomes one full-area + * supporter. Every returned list stays in placement-index order, so remainder and + * traversal decisions remain canonical. * * @param list $placements */ public static function candidateView(array $placements,ItemInstance $item,AxisAlignedBox $box):DirectSupportView { - $surfaceEntries=[];$supporterEntries=[];$nearestLower=null; + $supporterEntries=[];$nearestLower=null; $nesting=$item->item->nestingHeight; foreach($placements as $index=>$placement){ $other=$placement->envelopeBox(); if($other->z2()===$box->origin->z){ - $surfaceEntries[]=['index'=>$index,'box'=>$other]; $area=$other->overlapAreaXY($box); if($area>0)$supporterEntries[]=['index'=>$index,'box'=>$other,'area'=>$area]; } @@ -241,17 +241,10 @@ public static function candidateView(array $placements,ItemInstance $item,AxisAl &&$nearestLower['box']->z2()-$box->origin->z===$nesting->ticks ?$nearestLower:null; if($predecessor!==null){ - $surfaceEntries=array_values(array_filter( - $surfaceEntries, - static fn(array $entry):bool=>!self::sameNestingColumn($placements[$entry['index']],$item,$box), - )); $supporterEntries=array_values(array_filter( $supporterEntries, static fn(array $entry):bool=>!self::sameNestingColumn($placements[$entry['index']],$item,$box), )); - $surfaceAt=0; - while($surfaceAt$entry['box'],$surfaceEntries), - $indexes,$boxes,$areas,$totalArea, - ); + return new DirectSupportView($indexes,$boxes,$areas,$totalArea); } } diff --git a/src/Constraint/Internal/PlacedSupportBase.php b/src/Constraint/Internal/PlacedSupportBase.php new file mode 100644 index 0000000..c84d7a0 --- /dev/null +++ b/src/Constraint/Internal/PlacedSupportBase.php @@ -0,0 +1,63 @@ +|null */ + private ?array $placements=null; + private ?LoadSupportGraph $base=null; + /** @var list */ + private array $baseUnits=[]; + private int $hint=1; + + /** + * `$placements`' units and graph with `$unit` appended at the last index. + * + * @param list $placements + * @return array{0:list,1:LoadSupportGraph} + */ + public function withCandidate(array $placements,LoadUnit $unit):array + { + $box=$unit->box; + $base=$this->baseFor($placements,max($box->x2()-$box->origin->x,$box->y2()-$box->origin->y)); + $units=$this->baseUnits; + $units[]=$unit; + return [$units,$base->withUnit($unit,$this->hint)]; + } + + /** + * The support graph over `$placements` alone, rebuilt only when it cannot serve. + * + * The cell hint has to cover every candidate that will be appended to this base, and + * the widest of them is not known in advance -- a candidate is a *new* item and may + * be the widest in the request. So the hint grows to fit the first candidate that + * needs it and the base is rebuilt that once; after that the run is served from + * cache. Sizing it from the container instead would always be safe and always + * coarse, and a cell far larger than the boxes collapses the spatial hash back into + * the all-pairs scan it exists to avoid. + * + * @param list $placements + */ + private function baseFor(array $placements,int $footprint):LoadSupportGraph + { + $same=$this->base!==null&&$this->placements===$placements; + if($same&&$footprint<=$this->hint)return $this->base; + $this->hint=max($same?$this->hint:1,$footprint); + $this->placements=$placements; + $this->baseUnits=LoadCalculator::units($placements); + $this->base=new LoadSupportGraph($this->baseUnits,$this->hint); + return $this->base; + } +} diff --git a/src/Constraint/LoadCalculator.php b/src/Constraint/LoadCalculator.php index f91cc04..6ad833f 100644 --- a/src/Constraint/LoadCalculator.php +++ b/src/Constraint/LoadCalculator.php @@ -100,14 +100,8 @@ public static function stackedCounts(array $units):array */ public static function routeOrderViolated(array $units,array $stops):?array { - $routed=false; - foreach($stops as $stop)if($stop!==INF){$routed=true;break;} - if(!$routed)return null; - foreach(self::restingAbove($units) as $index=>$above) - foreach(array_keys($above) as $upper) - if($stops[$upper]>$stops[$index]) - return ['unloading_order_violation',$units[$index]->label.' blocked by '.$units[$upper]->label]; - return null; + if(!LoadAnalysis::routed($stops))return null; + return (new LoadAnalysis($units,new LoadSupportGraph($units)))->routeOrderViolated($stops); } /** First unit whose stacked-item limit is exceeded, as [code, detail]. @param list $units @return array{0:string,1:string}|null */ diff --git a/src/Constraint/RouteOrderConstraint.php b/src/Constraint/RouteOrderConstraint.php index 80aebf0..08af4e0 100644 --- a/src/Constraint/RouteOrderConstraint.php +++ b/src/Constraint/RouteOrderConstraint.php @@ -1,6 +1,7 @@ routeSensitive)return ConstraintResult::allow(); - $units=LoadCalculator::units( - $c->placements, - new LoadUnit( - $c->envelopeBox(),$c->item->weight()->ticks,null,null,$c->item->id(), - $c->item->item->nestingHeight===null?null:$c->item->item->id,$c->item->item->nestingHeight?->ticks, - ), + $candidate=new LoadUnit( + $c->envelopeBox(),$c->item->weight()->ticks,null,null,$c->item->id(), + $c->item->item->nestingHeight===null?null:$c->item->item->id,$c->item->item->nestingHeight?->ticks, ); $stops=[]; foreach($c->placements as $p)$stops[]=$p->instance->item->stopIndex===null?INF:(float)$p->instance->item->stopIndex; $stops[]=$c->item->item->stopIndex===null?INF:(float)$c->item->item->stopIndex; - $failure=LoadCalculator::routeOrderViolated($units,$stops); + if(!LoadAnalysis::routed($stops))return ConstraintResult::allow(); + [$units,$graph]=($this->support??=new PlacedSupportBase())->withCandidate($c->placements,$candidate); + $failure=(new LoadAnalysis($units,$graph))->routeOrderViolated($stops); return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); } } diff --git a/src/Constraint/StopAccessibilityConstraint.php b/src/Constraint/StopAccessibilityConstraint.php index 755a967..c452cb0 100644 --- a/src/Constraint/StopAccessibilityConstraint.php +++ b/src/Constraint/StopAccessibilityConstraint.php @@ -121,12 +121,26 @@ private function baseFor(array $placements,Dimensions $container,array $directio return [$clear,$stops]; } + /** + * The doors this constraint enforces in `$container`; empty means it is inert there. + * + * The container's own doors win; this instance's configured list is what a container + * that states none inherits. A flat bag has no walls, so it inherits none. + * Public so the candidate sweep asks the instance, as Python's `directions_for` + * does, rather than the configuration a custom instance may not have been built from. + * + * @return list + */ + public function directionsFor(\Packvium\Domain\Container $container):array + { + if($container->isFlatBag())return []; + return $container->accessDirections!==[]?$container->accessDirections:$this->defaultDirections; + } + public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->routeSensitive)return ConstraintResult::allow(); - // The container's own doors win; the configured list is what a container that - // states none inherits. A flat bag has no walls, so it inherits none. - $directions=$c->container->isFlatBag()?[]:($c->container->accessDirections!==[]?$c->container->accessDirections:$this->defaultDirections); + $directions=$this->directionsFor($c->container); if($directions===[])return ConstraintResult::allow(); $candidateStop=$c->item->item->stopIndex??INF; $inner=$c->container->innerDimensions; diff --git a/src/Constraint/SupportConstraint.php b/src/Constraint/SupportConstraint.php index cf68cae..0959737 100644 --- a/src/Constraint/SupportConstraint.php +++ b/src/Constraint/SupportConstraint.php @@ -37,12 +37,11 @@ public function evaluate(ConstraintContext $c):ConstraintResult if(!$this->canReject($c->item))return ConstraintResult::allow(); $box=$c->envelopeBox(); $support=LoadSupportGraph::candidateView($c->placements,$c->item,$box); - $surfaces=$support->surfaces; $supporters=$support->supporterBoxes; $rule=$c->item->item->groundContactRule; if($rule!==null&&$rule!=='free'){ $count=count($supporters); - if($rule==='covered'&&!self::touchesCorners($box,$surfaces)) + if($rule==='covered'&&!self::touchesCorners($box,$supporters)) return ConstraintResult::reject('ground_contact_violation',"covered: {$count} supporter(s), not all four corners touched"); if($rule==='single'&&$count!==1) return ConstraintResult::reject('ground_contact_violation',"single: rests on {$count} item(s)"); @@ -67,18 +66,18 @@ public function evaluate(ConstraintContext $c):ConstraintResult } /** - * Whether every one of the candidate's four base corners rests on some surface. + * Whether every one of the candidate's four base corners rests on some supporter. * * A ratio cannot express this: 90% of the footprint concentrated in the middle - * passes any ratio below that but leaves every corner hanging. + * passes any ratio below that but leaves every corner hanging. Only positive-area + * supporters count: a neighbour touching a corner along an edge carries nothing, + * and Rust, JS and every validator ignore it. * - * @param list<\Packvium\Domain\AxisAlignedBox> $surfaces - */ - /** * Public, not private: `Sequence\LoadingDependencyGraph::verifyLoadingPrefixBusinessRules` * reuses this exact corner-touch calculation against every loading - * prefix, not only the finished scene -- widened visibility only, no behaviour - * change, so every existing caller of this constraint is unaffected. + * prefix, not only the finished scene. + * + * @param list<\Packvium\Domain\AxisAlignedBox> $surfaces the candidate's positive-area supporters */ public static function touchesCorners(\Packvium\Domain\AxisAlignedBox $box,array $surfaces):bool { diff --git a/src/Constraint/TopLoadConstraint.php b/src/Constraint/TopLoadConstraint.php index 677ea7f..045b509 100644 --- a/src/Constraint/TopLoadConstraint.php +++ b/src/Constraint/TopLoadConstraint.php @@ -1,68 +1,30 @@ |null */ - private ?array $placements=null; - private ?LoadSupportGraph $base=null; - /** @var list */ - private array $baseUnits=[]; - private int $hint=1; - - /** - * The support graph over `$placements` alone, rebuilt only when it cannot serve. - * - * The cell hint has to cover every candidate that will be appended to this base, and - * the widest of them is not known in advance -- a candidate is a *new* item and may - * be the widest in the request. So the hint grows to fit the first candidate that - * needs it and the base is rebuilt that once; after that the run is served from - * cache. Sizing it from the container instead would always be safe and always - * coarse, and a cell far larger than the boxes collapses the spatial hash back into - * the all-pairs scan it exists to avoid. - * - * @param list $placements - */ - private function baseFor(array $placements,int $footprint):LoadSupportGraph - { - $same=$this->base!==null&&$this->placements===$placements; - if($same&&$footprint<=$this->hint)return $this->base; - $this->hint=max($same?$this->hint:1,$footprint); - $this->placements=$placements; - $this->baseUnits=LoadCalculator::units($placements); - $this->base=new LoadSupportGraph($this->baseUnits,$this->hint); - return $this->base; - } + // Created on first use rather than in a constructor, which would widen the frozen + // public surface (spec/api/php.json) for an internal cache. + private ?PlacedSupportBase $support=null; public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->stackSensitive)return ConstraintResult::allow(); - $candidate=$c->envelopeBox(); $item=$c->item->item; $unit=new LoadUnit( - $candidate,$c->item->weight()->ticks,$item->maxTopLoad?->ticks,$item->maxStackedItems,$c->item->id(), + $c->envelopeBox(),$c->item->weight()->ticks,$item->maxTopLoad?->ticks,$item->maxStackedItems,$c->item->id(), $item->nestingHeight===null?null:$item->id,$item->nestingHeight?->ticks, $item->compressionRatioPpm,$item->maxCompressionPressureKpa, ); - $footprint=max($candidate->x2()-$candidate->origin->x,$candidate->y2()-$candidate->origin->y); - $base=$this->baseFor($c->placements,$footprint); - $units=$this->baseUnits; - $units[]=$unit; - $graph=$base->withUnit($unit,$this->hint); + [$units,$graph]=($this->support??=new PlacedSupportBase())->withCandidate($c->placements,$unit); $nonStackable=$graph->nonStackableFailure($c->placements,$c->item,count($units)-1); if($nonStackable!==null)return ConstraintResult::reject($nonStackable[0],$nonStackable[1]); $densityLimit=$c->container->maxStackDensity?->ticks; diff --git a/src/Domain/Compression.php b/src/Domain/Compression.php index 4518825..8a68ede 100644 --- a/src/Domain/Compression.php +++ b/src/Domain/Compression.php @@ -3,6 +3,7 @@ namespace Packvium\Domain; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Unit\Length; use Packvium\Unit\Weight; @@ -127,7 +128,9 @@ public static function effectiveHeight( public static function ratioToPpm(float $ratio): int { if ($ratio < 0.0 || $ratio > 1.0) { - throw new InvalidArgumentException('compression_ratio must be between zero and one'); + // Below zero is the schema's floor; the schema sets no ceiling, so above one stays + // the catch-all `invalid_value` every engine answers. + throw new ObjectRefusal($ratio < 0.0 ? 'below_minimum' : 'invalid_value', 'compression_ratio must be between zero and one'); } return (int)($ratio * self::PPM + 0.5); } diff --git a/src/Domain/Container.php b/src/Domain/Container.php index 004f533..40375e7 100644 --- a/src/Domain/Container.php +++ b/src/Domain/Container.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Unit\Length; use Packvium\Unit\Weight; final readonly class Container @@ -36,8 +37,8 @@ * @param list $obstacles @param list $tags @param array $tagLimits @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections @param list $preloaded */ public function __construct(public string $id,public Dimensions $innerDimensions,public ?Dimensions $outerDimensions=null,public Weight $tareWeight=new Weight(0),public ?Weight $maxPayload=null,public int $costMinor=0,public ?int $quantity=null,public array $obstacles=[],public array $tags=[],public ?int $maxItems=null,public array $metadata=[],public float $voidFillReserveRatio=0.0,public array $tagLimits=[],public ?Weight $maxStackDensity=null,public ?array $axles=null,public ?RateTable $rateTable=null,array $accessDirections=[],public array $preloaded=[],public ?string $deformableBoundary=null,public ?MadeToMeasure $madeToMeasure=null) - {if($id==='')throw new InvalidArgumentException('Container id is required');$madeToMeasure?->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]);if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio);if($quantity!==null&&$quantity<=0)throw new InvalidArgumentException('Container quantity must be positive');if($costMinor<0)throw new InvalidArgumentException('Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new InvalidArgumentException('Container max_items must be at least 1');if($voidFillReserveRatio<0||$voidFillReserveRatio>1)throw new InvalidArgumentException('void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new InvalidArgumentException('tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new InvalidArgumentException('Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new InvalidArgumentException("Obstacle {$o->id} lies outside container"); - if($axles!==null){[$front,$rear]=$axles;if($front->position->ticks>=$rear->position->ticks)throw new InvalidArgumentException('The front axle must be strictly nearer the origin than the rear axle');if($front->position->ticks<0||$rear->position->ticks>$innerDimensions->length->ticks)throw new InvalidArgumentException("Axle positions must lie within the container's length");} + {if($id==='')throw new ObjectRefusal('invalid_value','Container id is required');$madeToMeasure?->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]);if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio);if($quantity!==null&&$quantity<=0)throw new ObjectRefusal('below_minimum','Container quantity must be positive');if($costMinor<0)throw new ObjectRefusal('below_minimum','Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new ObjectRefusal('below_minimum','Container max_items must be at least 1');if(!($voidFillReserveRatio>=0&&$voidFillReserveRatio<=1))throw ObjectRefusal::ratio($voidFillReserveRatio,'void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new ObjectRefusal('below_minimum','tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new ObjectRefusal('invalid_value','Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new ObjectRefusal('invalid_value',"Obstacle {$o->id} lies outside container"); + if($axles!==null){[$front,$rear]=$axles;if($front->position->ticks>=$rear->position->ticks)throw new ObjectRefusal('invalid_value','The front axle must be strictly nearer the origin than the rear axle');if($front->position->ticks<0||$rear->position->ticks>$innerDimensions->length->ticks)throw new ObjectRefusal('invalid_value',"Axle positions must lie within the container's length");} foreach($accessDirections as $direction)if(!in_array($direction,SweptRegion::ALL_DIRECTIONS,true))throw new InvalidArgumentException("unknown movement direction {$direction}"); // Deduplicated into the canonical order rather than kept as given: two callers // naming the same doors in a different order must search identically. @@ -79,9 +80,9 @@ private static function dimensionsOf(array $sides):Dimensions{return new Dimensi */ private static function requireBagFields(string $kind,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio):void { - if(!in_array($kind,FlatBag::KINDS,true))throw new InvalidArgumentException("unknown deformable_boundary kind {$kind}"); + if(!in_array($kind,FlatBag::KINDS,true))throw new ObjectRefusal('not_allowed',"unknown deformable_boundary kind {$kind}"); $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'max_stack_density'=>$maxStackDensity!==null,'outer_dimensions'=>$outerDimensions!==null,'void_fill_reserve_ratio'=>$voidFillReserveRatio>0]; - foreach($present as $name=>$set)if($set)throw new InvalidArgumentException("{$name} cannot be combined with deformable_boundary"); + foreach($present as $name=>$set)if($set)throw new ObjectRefusal('not_allowed',"{$name} cannot be combined with deformable_boundary"); } public static function create(string $id,Dimensions $innerDimensions,Weight|int|string|array $tareWeight=0,Weight|int|string|array|null $maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],Weight|int|string|array|null $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],?string $deformableBoundary=null):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections,[],$deformableBoundary);} } diff --git a/src/Domain/Dimensions.php b/src/Domain/Dimensions.php index de073cb..0728f74 100644 --- a/src/Domain/Dimensions.php +++ b/src/Domain/Dimensions.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Support\BigInt; use Packvium\Unit\Length; use Packvium\Unit\Rounding; @@ -9,10 +10,12 @@ final readonly class Dimensions { public function __construct(public Length $length,public Length $width,public Length $height){if(min($length->ticks,$width->ticks,$height->ticks)<=0)throw new InvalidArgumentException('All dimensions must be positive');} - public static function of(int|string $l,int|string $w,int|string $h,string $unit='mm',Rounding $rounding=Rounding::Nearest):self{return new self(Length::of($l,$unit,$rounding),Length::of($w,$unit,$rounding),Length::of($h,$unit,$rounding));} + public static function of(int|string $l,int|string $w,int|string $h,string $unit='mm',Rounding $rounding=Rounding::Nearest):self{return self::read(Length::of($l,$unit,$rounding),Length::of($w,$unit,$rounding),Length::of($h,$unit,$rounding));} public static function mm(int|string $l,int|string $w,int|string $h,Rounding $rounding=Rounding::Nearest):self{return self::of($l,$w,$h,'mm',$rounding);} public static function inches(int|string $l,int|string $w,int|string $h,Rounding $rounding=Rounding::Nearest):self{return self::of($l,$w,$h,'in',$rounding);} - /** @param array{length:mixed,width:mixed,height:mixed} $data */ public static function fromArray(array $data,string $unit='mm',Rounding $rounding=Rounding::Nearest):self{return new self(Length::parse($data['length'],$unit,$rounding),Length::parse($data['width'],$unit,$rounding),Length::parse($data['height'],$unit,$rounding));} + /** @param array{length:mixed,width:mixed,height:mixed} $data */ public static function fromArray(array $data,string $unit='mm',Rounding $rounding=Rounding::Nearest):self{return self::read(Length::parse($data['length'],$unit,$rounding),Length::parse($data['width'],$unit,$rounding),Length::parse($data['height'],$unit,$rounding));} + /** Sides read from the caller's input, where a zero side is a request refusal; the constructor still guards the arithmetic. */ + private static function read(Length $length,Length $width,Length $height):self{if(min($length->ticks,$width->ticks,$height->ticks)<=0)throw new ObjectRefusal('invalid_value','All dimensions must be positive');return new self($length,$width,$height);} public function rotated(Rotation $r):self{return match($r){Rotation::LWH=>new self($this->length,$this->width,$this->height),Rotation::LHW=>new self($this->length,$this->height,$this->width),Rotation::WLH=>new self($this->width,$this->length,$this->height),Rotation::WHL=>new self($this->width,$this->height,$this->length),Rotation::HLW=>new self($this->height,$this->length,$this->width),Rotation::HWL=>new self($this->height,$this->width,$this->length)};} /** @param list $allowed @return list */ public function uniqueRotations(array $allowed):array{$seen=[];$out=[];foreach($allowed as $r){$d=$this->rotated($r);$k=$d->length->ticks.':'.$d->width->ticks.':'.$d->height->ticks;if(!isset($seen[$k])){$seen[$k]=true;$out[]=[$r,$d];}}return $out;} public function fitsInside(self $o):bool{return $this->length->ticks<=$o->length->ticks&&$this->width->ticks<=$o->width->ticks&&$this->height->ticks<=$o->height->ticks;} diff --git a/src/Domain/FixedPlacement.php b/src/Domain/FixedPlacement.php index d4279af..ce3efa2 100644 --- a/src/Domain/FixedPlacement.php +++ b/src/Domain/FixedPlacement.php @@ -1,7 +1,6 @@ containerId}#{$this->containerInstance}";} diff --git a/src/Domain/Item.php b/src/Domain/Item.php index e7afc96..70f8aa9 100644 --- a/src/Domain/Item.php +++ b/src/Domain/Item.php @@ -1,7 +1,7 @@ 1)throw new InvalidArgumentException('Minimum support ratio must be between 0 and 1');if($maxStackedItems!==null&&$maxStackedItems<1)throw new InvalidArgumentException('max_stacked_items must be at least 1');if($groundContactRule!==null&&!in_array($groundContactRule,self::GROUND_CONTACT_RULES,true))throw new InvalidArgumentException('ground_contact_rule must be one of '.implode(', ',self::GROUND_CONTACT_RULES)); - if($nestingHeight!==null&&!($nestingHeight->ticks>=0&&$nestingHeight->ticks<$dimensions->height->ticks))throw new InvalidArgumentException("nesting_height must be at least zero and strictly less than the item's own height"); - if($stopIndex!==null&&($stopIndex<0||$stopIndex>self::MAX_EXACT_STOP_INDEX))throw new InvalidArgumentException('stop_index must be a non-negative safe integer'); - if($value!==null&&$value<0)throw new InvalidArgumentException('value must be non-negative'); - if($keepUpright)$allowedRotations=array_values(array_filter($allowedRotations,static fn(Rotation $r)=>in_array($r,Rotation::upright(),true)));if($allowedRotations===[])throw new InvalidArgumentException('At least one rotation must be allowed'); + if($id==='')throw new ObjectRefusal('invalid_value','Item id is required');if($quantity<=0)throw new ObjectRefusal('below_minimum','Item quantity must be positive');if(!($minimumSupportRatio>=0&&$minimumSupportRatio<=1))throw ObjectRefusal::ratio($minimumSupportRatio,'Minimum support ratio must be between 0 and 1');if($maxStackedItems!==null&&$maxStackedItems<1)throw new ObjectRefusal('below_minimum','max_stacked_items must be at least 1');if($groundContactRule!==null&&!in_array($groundContactRule,self::GROUND_CONTACT_RULES,true))throw new ObjectRefusal('not_allowed','ground_contact_rule must be one of '.implode(', ',self::GROUND_CONTACT_RULES)); + if($nestingHeight!==null&&!($nestingHeight->ticks>=0&&$nestingHeight->ticks<$dimensions->height->ticks))throw new ObjectRefusal('invalid_value',"nesting_height must be at least zero and strictly less than the item's own height"); + if($stopIndex!==null&&($stopIndex<0||$stopIndex>self::MAX_EXACT_STOP_INDEX))throw new ObjectRefusal($stopIndex<0?'below_minimum':'above_maximum','stop_index must be a non-negative safe integer'); + if($value!==null&&$value<0)throw new ObjectRefusal('below_minimum','value must be non-negative'); + if($keepUpright)$allowedRotations=array_values(array_filter($allowedRotations,static fn(Rotation $r)=>in_array($r,Rotation::upright(),true)));if($allowedRotations===[])throw new ObjectRefusal('invalid_value','At least one rotation must be allowed'); $this->id=$id;$this->dimensions=$dimensions;$this->weight=$weight??new Weight(0);$this->quantity=$quantity;$this->allowedRotations=$allowedRotations;$this->keepUpright=$keepUpright;$this->stackable=$stackable;$this->mustBeOnFloor=$mustBeOnFloor;$this->maxTopLoad=$maxTopLoad;$this->minimumSupportRatio=$minimumSupportRatio;$this->groundContactRule=$groundContactRule;$this->group=$group;$this->tags=array_values(array_unique($tags));$this->incompatibleTags=array_values(array_unique($incompatibleTags));$this->priority=$priority;$this->metadata=$metadata;$this->maxStackedItems=$maxStackedItems;$this->eligibleContainerTags=array_values(array_unique($eligibleContainerTags));$this->nestingHeight=$nestingHeight;$this->stopIndex=$stopIndex;$this->value=$value; $this->shapeType=$shapeType; $this->hullVertices=self::admitShape($shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa,$dimensions,$nestingHeight); @@ -77,15 +77,18 @@ private static function admitShape(ShapeType $shapeType,?array $hullVertices,?in ShapeType::COMPRESSIBLE=>['hull_vertices'=>$hullVertices], ShapeType::RIGID_CUBOID=>['hull_vertices'=>$hullVertices,'compression_ratio'=>$ratioPpm,'max_compression_pressure_kpa'=>$limitKpa], }; + // The value's own floor first, as the JSON rules check it before the shape. + if($limitKpa!==null&&$limitKpa<0) + throw new ObjectRefusal('below_minimum','max_compression_pressure_kpa cannot be negative'); foreach($foreign as $name=>$value){ - if($value!==null)throw new InvalidArgumentException("{$name} is not part of a {$shapeType->value} item"); + if($value!==null)throw new ObjectRefusal('invalid_value',"{$name} is not part of a {$shapeType->value} item"); } // Both rewrite occupied height. Choosing an order silently would give four engines // four contracts, so the interaction is refused until a task defines it. if($nestingHeight!==null&&$shapeType!==ShapeType::RIGID_CUBOID) - throw new InvalidArgumentException("nesting_height with shape_type {$shapeType->value} is not supported yet"); + throw new ObjectRefusal('invalid_value',"nesting_height with shape_type {$shapeType->value} is not supported yet"); if($shapeType===ShapeType::CONVEX_HULL){ - if($hullVertices===null)throw new InvalidArgumentException('a convex_hull item requires hull_vertices'); + if($hullVertices===null)throw new ObjectRefusal('invalid_value','a convex_hull item requires hull_vertices'); $hullVertices=HullShape::validate($hullVertices); [$low,$high]=HullShape::boundingExtent($hullVertices); $declared=[$dimensions->length->ticks,$dimensions->width->ticks,$dimensions->height->ticks]; @@ -94,17 +97,15 @@ private static function admitShape(ShapeType $shapeType,?array $hullVertices,?in // a hull poking out of it would be collision-tested against space the solver // never reserved. if($high[$axis]-$low[$axis]>$declared[$axis]) - throw new InvalidArgumentException('hull_vertices span does not fit inside dimensions'); + throw new ObjectRefusal('invalid_value','hull_vertices span does not fit inside dimensions'); } return $hullVertices; } if($shapeType===ShapeType::COMPRESSIBLE){ if($ratioPpm===null||$limitKpa===null) - throw new InvalidArgumentException('a compressible item requires both compression_ratio and max_compression_pressure_kpa'); + throw new ObjectRefusal('invalid_value','a compressible item requires both compression_ratio and max_compression_pressure_kpa'); if($ratioPpm<0||$ratioPpm>Compression::PPM) - throw new InvalidArgumentException('compression_ratio must be between zero and one'); - if($limitKpa<0) - throw new InvalidArgumentException('max_compression_pressure_kpa cannot be negative'); + throw new ObjectRefusal('invalid_value','compression_ratio must be between zero and one'); } return $hullVertices; } diff --git a/src/Domain/MadeToMeasure.php b/src/Domain/MadeToMeasure.php index 2bd303a..be8f1e0 100644 --- a/src/Domain/MadeToMeasure.php +++ b/src/Domain/MadeToMeasure.php @@ -1,7 +1,7 @@ $name){ - if($this->minimum[$axis]>$maximum[$axis])throw new InvalidArgumentException("made_to_measure minimum {$name} exceeds inner_dimensions"); - if(($maximum[$axis]-$this->minimum[$axis])%$this->increment[$axis]!==0)throw new InvalidArgumentException("made_to_measure increment {$name} does not divide inner_dimensions minus minimum"); + if($this->minimum[$axis]>$maximum[$axis])throw new ObjectRefusal('invalid_value',"made_to_measure minimum {$name} exceeds inner_dimensions"); + if(($maximum[$axis]-$this->minimum[$axis])%$this->increment[$axis]!==0)throw new ObjectRefusal('invalid_value',"made_to_measure increment {$name} does not divide inner_dimensions minus minimum"); } } diff --git a/src/Domain/PackingRequest.php b/src/Domain/PackingRequest.php index 36840bb..846a844 100644 --- a/src/Domain/PackingRequest.php +++ b/src/Domain/PackingRequest.php @@ -1,10 +1,10 @@ $items @param list $containers @param list $fixedPlacements */ public function __construct(public array $items,public array $containers,public array $fixedPlacements=[]){if($items===[])throw new InvalidArgumentException('At least one item is required');if($containers===[])throw new InvalidArgumentException('At least one container is required');self::unique(array_map(fn(Item $i)=>$i->id,$items),'item');self::unique(array_map(fn(Container $c)=>$c->id,$containers),'container');} + /** @param list $items @param list $containers @param list $fixedPlacements */ public function __construct(public array $items,public array $containers,public array $fixedPlacements=[]){if($items===[])throw new ObjectRefusal('invalid_value','At least one item is required');if($containers===[])throw new ObjectRefusal('invalid_value','At least one container is required');self::unique(array_map(fn(Item $i)=>$i->id,$items),'item');self::unique(array_map(fn(Container $c)=>$c->id,$containers),'container');} /** @return list */ public function instances():array{$out=[];foreach($this->items as $i)array_push($out,...$i->instances());return $out;} - private static function unique(array $ids,string $kind):void{if(count($ids)!==count(array_unique($ids)))throw new InvalidArgumentException(ucfirst($kind).' ids must be unique');} + private static function unique(array $ids,string $kind):void{if(count($ids)!==count(array_unique($ids)))throw new ObjectRefusal('duplicate_id',ucfirst($kind).' ids must be unique');} } diff --git a/src/Domain/RateTable.php b/src/Domain/RateTable.php index 1f0f677..afe9e7d 100644 --- a/src/Domain/RateTable.php +++ b/src/Domain/RateTable.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; -use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; /** * A carrier rate card carried by the request rather than by a code plugin. @@ -30,31 +30,31 @@ public function __construct( public readonly int $fuelSurchargePermille = 0, ) { if ($weightBracketsG === []) { - throw new InvalidArgumentException('rate_table requires at least one weight bracket'); + throw new ObjectRefusal('invalid_value', 'rate_table requires at least one weight bracket'); } if (count($weightBracketsG) !== count($pricesMinor)) { - throw new InvalidArgumentException('rate_table weight_brackets_g and prices_minor must be the same length'); + throw new ObjectRefusal('invalid_value', 'rate_table weight_brackets_g and prices_minor must be the same length'); } $previous = 0; foreach ($weightBracketsG as $bound) { if ($bound <= 0) { - throw new InvalidArgumentException('rate_table weight brackets must be positive'); + throw new ObjectRefusal('below_minimum', 'rate_table weight brackets must be positive'); } if ($bound <= $previous) { - throw new InvalidArgumentException('rate_table weight brackets must be strictly ascending'); + throw new ObjectRefusal('invalid_value', 'rate_table weight brackets must be strictly ascending'); } $previous = $bound; } foreach ($pricesMinor as $price) { if ($price < 0) { - throw new InvalidArgumentException('rate_table prices cannot be negative'); + throw new ObjectRefusal('below_minimum', 'rate_table prices cannot be negative'); } } if ($minimumChargeMinor < 0) { - throw new InvalidArgumentException('rate_table minimum_charge_minor cannot be negative'); + throw new ObjectRefusal('below_minimum', 'rate_table minimum_charge_minor cannot be negative'); } if ($fuelSurchargePermille < 0) { - throw new InvalidArgumentException('rate_table fuel_surcharge_permille cannot be negative'); + throw new ObjectRefusal('below_minimum', 'rate_table fuel_surcharge_permille cannot be negative'); } } diff --git a/src/Packer.php b/src/Packer.php index 608e8f7..9585f46 100644 --- a/src/Packer.php +++ b/src/Packer.php @@ -4,7 +4,7 @@ namespace Packvium; use Packvium\Algorithm\{Deadline, FixedPlacementAdmission, SolverOrchestrator}; -use Packvium\Support\{StableSorter, UnsupportedPlacements}; +use Packvium\Support\{RequestObjects, StableSorter, UnsupportedPlacements}; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, UnratedWeightException}; use Packvium\Extension\ExtensionRegistry; @@ -29,6 +29,9 @@ public function __construct( /** @param list $items @param list $containers @param list $fixedPlacements */ public function pack(array $items, array $containers, array $fixedPlacements = []): PackingResult { + // The JSON path's rules, with the JSON path's reason and field: a request + // built from objects is refused exactly where the same request as JSON would be. + RequestObjects::check($items, $containers, $this->config, $fixedPlacements); $request = new PackingRequest($items, $containers, $fixedPlacements); // Both cost objectives price the same billed weight, so both need the divisor. // There is no library-chosen default: a wrong guess would silently misprice diff --git a/src/Revisions/PlanRevision.php b/src/Revisions/PlanRevision.php index 6231965..d99e25b 100644 --- a/src/Revisions/PlanRevision.php +++ b/src/Revisions/PlanRevision.php @@ -364,7 +364,7 @@ private static function validatePlacement(stdClass $event): void self::requireName(JsonValue::get($placement, 'item_type'), 'placement.item_type'); self::requireName(JsonValue::get($placement, 'container_type'), 'placement.container_type'); if (!\in_array(JsonValue::get($placement, 'orientation'), FixedPlacementShape::ORIENTATIONS, true)) { - throw new PlanRevisionException('invalid_event', 'placement.orientation is one of the six codes'); + throw new PlanRevisionException('invalid_event', 'placement.orientation must be one of ' . CanonicalJson::spelling(FixedPlacementShape::ORIENTATIONS)); } $instance = JsonValue::has($placement, 'container_instance') ? JsonValue::integer($placement->container_instance) : 1; if ($instance === null || $instance < 1) { diff --git a/src/Sequence/LoadingDependencyGraph.php b/src/Sequence/LoadingDependencyGraph.php index 2276bc2..f27a790 100644 --- a/src/Sequence/LoadingDependencyGraph.php +++ b/src/Sequence/LoadingDependencyGraph.php @@ -243,7 +243,7 @@ public static function verifyLoadingPrefixBusinessRules(array $placements, array array_slice($present, 0, -1), $candidate->instance, $candidateBox, ); $count = count($support->supporterBoxes); - $violated = ($rule === 'covered' && !\Packvium\Constraint\SupportConstraint::touchesCorners($candidateBox, $support->surfaces)) + $violated = ($rule === 'covered' && !\Packvium\Constraint\SupportConstraint::touchesCorners($candidateBox, $support->supporterBoxes)) || ($rule === 'single' && $count !== 1) || ($rule === 'multiple' && $count < 2); if ($violated) { diff --git a/src/Sequence/SequenceGeometry.php b/src/Sequence/SequenceGeometry.php index 3b777fe..61d472d 100644 --- a/src/Sequence/SequenceGeometry.php +++ b/src/Sequence/SequenceGeometry.php @@ -102,25 +102,32 @@ public static function validateBoxAtStep(int $index, int $step, array $boxes, ar } } - /** @param array> $dependsOn */ + /** + * Kahn's algorithm: acyclic exactly when every node can be released. O(V + E). + * + * Iterative, not a depth-first walk: a stack of sheets is a dependency chain as long + * as the stack, and recursion spent one frame per level. + * + * @param array> $dependsOn + */ public static function isAcyclic(array $dependsOn): bool { - $visiting = []; - $visited = []; - $visit = function (int $node) use (&$visit, &$visiting, &$visited, $dependsOn): bool { - if (isset($visited[$node])) { return true; } - if (isset($visiting[$node])) { return false; } - $visiting[$node] = true; + $waiting = []; + foreach ($dependsOn as $node => $dependencies) { + $waiting[$node] = $waiting[$node] ?? 0; + foreach (array_keys($dependencies) as $dependency) { + $waiting[$dependency] = ($waiting[$dependency] ?? 0) + 1; + } + } + $ready = array_keys(array_filter($waiting, static fn(int $count): bool => $count === 0)); + $released = 0; + while ($ready !== []) { + $node = array_pop($ready); + $released++; foreach (array_keys($dependsOn[$node] ?? []) as $dependency) { - if (!$visit($dependency)) { return false; } + if (--$waiting[$dependency] === 0) { $ready[] = $dependency; } } - unset($visiting[$node]); - $visited[$node] = true; - return true; - }; - foreach (array_keys($dependsOn) as $node) { - if (!$visit($node)) { return false; } } - return true; + return $released === count($waiting); } } diff --git a/src/Serialization/ArrayCodec.php b/src/Serialization/ArrayCodec.php index 96c15cf..8e3db02 100644 --- a/src/Serialization/ArrayCodec.php +++ b/src/Serialization/ArrayCodec.php @@ -9,7 +9,7 @@ use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; use Packvium\Policy\PolicyRuleSet; -use Packvium\Support\{FixedPlacementShape,JsonValue,MeasureReading,RequestRules}; +use Packvium\Support\{FixedPlacementShape,JsonValue,MeasureReading,ObjectRefusal,RequestRules}; use Packvium\Unit\{Length,Weight}; use Throwable; use TypeError; @@ -150,6 +150,17 @@ public static function madeToMeasureCombinations(array $data):array } /** @return array a collection to scan, or nothing when it is not one */ + /** + * The output unit a request without `output.length_unit` is written in: the + * request's own `units.length`, spelt as the schema's output code, so `Inches` is `in`. + * A unit no output code names -- the internal `tick` -- gives `mm`, the default of both blocks. + */ + private static function outputLengthCode(string $requestUnit):string + { + $multiplier=Length::multiplier($requestUnit); + foreach(['mm','cm','m','in','ft'] as $code)if(Length::multiplier($code)===$multiplier)return $code; + return 'mm'; + } private static function entries(array $data,string $collection):array{$entries=$data[$collection]??[];return is_array($entries)?$entries:[];} /** @@ -172,7 +183,7 @@ public static function pack($data):array catch(InvalidArgumentException|TypeError|ValueError|ArithmeticError $error){throw self::asRequestError($error);} $unit=(string)($data['units']['length']??'mm'); $out=$data['output']??[]; - $result=(new Packer($config,$extensions))->pack($items,$containers,$fixed)->toArray($out['length_unit']??$unit,$out['weight_unit']??'g'); + $result=(new Packer($config,$extensions))->pack($items,$containers,$fixed)->toArray($out['length_unit']??self::outputLengthCode($unit),$out['weight_unit']??'g'); $result['catalog_versions_used']=$references; return $result; } @@ -209,6 +220,9 @@ private static function model(array $data):array */ private static function asRequestError(Throwable $error):Throwable { + // A model's own refusal names a reason for the object API; these rules did not name + // this value, and every engine reports that as `invalid_value` with no field. + if($error instanceof ObjectRefusal)return new InvalidRequestException('invalid_value','',$error->detail(),$error); if($error instanceof InvalidRequestException||$error instanceof UnsupportedFeatureException||method_exists($error,'errorCode'))return $error; return new InvalidRequestException('invalid_value','',$error->getMessage(),$error); } diff --git a/src/Support/FixedPlacementShape.php b/src/Support/FixedPlacementShape.php index c566d35..fad8cdb 100644 --- a/src/Support/FixedPlacementShape.php +++ b/src/Support/FixedPlacementShape.php @@ -93,7 +93,7 @@ private static function requireEntry($entry, string $where, string $field, strin } } if (!\in_array(JsonValue::get($entry, 'orientation'), self::ORIENTATIONS, true)) { - throw self::malformed("{$where}.orientation is one of the six codes", "{$field}/orientation"); + throw self::malformed("{$where}.orientation must be one of " . CanonicalJson::spelling(self::ORIENTATIONS), "{$field}/orientation"); } $instance = JsonValue::has($entry, 'container_instance') ? JsonValue::integer(JsonValue::get($entry, 'container_instance')) : 1; if ($instance === null || $instance < 1) { diff --git a/src/Support/ObjectRefusal.php b/src/Support/ObjectRefusal.php new file mode 100644 index 0000000..674ebb9 --- /dev/null +++ b/src/Support/ObjectRefusal.php @@ -0,0 +1,40 @@ + 1 ? 'above_maximum' : 'invalid_value'); + return new self($reason, $detail); + } + + /** + * The text a model has always thrown, so a wrapper that quotes it (a commerce document, + * a measure verdict, cross-engine conformance) reads exactly what it read before. + */ + protected function composeMessage(): string + { + return $this->detail(); + } +} diff --git a/src/Support/RationalParser.php b/src/Support/RationalParser.php index b23a5cf..c224122 100644 --- a/src/Support/RationalParser.php +++ b/src/Support/RationalParser.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Support; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Unit\Rounding; final class RationalParser { @@ -30,13 +31,13 @@ public static function parse(int|string $value): array if (preg_match('/^([+-]?\d+)\s*\/\s*(\d+)$/', $text, $m)) { $n = self::parseWhole($m[1]); $d = self::parseWhole($m[2]); self::assertDenominator($d); return [$n, $d]; } - if (!preg_match('/^([+-]?)(\d+)(?:\.(\d+))?$/', $text, $m)) { throw new InvalidArgumentException("Invalid decimal or fraction: {$text}"); } + if (!preg_match('/^([+-]?)(\d+)(?:\.(\d+))?$/', $text, $m)) { throw new ObjectRefusal('wrong_type', "Invalid decimal or fraction: {$text}"); } $fraction = $m[3] ?? ''; if ($fraction === '') { $num = self::parseWhole($m[2]); return [$negative ? -$num : $num, 1]; } - if (strlen($fraction) > 18) { throw new InvalidArgumentException('Decimal has more fractional digits than a tick can distinguish'); } + if (strlen($fraction) > 18) { throw new ObjectRefusal('wrong_type', 'Decimal has more fractional digits than a tick can distinguish'); } $den = 10 ** strlen($fraction); $intPart = self::parseWhole($m[2]); if ($intPart !== 0 && $intPart > intdiv(PHP_INT_MAX - (int)$fraction, $den)) { diff --git a/src/Support/RequestObjects.php b/src/Support/RequestObjects.php new file mode 100644 index 0000000..4c44bc8 --- /dev/null +++ b/src/Support/RequestObjects.php @@ -0,0 +1,225 @@ + `PackingConfig` property, for each of `RequestRules::CONFIGURATION_INTEGERS`. */ + private const CONFIGURATION_PROPERTIES = [ + 'time_limit_ms' => 'timeLimitMs', 'alternatives' => 'topK', 'max_containers' => 'maxContainers', + 'exact_item_limit' => 'exactItemLimit', 'multi_start_orders' => 'multiStartOrders', + 'max_candidates_per_item' => 'maxCandidatesPerItem', 'max_candidate_points' => 'maxCandidatePoints', + 'container_plan_beam_width' => 'containerPlanBeamWidth', 'container_plan_node_limit' => 'containerPlanNodeLimit', + 'dimensional_weight_divisor' => 'dimensionalWeightDivisor', + ]; + /** JSON name => `EffortBudget` property, for each of `RequestRules::EFFORT_LIMITS`. */ + private const EFFORT_PROPERTIES = [ + 'max_candidates_evaluated' => 'maxCandidatesEvaluated', 'max_placement_attempts' => 'maxPlacementAttempts', + 'max_search_nodes' => 'maxSearchNodes', 'max_restarts' => 'maxRestarts', + ]; + + /** + * Refuse the request with its first violation, or return. + * + * @param list $items + * @param list $containers + * @param list $fixedPlacements + * @throws InvalidRequestException + */ + public static function check(array $items, array $containers, PackingConfig $config, array $fixedPlacements = []): void + { + self::configuration($config); + foreach ($items as $index => $item) { + self::item($item, "/items/{$index}"); + } + RequestRules::requireUniqueIds(\array_map(static fn(Item $item): string => $item->id, $items), 'items'); + foreach ($containers as $index => $container) { + self::container($container, "/containers/{$index}"); + } + RequestRules::requireUniqueIds(\array_map(static fn(Container $container): string => $container->id, $containers), 'containers'); + foreach ($fixedPlacements as $index => $placement) { + self::fixedPlacement($placement, "fixed_placements[{$index}]", "/fixed_placements/{$index}"); + } + } + + /** + * `FixedPlacementShape`'s rules that an object can break, in its order and with its refusal; + * the types hold the orientation and the position, and `Point` refuses a negative + * coordinate. Whether the set can hold is `FixedPlacementAdmission`'s to say. + */ + private static function fixedPlacement(FixedPlacement $placement, string $where, string $field): void + { + foreach (['item_type' => $placement->itemId, 'container_type' => $placement->containerId] as $name => $value) { + if ($value === '') { + throw new FixedPlacementException("{$where}.{$name} is a non-empty string", 'malformed', "{$field}/{$name}"); + } + } + $instance = JsonValue::integer($placement->containerInstance); + if ($instance === null || $instance < 1) { + throw new FixedPlacementException("{$where}.container_instance counts from 1", 'malformed', "{$field}/container_instance"); + } + } + + /** + * `objective` is not checked here: an unknown one keeps its own, older error on this path, + * `UnknownObjectiveException`, thrown when the objective is resolved. + */ + private static function configuration(PackingConfig $config): void + { + $where = '/configuration'; + foreach (RequestRules::CONFIGURATION_INTEGERS as $name => $minimum) { + $property = self::CONFIGURATION_PROPERTIES[$name]; + self::optionalInteger($config->{$property}, "{$where}/{$name}", $minimum); + } + RequestRules::ratio($config->minimumSupportRatio, "{$where}/minimum_support_ratio", 1); + $budget = $config->effortBudget; + if ($budget === null) { + return; + } + foreach (RequestRules::EFFORT_LIMITS as $name) { + $property = self::EFFORT_PROPERTIES[$name]; + self::optionalInteger($budget->{$property}, "{$where}/effort_budget/{$name}", 1); + } + } + + private static function item(Item $item, string $where): void + { + RequestRules::integer($item->quantity, "{$where}/quantity", 1); + self::optionalInteger($item->maxStackedItems, "{$where}/max_stacked_items", 1); + self::optionalInteger($item->stopIndex, "{$where}/stop_index", 0); + self::optionalInteger($item->value, "{$where}/value", 0); + self::optionalInteger($item->maxCompressionPressureKpa, "{$where}/max_compression_pressure_kpa", 0); + RequestRules::ratio($item->minimumSupportRatio, "{$where}/minimum_support_ratio", 1); + if ($item->stackingGroup !== null) { + RequestRules::stackingGroupName($item->stackingGroup, "{$where}/stacking_group"); + } + foreach (self::codePointOrder($item->acceptsStackingGroups) as $index => $name) { + RequestRules::stackingGroupName($name, "{$where}/accepts_stacking_groups/{$index}"); + } + } + + private static function container(Container $container, string $where): void + { + self::optionalInteger($container->quantity, "{$where}/quantity", 1); + self::optionalInteger($container->maxItems, "{$where}/max_items", 1); + RequestRules::integer($container->costMinor, "{$where}/cost_minor", 0); + RequestRules::ratio($container->voidFillReserveRatio, "{$where}/void_fill_reserve_ratio", 1); + self::tagLimits($container->tagLimits, "{$where}/tag_limits"); + if ($container->rateTable !== null) { + self::rateTable($container->rateTable, "{$where}/rate_table"); + } + if ($container->deformableBoundary !== null) { + self::flatBag($container, $where); + } + if ($container->madeToMeasure !== null) { + self::madeToMeasure($container, $container->madeToMeasure, $where); + } + } + + /** + * `strcmp` on the tags' strings -- PHP made `"10"` the key 10 -- is UTF-8 byte order, + * which is code-point order. O(t log t) for t tags. + * + * @param array $limits + */ + private static function tagLimits(array $limits, string $where): void + { + $tags = \array_map('strval', \array_keys($limits)); + \usort($tags, 'strcmp'); + foreach ($tags as $tag) { + RequestRules::integer($limits[$tag], RequestRules::pointer($where, $tag), 1); + } + } + + private static function rateTable(RateTable $table, string $where): void + { + foreach (['weight_brackets_g' => [$table->weightBracketsG, 1], 'prices_minor' => [$table->pricesMinor, 0]] as $name => [$values, $minimum]) { + foreach ($values as $index => $value) { + RequestRules::integer($value, "{$where}/{$name}/{$index}", $minimum); + } + } + RequestRules::integer($table->minimumChargeMinor, "{$where}/minimum_charge_minor", 0); + RequestRules::integer($table->fuelSurchargePermille, "{$where}/fuel_surcharge_permille", 0); + } + + /** + * The fields a flat bag refuses, in the JSON rules' order. The container's constructor + * already refused an unknown kind and every field but `made_to_measure`, with no field + * named; walking them all keeps the order the JSON path reports in. An empty list is how + * an object leaves a list field out; JSON leaves it absent. + */ + private static function flatBag(Container $container, string $where): void + { + $fields = [ + 'obstacles' => $container->obstacles, 'axles' => $container->axles, + 'access_directions' => $container->accessDirections, 'max_stack_density' => $container->maxStackDensity, + 'outer_dimensions' => $container->outerDimensions, 'void_fill_reserve_ratio' => $container->voidFillReserveRatio, + 'made_to_measure' => $container->madeToMeasure, + ]; + foreach (RequestRules::BAG_EXCLUSIONS as $name) { + $value = $fields[$name] === [] ? null : $fields[$name]; + if (RequestRules::setBesideABag($name, $value)) { + throw new InvalidRequestException('not_allowed', "{$where}/{$name}", 'cannot be combined with deformable_boundary'); + } + } + } + + private static function madeToMeasure(Container $container, MadeToMeasure $machine, string $where): void + { + $price = "{$where}/made_to_measure/cost_per_square_metre_minor"; + RequestRules::integer($machine->costPerSquareMetreMinor, $price, 0); + if ($container->outerDimensions !== null) { + throw new InvalidRequestException('not_allowed', "{$where}/outer_dimensions", 'cannot be combined with made_to_measure'); + } + $inner = $container->innerDimensions; + $largest = MadeToMeasure::boxCostFor($machine->costPerSquareMetreMinor, $container->costMinor, + [$inner->length->ticks, $inner->width->ticks, $inner->height->ticks]); + if (BigInt::compare($largest, MadeToMeasure::MAX_EXACT_INTEGER) > 0) { + throw new InvalidRequestException('invalid_value', $price, 'prices the largest box above ' . CanonicalJson::MAX_EXACT_MAGNITUDE); + } + } + + private static function optionalInteger(?int $value, string $field, int $minimum): void + { + if ($value !== null) { + RequestRules::integer($value, $field, $minimum); + } + } + + /** + * Strings in code-point order; anything mistyped after them, so it is still checked. + * + * @param list $values + * @return list + */ + private static function codePointOrder(array $values): array + { + \usort($values, static fn($left, $right): int => (\is_string($right) <=> \is_string($left)) + ?: (\is_string($left) && \is_string($right) ? \strcmp($left, $right) : 0)); + return $values; + } +} diff --git a/src/Support/RequestRules.php b/src/Support/RequestRules.php index 3100b3f..b5748f6 100644 --- a/src/Support/RequestRules.php +++ b/src/Support/RequestRules.php @@ -13,7 +13,7 @@ * The request schema's rules, walked over the decoded JSON before any model is built. * * Held to `packvium.request_errors.check_request`: the first violation wins, in the order every - * engine follows -- units, configuration, items, containers -- and is refused with the same + * engine follows -- units, output, configuration, items, containers -- and is refused with the same * reason, JSON Pointer and message the reference raises. * * The request arrives from `json_decode(..., true)`, where `{}` and `[]` are the same empty @@ -25,13 +25,21 @@ final class RequestRules public const SOLVER_PROFILES = ['fast', 'balanced', 'quality', 'exact_small']; public const OBJECTIVES = ['default', 'lowest_cost', 'shipping_cost', 'lowest_landed_cost', 'open_dimension_height', 'maximum_value', 'maximum_volume']; public const ACCESS_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; - - private const CONFIGURATION_INTEGERS = [ + /** The schema's closed vocabularies, each refused as `not_allowed` like the two above. */ + public const SOLVERS = ['grid', 'extreme_points', 'homogeneous_blocks', 'layer', 'maximal_spaces', 'exact_small']; + public const ROTATIONS = ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']; + public const LENGTH_UNITS = ['mm', 'cm', 'm', 'in', 'ft']; + public const WEIGHT_UNITS = ['mg', 'g', 'kg', 'oz', 'lb']; + public const GROUND_CONTACT_RULES = ['free', 'covered', 'single', 'multiple']; + public const SHAPE_TYPES = ['rigid_cuboid', 'convex_hull', 'compressible']; + + /** Shared with `RequestObjects`, which walks the same fields over a request of objects. */ + public const CONFIGURATION_INTEGERS = [ 'time_limit_ms' => 1, 'alternatives' => 1, 'max_containers' => 1, 'exact_item_limit' => 1, 'multi_start_orders' => 1, 'max_candidates_per_item' => 1, 'max_candidate_points' => 16, 'container_plan_beam_width' => 1, 'container_plan_node_limit' => 1, 'dimensional_weight_divisor' => 1, ]; - private const EFFORT_LIMITS = ['max_candidates_evaluated', 'max_placement_attempts', 'max_search_nodes', 'max_restarts']; + public const EFFORT_LIMITS = ['max_candidates_evaluated', 'max_placement_attempts', 'max_search_nodes', 'max_restarts']; /** Every key the request schema's `configuration` declares; it sets `additionalProperties: false`. */ private const CONFIGURATION_FIELDS = [ 'alternatives', 'clearance', 'container_plan_beam_width', 'container_plan_node_limit', @@ -42,7 +50,7 @@ final class RequestRules ]; private const SIDES = ['length', 'width', 'height']; /** Container fields a flat bag refuses, in reporting order (docs/DEFORMABLE-CONTAINERS.md). */ - private const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', + public const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure']; /** Every key the request schema's `made_to_measure` declares; it sets `additionalProperties: false`. */ private const MADE_TO_MEASURE_FIELDS = ['cost_per_square_metre_minor', 'increment', 'minimum', 'outer_allowance', @@ -59,21 +67,22 @@ public static function check($data): void { $request = self::objectAt($data, ''); $unit = self::units(JsonValue::get($request, 'units')); + self::output(JsonValue::get($request, 'output')); self::configuration(JsonValue::get($request, 'configuration'), $unit); $items = self::requiredList($request, 'items', ''); foreach ($items as $index => $raw) { self::item($raw, "/items/{$index}", $unit); } - self::requireUniqueIds($items, 'items'); + self::requireUniqueIds(self::identifiers($items), 'items'); $containers = self::requiredList($request, 'containers', ''); foreach ($containers as $index => $raw) { self::container($raw, "/containers/{$index}", $unit); } - self::requireUniqueIds($containers, 'containers'); + self::requireUniqueIds(self::identifiers($containers), 'containers'); } /** The RFC 6901 pointer to one member, escaping `~` and `/` in its name. */ - private static function pointer(string $base, string $name): string + public static function pointer(string $base, string $name): string { return $base . '/' . \str_replace(['~', '/'], ['~0', '~1'], $name); } @@ -96,6 +105,17 @@ private static function units($raw): string return $length; } + /** @param mixed $raw */ + private static function output($raw): void + { + if ($raw === null) { + return; + } + $output = self::objectAt($raw, '/output'); + self::optionalOneOf($output, 'length_unit', '/output', self::LENGTH_UNITS); + self::optionalOneOf($output, 'weight_unit', '/output', self::WEIGHT_UNITS); + } + /** @param mixed $raw */ private static function configuration($raw, string $unit): void { @@ -105,16 +125,11 @@ private static function configuration($raw, string $unit): void $where = '/configuration'; $configuration = self::objectAt($raw, $where); self::knownFields($configuration, $where, self::CONFIGURATION_FIELDS); - $profile = JsonValue::get($configuration, 'solver_profile'); - if ($profile !== null && !\in_array($profile, self::SOLVER_PROFILES, true)) { - throw self::refuse('not_allowed', "{$where}/solver_profile", - 'must be one of ' . CanonicalJson::spelling(self::SOLVER_PROFILES)); - } - $objective = JsonValue::get($configuration, 'objective'); - if ($objective !== null && !\in_array($objective, self::OBJECTIVES, true)) { - throw self::refuse('not_allowed', "{$where}/objective", - 'must be one of ' . CanonicalJson::spelling(self::OBJECTIVES)); - } + self::optionalOneOf($configuration, 'solver_profile', $where, self::SOLVER_PROFILES); + self::optionalOneOf($configuration, 'objective', $where, self::OBJECTIVES); + self::optionalEachOneOf($configuration, 'solvers', $where, self::SOLVERS); + self::optionalOneOf($configuration, 'dimensional_weight_length_unit', $where, self::LENGTH_UNITS); + self::optionalOneOf($configuration, 'dimensional_weight_weight_unit', $where, self::WEIGHT_UNITS); foreach (self::CONFIGURATION_INTEGERS as $name => $minimum) { self::optionalInteger($configuration, $name, $where, $minimum); } @@ -130,6 +145,24 @@ private static function configuration($raw, string $unit): void } } + /** + * A nested copy sinks by less than its own height, or it would vanish into the one below + *. Both measures have passed their own rules already. O(1). + * + * @param stdClass|array $item + */ + private static function nestingBelowHeight($item, string $where, string $unit): void + { + $nesting = JsonValue::get($item, 'nesting_height'); + if ($nesting === null) { + return; + } + $height = JsonValue::get(JsonValue::get($item, 'dimensions'), 'height'); + if (MeasureReading::ticks($nesting, Length::class, $unit) >= MeasureReading::ticks($height, Length::class, $unit)) { + throw self::refuse('invalid_value', "{$where}/nesting_height", "must be less than the item's height"); + } + } + /** @param mixed $raw */ private static function item($raw, string $where, string $unit): void { @@ -140,6 +173,7 @@ private static function item($raw, string $where, string $unit): void self::optionalMeasure($item, 'weight', $where, Weight::class, self::WEIGHT_UNIT); self::optionalMeasure($item, 'max_top_load', $where, Weight::class, self::WEIGHT_UNIT); self::optionalMeasure($item, 'nesting_height', $where, Length::class, $unit); + self::nestingBelowHeight($item, $where, $unit); self::optionalInteger($item, 'max_stacked_items', $where, 1); self::optionalInteger($item, 'stop_index', $where, 0); self::optionalInteger($item, 'value', $where, 0); @@ -156,10 +190,13 @@ private static function item($raw, string $where, string $unit): void self::stackingGroupName($name, "{$where}/accepts_stacking_groups/{$index}"); } } + self::optionalEachOneOf($item, 'allowed_rotations', $where, self::ROTATIONS); + self::optionalOneOf($item, 'ground_contact_rule', $where, self::GROUND_CONTACT_RULES); + self::optionalOneOf($item, 'shape_type', $where, self::SHAPE_TYPES); } /** @param mixed $value */ - private static function stackingGroupName($value, string $field): void + public static function stackingGroupName($value, string $field): void { if (!\is_string($value)) { throw self::refuse('wrong_type', $field, 'must be a string'); @@ -303,7 +340,7 @@ private static function deformableBoundary($container, $raw, string $where): voi * * @param mixed $value */ - private static function setBesideABag(string $name, $value): bool + public static function setBesideABag(string $name, $value): bool { if ($name === 'obstacles') { return $value !== null && $value !== []; @@ -317,12 +354,52 @@ private static function setBesideABag(string $name, $value): bool /** @param mixed $raw */ private static function accessDirections($raw, string $where): void { - $list = self::listAt($raw, $where); - foreach ($list as $index => $direction) { - if (!\in_array($direction, self::ACCESS_DIRECTIONS, true)) { - throw self::refuse('not_allowed', "{$where}/{$index}", - 'must be one of ' . CanonicalJson::spelling(self::ACCESS_DIRECTIONS)); - } + self::eachOneOf($raw, $where, self::ACCESS_DIRECTIONS); + } + + /** + * @param stdClass|array $object + * @param list $allowed + */ + private static function optionalOneOf($object, string $name, string $where, array $allowed): void + { + $value = JsonValue::get($object, $name); + if ($value !== null) { + self::oneOf($value, "{$where}/{$name}", $allowed); + } + } + + /** + * @param stdClass|array $object + * @param list $allowed + */ + private static function optionalEachOneOf($object, string $name, string $where, array $allowed): void + { + $value = JsonValue::get($object, $name); + if ($value !== null) { + self::eachOneOf($value, "{$where}/{$name}", $allowed); + } + } + + /** + * @param mixed $raw + * @param list $allowed + */ + private static function eachOneOf($raw, string $where, array $allowed): void + { + foreach (self::listAt($raw, $where) as $index => $value) { + self::oneOf($value, "{$where}/{$index}", $allowed); + } + } + + /** + * @param mixed $value + * @param list $allowed + */ + private static function oneOf($value, string $field, array $allowed): void + { + if (!\in_array($value, $allowed, true)) { + throw self::refuse('not_allowed', $field, 'must be one of ' . CanonicalJson::spelling($allowed)); } } @@ -389,7 +466,7 @@ private static function obstacles($raw, string $where, string $unit): void // ------------------------------------------------------------------------- primitives /** @param mixed $value */ - private static function integer($value, string $field, int $minimum): void + public static function integer($value, string $field, int $minimum): void { $number = JsonValue::integer($value); if ($number === null) { @@ -421,7 +498,7 @@ private static function refuseNonInteger($value, string $field, int $minimum): v } /** @param mixed $value */ - private static function ratio($value, string $field, ?int $maximum): void + public static function ratio($value, string $field, ?int $maximum): void { if (!\is_int($value) && !\is_float($value)) { throw self::refuse('wrong_type', $field, 'must be a number'); @@ -583,13 +660,12 @@ private static function requiredString($object, string $name, string $where): vo /** * Checked once every entry is well formed, so the later of two equal ids is named. * - * @param list $entries + * @param list $identifiers */ - private static function requireUniqueIds(array $entries, string $key): void + public static function requireUniqueIds(array $identifiers, string $key): void { $seen = []; - foreach ($entries as $index => $entry) { - $identifier = (string) JsonValue::get($entry, 'id'); + foreach ($identifiers as $index => $identifier) { if (isset($seen[$identifier])) { throw self::refuse('duplicate_id', "/{$key}/{$index}/id", 'repeats the id ' . CanonicalJson::spelling($identifier)); } @@ -597,6 +673,15 @@ private static function requireUniqueIds(array $entries, string $key): void } } + /** + * @param list $entries + * @return list + */ + private static function identifiers(array $entries): array + { + return \array_map(static fn($entry): string => (string) JsonValue::get($entry, 'id'), $entries); + } + private static function refuse(string $reason, string $field, string $detail): InvalidRequestException { return new InvalidRequestException($reason, $field, $detail); diff --git a/src/Support/ResultValidation/Accounting.php b/src/Support/ResultValidation/Accounting.php new file mode 100644 index 0000000..a94048f --- /dev/null +++ b/src/Support/ResultValidation/Accounting.php @@ -0,0 +1,329 @@ + $issues */ + public static function checkStructure($result, array &$issues): void + { + $summary = Json::at($result, 'summary'); + $containers = Json::items(Json::at($result, 'containers'), 'result.containers'); + $packed = 0; + foreach ($containers as $container) { + $packed += \count(Json::items(Json::at($container, 'placements'), 'placements')); + } + $unpacked = \count(Json::items(Json::at($result, 'unpacked_items'), 'result.unpacked_items')); + foreach (['container_count' => \count($containers), 'packed_item_count' => $packed, 'unpacked_item_count' => $unpacked] as $field => $actual) { + $reported = Json::at($summary, $field); + if (!Json::equalsInt($reported, $actual)) { + $issues[] = new ResultIssue('summary_mismatch', "{$field} " . PyFormat::str($reported) . " != {$actual}"); + } + } + $complete = Json::at($result, 'complete'); + if (!Json::equalsInt($complete, $unpacked === 0 ? 1 : 0)) { + $issues[] = new ResultIssue('complete_mismatch', 'complete=' . PyFormat::str($complete) . " with {$unpacked} unpacked"); + } + } + + /** + * Participating `require_container_tag` rules, resolved from the request alone -- a second + * implementation of docs/POLICY-RULES.md, so a resolution bug shared with an engine cannot + * hide behind agreement with it. + * + * @param mixed $request @return list + */ + public static function containerTagRules($request): array + { + $policy = Json::get($request, 'policy'); + if (!Json::isDict($policy)) { + return []; + } + $declared = Json::get($policy, 'rules'); + if (!Json::isList($declared) || $declared === []) { + return []; + } + $asOf = Json::intInstance(Json::get($policy, 'as_of')); + if ($asOf === null) { + return []; + } + $shipment = Json::get($policy, 'shipment'); + $shipment = Json::truthy($shipment) ? $shipment : []; + $latest = new Ordered(); + foreach ($declared as $rule) { + if (!Json::isDict($rule) || !Json::has($rule, 'require_container_tag')) { + continue; + } + $appliesTo = Json::get($rule, 'applies_to'); + $appliesTo = Json::truthy($appliesTo) ? $appliesTo : []; + if (!Json::isDict($appliesTo)) { + throw MalformedResult::shape('applies_to must be an object'); + } + foreach ($appliesTo as $fact => $value) { + if (!Json::equals(Json::get($shipment, (string)$fact), $value)) { + continue 2; + } + } + if (Json::compare(Json::get($rule, 'effective_at', 0), $asOf) > 0) { + continue; + } + $id = Json::get($rule, 'id'); + $current = $latest->get($id); + $newer = $current === null || Json::compare( + [Json::get($rule, 'effective_at', 0), Json::get($rule, 'version', 0)], + [Json::get($current, 'effective_at', 0), Json::get($current, 'version', 0)] + ) > 0; + if ($newer) { + $latest->set($id, $rule); + } + } + return $latest->values(); + } + + /** @param mixed $result @param list $issues */ + public static function checkAccounting($result, Context $context, array &$issues): void + { + $seen = new Ordered(); + $perType = new Ordered(); + foreach (Json::items(Json::at($result, 'containers'), 'result.containers') as $container) { + foreach (Json::items(Json::at($container, 'placements'), 'placements') as $placement) { + $itemId = Json::at($placement, 'item_id'); + if ($seen->has($itemId)) { + $issues[] = new ResultIssue('duplicate_item', PyFormat::str($itemId)); + } + $seen->set($itemId, true); + $itemType = Json::at($placement, 'item_type'); + $perType->set($itemType, $perType->get($itemType, 0) + 1); + } + } + $algorithm = Json::at($result, 'algorithm'); + $timedOut = Json::truthy(Json::at($algorithm, 'time_limit_reached')); + $effortLimited = Json::truthy(Json::at($algorithm, 'effort_limit_reached')); + foreach (Json::items(Json::at($result, 'unpacked_items'), 'result.unpacked_items') as $unpacked) { + $itemId = Json::at($unpacked, 'item_id'); + if ($seen->has($itemId)) { + $issues[] = new ResultIssue('duplicate_item', PyFormat::str($itemId) . ' is both packed and unpacked'); + } + $seen->set($itemId, true); + $itemType = Json::at($unpacked, 'item_type'); + $perType->set($itemType, $perType->get($itemType, 0) + 1); + if (!Json::truthy(Json::get($unpacked, 'reason'))) { + $issues[] = new ResultIssue('missing_reason', PyFormat::str($itemId)); + } + self::checkReasonProof($unpacked, $context->items->get($itemType), $context, $timedOut, $effortLimited, $issues); + } + foreach ($perType->entries() as [$itemType, $count]) { + $spec = $context->items->get($itemType); + if ($spec === null) { + $issues[] = new ResultIssue('unknown_item', PyFormat::str($itemType)); + } elseif (!Json::equalsInt($spec->quantity, $count)) { + $issues[] = new ResultIssue('quantity_mismatch', PyFormat::str($itemType) . ": {$count} accounted for, " . PyFormat::str($spec->quantity) . ' requested'); + } + } + foreach ($context->items->entries() as [$itemType, $spec]) { + if (!$perType->has($itemType)) { + $issues[] = new ResultIssue('quantity_mismatch', PyFormat::str($itemType) . ': 0 accounted for, ' . PyFormat::str($spec->quantity) . ' requested'); + } + } + } + + /** + * Whether one envelope of this size fits the empty container: its frame and, for a flat bag, + * both girth sums with the envelope alone at the origin. + * + * @param array $size + */ + public static function fitsEmpty(ContainerSpec $container, array $size): bool + { + for ($axis = 0; $axis < 3; ++$axis) { + if (Exact::compare($size[$axis], $container->inner[$axis]) > 0) { + return false; + } + } + return !$container->flatBag + || (Exact::compare(Exact::add($size[0], $size[2]), $container->inner[0]) <= 0 + && Exact::compare(Exact::add($size[1], $size[2]), $container->inner[1]) <= 0); + } + + /** + * `any(fits_empty(container, rotated envelope) for container ... for rotation ...)`, stopping + * at the first fit as Python's generator does, so an unknown rotation is only an error when + * the search reaches it. + * + * @param list $rotations + */ + private static function fitsSome(ItemSpec $spec, Context $context, array $rotations): bool + { + $margin = Exact::mul(2, $context->clearance); + foreach ($context->containers->values() as $container) { + foreach ($rotations as $rotation) { + $axes = Geometry::axes(Json::text($rotation, 'a rotation')); + $size = [ + Exact::add($spec->dimensions[$axes[0]], $margin), + Exact::add($spec->dimensions[$axes[1]], $margin), + Exact::add($spec->dimensions[$axes[2]], $margin), + ]; + if (self::fitsEmpty($container, $size)) { + return true; + } + } + } + return false; + } + + /** `value in tags` for a frozenset of strings; an unhashable value is Python's `TypeError`. @param array $tags @param mixed $value */ + public static function holds(array $tags, $value): bool + { + Json::hashKey($value); + return \is_string($value) && isset($tags[$value]); + } + + /** @param mixed $unpacked @param list $issues */ + private static function checkReasonProof($unpacked, ?ItemSpec $spec, Context $context, bool $timedOut, bool $effortLimited, array &$issues): void + { + $itemId = PyFormat::str(Json::get($unpacked, 'item_id', '?')); + $reason = Json::get($unpacked, 'reason', ''); + $proof = Json::get($unpacked, 'proof'); + if (!Json::isDict($proof)) { + $issues[] = new ResultIssue('missing_reason_proof', $itemId); + return; + } + Json::hashKey($reason); + $is = static function (array $names) use ($reason): bool { return \is_string($reason) && \in_array($reason, $names, true); }; + $expected = $is(self::PROVEN) ? 'proven' : ($is(self::LIMITED) ? 'unknown_due_to_limit' : ($is(self::OBSERVED) ? 'observed' : 'inferred')); + $level = Json::get($proof, 'level'); + if (!Json::isText($level, $expected)) { + $issues[] = new ResultIssue('reason_proof_mismatch', "{$itemId}: " . PyFormat::repr($reason) . ' has proof ' . PyFormat::repr($level) . ', expected ' . PyFormat::stringRepr($expected)); + } + if (Json::isText($reason, 'time_limit') && !$timedOut) { + $issues[] = new ResultIssue('reason_limit_mismatch', "{$itemId}: time_limit reason without a reached time limit"); + } + if (Json::isText($reason, 'effort_limit') && !$effortLimited) { + $issues[] = new ResultIssue('reason_limit_mismatch', "{$itemId}: effort_limit reason without a reached effort limit"); + } + if ($spec !== null) { + self::checkProvenReason($unpacked, $reason, $spec, $context, $itemId, $issues); + } + self::checkObservations($proof, $reason, $itemId, $issues); + } + + /** @param mixed $unpacked @param mixed $reason @param list $issues */ + private static function checkProvenReason($unpacked, $reason, ItemSpec $spec, Context $context, string $itemId, array &$issues): void + { + $every = \array_keys(Geometry::ROTATIONS); + if (Json::isText($reason, 'no_compatible_container_dimensions')) { + if (self::fitsSome($spec, $context, $spec->allowedRotations)) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: at least one allowed orientation fits a container"); + } + if (self::fitsSome($spec, $context, $every)) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: fits at least one container once every rotation is tried, not only its own allowed set -- should be rotation_restricted"); + } + } + if (Json::isText($reason, 'rotation_restricted')) { + if (self::fitsSome($spec, $context, $spec->allowedRotations)) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: already fits a container within its own allowed rotations"); + } + if (!self::fitsSome($spec, $context, $every)) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: does not fit any container even with every rotation tried -- should be no_compatible_container_dimensions"); + } + } + if (Json::isText($reason, 'payload_exceeded')) { + foreach ($context->containers->values() as $container) { + if ($container->maxPayload === null || Exact::compare($spec->weight, $container->maxPayload) <= 0) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: its weight is within at least one container payload limit"); + break; + } + } + } + if (Json::isText($reason, 'no_eligible_container')) { + foreach ($context->containers->values() as $container) { + if ($spec->eligibleContainerTags === [] || \array_intersect_key($spec->eligibleContainerTags, $container->tags) !== []) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: at least one container satisfies its eligible tags"); + break; + } + } + } + if (Json::isText($reason, 'policy_rule')) { + self::checkPolicyCitation($unpacked, $spec, $context, $itemId, $issues); + } + } + + /** + * Two claims, both checked: that some rule rules this item out of every container, and that + * the rule the result *names* is that rule. + * + * @param mixed $unpacked @param list $issues + */ + private static function checkPolicyCitation($unpacked, ItemSpec $spec, Context $context, string $itemId, array &$issues): void + { + $blocking = []; + foreach ($context->rules as $rule) { + if (!self::holds($spec->tags, Json::get(Json::at($rule, 'require_container_tag'), 'item_tag'))) { + continue; + } + $admitted = false; + foreach ($context->containers->values() as $container) { + if (self::holds($container->tags, Json::get(Json::at($rule, 'require_container_tag'), 'container_tag'))) { + $admitted = true; + break; + } + } + if (!$admitted) { + $blocking[] = $rule; + } + } + if ($blocking === []) { + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: no participating policy rule rules it out of every container"); + return; + } + $details = Json::get($unpacked, 'details'); + $cited = Json::truthy($details) + ? \implode(' ', \array_map(static function ($detail): string { return Json::text($detail, 'details'); }, Json::items($details, 'details'))) + : ''; + foreach ($blocking as $rule) { + $name = PyFormat::str(Json::at($rule, 'id')) . '@' . PyFormat::str(Json::at($rule, 'version')); + if (\strpos($cited, $name) !== false) { + return; + } + } + $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: cites " . PyFormat::stringRepr($cited) . ', which names no rule that actually blocks it'); + } + + /** @param mixed $proof @param mixed $reason @param list $issues */ + private static function checkObservations($proof, $reason, string $itemId, array &$issues): void + { + $observations = Json::get($proof, 'observations'); + if (!Json::isList($observations) || $observations === []) { + $issues[] = new ResultIssue('missing_reason_observations', $itemId); + return; + } + $observedReason = false; + foreach ($observations as $observation) { + if (!Json::isDict($observation)) { + $issues[] = new ResultIssue('malformed_reason_observation', $itemId); + continue; + } + $code = Json::get($observation, 'code'); + $count = Json::intInstance(Json::get($observation, 'count')); + $details = Json::get($observation, 'details'); + if (!\is_string($code) || $code === '' || $count === null || $count < 1 || !Json::isList($details)) { + $issues[] = new ResultIssue('malformed_reason_observation', $itemId); + continue; + } + if (Json::equals($code, $reason)) { + $observedReason = true; + } + } + if (!$observedReason) { + $issues[] = new ResultIssue('reason_observation_mismatch', "{$itemId}: " . PyFormat::str($reason)); + } + } +} diff --git a/src/Support/ResultValidation/ContainerCheck.php b/src/Support/ResultValidation/ContainerCheck.php new file mode 100644 index 0000000..c12aa7a --- /dev/null +++ b/src/Support/ResultValidation/ContainerCheck.php @@ -0,0 +1,477 @@ +getMessage()); + } + } + + /** The largest envelope x2, y2 and z2 over a container's placements. @param mixed $packed @param int|string $clearance @return array{0:int|string,1:int|string,2:int|string} */ + public static function achievedExtent($packed, $clearance): array + { + $extent = null; + foreach (Json::items(Json::at($packed, 'placements'), 'placements') as $placement) { + $envelope = self::envelope($placement, $clearance); + $extent = $extent === null + ? [$envelope->x2, $envelope->y2, $envelope->z2] + : [Exact::max($extent[0], $envelope->x2), Exact::max($extent[1], $envelope->y2), Exact::max($extent[2], $envelope->z2)]; + } + return $extent ?? [0, 0, 0]; + } + + /** + * `achieved_dimensions` is present exactly when the container declares a soft size, and equals + * the tight extent; a flat bag's extent must pass the girth rule. + * + * @param mixed $packed @param int|string $clearance @param list $issues + */ + public static function checkAchievedExtent($packed, ContainerSpec $spec, $clearance, array &$issues): void + { + $reported = Json::get($packed, 'achieved_dimensions'); + $packedId = new Label($packed); + if (!$spec->reportsAchievedExtent) { + if ($reported !== null) { + $issues[] = new ResultIssue('achieved_dimensions_mismatch', "{$packedId}: reported for a container of fixed size"); + } + $packedId->verify(); + return; + } + [$a, $b, $c] = self::achievedExtent($packed, $clearance); + $stated = null; + if (Json::isDict($reported)) { + $stated = []; + foreach (self::SIDES as $side) { + $stated[] = Json::get(Json::get($reported, $side, []), 'ticks'); + } + } + if (!self::matches($stated, [$a, $b, $c])) { + $issues[] = new ResultIssue('achieved_dimensions_mismatch', "{$packedId}: reported " . self::optionalTuple($stated) . ', computed ' . PyFormat::intTuple([$a, $b, $c])); + } + if ($spec->flatBag && (Exact::compare(Exact::add($a, $c), $spec->inner[0]) > 0 || Exact::compare(Exact::add($b, $c), $spec->inner[1]) > 0)) { + $issues[] = new ResultIssue('bag_girth_exceeded', "{$packedId}: a + c = " . Exact::add($a, $c) . ', b + c = ' . Exact::add($b, $c) . ", flat size {$spec->inner[0]} x {$spec->inner[1]}"); + } + $packedId->verify(); + } + + /** @param list|null $stated @param list $expected */ + private static function matches(?array $stated, array $expected): bool + { + if ($stated === null) { + return false; + } + foreach ($expected as $index => $value) { + if (!Json::equalsInt($stated[$index], $value)) { + return false; + } + } + return true; + } + + /** @param list|null $values */ + private static function optionalTuple(?array $values): string + { + return $values === null ? 'None' : PyFormat::valueTuple($values); + } + + /** `(value.get(key) or {}).get("ticks")` per side, or null when `value` is not an object. @param mixed $value @return list|null */ + private static function reportedTicks($value): ?array + { + if (!Json::isDict($value)) { + return null; + } + $ticks = []; + foreach (self::SIDES as $side) { + $ticks[] = self::nestedTicks($value, $side); + } + return $ticks; + } + + /** `(block.get(key) or {}).get("ticks")`. @param mixed $block @return mixed */ + private static function nestedTicks($block, string $key) + { + $value = Json::get($block, $key); + return Json::truthy($value) ? Json::get($value, 'ticks') : null; + } + + /** + * Recompute a made-to-measure container's box from its placements alone and return the spec + * every later check uses: the recomputed box, never the reported one. + * + * @param mixed $packed @param Ordered $items @param int|string $clearance @param list $issues + */ + public static function checkMadeToMeasure($packed, bool $compact, ContainerSpec $spec, Ordered $items, $clearance, array &$issues): ContainerSpec + { + $containerId = PyFormat::str(Json::get($packed, 'id', '?')); + $block = Json::get($packed, 'made_to_measure'); + $machine = $spec->madeToMeasure; + if ($machine === null) { + if ($block !== null) { + $issues[] = new ResultIssue('made_to_measure_unexpected', $containerId); + } + return $spec; + } + if (!Json::isDict($block)) { + $issues[] = new ResultIssue('made_to_measure_missing', $containerId); + $block = []; + } + if ($compact) { + $issues[] = new ResultIssue('lattice_summary_on_made_to_measure', $containerId); + } + $achieved = self::achievedExtent($packed, $clearance); + $fabricated = []; + for ($axis = 0; $axis < 3; ++$axis) { + $minimum = $machine->minimum[$axis]; + $increment = $machine->increment[$axis]; + $steps = Exact::ceilDiv(Exact::sub(Exact::max($achieved[$axis], $minimum), $minimum), $increment); + $fabricated[] = Exact::add($minimum, Exact::mul($steps, $increment)); + } + for ($axis = 0; $axis < 3; ++$axis) { + if (Exact::compare($fabricated[$axis], $spec->inner[$axis]) > 0) { + $issues[] = new ResultIssue('fabricated_dimensions_exceed_machine', "{$containerId}: " . PyFormat::intTuple($fabricated) . ' beyond ' . PyFormat::intTuple($spec->inner)); + break; + } + } + $reportedInner = self::reportedTicks(Json::get($packed, 'inner_dimensions')); + if (!self::matches($reportedInner, $fabricated)) { + $issues[] = new ResultIssue('fabricated_dimensions_mismatch', "{$containerId}: reported " . self::optionalTuple($reportedInner) . ', computed ' . PyFormat::intTuple($fabricated)); + } + $outer = []; + for ($axis = 0; $axis < 3; ++$axis) { + $outer[] = Exact::add($fabricated[$axis], $machine->allowance[$axis]); + } + $reportedOuter = self::reportedTicks(Json::get($packed, 'outer_dimensions')); + if (!self::matches($reportedOuter, $outer)) { + $issues[] = new ResultIssue('outer_dimensions_mismatch', "{$containerId}: reported " . self::optionalTuple($reportedOuter) . ', computed ' . PyFormat::intTuple($outer)); + } + $cost = Exact::add($spec->costMinor, self::perSquareMetreCeiling($machine->pricePerSquareMetreMinor, $fabricated)); + $reportedCost = Json::get($block, 'cost_minor'); + if (!Json::equalsInt($reportedCost, $cost)) { + $issues[] = new ResultIssue('made_to_measure_cost_mismatch', "{$containerId}: reported " . PyFormat::str($reportedCost) . ", computed {$cost}"); + } + $tare = Exact::add($spec->tareWeight, self::perSquareMetreCeiling($machine->tarePerSquareMetre, $fabricated)); + $reportedTare = self::nestedTicks($block, 'tare_weight'); + if (!Json::equalsInt($reportedTare, $tare)) { + $issues[] = new ResultIssue('made_to_measure_tare_mismatch', "{$containerId}: reported " . PyFormat::str($reportedTare) . ", computed {$tare}"); + } + $gross = Exact::add($tare, self::payloadOf($packed, $items)); + $reportedGross = self::nestedTicks($packed, 'gross_weight'); + if (!Json::equalsInt($reportedGross, $gross)) { + $issues[] = new ResultIssue('gross_weight_mismatch', "{$containerId}: reported " . PyFormat::str($reportedGross) . ", computed {$gross}"); + } + $recomputed = clone $spec; + $recomputed->inner = $fabricated; + $recomputed->outer = $outer; + $recomputed->costMinor = $cost; + $recomputed->tareWeight = $tare; + return $recomputed; + } + + /** `ceil(rate * 2(LW + LH + WH) / 1 m^2)`. @param int|string $rate @param array $sides @return int|string */ + private static function perSquareMetreCeiling($rate, array $sides) + { + [$length, $width, $height] = $sides; + $area = Exact::mul(2, Exact::add(Exact::add(Exact::mul($length, $width), Exact::mul($length, $height)), Exact::mul($width, $height))); + return Exact::ceilDiv(Exact::mul($rate, $area), Stacking::SQUARE_METRE_TICKS); + } + + /** The summed weight of every placement whose type the request declares. @param mixed $packed @param Ordered $items @return int|string */ + public static function payloadOf($packed, Ordered $items) + { + $payload = 0; + foreach (Json::items(Json::at($packed, 'placements'), 'placements') as $placement) { + $spec = $items->get(Json::at($placement, 'item_type')); + if ($spec !== null) { + $payload = Exact::add($payload, $spec->weight); + } + } + return $payload; + } + + /** @param mixed $packed @param Ordered $items @param int|string $clearance @param list $issues */ + public static function check($packed, ContainerSpec $spec, Ordered $items, $clearance, Ratio $globalSupport, array &$issues): void + { + $packedId = new Label($packed); + $placements = Json::items(Json::at($packed, 'placements'), 'placements'); + $boundary = new Cuboid(0, 0, 0, $spec->inner[0], $spec->inner[1], $spec->inner[2]); + $byId = new Ordered(); + $payload = 0; + foreach ($placements as $placement) { + $itemId = Json::at($placement, 'item_id'); + $itemSpec = $items->get(Json::at($placement, 'item_type')); + $envelope = self::envelope($placement, $clearance); + $byId->set($itemId, new Entry($itemId, $envelope, $placement, $itemSpec)); + $label = PyFormat::str($itemId); + if (!$boundary->contains($envelope)) { + $issues[] = new ResultIssue('outside_container', "{$label} in {$packedId}"); + } + foreach ($spec->obstacles as $obstacle) { + if ($envelope->intersects($obstacle) && Geometry::solidsOverlap(Stacking::placedHull($envelope, $placement, $itemSpec), $obstacle->vertices())) { + $issues[] = new ResultIssue('obstacle_collision', "{$label} in {$packedId}"); + } + } + if ($itemSpec === null) { + continue; + } + $payload = Exact::add($payload, $itemSpec->weight); + self::checkRotation($placement, $itemSpec, $label, $issues); + if ($itemSpec->eligibleContainerTags !== [] && \array_intersect_key($itemSpec->eligibleContainerTags, $spec->tags) === []) { + $tags = \array_map('strval', \array_keys($itemSpec->eligibleContainerTags)); + \sort($tags, SORT_STRING); + $issues[] = new ResultIssue('container_ineligible', "{$label}: " . PyFormat::str(Json::at($packed, 'container_type')) . ' has none of ' . PyFormat::listOf(\array_map([PyFormat::class, 'stringRepr'], $tags))); + } + if ($itemSpec->mustBeOnFloor && Exact::sign($envelope->z) !== 0) { + $issues[] = new ResultIssue('floor_violation', "{$label} at z={$envelope->z}"); + } + } + $entries = $byId->values(); + self::checkPairs($entries, $packedId, $issues); + [$supporters, $directAbove] = Stacking::supportGraph($entries); + Stacking::checkSupportAndLoad($entries, $supporters, $directAbove, $globalSupport, $issues); + $loads = Stacking::propagateLoad($entries, $supporters); + if ($spec->maxStackDensity !== null) { + Stacking::checkStackDensity($packedId, $entries, $loads, $spec->maxStackDensity, $issues); + } + Stacking::checkCrush($packedId, $entries, $loads, $issues); + Stacking::checkRouteRemovalOrder($packedId, $entries, $directAbove, $spec->inner, $spec->accessDirections, $issues); + self::checkLimits($packed, $packedId, $placements, $spec, $items, $payload, $issues); + self::checkVolumes($packed, $packedId, $placements, $spec, $items, $byId, $loads, $issues); + $totalWeight = self::payloadOf($packed, $items); + self::checkCentreOfMass($packed, $packedId, $placements, $spec, $items, $totalWeight, $issues); + self::checkAxles($packed, $packedId, $placements, $spec, $items, $totalWeight, $issues); + $packedId->verify(); + } + + /** @param mixed $placement @param list $issues */ + private static function checkRotation($placement, ItemSpec $spec, string $itemId, array &$issues): void + { + $orientation = Json::at($placement, 'orientation'); + if (!Geometry::isRotation($orientation)) { + $issues[] = new ResultIssue('unknown_orientation', "{$itemId}: " . PyFormat::str($orientation)); + return; + } + if (!$spec->allows($orientation)) { + $issues[] = new ResultIssue('forbidden_rotation', "{$itemId}: {$orientation}"); + } + $expected = $spec->rotated($orientation); + $dimensions = Json::at($placement, 'dimensions'); + $actual = []; + foreach (self::SIDES as $side) { + $actual[] = Json::at(Json::at($dimensions, $side), 'ticks'); + } + if (!self::matches($actual, $expected)) { + $issues[] = new ResultIssue('dimension_mismatch', "{$itemId}: {$orientation} of " . PyFormat::intTuple($spec->dimensions) . ' is ' . PyFormat::intTuple($expected) . ', got ' . PyFormat::valueTuple($actual)); + } + } + + /** @param list $entries @param list $issues */ + private static function checkPairs(array $entries, Label $packedId, array &$issues): void + { + $count = \count($entries); + for ($first = 0; $first < $count; ++$first) { + $left = $entries[$first]; + for ($second = $first + 1; $second < $count; ++$second) { + $right = $entries[$second]; + if ($left->envelope->intersects($right->envelope) + && Geometry::solidsOverlap(Stacking::placedHull($left->envelope, $left->placement, $left->spec), Stacking::placedHull($right->envelope, $right->placement, $right->spec)) + && !Stacking::validNesting($left, $right)) { + $issues[] = new ResultIssue('collision', PyFormat::str($left->id) . ' with ' . PyFormat::str($right->id) . " in {$packedId}"); + } + if ($left->spec !== null && $right->spec !== null + && (\array_intersect_key($left->spec->incompatibleTags, $right->spec->tags) !== [] + || \array_intersect_key($right->spec->incompatibleTags, $left->spec->tags) !== [])) { + $issues[] = new ResultIssue('incompatible_items', PyFormat::str($left->id) . ' is incompatible with ' . PyFormat::str($right->id) . " in {$packedId}"); + } + } + } + } + + /** @param mixed $packed @param list $placements @param Ordered $items @param int|string $payload @param list $issues */ + private static function checkLimits($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, $payload, array &$issues): void + { + if ($spec->maxPayload !== null && Exact::compare($payload, $spec->maxPayload) > 0) { + $issues[] = new ResultIssue('payload_exceeded', "{$packedId}: {$payload} > {$spec->maxPayload} ticks"); + } + $reported = Json::get(Json::get($packed, 'payload_weight', []), 'ticks'); + if ($reported !== null && !Json::equalsInt($reported, $payload)) { + $issues[] = new ResultIssue('payload_weight_mismatch', "{$packedId}: reported " . PyFormat::str($reported) . ", computed {$payload}"); + } + if ($spec->maxItems !== null && \count($placements) > $spec->maxItems) { + $issues[] = new ResultIssue('max_items_exceeded', "{$packedId}: " . \count($placements) . " > {$spec->maxItems}"); + } + foreach ($spec->tagLimits as [$tag, $limit]) { + $count = 0; + foreach ($placements as $placement) { + $item = $items->get(Json::at($placement, 'item_type')); + if ($item !== null && isset($item->tags[$tag])) { + ++$count; + } + } + if (Exact::compare($count, $limit) > 0) { + $issues[] = new ResultIssue('tag_count_exceeded', "{$packedId}: {$tag} count {$count} > limit {$limit}"); + } + } + } + + /** + * @param mixed $packed @param list $placements @param Ordered $items + * @param Ordered $byId @param list $loads @param list $issues + */ + private static function checkVolumes($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, Ordered $byId, array $loads, array &$issues): void + { + // Every placement counts, through the envelope its item id resolves to -- a repeated id + // resolves to its last placement, as the reference's dict does. + $used = 0; + foreach ($placements as $placement) { + $index = $byId->position(Json::at($placement, 'item_id')); + $entry = $byId->get(Json::at($placement, 'item_id')); + $used = Exact::add($used, Stacking::occupiedVolume($entry->envelope, $placement, $items->get(Json::at($placement, 'item_type')), $loads[$index])); + } + $entries = $byId->values(); + for ($first = 0, $count = \count($entries); $first < $count; ++$first) { + for ($second = $first + 1; $second < $count; ++$second) { + if (Stacking::validNesting($entries[$first], $entries[$second])) { + $left = $entries[$first]; + $used = Exact::sub($used, Exact::mul(Exact::mul($left->spec->nestingHeight, $left->envelope->length), $left->envelope->width)); + } + } + } + $reportedVolume = Json::get($packed, 'used_volume_ticks3'); + if ($reportedVolume !== null && Exact::compare(Json::pyInt($reportedVolume, 'used_volume_ticks3'), $used) !== 0) { + $issues[] = new ResultIssue('used_volume_mismatch', "{$packedId}: reported " . PyFormat::str($reportedVolume) . ", computed {$used}"); + } + $volume = $spec->volume(); + $scaledReserve = self::ratioPpm($spec->voidFillReserveRatio); + $reserved = Exact::add( + Exact::mul(Exact::floorDiv($volume, self::SCORE_SCALE), $scaledReserve), + Exact::floorDiv(Exact::mul(Exact::mod($volume, self::SCORE_SCALE), $scaledReserve), self::SCORE_SCALE) + ); + $reportedReserve = Json::get($packed, 'void_fill_reserve_ticks3'); + if ($reportedReserve !== null && Exact::compare(Json::pyInt($reportedReserve, 'void_fill_reserve_ticks3'), $reserved) !== 0) { + $issues[] = new ResultIssue('void_fill_reserve_mismatch', "{$packedId}: reported " . PyFormat::str($reportedReserve) . ", computed {$reserved}"); + } elseif (Exact::sign($reserved) !== 0 && $reportedReserve === null) { + $issues[] = new ResultIssue('void_fill_reserve_mismatch', "{$packedId}: non-zero reserve {$reserved} is not reported"); + } + $usable = Exact::sub($volume, $reserved); + if (Exact::compare($used, $usable) > 0) { + $issues[] = new ResultIssue('void_fill_reserve_exceeded', "{$packedId}: used {$used} > usable {$usable}"); + } + } + + /** + * A support, void-fill reserve or compression ratio in parts per million exactly as every solver + * converts it: the IEEE double `floor(ratio * 10^6 + 0.5)` of docs/UNITS-AND-NUMERICS.md. + * Rounding the exact rational instead disagrees on about one in a hundred seven-decimal + * halves and would refuse placements, and reported reserves, every solver produces. + */ + public static function ratioPpm(Ratio $ratio): int + { + return (int)($ratio->toFloat() * self::SCORE_SCALE + 0.5); + } + + /** `sum(weight * (2 * position + extent))` along one axis, over declared item types. @param list $placements @param Ordered $items @return int|string */ + private static function doubledMoment(array $placements, Ordered $items, string $axis, string $side) + { + $moment = 0; + foreach ($placements as $placement) { + $spec = $items->get(Json::at($placement, 'item_type')); + if ($spec === null) { + continue; + } + $position = Json::int(Json::at(Json::at(Json::at($placement, 'position'), $axis), 'ticks'), 'placement ticks'); + $extent = Json::int(Json::at(Json::at(Json::at($placement, 'dimensions'), $side), 'ticks'), 'placement ticks'); + $moment = Exact::add($moment, Exact::mul($spec->weight, Exact::add(Exact::mul(2, $position), $extent))); + } + return $moment; + } + + /** @param mixed $packed @param list $placements @param Ordered $items @param int|string $totalWeight @param list $issues */ + private static function checkCentreOfMass($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, $totalWeight, array &$issues): void + { + $expected = 0; + if (Exact::sign($totalWeight) !== 0) { + $offset = static function ($doubled, $side) use ($totalWeight) { + $centred = Exact::mul($totalWeight, $side); + return Exact::floorDiv(Exact::mul(Exact::abs(Exact::sub($doubled, $centred)), self::SCORE_SCALE), $centred); + }; + $expected = Exact::max( + $offset(self::doubledMoment($placements, $items, 'x', 'length'), $spec->inner[0]), + $offset(self::doubledMoment($placements, $items, 'y', 'width'), $spec->inner[1]) + ); + } + $reported = Json::get($packed, 'centre_of_mass_offset_ppm'); + if (!Json::equalsInt($reported, $expected)) { + $issues[] = new ResultIssue('centre_of_mass_mismatch', "{$packedId}: reported " . PyFormat::str($reported) . ", computed {$expected}"); + } + } + + /** @param mixed $packed @param list $placements @param Ordered $items @param int|string $totalWeight @param list $issues */ + private static function checkAxles($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, $totalWeight, array &$issues): void + { + if ($spec->axles === null) { + if (Json::has($packed, 'axle_reactions')) { + $issues[] = new ResultIssue('axle_reaction_mismatch', "{$packedId}: reactions reported without configured axles"); + } + return; + } + if (\count($spec->axles) !== 2) { + throw MalformedResult::shape("{$packedId}: axles must name exactly a front and a rear axle"); + } + [[$frontX, $frontLimit], [$rearX, $rearLimit]] = $spec->axles; + $denominator = Exact::mul(2, Exact::sub($rearX, $frontX)); + $gross = Exact::add($spec->tareWeight, $totalWeight); + $doubledWeightedX = Exact::add(Exact::mul($spec->tareWeight, $spec->inner[0]), self::doubledMoment($placements, $items, 'x', 'length')); + $frontNumerator = Exact::sub(Exact::mul(Exact::mul(2, $gross), $rearX), $doubledWeightedX); + $rearNumerator = Exact::sub($doubledWeightedX, Exact::mul(Exact::mul(2, $gross), $frontX)); + $expected = [ + 'basis' => 'gross', + 'denominator' => (string)$denominator, + 'front_numerator' => (string)$frontNumerator, + 'rear_numerator' => (string)$rearNumerator, + ]; + $reported = Json::get($packed, 'axle_reactions'); + if (!Json::equals($reported, $expected)) { + $issues[] = new ResultIssue('axle_reaction_mismatch', "{$packedId}: reported " . PyFormat::str($reported) . ', computed ' . PyFormat::repr($expected)); + } + $over = static function ($limit, $numerator) use ($denominator): bool { + return $limit !== null && Exact::compare($numerator, Exact::mul($limit, $denominator)) > 0; + }; + if ($over($frontLimit, $frontNumerator) || $over($rearLimit, $rearNumerator)) { + $issues[] = new ResultIssue('axle_overloaded', (string)$packedId); + } + } +} diff --git a/src/Support/ResultValidation/ContainerSpec.php b/src/Support/ResultValidation/ContainerSpec.php new file mode 100644 index 0000000..9357724 --- /dev/null +++ b/src/Support/ResultValidation/ContainerSpec.php @@ -0,0 +1,52 @@ + */ + public $obstacles; + /** @var array */ + public $tags; + /** @var list sorted by tag, the order the reference walks it in */ + public $tagLimits; + /** @var Ratio */ + public $voidFillReserveRatio; + /** @var int|string */ + public $tareWeight; + /** @var list|null each axle's position and load limit */ + public $axles; + /** @var int|string|null */ + public $maxStackDensity; + /** @var mixed */ + public $rateTable; + /** @var list */ + public $accessDirections; + /** @var bool */ + public $flatBag; + /** @var bool */ + public $reportsAchievedExtent; + /** @var MachineSpec|null */ + public $madeToMeasure; + + /** @return int|string */ + public function volume() + { + return Exact::mul(Exact::mul($this->inner[0], $this->inner[1]), $this->inner[2]); + } +} diff --git a/src/Support/ResultValidation/Context.php b/src/Support/ResultValidation/Context.php new file mode 100644 index 0000000..96823a6 --- /dev/null +++ b/src/Support/ResultValidation/Context.php @@ -0,0 +1,25 @@ + */ + public $items; + /** @var Ordered */ + public $containers; + /** @var int|string */ + public $clearance; + /** @var list the participating `require_container_tag` rules */ + public $rules; + + /** @param Ordered $items @param Ordered $containers @param int|string $clearance @param list $rules */ + public function __construct(Ordered $items, Ordered $containers, $clearance, array $rules) + { + $this->items = $items; + $this->containers = $containers; + $this->clearance = $clearance; + $this->rules = $rules; + } +} diff --git a/src/Support/ResultValidation/Cuboid.php b/src/Support/ResultValidation/Cuboid.php new file mode 100644 index 0000000..b1edbbf --- /dev/null +++ b/src/Support/ResultValidation/Cuboid.php @@ -0,0 +1,85 @@ +x = $x; + $this->y = $y; + $this->z = $z; + $this->length = $length; + $this->width = $width; + $this->height = $height; + $this->x2 = Exact::add($x, $length); + $this->y2 = Exact::add($y, $width); + $this->z2 = Exact::add($z, $height); + $this->baseArea = Exact::mul($length, $width); + } + + public function intersects(self $other): bool + { + return Exact::compare($this->x, $other->x2) < 0 && Exact::compare($other->x, $this->x2) < 0 + && Exact::compare($this->y, $other->y2) < 0 && Exact::compare($other->y, $this->y2) < 0 + && Exact::compare($this->z, $other->z2) < 0 && Exact::compare($other->z, $this->z2) < 0; + } + + public function contains(self $other): bool + { + return Exact::compare($this->x, $other->x) <= 0 && Exact::compare($this->y, $other->y) <= 0 + && Exact::compare($this->z, $other->z) <= 0 && Exact::compare($other->x2, $this->x2) <= 0 + && Exact::compare($other->y2, $this->y2) <= 0 && Exact::compare($other->z2, $this->z2) <= 0; + } + + /** @return int|string */ + public function overlapAreaXy(self $other) + { + $dx = Exact::max(0, Exact::sub(self::min($this->x2, $other->x2), Exact::max($this->x, $other->x))); + $dy = Exact::max(0, Exact::sub(self::min($this->y2, $other->y2), Exact::max($this->y, $other->y))); + return Exact::mul($dx, $dy); + } + + /** @return list the eight corners, in the reference's order */ + public function vertices(): array + { + $corners = []; + foreach ([false, true] as $farX) { + foreach ([false, true] as $farY) { + foreach ([false, true] as $farZ) { + $corners[] = [$farX ? $this->x2 : $this->x, $farY ? $this->y2 : $this->y, $farZ ? $this->z2 : $this->z]; + } + } + } + return $corners; + } + + /** @param int|string $a @param int|string $b @return int|string */ + private static function min($a, $b) + { + return Exact::compare($a, $b) <= 0 ? $a : $b; + } +} diff --git a/src/Support/ResultValidation/Entry.php b/src/Support/ResultValidation/Entry.php new file mode 100644 index 0000000..ce65a50 --- /dev/null +++ b/src/Support/ResultValidation/Entry.php @@ -0,0 +1,25 @@ +id = $id; + $this->envelope = $envelope; + $this->placement = $placement; + $this->spec = $spec; + } +} diff --git a/src/Support/ResultValidation/Exact.php b/src/Support/ResultValidation/Exact.php new file mode 100644 index 0000000..57c267c --- /dev/null +++ b/src/Support/ResultValidation/Exact.php @@ -0,0 +1,169 @@ + $b; + } + return SignedBigInt::compare($a, $b); + } + + /** @param int|string $value */ + public static function sign($value): int + { + return self::compare($value, 0); + } + + /** @param int|string $value @return int|string */ + public static function negate($value) + { + if (\is_int($value) && $value !== PHP_INT_MIN) { + return -$value; + } + return self::normalize(SignedBigInt::negate($value)); + } + + /** @param int|string $value @return int|string */ + public static function abs($value) + { + return self::sign($value) < 0 ? self::negate($value) : $value; + } + + /** @param int|string $a @param int|string $b @return int|string */ + public static function max($a, $b) + { + return self::compare($a, $b) >= 0 ? $a : $b; + } + + /** + * Python's `a // b`. + * + * @param int|string $a @param int|string $b @return int|string + */ + public static function floorDiv($a, $b) + { + if (self::sign($b) === 0) { + throw MalformedResult::shape('division by zero'); + } + if (\is_int($a) && \is_int($b) && !($a === PHP_INT_MIN && $b === -1)) { + $quotient = \intdiv($a, $b); + return ($a % $b !== 0 && (($a < 0) !== ($b < 0))) ? $quotient - 1 : $quotient; + } + $magnitude = BigInt::divide((string)self::abs($a), (string)self::abs($b)); + $negative = (self::sign($a) < 0) !== (self::sign($b) < 0); + if (!$negative) { + return self::normalize($magnitude); + } + $exact = self::compare(self::mul($magnitude, self::abs($b)), self::abs($a)) === 0; + return self::negate($exact ? self::normalize($magnitude) : self::add($magnitude, 1)); + } + + /** Python's `a % b`, which takes the divisor's sign. @param int|string $a @param int|string $b @return int|string */ + public static function mod($a, $b) + { + return self::sub($a, self::mul(self::floorDiv($a, $b), $b)); + } + + /** `-(-a // b)`. @param int|string $a @param int|string $b @return int|string */ + public static function ceilDiv($a, $b) + { + return self::negate(self::floorDiv(self::negate($a), $b)); + } + + /** @param int|string $a @param int|string $b @return int|string */ + public static function gcd($a, $b) + { + $a = self::abs($a); + $b = self::abs($b); + while (self::sign($b) !== 0) { + [$a, $b] = [$b, self::mod($a, $b)]; + } + return $a; + } + + /** @param list $values @return int|string */ + public static function sum(array $values) + { + $total = 0; + foreach ($values as $value) { + $total = self::add($total, $value); + } + return $total; + } + + /** `2 ** $power`, exactly. @return int|string */ + public static function powerOfTwo(int $power) + { + if ($power < 62) { + return 1 << $power; + } + $value = 1 << 61; + for ($i = 61; $i < $power; ++$i) { + $value = self::mul($value, 2); + } + return $value; + } +} diff --git a/src/Support/ResultValidation/Facts.php b/src/Support/ResultValidation/Facts.php new file mode 100644 index 0000000..17c439f --- /dev/null +++ b/src/Support/ResultValidation/Facts.php @@ -0,0 +1,243 @@ + $issues */ + public static function checkAlgorithmMetrics($result, array &$issues): void + { + $algorithm = self::algorithm($result); + $metrics = Json::get($algorithm, 'metrics'); + $wellFormed = Json::isDict($metrics); + foreach (self::METRICS as $field) { + $count = $wellFormed ? Json::strictInt(Json::get($metrics, $field)) : null; + $wellFormed = $wellFormed && $count !== null && $count >= 0; + } + if (!$wellFormed) { + $issues[] = new ResultIssue('solver_metrics_mismatch', 'algorithm.metrics must contain every non-negative integer counter'); + return; + } + $candidates = Json::strictInt(Json::get($algorithm, 'candidates_evaluated')); + $attempts = Json::strictInt(Json::get($algorithm, 'placements_attempted')); + if ($candidates === null || $attempts === null || $candidates !== $metrics['feasible_candidates'] || $attempts !== $metrics['orientations_considered']) { + $issues[] = new ResultIssue('solver_metrics_mismatch', 'legacy candidate counters must mirror algorithm.metrics'); + } + } + + /** Counted-work limits are respected, and the stop flag is evidenced by one. @param mixed $request @param mixed $result @param list $issues */ + public static function checkEffortBudget($request, $result, array &$issues): void + { + $algorithm = Json::at($result, 'algorithm'); + $effortLimited = Json::get($algorithm, 'effort_limit_reached'); + if (!\is_bool($effortLimited)) { + throw MalformedResult::contract('algorithm.effort_limit_reached must be a boolean'); + } + $budget = Json::get(Json::get($request, 'configuration', []), 'effort_budget'); + if ($budget === null) { + if ($effortLimited) { + $issues[] = new ResultIssue('effort_budget_mismatch', 'effort_limit_reached is true but the request has no effort_budget'); + } + return; + } + if (!Json::isDict($budget)) { + throw MalformedResult::contract('config.effort_budget must be an object'); + } + $metrics = Json::get($algorithm, 'metrics'); + if (!Json::isDict($metrics)) { + return; + } + $reached = false; + foreach (['max_candidates_evaluated' => 'feasible_candidates', 'max_placement_attempts' => 'orientations_considered', 'max_search_nodes' => 'search_nodes_expanded'] as $budgetName => $metricName) { + $limit = Json::get($budget, $budgetName); + $value = Json::strictInt(Json::get($metrics, $metricName)); + if ($limit === null || $value === null) { + continue; + } + $order = Json::compare($value, $limit); + if ($order > 0) { + $issues[] = new ResultIssue('effort_budget_exceeded', "{$metricName} is {$value}, above {$budgetName}=" . PyFormat::str($limit)); + } + $reached = $reached || $order >= 0; + } + $restartLimit = Json::get($budget, 'max_restarts'); + $starts = Json::get(Json::get($result, 'termination', []), 'starts', []); + $limit = Json::intInstance($restartLimit); + if ($limit !== null && Json::isList($starts)) { + $started = 0; + foreach ($starts as $start) { + if (Json::isDict($start) && Json::get($start, 'started') === true) { + ++$started; + } + } + if ($started > $limit) { + $issues[] = new ResultIssue('effort_budget_exceeded', "started {$started} solver runs, above max_restarts=" . PyFormat::str($restartLimit)); + } + $reached = $reached || $started >= $limit; + } + if ($effortLimited && !$reached) { + $issues[] = new ResultIssue('effort_budget_mismatch', 'effort_limit_reached is true but no configured counted-work boundary was reached'); + } + } + + /** @param mixed $algorithm */ + private static function flag($algorithm, string $name): bool + { + $value = Json::get($algorithm, $name); + if (!\is_bool($value)) { + throw MalformedResult::contract("algorithm.{$name} must be a boolean"); + } + return $value; + } + + /** @param mixed $result */ + private static function factCode($result, string $name): string + { + $fact = Json::at($result, $name); + if (!Json::isDict($fact)) { + throw MalformedResult::contract("{$name} must be an object"); + } + $code = Json::get($fact, 'code'); + if (!\is_string($code) || $code === '') { + throw MalformedResult::contract("{$name}.code must be a non-empty string"); + } + return $code; + } + + /** @param mixed $result @param list $issues */ + public static function checkResultFacts($result, array &$issues): void + { + $algorithm = self::algorithm($result); + $timedOut = self::flag($algorithm, 'time_limit_reached'); + $effortLimited = self::flag($algorithm, 'effort_limit_reached'); + if ($timedOut && $effortLimited) { + $issues[] = new ResultIssue('result_fact_mismatch', 'time_limit_reached and effort_limit_reached cannot both be true'); + } + $termination = Json::at($result, 'termination'); + if (!Json::isDict($termination)) { + throw MalformedResult::contract('termination must be an object'); + } + self::checkStarts($termination, $algorithm, $timedOut, $effortLimited, $issues); + + $status = Json::at($result, 'status'); + $complete = Json::truthy(Json::at($result, 'complete')); + $invalid = Json::isText($status, 'invalid_result'); + $expected = [ + 'feasibility' => Json::isText($status, 'infeasible') ? 'infeasible' : (($complete && !$invalid) ? 'feasible' : 'unknown'), + 'termination' => $invalid ? 'error' : ($timedOut ? 'time_limit' : ($effortLimited ? 'effort_limit' : 'complete')), + 'optimality' => Json::isText($status, 'optimal') ? 'proven_optimal' + : (Json::isText($status, 'infeasible') ? 'proven_infeasible' : ((!$complete && !$invalid) ? 'best_found' : 'not_proven')), + ]; + foreach ($expected as $name => $code) { + $actual = self::factCode($result, $name); + if ($actual !== $code) { + $issues[] = new ResultIssue('result_fact_mismatch', "{$name}.code is " . PyFormat::stringRepr($actual) . ', expected ' . PyFormat::stringRepr($code)); + } + } + } + + /** @param mixed $termination @param mixed $algorithm @param list $issues */ + private static function checkStarts($termination, $algorithm, bool $timedOut, bool $effortLimited, array &$issues): void + { + $starts = Json::get($termination, 'starts'); + if (!Json::isList($starts) || $starts === []) { + $issues[] = new ResultIssue('termination_aggregate_mismatch', 'termination.starts must contain at least one start'); + return; + } + $malformed = false; + foreach ($starts as $start) { + if (!Json::isDict($start) || !\is_string(Json::get($start, 'id'))) { + $malformed = true; + continue; + } + $flags = []; + foreach (['started', 'completed', 'truncated', 'selected', 'global_deadline_reached'] as $name) { + $flags[] = Json::get($start, $name); + } + if (\count(\array_filter($flags, 'is_bool')) !== 5) { + $malformed = true; + continue; + } + [$started, $completed, $truncated] = $flags; + if (($completed && (!$started || $truncated)) || ($truncated && (!$started || $completed)) || (!$started && ($completed || $truncated))) { + $issues[] = new ResultIssue('start_record_mismatch', Json::at($start, 'id') . ': inconsistent lifecycle flags'); + } + } + if ($malformed) { + $issues[] = new ResultIssue('start_record_mismatch', 'a start record is missing its id or boolean lifecycle fields'); + } + $isTrue = static function ($start, string $name): bool { + return Json::isDict($start) && Json::get($start, $name) === true; + }; + $selected = \array_values(\array_filter($starts, static function ($start) use ($isTrue): bool { return $isTrue($start, 'selected'); })); + if (\count($selected) !== 1) { + $issues[] = new ResultIssue('termination_aggregate_mismatch', 'expected one selected start, found ' . \count($selected)); + return; + } + foreach ($starts as $start) { + if (!Json::isDict($start)) { + return; + } + } + $winner = $selected[0]; + $any = static function (string $name) use ($starts, $isTrue): bool { + foreach ($starts as $start) { + if ($isTrue($start, $name)) { + return true; + } + } + return false; + }; + $all = static function (string $name) use ($starts, $isTrue): bool { + foreach ($starts as $start) { + if (!$isTrue($start, $name)) { + return false; + } + } + return true; + }; + $aggregate = [ + 'any_start_truncated' => $any('truncated'), + 'all_required_starts_completed' => $all('completed'), + 'winning_start_truncated' => $isTrue($winner, 'truncated'), + 'global_deadline_reached' => $any('global_deadline_reached'), + ]; + foreach ($aggregate as $name => $expected) { + $reported = Json::get($termination, $name); + if ($reported !== $expected) { + $issues[] = new ResultIssue('termination_aggregate_mismatch', "{$name} is " . PyFormat::repr($reported) . ', expected ' . PyFormat::boolRepr($expected)); + } + } + $solver = Json::get($algorithm, 'solver'); + $selectedId = Json::get($winner, 'id', ''); + if (\is_string($solver) && !Json::isText($selectedId, $solver) + && \strncmp(Json::text($selectedId, 'a start id'), "{$solver}#", \strlen($solver) + 1) !== 0) { + $issues[] = new ResultIssue('winning_start_mismatch', 'selected start ' . PyFormat::repr($selectedId) . ' does not identify solver ' . PyFormat::stringRepr($solver)); + } + if ($aggregate['global_deadline_reached'] && !$timedOut) { + $issues[] = new ResultIssue('legacy_time_limit_mismatch', 'global_deadline_reached requires time_limit_reached'); + } + if (($aggregate['global_deadline_reached'] || $aggregate['winning_start_truncated']) !== ($timedOut || $effortLimited)) { + $issues[] = new ResultIssue('termination_limit_mismatch', 'selected-start truncation must identify exactly one reached limit'); + } + } +} diff --git a/src/Support/ResultValidation/Geometry.php b/src/Support/ResultValidation/Geometry.php new file mode 100644 index 0000000..ed76d9d --- /dev/null +++ b/src/Support/ResultValidation/Geometry.php @@ -0,0 +1,278 @@ + [0, 1, 2], 'LHW' => [0, 2, 1], 'WLH' => [1, 0, 2], + 'WHL' => [1, 2, 0], 'HLW' => [2, 0, 1], 'HWL' => [2, 1, 0], + ]; + + /** `ROTATIONS[orientation]`. @return array{0:int,1:int,2:int} */ + public static function axes(string $orientation): array + { + if (!\array_key_exists($orientation, self::ROTATIONS)) { + throw MalformedResult::shape(\sprintf('unknown orientation "%s"', $orientation)); + } + return self::ROTATIONS[$orientation]; + } + + /** `orientation in ROTATIONS`, for any JSON value; an unhashable one is Python's `TypeError`. @param mixed $orientation */ + public static function isRotation($orientation): bool + { + Json::hashKey($orientation); + return \is_string($orientation) && \array_key_exists($orientation, self::ROTATIONS); + } + + /** @param array $left @param array $right @return array{0:int|string,1:int|string,2:int|string} */ + public static function difference(array $left, array $right): array + { + return [Exact::sub($left[0], $right[0]), Exact::sub($left[1], $right[1]), Exact::sub($left[2], $right[2])]; + } + + /** @param array $left @param array $right @return array{0:int|string,1:int|string,2:int|string} */ + public static function cross(array $left, array $right): array + { + return [ + Exact::sub(Exact::mul($left[1], $right[2]), Exact::mul($left[2], $right[1])), + Exact::sub(Exact::mul($left[2], $right[0]), Exact::mul($left[0], $right[2])), + Exact::sub(Exact::mul($left[0], $right[1]), Exact::mul($left[1], $right[0])), + ]; + } + + /** @param array $left @param array $right @return int|string */ + public static function dot(array $left, array $right) + { + return Exact::add(Exact::add(Exact::mul($left[0], $right[0]), Exact::mul($left[1], $right[1])), Exact::mul($left[2], $right[2])); + } + + /** The axis reduced by its gcd and signed so its first non-zero component is positive. @param array $axis @return array{0:int|string,1:int|string,2:int|string} */ + public static function primitiveAxis(array $axis): array + { + $divisor = Exact::gcd(Exact::gcd($axis[0], $axis[1]), $axis[2]); + if (Exact::sign($divisor) === 0) { + return [0, 0, 0]; + } + $reduced = [Exact::floorDiv($axis[0], $divisor), Exact::floorDiv($axis[1], $divisor), Exact::floorDiv($axis[2], $divisor)]; + foreach ($reduced as $value) { + if (Exact::sign($value) !== 0) { + return Exact::sign($value) < 0 ? [Exact::negate($reduced[0]), Exact::negate($reduced[1]), Exact::negate($reduced[2])] : $reduced; + } + } + return [0, 0, 0]; + } + + /** + * Reorient a hull the way `ROTATIONS` reorients its box, flipping one axis on an odd + * permutation so it stays a proper rotation, then translated so its bounds start at 0. + * + * @param list $vertices + * @param array{0:int,1:int,2:int} $axes + * @return list + */ + public static function rotateHull(array $vertices, array $axes): array + { + $inversions = 0; + for ($first = 0; $first < 3; ++$first) { + for ($second = $first + 1; $second < 3; ++$second) { + if ($axes[$first] > $axes[$second]) { + ++$inversions; + } + } + } + $turned = []; + foreach ($vertices as $vertex) { + $x = $vertex[$axes[0]]; + $turned[] = [$inversions % 2 === 1 ? Exact::negate($x) : $x, $vertex[$axes[1]], $vertex[$axes[2]]]; + } + if ($turned === []) { + throw MalformedResult::shape('a hull without vertices'); + } + $low = []; + for ($axis = 0; $axis < 3; ++$axis) { + $low[$axis] = $turned[0][$axis]; + foreach ($turned as $vertex) { + if (Exact::compare($vertex[$axis], $low[$axis]) < 0) { + $low[$axis] = $vertex[$axis]; + } + } + } + return \array_map(static function (array $vertex) use ($low): array { return self::difference($vertex, $low); }, $turned); + } + + /** Whether two convex solids share interior volume; touching is contact, not collision. @param list $left @param list $right */ + public static function solidsOverlap(array $left, array $right): bool + { + foreach (self::hullAxes($left, $right) as $axis) { + [$leftLow, $leftHigh] = self::extent($left, $axis); + [$rightLow, $rightHigh] = self::extent($right, $axis); + if (Exact::compare($leftHigh, $rightLow) <= 0 || Exact::compare($rightHigh, $leftLow) <= 0) { + return false; + } + } + return true; + } + + /** Exact volume of a convex hull, `6V = sum of a . (b x c)` over its outward faces. @param list $vertices @return int|string */ + public static function hullVolume(array $vertices) + { + $normals = []; + foreach (self::triples($vertices) as [$first, $second, $third]) { + $axis = self::primitiveAxis(self::cross(self::difference($second, $first), self::difference($third, $first))); + if (Exact::sign($axis[0]) !== 0 || Exact::sign($axis[1]) !== 0 || Exact::sign($axis[2]) !== 0) { + $normals[self::axisKey($axis)] = $axis; + } + } + $sixVolumes = 0; + foreach ($normals as $axis) { + foreach ([$axis, [Exact::negate($axis[0]), Exact::negate($axis[1]), Exact::negate($axis[2])]] as $outward) { + [, $highest] = self::extent($vertices, $outward); + $face = []; + foreach ($vertices as $vertex) { + if (Exact::compare(self::dot($vertex, $outward), $highest) === 0) { + $face[] = $vertex; + } + } + if (\count($face) < 3) { + continue; + } + $ordered = self::windFace($face, $outward); + for ($index = 1; $index + 1 < \count($ordered); ++$index) { + $sixVolumes = Exact::add($sixVolumes, self::dot($ordered[0], self::cross($ordered[$index], $ordered[$index + 1]))); + } + } + } + return Exact::floorDiv(Exact::abs($sixVolumes), 6); + } + + /** + * Corners of one planar convex face in cyclic order seen from outside, by gift-wrapping from + * the lexicographically smallest vertex; collinear candidates resolve to the farthest. + * + * @param list $face @param array $outward @return list + */ + private static function windFace(array $face, array $outward): array + { + $start = $face[0]; + foreach ($face as $vertex) { + if (self::compareVertices($vertex, $start) < 0) { + $start = $vertex; + } + } + $ordered = [$start]; + $current = $start; + for ($step = 0, $count = \count($face); $step < $count; ++$step) { + $following = null; + foreach ($face as $candidate) { + if (self::compareVertices($candidate, $current) === 0) { + continue; + } + if ($following === null) { + $following = $candidate; + continue; + } + $turn = self::dot(self::cross(self::difference($following, $current), self::difference($candidate, $current)), $outward); + $reachVector = self::difference($candidate, $current); + $heldVector = self::difference($following, $current); + $reach = self::dot($reachVector, $reachVector); + $held = self::dot($heldVector, $heldVector); + if (Exact::sign($turn) < 0 || (Exact::sign($turn) === 0 && Exact::compare($reach, $held) > 0)) { + $following = $candidate; + } + } + if ($following === null || self::compareVertices($following, $start) === 0) { + break; + } + $ordered[] = $following; + $current = $following; + } + return $ordered; + } + + /** The complete separating-axis superset: face normals of each hull and cross products of their edges. @param list $left @param list $right @return list */ + private static function hullAxes(array $left, array $right): array + { + $axes = []; + foreach ([$left, $right] as $hull) { + foreach (self::triples($hull) as [$first, $second, $third]) { + $axis = self::primitiveAxis(self::cross(self::difference($second, $first), self::difference($third, $first))); + $axes[self::axisKey($axis)] = $axis; + } + } + $rightDirections = self::pairDirections($right); + foreach (self::pairDirections($left) as $one) { + foreach ($rightDirections as $other) { + $axis = self::primitiveAxis(self::cross($one, $other)); + $axes[self::axisKey($axis)] = $axis; + } + } + unset($axes[self::axisKey([0, 0, 0])]); + return \array_values($axes); + } + + /** @param list $points @return list */ + private static function pairDirections(array $points): array + { + $directions = []; + for ($first = 0, $count = \count($points); $first < $count; ++$first) { + for ($second = $first + 1; $second < $count; ++$second) { + $directions[] = self::difference($points[$second], $points[$first]); + } + } + return $directions; + } + + /** Every 3-combination, in `itertools.combinations` order. @param list $points @return \Generator> */ + private static function triples(array $points): \Generator + { + for ($first = 0, $count = \count($points); $first < $count; ++$first) { + for ($second = $first + 1; $second < $count; ++$second) { + for ($third = $second + 1; $third < $count; ++$third) { + yield [$points[$first], $points[$second], $points[$third]]; + } + } + } + } + + /** @param list $points @param array $axis @return array{0:int|string,1:int|string} */ + private static function extent(array $points, array $axis): array + { + $low = $high = null; + foreach ($points as $point) { + $value = self::dot($point, $axis); + if ($low === null || Exact::compare($value, $low) < 0) { + $low = $value; + } + if ($high === null || Exact::compare($value, $high) > 0) { + $high = $value; + } + } + return [$low, $high]; + } + + /** @param array $axis */ + private static function axisKey(array $axis): string + { + return $axis[0] . ',' . $axis[1] . ',' . $axis[2]; + } + + /** @param array $left @param array $right */ + private static function compareVertices(array $left, array $right): int + { + for ($axis = 0; $axis < 3; ++$axis) { + $order = Exact::compare($left[$axis], $right[$axis]); + if ($order !== 0) { + return $order; + } + } + return 0; + } +} diff --git a/src/Support/ResultValidation/ItemSpec.php b/src/Support/ResultValidation/ItemSpec.php new file mode 100644 index 0000000..b1ca228 --- /dev/null +++ b/src/Support/ResultValidation/ItemSpec.php @@ -0,0 +1,77 @@ + */ + public $allowedRotations; + /** @var bool */ + public $stackable; + /** @var bool */ + public $mustBeOnFloor; + /** @var int|string|null */ + public $maxTopLoad; + /** @var Ratio */ + public $minimumSupportRatio; + /** @var array */ + public $tags; + /** @var array */ + public $eligibleContainerTags; + /** @var int|null */ + public $maxStackedItems; + /** @var mixed */ + public $groundContactRule; + /** @var int|string|null */ + public $nestingHeight; + /** @var array */ + public $incompatibleTags; + /** @var int|null */ + public $stopIndex; + /** @var mixed */ + public $value; + /** @var mixed */ + public $shapeType; + /** @var list|null */ + public $hullVertices; + /** @var int|string|null */ + public $compressionRatioPpm; + /** @var int|null */ + public $maxCompressionPressureKpa; + /** @var mixed */ + public $stackingGroup; + /** @var array */ + public $acceptsStackingGroups; + + /** `orientation in allowed_rotations`. @param mixed $orientation */ + public function allows($orientation): bool + { + foreach ($this->allowedRotations as $allowed) { + if (Json::equals($allowed, $orientation)) { + return true; + } + } + return false; + } + + public function isConvexHull(): bool + { + return Json::isText($this->shapeType, 'convex_hull'); + } + + /** @return array{0:int|string,1:int|string,2:int|string} */ + public function rotated(string $orientation): array + { + $axes = Geometry::axes($orientation); + return [$this->dimensions[$axes[0]], $this->dimensions[$axes[1]], $this->dimensions[$axes[2]]]; + } +} diff --git a/src/Support/ResultValidation/Json.php b/src/Support/ResultValidation/Json.php new file mode 100644 index 0000000..1517c34 --- /dev/null +++ b/src/Support/ResultValidation/Json.php @@ -0,0 +1,318 @@ + */ + public static function items($value, string $what): array + { + if (!self::isList($value)) { + throw MalformedResult::shape(\sprintf('%s must be a list, got %s', $what, self::kind($value))); + } + return $value; + } + + /** @param mixed $value */ + public static function text($value, string $what): string + { + if (!\is_string($value)) { + throw MalformedResult::shape(\sprintf('%s must be a string, got %s', $what, self::kind($value))); + } + return $value; + } + + /** + * An integer the reference does arithmetic on. A boolean is Python's `int`; a float would + * carry the reference into float arithmetic this port does not follow, so it is refused. + * + * @param mixed $value + */ + public static function int($value, string $what): int + { + if (\is_int($value)) { + return $value; + } + if (\is_bool($value)) { + return (int)$value; + } + throw MalformedResult::shape(\sprintf('%s must be an integer, got %s', $what, self::kind($value))); + } + + /** @param mixed $value */ + public static function optionalInt($value, string $what): ?int + { + return $value === null ? null : self::int($value, $what); + } + + /** `isinstance(value, int)`, which a boolean satisfies. @param mixed $value */ + public static function intInstance($value): ?int + { + if (\is_int($value)) { + return $value; + } + return \is_bool($value) ? (int)$value : null; + } + + /** `isinstance(value, int) and not isinstance(value, bool)`. @param mixed $value */ + public static function strictInt($value): ?int + { + return \is_int($value) ? $value : null; + } + + /** Python's `int(value)`: a number truncates, a string parses as a base-10 integer. @param mixed $value @return int|string */ + public static function pyInt($value, string $what) + { + if (\is_int($value) || \is_bool($value)) { + return (int)$value; + } + if (\is_float($value) && \is_finite($value)) { + $truncated = $value < 0 ? \ceil($value) : \floor($value); + if (\abs($truncated) < 9.0e18) { + return (int)$truncated; + } + return Exact::normalize(\sprintf('%.0f', $truncated)); + } + if (\is_string($value) && \preg_match('/^\s*([+-]?)(\d+(?:_\d+)*)\s*$/', $value, $parts) === 1) { + $digits = \ltrim(\str_replace('_', '', $parts[2]), '0'); + $magnitude = Exact::normalize($digits === '' ? '0' : $digits); + return $parts[1] === '-' ? Exact::negate($magnitude) : $magnitude; + } + throw MalformedResult::shape(\sprintf('%s: int() cannot convert %s', $what, self::kind($value))); + } + + /** Python truthiness. @param mixed $value */ + public static function truthy($value): bool + { + if ($value === null) { + return false; + } + if (\is_bool($value)) { + return $value; + } + if (\is_int($value) || \is_float($value)) { + return $value != 0; + } + if (\is_string($value)) { + return $value !== ''; + } + return $value !== []; + } + + /** + * Python `==`: a boolean equals its integer, an integer equals the float of the same value, + * containers compare element-wise and objects regardless of key order. + * + * @param mixed $left @param mixed $right + */ + public static function equals($left, $right): bool + { + $leftNumber = self::number($left); + $rightNumber = self::number($right); + if ($leftNumber !== null || $rightNumber !== null) { + return $leftNumber !== null && $rightNumber !== null && self::compareNumbers($leftNumber, $rightNumber) === 0; + } + if ($left === null || $right === null) { + return $left === $right; + } + if (\is_string($left) || \is_string($right)) { + return \is_string($left) && \is_string($right) && $left === $right; + } + if (\count($left) !== \count($right)) { + return false; + } + if (self::isList($left) && self::isList($right)) { + foreach ($left as $index => $element) { + if (!self::equals($element, $right[$index])) { + return false; + } + } + return true; + } + foreach ($left as $key => $element) { + if (!\array_key_exists($key, $right) || !self::equals($element, $right[$key])) { + return false; + } + } + return true; + } + + /** `value == number` for an exact integer. @param mixed $value @param int|string $number */ + public static function equalsInt($value, $number): bool + { + $read = self::number($value); + return $read !== null && self::compareNumbers($read, $number) === 0; + } + + /** `value == text`. @param mixed $value */ + public static function isText($value, string $text): bool + { + return \is_string($value) && $value === $text; + } + + /** + * Python's ordering for what the reference sorts or compares: numbers with numbers, strings + * with strings, lists element-wise. Anything else is Python's `TypeError`. + * + * @param mixed $left @param mixed $right + */ + public static function compare($left, $right): int + { + $leftNumber = self::number($left); + $rightNumber = self::number($right); + if ($leftNumber !== null && $rightNumber !== null) { + return self::compareNumbers($leftNumber, $rightNumber); + } + if (\is_string($left) && \is_string($right)) { + return \strcmp($left, $right) <=> 0; + } + if (self::isList($left) && self::isList($right)) { + foreach ($left as $index => $element) { + if (!\array_key_exists($index, $right)) { + return 1; + } + if (!self::equals($element, $right[$index])) { + return self::compare($element, $right[$index]); + } + } + return \count($left) <=> \count($right); + } + throw MalformedResult::shape(\sprintf('cannot order %s against %s', self::kind($left), self::kind($right))); + } + + /** + * The identity Python hashes a set member or dict key by, so `1`, `1.0` and `True` share one. + * A list or an object is unhashable. + * + * @param mixed $value + */ + public static function hashKey($value): string + { + $number = self::number($value); + if ($number !== null) { + return 'n' . (\is_float($number) ? \sprintf('%.17e', $number) : (string)$number); + } + if ($value === null) { + return 'null'; + } + if (\is_string($value)) { + return 's' . $value; + } + throw MalformedResult::shape(self::kind($value) . ' is unhashable'); + } + + /** Sort values in place by Python's ordering. @param list $values */ + public static function sort(array &$values): void + { + \usort($values, [self::class, 'compare']); + } + + /** @param mixed $value */ + public static function kind($value): string + { + if ($value === null) { + return 'null'; + } + if (\is_bool($value)) { + return 'a boolean'; + } + if (\is_int($value)) { + return 'an integer'; + } + if (\is_float($value)) { + return 'a number'; + } + if (\is_string($value)) { + return 'a string'; + } + return self::isList($value) && $value !== [] ? 'a list' : 'an object'; + } + + /** + * A JSON number as an exact integer when it is one (an integral float within range reads as + * that integer, as Python compares it), else the float. + * + * @param mixed $value @return int|float|null + */ + private static function number($value) + { + if (\is_bool($value)) { + return (int)$value; + } + if (\is_int($value)) { + return $value; + } + if (\is_float($value)) { + return (\floor($value) === $value && \abs($value) < 9.0e18) ? (int)$value : $value; + } + return null; + } + + /** @param int|float|string $left @param int|float|string $right */ + private static function compareNumbers($left, $right): int + { + if (\is_float($left) || \is_float($right)) { + return (float)$left <=> (float)$right; + } + return Exact::compare($left, $right); + } +} diff --git a/src/Support/ResultValidation/Label.php b/src/Support/ResultValidation/Label.php new file mode 100644 index 0000000..60a0320 --- /dev/null +++ b/src/Support/ResultValidation/Label.php @@ -0,0 +1,41 @@ +text = $id === $this ? null : PyFormat::str($id); + } + + public function __toString(): string + { + if ($this->text === null) { + $this->missingUsed = true; + return '?'; + } + return $this->text; + } + + public function verify(): void + { + if ($this->missingUsed) { + throw MalformedResult::shape('a packed container with an issue has no id'); + } + } +} diff --git a/src/Support/ResultValidation/Lattice.php b/src/Support/ResultValidation/Lattice.php new file mode 100644 index 0000000..8e80ed0 --- /dev/null +++ b/src/Support/ResultValidation/Lattice.php @@ -0,0 +1,212 @@ + $items @param Ordered $containers + * @param int|string $clearance @param list $issues + * @return mixed the result with every valid summary expanded into placements + */ + public static function materialize($request, $result, Ordered $items, Ordered $containers, $clearance, array &$issues) + { + $packedContainers = Json::items(Json::at($result, 'containers'), 'result.containers'); + $summarized = false; + foreach ($packedContainers as $packed) { + $summarized = $summarized || Json::has($packed, 'lattice_summary'); + } + if (!$summarized) { + return $result; + } + $optional = Json::get(Json::get($request, 'configuration', []), 'require_placement_coordinates') === false; + foreach ($packedContainers as $index => $packed) { + $placements = self::expand($packed, $optional, $items, $containers, $clearance, $issues); + if ($placements !== null) { + $packedContainers[$index]['placements'] = $placements; + } + } + $result['containers'] = $packedContainers; + return $result; + } + + /** + * @param mixed $packed @param Ordered $items @param Ordered $containers + * @param int|string $clearance @param list $issues + * @return list|null the placements to write into the container, or null to leave it + */ + private static function expand($packed, bool $optional, Ordered $items, Ordered $containers, $clearance, array &$issues): ?array + { + $summary = Json::get($packed, 'lattice_summary'); + if ($summary === null) { + return null; + } + $containerId = PyFormat::str(Json::get($packed, 'id', '?')); + if (!$optional) { + $issues[] = new ResultIssue('unexpected_lattice_summary', "{$containerId}: request requires explicit placement coordinates"); + } + if (Json::truthy(Json::get($packed, 'placements'))) { + $issues[] = new ResultIssue('lattice_placements_conflict', "{$containerId}: compact summary and explicit placements are mutually exclusive"); + } + $itemType = Json::get($summary, 'item_type'); + $item = $items->get($itemType); + $container = $containers->get(Json::get($packed, 'container_type')); + if ($item === null || $container === null) { + // The ordinary accounting and container checks report the unknown reference. + return null; + } + $fields = self::fields($summary, $containerId); + $problems = self::problems($fields, $item, $itemType, $container, $clearance); + if ($problems !== []) { + foreach ($problems as $problem) { + $issues[] = new ResultIssue('lattice_summary_mismatch', "{$containerId}: {$problem}"); + } + return []; + } + return self::synthesize($fields, $summary, $itemType, $containerId, $clearance); + } + + /** @param mixed $summary @return array */ + private static function fields($summary, string $containerId): array + { + try { + $sides = static function (string $key) use ($summary): array { + $block = Json::at($summary, $key); + return \array_map(static function (string $side) use ($block) { + return Json::at(Json::at($block, $side), 'ticks'); + }, self::SIDES); + }; + return [ + 'orientation' => Json::at($summary, 'orientation'), + 'physical' => $sides('physical_dimensions'), + 'envelope' => $sides('envelope_dimensions'), + 'nx' => Json::at($summary, 'nx'), + 'ny' => Json::at($summary, 'ny'), + 'layers_used' => Json::at($summary, 'layers_used'), + 'layer_step' => Json::at(Json::at($summary, 'layer_step'), 'ticks'), + 'count' => Json::at($summary, 'count'), + ]; + } catch (MalformedResult $missing) { + // The reference reports a missing field as a contract break, naming the container. + throw MalformedResult::contract("{$containerId}: lattice_summary is missing a canonical field: {$missing->getMessage()}"); + } + } + + /** @param array $fields @param mixed $itemType @param int|string $clearance @return list */ + private static function problems(array $fields, ItemSpec $item, $itemType, ContainerSpec $container, $clearance): array + { + $problems = []; + $orientation = $fields['orientation']; + if (!Geometry::isRotation($orientation)) { + $problems[] = 'unknown orientation ' . PyFormat::repr($orientation); + } else { + $expected = $item->rotated($orientation); + if (!self::matches($fields['physical'], $expected)) { + $problems[] = 'physical dimensions ' . PyFormat::valueTuple($fields['physical']) . ' != rotated item ' . PyFormat::intTuple($expected); + } + if (!$item->allows($orientation)) { + $problems[] = "orientation {$orientation} is forbidden for " . PyFormat::str($itemType); + } + } + $margin = Exact::mul(2, $clearance); + $expectedEnvelope = []; + foreach ($fields['physical'] as $side) { + $expectedEnvelope[] = Exact::add(Json::int($side, 'physical dimension'), $margin); + } + if (!self::matches($fields['envelope'], $expectedEnvelope)) { + $problems[] = 'envelope dimensions ' . PyFormat::valueTuple($fields['envelope']) . ' != physical+clearance ' . PyFormat::intTuple($expectedEnvelope); + } + if ($item->nestingHeight !== null) { + $problems[] = 'compact lattice form is not valid for nesting items'; + } + if (!Json::equals($fields['layer_step'], $fields['envelope'][2])) { + $problems[] = 'layer_step ' . PyFormat::str($fields['layer_step']) . ' != envelope height ' . PyFormat::str($fields['envelope'][2]); + } + foreach (['nx', 'ny', 'layers_used', 'layer_step', 'count'] as $name) { + $value = Json::strictInt($fields[$name]); + if ($value === null || $value < 1) { + $problems[] = "{$name} must be a positive integer, got " . PyFormat::repr($fields[$name]); + } + } + if ($problems === []) { + self::independentCounts($fields, $item, $container, $problems); + } + return $problems; + } + + /** Reached only once every field is a positive integer and the envelope is the expected one. @param array $fields @param list $problems */ + private static function independentCounts(array $fields, ItemSpec $item, ContainerSpec $container, array &$problems): void + { + $nx = $fields['nx']; + $ny = $fields['ny']; + $layersUsed = $fields['layers_used']; + $layerStep = $fields['layer_step']; + $count = $fields['count']; + $expectedNx = Exact::floorDiv($container->inner[0], $fields['envelope'][0]); + $expectedNy = Exact::floorDiv($container->inner[1], $fields['envelope'][1]); + $expectedLayers = Exact::ceilDiv($count, Exact::mul($nx, $ny)); + if (Exact::compare($nx, $expectedNx) !== 0) { + $problems[] = "nx {$nx} != independently computed {$expectedNx}"; + } + if (Exact::compare($ny, $expectedNy) !== 0) { + $problems[] = "ny {$ny} != independently computed {$expectedNy}"; + } + if (Exact::compare($layersUsed, $expectedLayers) !== 0) { + $problems[] = "layers_used {$layersUsed} != independently computed {$expectedLayers}"; + } + if ($count > Json::int($item->quantity, 'quantity')) { + $problems[] = "count {$count} exceeds requested quantity " . PyFormat::str($item->quantity); + } + $capacity = Exact::floorDiv($container->inner[2], $layerStep); + if (Exact::compare($layersUsed, $capacity) > 0) { + $problems[] = "layers_used {$layersUsed} exceeds vertical capacity {$capacity}"; + } + } + + /** @param array $fields @param mixed $summary @param mixed $itemType @param int|string $clearance @return list */ + private static function synthesize(array $fields, $summary, $itemType, string $containerId, $clearance): array + { + $nx = $fields['nx']; + $ny = $fields['ny']; + $perLayer = $nx * $ny; + $physical = Json::at($summary, 'physical_dimensions'); + $tick = static function ($value): array { return ['ticks' => $value]; }; + $placements = []; + for ($index = 0; $index < $fields['count']; ++$index) { + $placements[] = [ + 'item_id' => PyFormat::str($itemType) . "#lattice:{$containerId}:" . ($index + 1), + 'item_type' => $itemType, + 'orientation' => $fields['orientation'], + 'position' => [ + 'x' => $tick(Exact::add(Exact::mul($index % $nx, $fields['envelope'][0]), $clearance)), + 'y' => $tick(Exact::add(Exact::mul(\intdiv($index, $nx) % $ny, $fields['envelope'][1]), $clearance)), + 'z' => $tick(Exact::add(Exact::mul(\intdiv($index, $perLayer), $fields['layer_step']), $clearance)), + ], + 'dimensions' => $physical, + ]; + } + return $placements; + } + + /** Element-wise `reported == expected` for a tuple of JSON values. @param list $reported @param list $expected */ + private static function matches(array $reported, array $expected): bool + { + foreach ($expected as $index => $value) { + if (!Json::equalsInt($reported[$index], $value)) { + return false; + } + } + return true; + } +} diff --git a/src/Support/ResultValidation/MachineSpec.php b/src/Support/ResultValidation/MachineSpec.php new file mode 100644 index 0000000..96690ea --- /dev/null +++ b/src/Support/ResultValidation/MachineSpec.php @@ -0,0 +1,18 @@ + $last) { + $low = $middle + 1; + } else { + return true; + } + } + return false; + } +} diff --git a/src/Support/ResultValidation/ObjectiveCheck.php b/src/Support/ResultValidation/ObjectiveCheck.php new file mode 100644 index 0000000..f4ff2f9 --- /dev/null +++ b/src/Support/ResultValidation/ObjectiveCheck.php @@ -0,0 +1,314 @@ + $fabricated @param list $issues */ + public static function check($request, $result, Context $context, Ordered $fabricated, array &$issues): void + { + $configuration = Json::get($request, 'configuration', []); + $selected = Json::get($configuration, 'objective', 'default'); + $reportedName = Json::get($result, 'objective'); + if ((Json::has($configuration, 'objective') || $reportedName !== null) && !Json::equals($reportedName, $selected)) { + $issues[] = new ResultIssue('objective_mismatch', 'reported ' . PyFormat::repr($reportedName) . ', requested ' . PyFormat::repr($selected)); + } + $reported = \array_map(static function ($component) { return Json::pyInt($component, 'score'); }, Json::items(Json::at($result, 'score'), 'score')); + $billing = [ + 'divisor' => Json::get($configuration, 'dimensional_weight_divisor'), + 'length_unit' => Json::get($configuration, 'dimensional_weight_length_unit', 'in'), + 'weight_unit' => Json::get($configuration, 'dimensional_weight_weight_unit', 'lb'), + ]; + $recomputed = self::objective($result, $context, $fabricated, $selected, $billing); + $same = \count($reported) === \count($recomputed); + foreach ($recomputed as $index => $value) { + $same = $same && Exact::compare($reported[$index], $value) === 0; + } + if (!$same) { + $issues[] = new ResultIssue('score_mismatch', 'reported ' . PyFormat::intList($reported) . ', recomputed ' . PyFormat::intList($recomputed)); + } + } + + /** + * @param mixed $result @param Ordered $fabricated @param mixed $name + * @param array{divisor:mixed,length_unit:mixed,weight_unit:mixed} $billing + * @return list + */ + private static function objective($result, Context $context, Ordered $fabricated, $name, array $billing): array + { + $cost = $unused = $height = $billable = $achievedHeight = $landed = 0; + $billed = Json::isText($name, 'shipping_cost') || Json::isText($name, 'lowest_landed_cost'); + $containers = Json::items(Json::at($result, 'containers'), 'result.containers'); + foreach ($containers as $packed) { + $spec = $fabricated->get(Json::get($packed, 'id')) ?? $context->containers->get(Json::at($packed, 'container_type')); + if ($spec === null) { + continue; + } + $cost = Exact::add($cost, $spec->costMinor); + $volume = $spec->volume(); + if (Exact::sign($volume) === 0) { + continue; + } + $used = Json::pyInt(Json::at($packed, 'used_volume_ticks3'), 'used_volume_ticks3'); + $unused = Exact::add($unused, Exact::floorDiv(Exact::mul(Exact::sub($volume, $used), ContainerCheck::SCORE_SCALE), $volume)); + $top = null; + foreach (Json::items(Json::at($packed, 'placements'), 'placements') as $placement) { + $z = Json::int(Json::at(Json::at(Json::at($placement, 'position'), 'z'), 'ticks'), 'placement ticks'); + $extent = Json::int(Json::at(Json::at(Json::at($placement, 'dimensions'), 'height'), 'ticks'), 'placement ticks'); + $reach = Exact::add(Exact::add($z, $extent), $context->clearance); + $top = $top === null ? $reach : Exact::max($top, $reach); + } + $top = $top ?? 0; + $height = Exact::add($height, Exact::floorDiv(Exact::mul($top, ContainerCheck::SCORE_SCALE), $spec->inner[2])); + $achievedHeight = Exact::add($achievedHeight, $top); + if ($billed && $billing['divisor'] !== null) { + $gross = Json::pyInt(Json::get(Json::get($packed, 'gross_weight', []), 'ticks', 0), 'gross_weight'); + $size = $spec->flatBag ? ContainerCheck::achievedExtent($packed, $context->clearance) : ($spec->outer ?? $spec->inner); + $dimensional = self::dimensionalWeight( + $size, + Json::int($billing['divisor'], 'dimensional_weight_divisor'), + Json::text($billing['length_unit'], 'dimensional_weight_length_unit'), + Json::text($billing['weight_unit'], 'dimensional_weight_weight_unit') + ); + $charged = Exact::max($gross, $dimensional); + $billable = Exact::add($billable, $charged); + if (Json::isText($name, 'lowest_landed_cost')) { + $landed = Exact::add($landed, self::landedCharge($spec, $charged)); + } + } + } + $unpackedItems = Json::items(Json::at($result, 'unpacked_items'), 'result.unpacked_items'); + $unpacked = \count($unpackedItems); + $opened = \count($containers); + $requiresDivisor = static function (string $objective): MalformedResult { + return MalformedResult::contract("{$objective} objective requires configuration.dimensional_weight_divisor"); + }; + if (!\is_string($name)) { + throw MalformedResult::contract('unknown requested objective ' . PyFormat::repr($name)); + } + switch ($name) { + case 'default': + return [$unpacked, $opened, $cost, $unused, $height]; + case 'lowest_cost': + return [$unpacked, $cost, $opened, $unused, $height]; + case 'shipping_cost': + if ($billing['divisor'] === null) { + throw $requiresDivisor('shipping_cost'); + } + return [$unpacked, $billable, $opened, $unused, $height]; + case 'lowest_landed_cost': + if ($billing['divisor'] === null) { + throw $requiresDivisor('lowest_landed_cost'); + } + return [$unpacked, $landed, $opened, $unused, $height]; + case 'open_dimension_height': + return [$unpacked, $achievedHeight, $opened, $cost, $unused]; + case 'maximum_value': + $forgone = 0; + foreach ($unpackedItems as $item) { + $spec = $context->items->get(Json::at($item, 'item_type')); + if ($spec !== null && Json::truthy($spec->value)) { + $forgone = Exact::add($forgone, Json::int($spec->value, 'value')); + } + } + return [$unpacked, $forgone, $opened, $cost, $unused]; + case 'maximum_volume': + $nominal = static function (ItemSpec $spec) { + return Exact::mul(Exact::mul($spec->dimensions[0], $spec->dimensions[1]), $spec->dimensions[2]); + }; + $unpackedVolume = 0; + foreach ($unpackedItems as $item) { + $spec = $context->items->get(Json::at($item, 'item_type')); + if ($spec !== null) { + $unpackedVolume = Exact::add($unpackedVolume, $nominal($spec)); + } + } + $requested = 0; + foreach ($context->items->values() as $spec) { + $requested = Exact::add($requested, Exact::mul($nominal($spec), Json::int($spec->quantity, 'quantity'))); + } + $unpackedPpm = Exact::sign($requested) === 0 ? 0 : Exact::ceilDiv(Exact::mul($unpackedVolume, ContainerCheck::SCORE_SCALE), $requested); + return [$unpackedPpm, $unpacked, $opened, $cost, $unused]; + } + throw MalformedResult::contract('unknown requested objective ' . PyFormat::repr($name)); + } + + /** `floor(volume * weight ticks per unit / (length ticks per unit ^ 3 * divisor))`. @param array $size @return int|string */ + private static function dimensionalWeight(array $size, int $divisor, string $lengthUnit, string $weightUnit) + { + $length = Units::perUnit(Units::LENGTH, $lengthUnit); + $weight = Units::perUnit(Units::WEIGHT, $weightUnit); + $volume = Exact::mul(Exact::mul($size[0], $size[1]), $size[2]); + return Exact::floorDiv(Exact::mul($volume, $weight), Exact::mul(Exact::mul(Exact::mul($length, $length), $length), $divisor)); + } + + /** + * One container's carrier charge from the request's own rate card: billed weight up to whole + * grams, the minimum charge, then the fuel surcharge rounded up. + * + * @param int|string $billedTicks @return int|string + */ + private static function landedCharge(ContainerSpec $spec, $billedTicks) + { + if ($spec->rateTable === null) { + throw MalformedResult::contract('container ' . PyFormat::repr($spec->id) . ' has no rate_table, so lowest_landed_cost cannot price it'); + } + $table = $spec->rateTable; + $read = static function ($value, string $what) { return Json::pyInt($value, $what); }; + $brackets = \array_map(static function ($bound) use ($read) { return $read($bound, 'bracket'); }, Json::items(Json::at($table, 'weight_brackets_g'), 'weight_brackets_g')); + $prices = \array_map(static function ($price) use ($read) { return $read($price, 'price'); }, Json::items(Json::at($table, 'prices_minor'), 'prices_minor')); + $grams = Exact::ceilDiv($billedTicks, Units::TICKS_PER_GRAM); + foreach ($brackets as $index => $bound) { + if (!\array_key_exists($index, $prices)) { + break; + } + if (Exact::compare($grams, $bound) <= 0) { + $base = Exact::max($prices[$index], $read(Json::get($table, 'minimum_charge_minor', 0), 'minimum_charge_minor')); + $permille = $read(Json::get($table, 'fuel_surcharge_permille', 0), 'fuel_surcharge_permille'); + return Exact::add($base, Exact::ceilDiv(Exact::mul($base, $permille), 1000)); + } + } + if ($brackets === []) { + throw MalformedResult::shape('an empty rate table'); + } + $last = $brackets[\count($brackets) - 1]; + throw MalformedResult::contract('container ' . PyFormat::repr($spec->id) . " bills at {$grams} g, above its rate table's last bracket ({$last} g); the shipment has no published price"); + } + + /** @param mixed $request @param mixed $result @param list $issues */ + public static function checkSolverSelection($request, $result, array &$issues): void + { + $selected = Json::get(Json::get($request, 'configuration', []), 'solvers', []); + if (!Json::truthy($selected)) { + return; + } + $listed = Json::items($selected, 'configuration.solvers'); + $reported = Json::get(Json::at($result, 'algorithm'), 'solver'); + $base = \is_string($reported) ? \explode(':', $reported, 2)[0] : $reported; + foreach ($listed as $solver) { + if (Json::equals($solver, $base)) { + return; + } + } + $issues[] = new ResultIssue('solver_selection_mismatch', 'reported ' . PyFormat::repr($reported) . ', requested one of ' . PyFormat::repr($selected)); + } + + /** A group travels together or not at all: one container, and never half-packed. @param mixed $request @param mixed $result @param list $issues */ + public static function checkGroups($request, $result, array &$issues): void + { + $rawItems = Json::items(Json::at($request, 'items'), 'request.items'); + $groups = new Ordered(); + foreach ($rawItems as $raw) { + if (Json::get($raw, 'group') !== null) { + $groups->set(Json::at($raw, 'id'), Json::at($raw, 'group')); + } + } + if ($groups->count() === 0) { + return; + } + $located = new Ordered(); + $packed = new Ordered(); + foreach (Json::items(Json::at($result, 'containers'), 'result.containers') as $container) { + foreach (Json::items(Json::at($container, 'placements'), 'placements') as $placement) { + $group = $groups->get(Json::at($placement, 'item_type')); + if ($group === null) { + continue; + } + $places = $located->get($group) ?? new Ordered(); + $places->set(Json::at($container, 'id'), true); + $located->set($group, $places); + $packed->set($group, $packed->get($group, 0) + 1); + } + } + $expected = new Ordered(); + foreach ($rawItems as $raw) { + $group = Json::get($raw, 'group'); + if ($group !== null) { + $expected->set($group, Exact::add($expected->get($group, 0), Json::int(Json::get($raw, 'quantity', 1), 'quantity'))); + } + } + $names = $located->keys(); + Json::sort($names); + foreach ($names as $group) { + $places = $located->get($group); + if ($places->count() > 1) { + $where = \array_map(static function ($place): string { return Json::text($place, 'a container id'); }, $places->keys()); + \sort($where, SORT_STRING); + $issues[] = new ResultIssue('group_split', PyFormat::str($group) . ': ' . \implode(', ', $where)); + } + $placed = $packed->get($group, 0); + $wanted = $expected->get($group, 0); + if (Exact::compare($placed, $wanted) !== 0) { + $issues[] = new ResultIssue('group_partially_packed', PyFormat::str($group) . ": {$placed} of {$wanted} placed"); + } + } + } + + /** Every fixed placement is reported where the request put it, and nothing else claims to be. @param mixed $request @param mixed $result @param list $issues */ + public static function checkFixedPlacements($request, $result, string $unit, array &$issues): void + { + $requested = []; + foreach (Json::items(Json::get($request, 'fixed_placements', []), 'fixed_placements') as $entry) { + $containerId = PyFormat::str(Json::at($entry, 'container_type')) . '#' . PyFormat::str(Json::get($entry, 'container_instance', 1)); + $position = Json::get($entry, 'position', []); + $key = [$containerId, Json::at($entry, 'item_type')]; + foreach (['x', 'y', 'z'] as $axis) { + $key[] = Units::toTicks(Json::get($position, $axis, 0), $unit, Units::LENGTH); + } + $key[] = Json::at($entry, 'orientation'); + $requested[self::keyHash($key)] = $key; + } + $reported = []; + $containerTypes = new Ordered(); + foreach (Json::items(Json::at($result, 'containers'), 'result.containers') as $container) { + $containerId = Json::get($container, 'id', ''); + $containerTypes->set($containerId, Json::at($container, 'container_type')); + foreach (Json::items(Json::at($container, 'placements'), 'placements') as $placement) { + if (Json::get($placement, 'fixed') !== true) { + continue; + } + $position = Json::at($placement, 'position'); + $key = [$containerId, Json::at($placement, 'item_type')]; + foreach (['x', 'y', 'z'] as $axis) { + $key[] = Json::at(Json::at($position, $axis), 'ticks'); + } + $key[] = Json::at($placement, 'orientation'); + $reported[self::keyHash($key)] = $key; + } + } + foreach (self::sorted(\array_values($requested)) as $key) { + $containerId = $key[0]; + $hash = \strrpos($containerId, '#'); + $declaredType = $hash === false ? $containerId : \substr($containerId, 0, $hash); + if (!Json::isText($containerTypes->get($containerId), $declaredType)) { + $issues[] = new ResultIssue('fixed_container_missing', $containerId); + } elseif (!\array_key_exists(self::keyHash($key), $reported)) { + $issues[] = new ResultIssue('fixed_placement_moved', PyFormat::str($key[1]) . " fixed in {$containerId} at " . PyFormat::valueTuple([$key[2], $key[3], $key[4]]) . ' ' . PyFormat::str($key[5])); + } + } + $unexpected = \array_values(\array_diff_key($reported, $requested)); + foreach (self::sorted($unexpected) as $key) { + $issues[] = new ResultIssue('unexpected_fixed_placement', PyFormat::str($key[1]) . ' in ' . PyFormat::str($key[0]) . ' at ' . PyFormat::valueTuple([$key[2], $key[3], $key[4]]) . ' ' . PyFormat::str($key[5])); + } + } + + /** @param list $key */ + private static function keyHash(array $key): string + { + return \implode("\0", \array_map([Json::class, 'hashKey'], $key)); + } + + /** @param list> $keys @return list> */ + private static function sorted(array $keys): array + { + Json::sort($keys); + return $keys; + } +} diff --git a/src/Support/ResultValidation/Ordered.php b/src/Support/ResultValidation/Ordered.php new file mode 100644 index 0000000..7fdc30b --- /dev/null +++ b/src/Support/ResultValidation/Ordered.php @@ -0,0 +1,72 @@ + */ + private $entries = []; + /** @var array */ + private $index = []; + + /** @param mixed $key @param T $value */ + public function set($key, $value): void + { + $hashed = Json::hashKey($key); + if (isset($this->index[$hashed])) { + $this->entries[$this->index[$hashed]][1] = $value; + return; + } + $this->index[$hashed] = \count($this->entries); + $this->entries[] = [$key, $value]; + } + + /** @param mixed $key @param T|null $default @return T|null */ + public function get($key, $default = null) + { + $position = $this->position($key); + return $position === null ? $default : $this->entries[$position][1]; + } + + /** @param mixed $key */ + public function has($key): bool + { + return $this->position($key) !== null; + } + + /** The entry's place in insertion order. @param mixed $key */ + public function position($key): ?int + { + return $this->index[Json::hashKey($key)] ?? null; + } + + /** @return list key and value, in insertion order */ + public function entries(): array + { + return $this->entries; + } + + /** @return list */ + public function values(): array + { + return \array_map(static function (array $entry) { return $entry[1]; }, $this->entries); + } + + /** @return list */ + public function keys(): array + { + return \array_map(static function (array $entry) { return $entry[0]; }, $this->entries); + } + + public function count(): int + { + return \count($this->entries); + } +} diff --git a/src/Support/ResultValidation/PyFormat.php b/src/Support/ResultValidation/PyFormat.php new file mode 100644 index 0000000..dc130f6 --- /dev/null +++ b/src/Support/ResultValidation/PyFormat.php @@ -0,0 +1,188 @@ + $element) { + $pairs[] = self::stringRepr((string)$key) . ': ' . self::repr($element); + } + return $value === [] ? '[]' : '{' . \implode(', ', $pairs) . '}'; + } + + /** `[a, b]` from already-formatted elements. @param list $elements */ + public static function listOf(array $elements): string + { + return '[' . \implode(', ', $elements) . ']'; + } + + /** `(a, b)`; a one-element tuple keeps its trailing comma. @param list $elements */ + public static function tupleOf(array $elements): string + { + return \count($elements) === 1 ? '(' . $elements[0] . ',)' : '(' . \implode(', ', $elements) . ')'; + } + + /** @param list $values */ + public static function intTuple(array $values): string + { + return self::tupleOf(\array_map('strval', $values)); + } + + /** @param list $values */ + public static function intList(array $values): string + { + return self::listOf(\array_map('strval', $values)); + } + + /** @param list $values */ + public static function valueTuple(array $values): string + { + return self::tupleOf(\array_map([self::class, 'repr'], $values)); + } + + public static function boolRepr(bool $flag): string + { + return $flag ? 'True' : 'False'; + } + + /** `f"{value:.6f}"`; PHP's `%f` and Python's both round the exact binary value half to even. */ + public static function fixed6(float $value): string + { + return \sprintf('%.6f', $value); + } + + /** + * `repr(float)`: the shortest digits that round-trip, in fixed notation for decimal exponents + * from -4 to 15 and scientific (`1e-05`, `1e+16`) outside that. + */ + public static function floatRepr(float $value): string + { + if (\is_nan($value)) { + return 'nan'; + } + if (\is_infinite($value)) { + return $value > 0 ? 'inf' : '-inf'; + } + // `atan2` is the one portable reading of negative zero's sign: -pi for -0.0, pi for 0.0. + $sign = ($value < 0 || ($value == 0.0 && \atan2($value, -1.0) < 0)) ? '-' : ''; + if ($value == 0.0) { + return $sign . '0.0'; + } + [$digits, $point] = ShortestFloat::digits(\abs($value)); + $exponent = $point - 1; + $count = \strlen($digits); + if ($exponent >= -4 && $exponent < 16) { + if ($point <= 0) { + return $sign . '0.' . \str_repeat('0', -$point) . $digits; + } + if ($count <= $point) { + return $sign . $digits . \str_repeat('0', $point - $count) . '.0'; + } + return $sign . \substr($digits, 0, $point) . '.' . \substr($digits, $point); + } + $fraction = $count > 1 ? '.' . \substr($digits, 1) : ''; + return \sprintf('%s%s%se%s%02d', $sign, $digits[0], $fraction, $exponent < 0 ? '-' : '+', \abs($exponent)); + } + + /** + * `repr(str)`: single quotes unless the text holds a single quote and no double quote, + * Python's escapes for the backslash, the quote, `\t`, `\n`, `\r` and other non-printables. + */ + public static function stringRepr(string $text): string + { + $quote = (\strpos($text, "'") !== false && \strpos($text, '"') === false) ? '"' : "'"; + $out = $quote; + foreach (self::codePoints($text) as [$character, $code]) { + if ($character === '\\') { + $out .= '\\\\'; + } elseif ($character === "\t") { + $out .= '\\t'; + } elseif ($character === "\n") { + $out .= '\\n'; + } elseif ($character === "\r") { + $out .= '\\r'; + } elseif ($character === $quote) { + $out .= '\\' . $character; + } elseif ($code < 0x20 || $code === 0x7f) { + $out .= \sprintf('\\x%02x', $code); + } elseif ($code < 0x7f || self::printable($code)) { + $out .= $character; + } elseif ($code <= 0xff) { + $out .= \sprintf('\\x%02x', $code); + } elseif ($code <= 0xffff) { + $out .= \sprintf('\\u%04x', $code); + } else { + $out .= \sprintf('\\U%08x', $code); + } + } + return $out . $quote; + } + + /** @return list each UTF-8 character and its code point */ + private static function codePoints(string $text): array + { + $characters = \preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY); + if ($characters === false) { + $characters = \str_split($text); + } + $points = []; + foreach ($characters as $character) { + $bytes = \array_values(\unpack('C*', $character)); + $length = \count($bytes); + if ($length === 1) { + $code = $bytes[0]; + } elseif ($length === 2) { + $code = (($bytes[0] & 0x1f) << 6) | ($bytes[1] & 0x3f); + } elseif ($length === 3) { + $code = (($bytes[0] & 0x0f) << 12) | (($bytes[1] & 0x3f) << 6) | ($bytes[2] & 0x3f); + } else { + $code = (($bytes[0] & 0x07) << 18) | (($bytes[1] & 0x3f) << 12) | (($bytes[2] & 0x3f) << 6) | ($bytes[3] & 0x3f); + } + $points[] = [$character, $code]; + } + return $points; + } + + /** Python's `str.isprintable` for a code point at or above U+007F, from the generated table. */ + private static function printable(int $code): bool + { + return !NonPrintable::contains($code); + } +} diff --git a/src/Support/ResultValidation/Ratio.php b/src/Support/ResultValidation/Ratio.php new file mode 100644 index 0000000..383221d --- /dev/null +++ b/src/Support/ResultValidation/Ratio.php @@ -0,0 +1,144 @@ +numerator = $numerator; + $this->denominator = $denominator; + } + + /** @param int|string $numerator @param int|string $denominator */ + public static function of($numerator, $denominator): self + { + if (Exact::sign($denominator) === 0) { + throw MalformedResult::shape('Fraction with a zero denominator'); + } + $divisor = Exact::gcd($numerator, $denominator); + if (Exact::sign($divisor) === 0) { + $divisor = 1; + } + $numerator = Exact::floorDiv($numerator, $divisor); + $denominator = Exact::floorDiv($denominator, $divisor); + if (Exact::sign($denominator) < 0) { + return new self(Exact::negate($numerator), Exact::negate($denominator)); + } + return new self($numerator, $denominator); + } + + /** @param int|string $value */ + public static function integer($value): self + { + return new self($value, 1); + } + + public function add(self $other): self + { + return self::of( + Exact::add(Exact::mul($this->numerator, $other->denominator), Exact::mul($other->numerator, $this->denominator)), + Exact::mul($this->denominator, $other->denominator) + ); + } + + public function mul(self $other): self + { + return self::of(Exact::mul($this->numerator, $other->numerator), Exact::mul($this->denominator, $other->denominator)); + } + + /** @param int|string $value */ + public function mulInt($value): self + { + return $this->mul(self::integer($value)); + } + + public function negate(): self + { + return new self(Exact::negate($this->numerator), $this->denominator); + } + + public function compare(self $other): int + { + return Exact::compare( + Exact::mul($this->numerator, $other->denominator), + Exact::mul($other->numerator, $this->denominator) + ); + } + + /** @param int|string $value */ + public function compareInt($value): int + { + return $this->compare(self::integer($value)); + } + + /** `numerator // denominator`. @return int|string */ + public function floor() + { + return Exact::floorDiv($this->numerator, $this->denominator); + } + + /** + * Python's `float(fraction)`: the nearest double, ties to even. The quotient is taken to 53 + * significant bits exactly and the remainder decides the last one. + */ + public function toFloat(): float + { + $numerator = Exact::abs($this->numerator); + if (Exact::sign($numerator) === 0) { + return 0.0; + } + $denominator = $this->denominator; + $limit = 1 << 53; + if (\is_int($numerator) && \is_int($denominator) && $numerator <= $limit && $denominator <= $limit) { + $value = $numerator / $denominator; + } else { + $value = self::nearestDouble($numerator, $denominator); + } + return Exact::sign($this->numerator) < 0 ? -$value : $value; + } + + /** @param int|string $numerator @param int|string $denominator */ + private static function nearestDouble($numerator, $denominator): float + { + // Scale so the quotient has exactly 53 bits; the float estimate only picks the start. + $shift = 52 - (int)\floor(\log((float)$numerator, 2) - \log((float)$denominator, 2)); + for (;;) { + [$scaledNumerator, $scaledDenominator] = $shift >= 0 + ? [Exact::mul($numerator, Exact::powerOfTwo($shift)), $denominator] + : [$numerator, Exact::mul($denominator, Exact::powerOfTwo(-$shift))]; + $quotient = Exact::floorDiv($scaledNumerator, $scaledDenominator); + if (Exact::compare($quotient, 1 << 52) < 0) { + ++$shift; + continue; + } + if (Exact::compare($quotient, 1 << 53) >= 0) { + --$shift; + continue; + } + break; + } + $remainder = Exact::sub($scaledNumerator, Exact::mul($quotient, $scaledDenominator)); + $order = Exact::compare(Exact::mul($remainder, 2), $scaledDenominator); + if ($order > 0 || ($order === 0 && $quotient % 2 === 1)) { + ++$quotient; + if ($quotient === 1 << 53) { + $quotient = 1 << 52; + --$shift; + } + } + return (float)$quotient * \pow(2.0, -$shift); + } +} diff --git a/src/Support/ResultValidation/Spec.php b/src/Support/ResultValidation/Spec.php new file mode 100644 index 0000000..f255c6a --- /dev/null +++ b/src/Support/ResultValidation/Spec.php @@ -0,0 +1,215 @@ + */ + public static function items($request, string $unit): Ordered + { + $items = new Ordered(); + foreach (Json::items(Json::at($request, 'items'), 'request.items') as $raw) { + $rotations = Json::get($raw, 'allowed_rotations'); + if ($rotations === null) { + $rotations = Json::truthy(Json::get($raw, 'keep_upright')) ? self::UPRIGHT_ROTATIONS : \array_keys(Geometry::ROTATIONS); + } else { + $rotations = Json::items($rotations, 'allowed_rotations'); + } + $id = Json::at($raw, 'id'); + $spec = new ItemSpec(); + $spec->id = Json::text($id, 'an item id'); + $spec->dimensions = Units::dimensions(Json::at($raw, 'dimensions'), $unit); + $spec->weight = Units::toTicks(Json::get($raw, 'weight', 0), 'g', Units::WEIGHT); + $spec->quantity = Json::get($raw, 'quantity', 1); + $spec->allowedRotations = \array_values($rotations); + $spec->stackable = Json::truthy(Json::get($raw, 'stackable', true)); + $spec->mustBeOnFloor = Json::truthy(Json::get($raw, 'must_be_on_floor')); + $spec->maxTopLoad = self::measured($raw, 'max_top_load', 'g', Units::WEIGHT); + $spec->minimumSupportRatio = Units::ratioOf(Json::get($raw, 'minimum_support_ratio', 0)); + $spec->tags = self::tagSet(Json::get($raw, 'tags', []), 'tags'); + $spec->eligibleContainerTags = self::tagSet(Json::get($raw, 'eligible_container_tags', []), 'eligible_container_tags'); + $spec->maxStackedItems = Json::optionalInt(Json::get($raw, 'max_stacked_items'), 'max_stacked_items'); + $spec->groundContactRule = Json::get($raw, 'ground_contact_rule'); + $spec->nestingHeight = self::measured($raw, 'nesting_height', $unit, Units::LENGTH); + $spec->incompatibleTags = self::tagSet(Json::get($raw, 'incompatible_tags', []), 'incompatible_tags'); + $spec->stopIndex = Json::optionalInt(Json::get($raw, 'stop_index'), 'stop_index'); + $spec->value = Json::get($raw, 'value'); + $spec->shapeType = Json::get($raw, 'shape_type', 'rigid_cuboid'); + $spec->hullVertices = self::hull($raw, $unit); + $ratio = Json::get($raw, 'compression_ratio'); + // The solvers' ratio rule, applied once: floor(ratio * 1000000 + 0.5) on the double. + $spec->compressionRatioPpm = $ratio === null ? null + : ContainerCheck::ratioPpm(Units::ratioOf($ratio)); + $spec->maxCompressionPressureKpa = Json::optionalInt(Json::get($raw, 'max_compression_pressure_kpa'), 'max_compression_pressure_kpa'); + $spec->stackingGroup = Json::get($raw, 'stacking_group'); + $accepted = Json::get($raw, 'accepts_stacking_groups'); + $spec->acceptsStackingGroups = Json::truthy($accepted) ? self::tagSet($accepted, 'accepts_stacking_groups') : []; + $items->set($id, $spec); + } + return $items; + } + + /** @param mixed $request @return Ordered */ + public static function containers($request, string $unit): Ordered + { + $containers = new Ordered(); + foreach (Json::items(Json::at($request, 'containers'), 'request.containers') as $raw) { + $spec = new ContainerSpec(); + $spec->id = Json::at($raw, 'id'); + $spec->inner = Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit); + $spec->accessDirections = self::accessDirections($raw); + $outer = Json::get($raw, 'outer_dimensions'); + $spec->outer = $outer === null ? null : Units::dimensions($outer, $unit); + $spec->costMinor = Json::int(Json::get($raw, 'cost_minor', 0), 'cost_minor'); + $spec->maxPayload = self::measured($raw, 'max_payload', 'g', Units::WEIGHT); + $spec->maxItems = Json::optionalInt(Json::get($raw, 'max_items'), 'max_items'); + $spec->quantity = Json::optionalInt(Json::get($raw, 'quantity'), 'quantity'); + $spec->obstacles = self::obstacles($raw, $unit); + $spec->tags = self::tagSet(Json::get($raw, 'tags', []), 'tags'); + $spec->tagLimits = self::tagLimits($raw); + $spec->voidFillReserveRatio = Units::ratioOf(Json::get($raw, 'void_fill_reserve_ratio', 0)); + $spec->tareWeight = Units::toTicks(Json::get($raw, 'tare_weight', 0), 'g', Units::WEIGHT); + $spec->axles = self::axles($raw, $unit); + $spec->maxStackDensity = self::measured($raw, 'max_stack_density', 'g', Units::WEIGHT); + $spec->rateTable = Json::get($raw, 'rate_table'); + $spec->flatBag = Json::get($raw, 'deformable_boundary') !== null; + $spec->reportsAchievedExtent = $spec->flatBag || Json::get($raw, 'made_to_measure') !== null; + $machine = Json::get($raw, 'made_to_measure'); + $spec->madeToMeasure = $machine === null ? null : self::machine($machine, $unit); + $containers->set($spec->id, $spec); + } + return $containers; + } + + /** `None if raw.get(key) is None else to_ticks(...)`. @param mixed $raw @param array $table @return int|string|null */ + private static function measured($raw, string $key, string $unit, array $table) + { + $value = Json::get($raw, $key); + return $value === null ? null : Units::toTicks($value, $unit, $table); + } + + /** `frozenset(value)` of a request's tag list; the contract's tags are strings. @param mixed $value @return array */ + private static function tagSet($value, string $what): array + { + $tags = []; + foreach (Json::items($value, $what) as $tag) { + $tags[Json::text($tag, $what)] = true; + } + return $tags; + } + + /** @param mixed $raw @return list|null */ + private static function hull($raw, string $unit): ?array + { + $declared = Json::get($raw, 'hull_vertices'); + if ($declared === null) { + return null; + } + $vertices = []; + foreach (Json::items($declared, 'hull_vertices') as $vertex) { + $vertices[] = [ + Units::toTicks(Json::at($vertex, 'x'), $unit, Units::LENGTH), + Units::toTicks(Json::at($vertex, 'y'), $unit, Units::LENGTH), + Units::toTicks(Json::at($vertex, 'z'), $unit, Units::LENGTH), + ]; + } + return $vertices; + } + + /** @param mixed $raw @return list */ + private static function accessDirections($raw): array + { + $declared = Json::items(Json::get($raw, 'access_directions', []), 'access_directions'); + foreach ($declared as $direction) { + Json::hashKey($direction); + } + return \array_values(\array_filter(self::EXIT_DIRECTIONS, static function (string $direction) use ($declared): bool { + foreach ($declared as $named) { + if (Json::isText($named, $direction)) { + return true; + } + } + return false; + })); + } + + /** @param mixed $raw @return list */ + private static function obstacles($raw, string $unit): array + { + $boxes = []; + foreach (Json::items(Json::get($raw, 'obstacles', []), 'obstacles') as $obstacle) { + $additional = Json::items(Json::get($obstacle, 'additional_boxes', []), 'additional_boxes'); + foreach (\array_merge([$obstacle], $additional) as $component) { + $origin = Json::get($component, 'origin', []); + [$length, $width, $height] = Units::dimensions(Json::at($component, 'dimensions'), $unit); + $boxes[] = new Cuboid( + Units::toTicks(Json::get($origin, 'x', 0), $unit, Units::LENGTH), + Units::toTicks(Json::get($origin, 'y', 0), $unit, Units::LENGTH), + Units::toTicks(Json::get($origin, 'z', 0), $unit, Units::LENGTH), + $length, + $width, + $height + ); + } + } + return $boxes; + } + + /** `{str(tag): int(limit)}`, sorted by tag as the reference iterates it. @param mixed $raw @return list */ + private static function tagLimits($raw): array + { + $declared = Json::get($raw, 'tag_limits', []); + if (!Json::isDict($declared)) { + throw MalformedResult::shape('tag_limits must be an object'); + } + $limits = []; + foreach ($declared as $tag => $limit) { + $limits[] = [(string)$tag, Json::pyInt($limit, 'tag_limits')]; + } + \usort($limits, static function (array $a, array $b): int { return \strcmp($a[0], $b[0]); }); + return $limits; + } + + /** @param mixed $raw @return list|null */ + private static function axles($raw, string $unit): ?array + { + $declared = Json::get($raw, 'axles'); + if ($declared === null) { + return null; + } + $axles = []; + foreach (Json::items($declared, 'axles') as $axle) { + $axles[] = [ + Units::toTicks(Json::at($axle, 'position'), $unit, Units::LENGTH), + self::measured($axle, 'max_load', 'g', Units::WEIGHT), + ]; + } + return $axles; + } + + /** @param mixed $raw */ + private static function machine($raw, string $unit): MachineSpec + { + $sides = static function (string $name) use ($raw, $unit): array { + $value = Json::get($raw, $name); + return $value === null ? [0, 0, 0] : Units::dimensions($value, $unit); + }; + $machine = new MachineSpec(); + $machine->minimum = $sides('minimum'); + $machine->increment = $sides('increment'); + $price = Json::get($raw, 'cost_per_square_metre_minor'); + $machine->pricePerSquareMetreMinor = Json::truthy($price) ? Json::int($price, 'cost_per_square_metre_minor') : 0; + $tare = Json::get($raw, 'tare_per_square_metre'); + $machine->tarePerSquareMetre = $tare === null ? 0 : Units::toTicks($tare, 'g', Units::WEIGHT); + $machine->allowance = $sides('outer_allowance'); + return $machine; + } +} diff --git a/src/Support/ResultValidation/Stacking.php b/src/Support/ResultValidation/Stacking.php new file mode 100644 index 0000000..ef43d03 --- /dev/null +++ b/src/Support/ResultValidation/Stacking.php @@ -0,0 +1,455 @@ + $entries + * @return array{0:list>,1:list>} supporters and the items directly above each + */ + public static function supportGraph(array $entries): array + { + $byTop = []; + foreach ($entries as $index => $entry) { + $byTop[(string)$entry->envelope->z2][] = $index; + } + $supporters = \array_fill(0, \count($entries), []); + foreach ($entries as $upper => $entry) { + foreach ($byTop[(string)$entry->envelope->z] ?? [] as $lower) { + if ($lower === $upper) { + continue; + } + $area = $entries[$lower]->envelope->overlapAreaXy($entry->envelope); + if (Exact::sign($area) > 0) { + $supporters[$upper][] = [$lower, $area]; + } + } + } + + $groupKeys = []; + $groups = []; + foreach ($entries as $index => $entry) { + if ($entry->spec === null || $entry->spec->nestingHeight === null) { + continue; + } + $envelope = $entry->envelope; + $key = Json::hashKey(Json::at($entry->placement, 'item_type')) . "\0" . \implode(',', [ + $envelope->x, $envelope->y, $envelope->x2, $envelope->y2, $entry->spec->nestingHeight, + ]); + $groupKeys[$index] = $key; + $groups[$key][] = $index; + } + $predecessors = []; + foreach ($groups as $group) { + \usort($group, static function (int $a, int $b) use ($entries): int { + return Exact::compare($entries[$a]->envelope->z, $entries[$b]->envelope->z) ?: $a <=> $b; + }); + for ($position = 0; $position + 1 < \count($group); ++$position) { + [$lower, $upper] = [$group[$position], $group[$position + 1]]; + $nesting = $entries[$lower]->spec->nestingHeight; + if (Exact::compare(Exact::sub($entries[$lower]->envelope->z2, $entries[$upper]->envelope->z), $nesting) === 0) { + $predecessors[$upper] = $lower; + } + } + } + foreach ($predecessors as $upper => $lower) { + $key = $groupKeys[$upper]; + $edges = \array_values(\array_filter($supporters[$upper], static function (array $edge) use ($groupKeys, $key): bool { + return ($groupKeys[$edge[0]] ?? null) !== $key; + })); + $position = \count($edges); + foreach ($edges as $at => $edge) { + if ($edge[0] > $lower) { + $position = $at; + break; + } + } + \array_splice($edges, $position, 0, [[$lower, $entries[$upper]->envelope->baseArea]]); + $supporters[$upper] = $edges; + } + + $directAbove = \array_fill(0, \count($entries), []); + foreach ($supporters as $upper => $edges) { + foreach ($edges as [$lower]) { + $directAbove[$lower][$upper] = true; + } + } + return [$supporters, $directAbove]; + } + + /** + * @param list $entries @param list> $supporters + * @param list> $directAbove @param list $issues + */ + public static function checkSupportAndLoad(array $entries, array $supporters, array $directAbove, Ratio $globalSupport, array &$issues): void + { + foreach ($entries as $index => $entry) { + $spec = $entry->spec; + if ($spec === null || Exact::sign($entry->envelope->z) === 0) { + continue; + } + $itemId = PyFormat::str($entry->id); + $supporting = $supporters[$index]; + $required = $globalSupport->compare($spec->minimumSupportRatio) < 0 ? $spec->minimumSupportRatio : $globalSupport; + self::checkGroundContact($itemId, $entry->envelope, $supporting, $entries, $spec->groundContactRule, $issues); + if ($required->compareInt(0) > 0) { + $area = Exact::sum(\array_map(static function (array $edge) { return $edge[1]; }, $supporting)); + if (Exact::compare($area, self::requiredSupportArea($entry->envelope->baseArea, ContainerCheck::ratioPpm($required))) < 0) { + $ratio = Ratio::of($area, $entry->envelope->baseArea); + $issues[] = new ResultIssue('insufficient_support', "{$itemId}: " . PyFormat::fixed6($ratio->toFloat()) . ' < ' . PyFormat::fixed6($required->toFloat())); + } + } + foreach ($supporting as [$lower]) { + $lowerSpec = $entries[$lower]->spec; + if ($lowerSpec === null) { + continue; + } + $lowerId = PyFormat::str($entries[$lower]->id); + if (!$lowerSpec->stackable) { + $issues[] = new ResultIssue('non_stackable', "{$itemId} rests on {$lowerId}"); + } elseif ($lowerSpec->acceptsStackingGroups !== [] && !Accounting::holds($lowerSpec->acceptsStackingGroups, $spec->stackingGroup)) { + $issues[] = new ResultIssue('stacking_group_incompatible', "{$itemId} rests on {$lowerId}"); + } + if ($lowerSpec->maxTopLoad !== null && Exact::compare($spec->weight, $lowerSpec->maxTopLoad) > 0) { + $issues[] = new ResultIssue('top_load_exceeded', "{$itemId} ({$spec->weight} ticks) on {$lowerId} (limit {$lowerSpec->maxTopLoad})"); + } + } + } + foreach ($entries as $index => $entry) { + if ($entry->spec === null || $entry->spec->maxStackedItems === null) { + continue; + } + $descendants = []; + $pending = \array_keys($directAbove[$index]); + while ($pending !== []) { + $above = \array_pop($pending); + if (isset($descendants[$above])) { + continue; + } + $descendants[$above] = true; + foreach (\array_keys($directAbove[$above]) as $next) { + $pending[] = $next; + } + } + if (\count($descendants) > $entry->spec->maxStackedItems) { + $issues[] = new ResultIssue('max_stacked_items_exceeded', PyFormat::str($entry->id) . ': ' . \count($descendants) . " above > limit {$entry->spec->maxStackedItems}"); + } + } + } + + /** Exact `floor(baseArea * ppm / 10^6)`, the least supported area the ratio allows. @param int|string $baseArea @return int|string */ + private static function requiredSupportArea($baseArea, int $ppm) + { + return Exact::floorDiv(Exact::mul($baseArea, $ppm), ContainerCheck::SCORE_SCALE); + } + + /** @param list $supporting @param list $entries @param mixed $rule @param list $issues */ + private static function checkGroundContact(string $itemId, Cuboid $envelope, array $supporting, array $entries, $rule, array &$issues): void + { + if ($rule === null || Json::isText($rule, 'free')) { + return; + } + if (Json::isText($rule, 'covered')) { + $corners = [[$envelope->x, $envelope->y], [$envelope->x2, $envelope->y], [$envelope->x, $envelope->y2], [$envelope->x2, $envelope->y2]]; + foreach ($corners as [$x, $y]) { + $covered = false; + foreach ($supporting as [$lower]) { + $surface = $entries[$lower]->envelope; + if (Exact::compare($surface->x, $x) <= 0 && Exact::compare($x, $surface->x2) <= 0 + && Exact::compare($surface->y, $y) <= 0 && Exact::compare($y, $surface->y2) <= 0) { + $covered = true; + break; + } + } + if (!$covered) { + $issues[] = new ResultIssue('ground_contact_violation', "{$itemId}: covered requires all four base corners"); + return; + } + } + } elseif (Json::isText($rule, 'single') && \count($supporting) !== 1) { + $issues[] = new ResultIssue('ground_contact_violation', "{$itemId}: single has " . \count($supporting) . ' supporters'); + } elseif (Json::isText($rule, 'multiple') && \count($supporting) < 2) { + $issues[] = new ResultIssue('ground_contact_violation', "{$itemId}: multiple has " . \count($supporting) . ' supporters'); + } + } + + /** + * Cumulative weight each item bears from everything resting on it, split across supporters by + * contact area and conserved exactly (the remainder goes to the last supporter), top-down. + * + * @param list $entries @param list> $supporters + * @return list + */ + public static function propagateLoad(array $entries, array $supporters): array + { + $order = \array_keys($entries); + \usort($order, static function (int $a, int $b) use ($entries): int { + $left = $entries[$a]->envelope; + $right = $entries[$b]->envelope; + return Exact::compare($right->z2, $left->z2) ?: (Exact::compare($right->z, $left->z) ?: Json::compare($entries[$a]->id, $entries[$b]->id)); + }); + $loads = \array_fill(0, \count($entries), 0); + foreach ($order as $upper) { + $spec = $entries[$upper]->spec; + if ($spec === null) { + continue; + } + $supports = $supporters[$upper]; + $totalArea = Exact::sum(\array_map(static function (array $edge) { return $edge[1]; }, $supports)); + if (Exact::sign($totalArea) === 0) { + continue; + } + $downward = Exact::add($spec->weight, $loads[$upper]); + $assigned = 0; + foreach ($supports as $position => [$lower, $area]) { + $share = $position === \count($supports) - 1 + ? Exact::sub($downward, $assigned) + : Exact::floorDiv(Exact::mul($downward, $area), $totalArea); + $assigned = Exact::add($assigned, $share); + $loads[$lower] = Exact::add($loads[$lower], $share); + } + } + return $loads; + } + + /** + * The pressure a footprint carries, in kPa, exactly: + * `load * g * (ticks per metre)^2 / (ticks per kg * g denominator * Pa per kPa * area)`. + * + * @param int|string $load @param int|string $baseArea + */ + private static function pressure($load, $baseArea): Ratio + { + return Ratio::of( + Exact::mul($load, Exact::mul(980665, self::SQUARE_METRE_TICKS)), + Exact::mul(Exact::mul(Units::TICKS_PER_KG, 100000000), $baseArea) + ); + } + + /**: no `compressible` item may carry more pressure than it declared. @param list $entries @param list $loads @param list $issues */ + public static function checkCrush(Label $packedId, array $entries, array $loads, array &$issues): void + { + foreach ($entries as $index => $entry) { + $limit = $entry->spec === null ? null : $entry->spec->maxCompressionPressureKpa; + if ($limit === null) { + continue; + } + $pressure = self::pressure($loads[$index], $entry->envelope->baseArea); + if ($pressure->compareInt($limit) > 0) { + $issues[] = new ResultIssue('crush_violation', PyFormat::str($entry->id) . " in {$packedId}: " . PyFormat::fixed6($pressure->toFloat()) . " kPa exceeds {$limit} kPa"); + } + } + } + + /** + * Occupied height under load, rounded up, never below one tick. A crushed item keeps its + * height: `checkCrush` already reports it. + * + * @param int|string $load @return int|string + */ + public static function compressedHeight(Cuboid $envelope, ItemSpec $spec, $load) + { + $limit = $spec->maxCompressionPressureKpa; + if ($limit === null) { + return $envelope->height; + } + if ($spec->compressionRatioPpm === null) { + // The reference asserts the pair: a pressure limit without a ratio is not a request it reads. + throw MalformedResult::shape("{$spec->id}: max_compression_pressure_kpa without compression_ratio"); + } + $pressure = self::pressure($load, $envelope->baseArea); + if ($pressure->compareInt($limit) > 0 || $limit === 0) { + return $envelope->height; + } + $divisor = Exact::mul(Exact::mul($limit, 1000000), $pressure->denominator); + $retained = Exact::sub($divisor, Exact::mul($spec->compressionRatioPpm, $pressure->numerator)); + return Exact::max(1, Exact::ceilDiv(Exact::mul($envelope->height, $retained), $divisor)); + } + + /**: weight per square metre of an item's own base, at every level of the stack. @param list $entries @param list $loads @param int|string $maxDensity @param list $issues */ + public static function checkStackDensity(Label $packedId, array $entries, array $loads, $maxDensity, array &$issues): void + { + foreach ($entries as $index => $entry) { + if ($entry->spec === null) { + continue; + } + $total = Exact::add($entry->spec->weight, $loads[$index]); + if (Exact::compare(Exact::mul($total, self::SQUARE_METRE_TICKS), Exact::mul($maxDensity, $entry->envelope->baseArea)) > 0) { + $issues[] = new ResultIssue('stack_density_exceeded', PyFormat::str($entry->id) . " in {$packedId}: {$total} ticks over {$entry->envelope->baseArea} ticks^2 exceeds {$maxDensity} ticks/m^2"); + } + } + } + + /** + * Items due at an earlier stop must all be removable -- unblocked from + * above and slidable out a door (all six walls when the container names none) -- before the + * route moves on. + * + * @param list $entries @param list> $directAbove + * @param array $container @param list $doors @param list $issues + */ + public static function checkRouteRemovalOrder(Label $packedId, array $entries, array $directAbove, array $container, array $doors, array &$issues): void + { + $stops = []; + foreach ($entries as $index => $entry) { + if ($entry->spec !== null && $entry->spec->stopIndex !== null) { + $stops[$index] = $entry->spec->stopIndex; + } + } + if ($stops === []) { + return; + } + $directions = $doors === [] ? Spec::EXIT_DIRECTIONS : $doors; + $present = \array_fill_keys(\array_keys($entries), true); + $distinct = \array_values(\array_unique($stops)); + \sort($distinct); + foreach ($distinct as $stop) { + $due = []; + foreach ($stops as $index => $value) { + if ($value === $stop && isset($present[$index])) { + $due[$index] = true; + } + } + while ($due !== []) { + $chosen = null; + foreach (\array_keys($due) as $item) { + if (\array_intersect_key($directAbove[$item], $present) !== []) { + continue; + } + if (self::hasClearExit($item, $entries, $present, $container, $directions) + && ($chosen === null || Json::compare($entries[$item]->id, $entries[$chosen]->id) < 0)) { + $chosen = $item; + } + } + if ($chosen === null) { + $names = \array_map(static function (int $index) use ($entries) { return $entries[$index]->id; }, \array_keys($due)); + Json::sort($names); + $listed = PyFormat::listOf(\array_map([PyFormat::class, 'repr'], $names)); + $issues[] = new ResultIssue('unloading_order_violation', "{$packedId}: stop {$stop} cannot fully unload {$listed} before the route moves on"); + return; + } + unset($present[$chosen], $due[$chosen]); + } + } + } + + /** @param list $entries @param array $present @param array $container @param list $directions */ + private static function hasClearExit(int $item, array $entries, array $present, array $container, array $directions): bool + { + foreach ($directions as $direction) { + $region = self::sweptRegion($entries[$item]->envelope, $container, $direction); + $blocked = false; + foreach (\array_keys($present) as $other) { + if ($other !== $item && $region->intersects($entries[$other]->envelope)) { + $blocked = true; + break; + } + } + if (!$blocked) { + return true; + } + } + return false; + } + + /** @param array $container */ + private static function sweptRegion(Cuboid $envelope, array $container, string $direction): Cuboid + { + [$x1, $y1, $z1, $x2, $y2, $z2] = [$envelope->x, $envelope->y, $envelope->z, $envelope->x2, $envelope->y2, $envelope->z2]; + if ($direction === '+x') { + [$x1, $x2] = [$x2, $container[0]]; + } elseif ($direction === '-x') { + [$x1, $x2] = [0, $x1]; + } elseif ($direction === '+y') { + [$y1, $y2] = [$y2, $container[1]]; + } elseif ($direction === '-y') { + [$y1, $y2] = [0, $y1]; + } elseif ($direction === '+z') { + [$z1, $z2] = [$z2, $container[2]]; + } else { + [$z1, $z2] = [0, $z1]; + } + return new Cuboid($x1, $y1, $z1, Exact::sub($x2, $x1), Exact::sub($y2, $y1), Exact::sub($z2, $z1)); + } + + /** Whether two stacked instances form a valid nested column. */ + public static function validNesting(Entry $left, Entry $right): bool + { + if ($left->spec === null || $right->spec === null || $left->spec->nestingHeight === null) { + return false; + } + $nesting = $left->spec->nestingHeight; + if ($left->spec->id !== $right->spec->id + || !Json::equals(Json::at($left->placement, 'item_type'), Json::at($right->placement, 'item_type')) + || $right->spec->nestingHeight === null || Exact::compare($right->spec->nestingHeight, $nesting) !== 0) { + return false; + } + $a = $left->envelope; + $b = $right->envelope; + foreach (['x', 'y', 'x2', 'y2'] as $edge) { + if (Exact::compare($a->{$edge}, $b->{$edge}) !== 0) { + return false; + } + } + [$lower, $upper] = Exact::compare($a->z, $b->z) <= 0 ? [$a, $b] : [$b, $a]; + return Exact::compare($lower->z, $upper->z) !== 0 && Exact::compare(Exact::sub($lower->z2, $upper->z), $nesting) === 0; + } + + /** Space a placement actually takes: its compressed box, its hull, or its box. @param mixed $placement @param int|string $load @return int|string */ + public static function occupiedVolume(Cuboid $envelope, $placement, ?ItemSpec $spec, $load) + { + if ($spec !== null && $spec->maxCompressionPressureKpa !== null) { + return Exact::mul($envelope->baseArea, self::compressedHeight($envelope, $spec, $load)); + } + if ($spec !== null && $spec->isConvexHull() && $spec->hullVertices !== null) { + return Geometry::hullVolume(Geometry::rotateHull($spec->hullVertices, Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')))); + } + $solid = self::placedHull($envelope, $placement, $spec); + if ($solid === $envelope->vertices()) { + $dimensions = Json::at($placement, 'dimensions'); + $side = static function (string $name) use ($dimensions): int { + return Json::int(Json::at(Json::at($dimensions, $name), 'ticks'), 'a placement dimension'); + }; + return Exact::mul(Exact::mul($side('length'), $side('width')), $side('height')); + } + return Geometry::hullVolume($solid); + } + + /** + * The solid a placement occupies, as vertices in container coordinates: the exact hull when the + * request allows it and the reported box matches, otherwise the envelope's corners. + * + * @param mixed $placement @return list + */ + public static function placedHull(Cuboid $envelope, $placement, ?ItemSpec $spec): array + { + if ($spec === null || $spec->hullVertices === null || !$spec->isConvexHull() || $spec->stopIndex !== null) { + return $envelope->vertices(); + } + $axes = Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')); + $rotated = [$spec->dimensions[$axes[0]], $spec->dimensions[$axes[1]], $spec->dimensions[$axes[2]]]; + if (Exact::compare($envelope->length, $rotated[0]) !== 0 || Exact::compare($envelope->width, $rotated[1]) !== 0 + || Exact::compare($envelope->height, $rotated[2]) !== 0) { + return $envelope->vertices(); + } + return \array_map(static function (array $vertex) use ($envelope): array { + return [Exact::add($envelope->x, $vertex[0]), Exact::add($envelope->y, $vertex[1]), Exact::add($envelope->z, $vertex[2])]; + }, Geometry::rotateHull($spec->hullVertices, $axes)); + } +} diff --git a/src/Support/ResultValidation/Units.php b/src/Support/ResultValidation/Units.php new file mode 100644 index 0000000..84774c7 --- /dev/null +++ b/src/Support/ResultValidation/Units.php @@ -0,0 +1,197 @@ + 16000, 'cm' => 160000, 'm' => 16000000, 'in' => 406400, 'inch' => 406400, + 'inches' => 406400, 'ft' => 4876800, 'tick' => 1, 'ticks' => 1, + ]; + + /** Weight ticks per unit. One tick is 1/8 microgram. */ + public const WEIGHT = [ + 'mg' => 8000, 'g' => 8000000, 'kg' => 8000000000, 'oz' => 226796185, + 'lb' => 3628738960, 'lbs' => 3628738960, 'tick' => 1, 'ticks' => 1, + ]; + + public const TICKS_PER_MM = 16000; + public const TICKS_PER_GRAM = 8000000; + public const TICKS_PER_KG = 8000000000; + + /** `table[unit]`, an exact key. @param array $table */ + public static function perUnit(array $table, string $unit): int + { + if (!\array_key_exists($unit, $table)) { + throw MalformedResult::shape(\sprintf('unknown unit "%s"', $unit)); + } + return $table[$unit]; + } + + /** + * A measure (a number, a string with an optional unit suffix, or `{value, unit}`) to exact + * ticks, rounding halves to even. + * + * @param mixed $measure @param array $table @return int|string + */ + public static function toTicks($measure, string $defaultUnit, array $table) + { + $unit = $defaultUnit; + $raw = $measure; + if (Json::isDict($measure) && $measure !== []) { + $raw = Json::at($measure, 'value'); + if (\array_key_exists('unit', $measure)) { + $unit = Json::text($measure['unit'], "a measure's unit"); + } + } elseif (\is_string($measure)) { + $suffixed = self::unitSuffix(self::strip($measure), $table); + if ($suffixed !== null) { + [$raw, $unit] = $suffixed; + } + } + $scaled = self::parseRational($raw)->mulInt(self::perUnit($table, \strtolower($unit))); + return self::roundHalfEven($scaled); + } + + /** + * The longest unit suffix the text ends with, case-insensitively, that leaves a non-empty + * number before it; ties in length go to the table's earlier entry, as Python's stable sort + * over the table does. + * + * @param array $table @return array{0:string,1:string}|null + */ + private static function unitSuffix(string $stripped, array $table): ?array + { + $suffixes = \array_keys($table); + $order = \array_flip($suffixes); + \usort($suffixes, static function (string $a, string $b) use ($order): int { + return [\strlen($b), $order[$a]] <=> [\strlen($a), $order[$b]]; + }); + $lowered = \strtolower($stripped); + foreach ($suffixes as $suffix) { + $length = \strlen($suffix); + if (\strlen($lowered) < $length || \substr($lowered, -$length) !== $suffix) { + continue; + } + $number = self::strip(\substr($stripped, 0, -$length)); + if ($number !== '') { + return [$number, $suffix]; + } + } + return null; + } + + /** @return int|string */ + private static function roundHalfEven(Ratio $scaled) + { + $floor = $scaled->floor(); + $remainder = Ratio::of(Exact::sub($scaled->numerator, Exact::mul($floor, $scaled->denominator)), $scaled->denominator); + $order = $remainder->compare(Ratio::of(1, 2)); + if ($order > 0) { + return Exact::add($floor, 1); + } + if ($order < 0) { + return $floor; + } + return Exact::mod($floor, 2) === 0 ? $floor : Exact::add($floor, 1); + } + + /** + * `parse_rational`: an integer exactly, anything else through its `str()` as a fraction, a + * mixed fraction (`12 3/8`) when the text holds a space. + * + * @param mixed $value + */ + public static function parseRational($value): Ratio + { + $integer = Json::intInstance($value); + if ($integer !== null) { + return Ratio::integer($integer); + } + $stripped = self::strip(PyFormat::str($value)); + if (\strpos($stripped, ' ') === false) { + return self::parseFraction($stripped); + } + $parts = \preg_split('/[\s\p{Z}]+/u', $stripped, 2); + $fraction = self::parseFraction($parts[1] ?? ''); + if (\strncmp($parts[0], '-', 1) === 0) { + $fraction = $fraction->negate(); + } + return self::parseFraction($parts[0])->add($fraction); + } + + /** `Fraction(str(value))`, the reference's reading of a ratio field. @param mixed $value */ + public static function ratioOf($value): Ratio + { + return self::parseFraction(PyFormat::str($value)); + } + + /** + * `Fraction(text)` by the grammar of CPython 3.11's `fractions._RATIONAL_FORMAT`: optional + * whitespace and sign, then `n/d`, or a decimal with an optional exponent; digit groups may + * be split by single underscores. Only ASCII digits are read. + */ + public static function parseFraction(string $text): Ratio + { + $digits = '\d+(?:_\d+)*'; + $pattern = "/^[\\s\\p{Z}]*([-+]?)(?=\\d|\\.\\d)({$digits})?(?:\\/({$digits})|(?:\\.({$digits})?)?(?:[eE]([-+]?{$digits}))?)[\\s\\p{Z}]*$/u"; + if (\preg_match($pattern, $text, $parts) !== 1) { + throw MalformedResult::shape(\sprintf('Invalid literal for Fraction: %s', PyFormat::stringRepr($text))); + } + $clean = static function (string $group) { + return Exact::normalize(\ltrim(\str_replace('_', '', $group), '0') ?: '0'); + }; + $numerator = $clean($parts[2] ?? ''); + $denominator = 1; + if (($parts[3] ?? '') !== '') { + $denominator = $clean($parts[3]); + } else { + $decimals = \str_replace('_', '', $parts[4] ?? ''); + if ($decimals !== '') { + $scale = Exact::normalize('1' . \str_repeat('0', \strlen($decimals))); + $numerator = Exact::add(Exact::mul($numerator, $scale), $clean($decimals)); + $denominator = $scale; + } + $exponent = $parts[5] ?? ''; + if ($exponent !== '') { + $power = (int)\str_replace(['_', '+'], '', $exponent); + if (\abs($power) > 400) { + throw MalformedResult::shape('arithmetic overflow: an exponent beyond what this validator computes'); + } + $factor = Exact::normalize('1' . \str_repeat('0', \abs($power))); + if ($power < 0) { + $denominator = Exact::mul($denominator, $factor); + } else { + $numerator = Exact::mul($numerator, $factor); + } + } + } + if ($parts[1] === '-') { + $numerator = Exact::negate($numerator); + } + return Ratio::of($numerator, $denominator); + } + + /** Python's `str.strip()`: Unicode whitespace from both ends. */ + public static function strip(string $text): string + { + return \preg_replace('/^[\s\p{Z}]+|[\s\p{Z}]+$/u', '', $text) ?? $text; + } + + /** @param mixed $value @return array{0:int|string,1:int|string,2:int|string} */ + public static function dimensions($value, string $unit): array + { + return [ + self::toTicks(Json::at($value, 'length'), $unit, self::LENGTH), + self::toTicks(Json::at($value, 'width'), $unit, self::LENGTH), + self::toTicks(Json::at($value, 'height'), $unit, self::LENGTH), + ]; + } +} diff --git a/src/Support/ResultValidation/Validator.php b/src/Support/ResultValidation/Validator.php new file mode 100644 index 0000000..8195a80 --- /dev/null +++ b/src/Support/ResultValidation/Validator.php @@ -0,0 +1,123 @@ + */ + public static function validate($request, $result): array + { + foreach (self::REQUIRED_KEYS as $key) { + if (!Json::has($result, $key)) { + throw MalformedResult::contract('result is missing ' . PyFormat::stringRepr($key)); + } + } + $unit = Json::text(Json::get(Json::get($request, 'units', []), 'length', 'mm'), 'units.length'); + $configuration = Json::get($request, 'configuration', []); + $clearance = Units::toTicks(Json::get($configuration, 'clearance', 0), $unit, Units::LENGTH); + $globalSupport = Units::ratioOf(Json::get($configuration, 'minimum_support_ratio', 0)); + $items = Spec::items($request, $unit); + $containers = Spec::containers($request, $unit); + + $issues = []; + $validated = Lattice::materialize($request, $result, $items, $containers, $clearance, $issues); + Accounting::checkStructure($validated, $issues); + Facts::checkAlgorithmMetrics($validated, $issues); + Facts::checkEffortBudget($request, $validated, $issues); + Facts::checkResultFacts($validated, $issues); + $context = new Context($items, $containers, $clearance, Accounting::containerTagRules($request)); + Accounting::checkAccounting($validated, $context, $issues); + self::checkInfeasibleProof($validated, $issues); + + $fabricated = self::checkContainers($validated, $result, $context, $globalSupport, $issues); + self::checkContainerCounts($validated, $configuration, $containers, $issues); + + ObjectiveCheck::checkFixedPlacements($request, $validated, $unit, $issues); + ObjectiveCheck::checkGroups($request, $validated, $issues); + ObjectiveCheck::checkSolverSelection($request, $validated, $issues); + ObjectiveCheck::check($request, $validated, $context, $fabricated, $issues); + return $issues; + } + + /** @param mixed $result @param list $issues */ + private static function checkInfeasibleProof($result, array &$issues): void + { + if (!Json::isText(Json::at($result, 'status'), 'infeasible')) { + return; + } + foreach (Json::items(Json::at($result, 'unpacked_items'), 'result.unpacked_items') as $unpacked) { + if (!Json::isText(Json::get(Json::get($unpacked, 'proof', []), 'level'), 'proven')) { + $issues[] = new ResultIssue('unproven_infeasible', 'infeasible status requires a proven rejection for every unpacked item'); + return; + } + } + } + + /** + * Each packed container against its type, recomputing a made-to-measure box first; returns + * those recomputed boxes by container id, for the objective. + * + * @param mixed $validated @param mixed $reported @param list $issues @return Ordered + */ + private static function checkContainers($validated, $reported, Context $context, Ratio $globalSupport, array &$issues): Ordered + { + $fabricated = new Ordered(); + $originals = Json::items(Json::at($reported, 'containers'), 'result.containers'); + foreach (Json::items(Json::at($validated, 'containers'), 'result.containers') as $index => $packed) { + if (!\array_key_exists($index, $originals)) { + break; + } + $containerType = Json::at($packed, 'container_type'); + $spec = $context->containers->get($containerType); + if ($spec === null) { + $issues[] = new ResultIssue('unknown_container_type', PyFormat::str($containerType)); + continue; + } + $spec = ContainerCheck::checkMadeToMeasure($packed, Json::has($originals[$index], 'lattice_summary'), $spec, $context->items, $context->clearance, $issues); + if ($spec->madeToMeasure !== null) { + $fabricated->set(Json::at($packed, 'id'), $spec); + } + ContainerCheck::check($packed, $spec, $context->items, $context->clearance, $globalSupport, $issues); + ContainerCheck::checkAchievedExtent($packed, $spec, $context->clearance, $issues); + } + return $fabricated; + } + + /** @param mixed $validated @param mixed $configuration @param Ordered $containers @param list $issues */ + private static function checkContainerCounts($validated, $configuration, Ordered $containers, array &$issues): void + { + $opened = Json::items(Json::at($validated, 'containers'), 'result.containers'); + $inventory = new Ordered(); + foreach ($opened as $packed) { + $containerType = Json::at($packed, 'container_type'); + if ($containers->has($containerType)) { + $inventory->set($containerType, $inventory->get($containerType, 0) + 1); + } + } + foreach ($inventory->entries() as [$containerType, $count]) { + $quantity = $containers->get($containerType)->quantity; + if ($quantity !== null && $count > $quantity) { + $issues[] = new ResultIssue('container_inventory_exceeded', PyFormat::str($containerType) . ": used {$count}, available {$quantity}"); + } + } + $limit = Json::optionalInt(Json::get($configuration, 'max_containers'), 'max_containers'); + if ($limit !== null && \count($opened) > $limit) { + $issues[] = new ResultIssue('max_containers_exceeded', \count($opened) . " containers opened, limit {$limit}"); + } + } +} diff --git a/src/Unit/Length.php b/src/Unit/Length.php index 61c152a..5b83df0 100644 --- a/src/Unit/Length.php +++ b/src/Unit/Length.php @@ -2,13 +2,14 @@ declare(strict_types=1); namespace Packvium\Unit; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Support\RationalParser; final readonly class Length { public const TICKS_PER_MM=16000; public const TICKS_PER_INCH=406400; public function __construct(public int $ticks){if($ticks<0)throw new InvalidArgumentException('Length cannot be negative');} public static function of(int|string $value,string $unit='mm',Rounding $rounding=Rounding::Nearest):self - { return new self(RationalParser::scaled($value,self::multiplier($unit),$rounding)); } + { return self::read(RationalParser::scaled($value,self::multiplier($unit),$rounding)); } public static function mm(int|string $value,Rounding $rounding=Rounding::Nearest):self{return self::of($value,'mm',$rounding);} public static function inches(int|string $value,Rounding $rounding=Rounding::Nearest):self{return self::of($value,'in',$rounding);} public static function parse(self|int|string|array $value,string $defaultUnit='mm',Rounding $rounding=Rounding::Nearest):self @@ -23,5 +24,7 @@ public function decimal(string $unit='mm',int $places=8):string { return RationalParser::decimalString($this->ticks,self::multiplier($unit),$places); } /** @return array{ticks:int,value:string,unit:string} */ public function toArray(string $unit='mm'):array{return ['ticks'=>$this->ticks,'value'=>$this->decimal($unit),'unit'=>$unit];} - public static function multiplier(string $unit):int{return match(strtolower(trim($unit))){'tick','ticks'=>1,'mm','millimeter','millimeters'=>self::TICKS_PER_MM,'cm'=>self::TICKS_PER_MM*10,'m'=>self::TICKS_PER_MM*1000,'in','inch','inches'=>self::TICKS_PER_INCH,'ft'=>self::TICKS_PER_INCH*12,default=>throw new InvalidArgumentException("Unsupported length unit: {$unit}")};} + public static function multiplier(string $unit):int{return match(strtolower(trim($unit))){'tick','ticks'=>1,'mm','millimeter','millimeters'=>self::TICKS_PER_MM,'cm'=>self::TICKS_PER_MM*10,'m'=>self::TICKS_PER_MM*1000,'in','inch','inches'=>self::TICKS_PER_INCH,'ft'=>self::TICKS_PER_INCH*12,default=>throw new ObjectRefusal('invalid_unit',"Unsupported length unit: {$unit}")};} + /** A length read from the caller's input; the constructor still guards the arithmetic, where a negative is a defect, not a caller's mistake. */ + private static function read(int $ticks):self{if($ticks<0)throw new ObjectRefusal('negative_measure','Length cannot be negative');return new self($ticks);} } diff --git a/src/Unit/Weight.php b/src/Unit/Weight.php index 491e29b..822ac4c 100644 --- a/src/Unit/Weight.php +++ b/src/Unit/Weight.php @@ -2,17 +2,20 @@ declare(strict_types=1); namespace Packvium\Unit; use InvalidArgumentException; +use Packvium\Support\ObjectRefusal; use Packvium\Support\RationalParser; final readonly class Weight { public const TICKS_PER_MG=8000; public const TICKS_PER_G=8000000; public const TICKS_PER_KG=8000000000; public const TICKS_PER_OZ=226796185; public const TICKS_PER_LB=3628738960; public function __construct(public int $ticks){if($ticks<0)throw new InvalidArgumentException('Weight cannot be negative');} - public static function of(int|string $value,string $unit='g',Rounding $rounding=Rounding::Nearest):self{return new self(RationalParser::scaled($value,self::multiplier($unit),$rounding));} + public static function of(int|string $value,string $unit='g',Rounding $rounding=Rounding::Nearest):self{return self::read(RationalParser::scaled($value,self::multiplier($unit),$rounding));} public static function parse(self|int|string|array $value,string $defaultUnit='g',Rounding $rounding=Rounding::Nearest):self {if($value instanceof self)return $value;if(is_array($value))return self::of((string)$value['value'],(string)($value['unit']??$defaultUnit),$rounding);if(is_string($value)&&preg_match('/^(.+?)\s*(mg|kg|g|oz|lbs?|ticks?)$/i',trim($value),$m))return self::of(trim($m[1]),$m[2],$rounding);return self::of($value,$defaultUnit,$rounding);} /** Exact decimal string. Float division loses digits once ticks exceed 2^53. */ public function decimal(string $unit='g',int $places=8):string { return RationalParser::decimalString($this->ticks,self::multiplier($unit),$places); } /** @return array{ticks:int,value:string,unit:string} */ public function toArray(string $unit='g'):array{return ['ticks'=>$this->ticks,'value'=>$this->decimal($unit),'unit'=>$unit];} - public static function multiplier(string $unit):int{return match(strtolower(trim($unit))){'tick','ticks'=>1,'mg'=>self::TICKS_PER_MG,'g'=>self::TICKS_PER_G,'kg'=>self::TICKS_PER_KG,'oz'=>self::TICKS_PER_OZ,'lb','lbs'=>self::TICKS_PER_LB,default=>throw new InvalidArgumentException("Unsupported weight unit: {$unit}")};} + public static function multiplier(string $unit):int{return match(strtolower(trim($unit))){'tick','ticks'=>1,'mg'=>self::TICKS_PER_MG,'g'=>self::TICKS_PER_G,'kg'=>self::TICKS_PER_KG,'oz'=>self::TICKS_PER_OZ,'lb','lbs'=>self::TICKS_PER_LB,default=>throw new ObjectRefusal('invalid_unit',"Unsupported weight unit: {$unit}")};} + /** A weight read from the caller's input; the constructor still guards the arithmetic, where a negative is a defect, not a caller's mistake. */ + private static function read(int $ticks):self{if($ticks<0)throw new ObjectRefusal('negative_measure','Weight cannot be negative');return new self($ticks);} } diff --git a/src/Validation/MalformedResult.php b/src/Validation/MalformedResult.php new file mode 100644 index 0000000..e80948f --- /dev/null +++ b/src/Validation/MalformedResult.php @@ -0,0 +1,37 @@ +kind = $kind; + } + + public static function contract(string $message): self + { + return new self($message, self::CONTRACT); + } + + public static function shape(string $message): self + { + return new self($message, self::SHAPE); + } +} diff --git a/src/Validation/ResultIssue.php b/src/Validation/ResultIssue.php new file mode 100644 index 0000000..f1c85e8 --- /dev/null +++ b/src/Validation/ResultIssue.php @@ -0,0 +1,26 @@ +code = $code; + $this->detail = $detail; + } + + public function __toString(): string + { + return "{$this->code}: {$this->detail}"; + } +} diff --git a/src/Validation/functions.php b/src/Validation/functions.php new file mode 100644 index 0000000..d631ae7 --- /dev/null +++ b/src/Validation/functions.php @@ -0,0 +1,33 @@ + $request + * @param array $result + * @return list + * @throws MalformedResult when the result does not have the documented shape at all + */ + function validate(array $request, array $result): array + { + return Validator::validate($request, $result); + } +} diff --git a/tests/AxleLoadTest.php b/tests/AxleLoadTest.php index fdeb8f5..4de8d18 100644 --- a/tests/AxleLoadTest.php +++ b/tests/AxleLoadTest.php @@ -3,14 +3,17 @@ namespace Packvium\Tests; +use Packvium\Algorithm\CandidateFinder; use Packvium\Constraint\AxleLoad; use Packvium\Constraint\LoadUnit; use Packvium\Domain\Axle; use Packvium\Domain\AxisAlignedBox; use Packvium\Domain\Dimensions; use Packvium\Domain\Point; +use Packvium\Serialization\ArrayCodec; use Packvium\Unit\Length; use Packvium\Unit\Weight; +use ReflectionMethod; /** * Two-axle weight distribution, checked against hand-computed values. @@ -136,4 +139,36 @@ public static function testAnItemAloneIsAdmittedExactlyWhereBothAxlesHold(): voi self::assertTrue(AxleLoad::admitsAlone([new Axle(new Length(0), new Weight(400)), new Axle(new Length(100), null)], 800, 100, 0, 10)); self::assertFalse(AxleLoad::admitsAlone([new Axle(new Length(0), new Weight(399)), new Axle(new Length(100), null)], 800, 100, 0, 10)); } + public static function testAxlePointsAlreadyOfferedAreNotOfferedAgain(): void + { + // S20: an axle point equal to an ordinary point, or to an earlier axle point, is the + // same candidate scanned twice; it is dropped and every other point keeps its place. + $ordinary = [new Point(0, 0, 0), new Point(5, 0, 0), new Point(0, 5, 0)]; + $axle = [new Point(7, 0, 0), new Point(5, 0, 0), new Point(7, 5, 0), new Point(7, 0, 0), new Point(0, 5, 0)]; + $scan = (new ReflectionMethod(CandidateFinder::class, 'appendUnseen'))->invoke(null, $ordinary, $axle); + self::assertEquals([...$ordinary, new Point(7, 0, 0), new Point(7, 5, 0)], $scan); + } + + public static function testAnAxleBalancedPointSeatsTheEnvelopeUnderAClearance(): void + { + // S10: feasible centres are 300..305 mm, narrower than the 10 mm clearance, so only an + // envelope origin computed from the envelope's own length lands inside the window. + foreach (['fast', 'balanced', 'quality'] as $profile) { + $result = ArrayCodec::pack([ + 'units' => ['length' => 'mm'], + 'configuration' => ['solver_profile' => $profile, 'clearance' => '10'], + 'items' => [['id' => 'drum', 'allowed_rotations' => ['LWH'], + 'weight' => ['value' => '1000', 'unit' => 'g'], + 'dimensions' => ['length' => '200', 'width' => '100', 'height' => '100']]], + 'containers' => [['id' => 'trailer', + 'inner_dimensions' => ['length' => '1000', 'width' => '200', 'height' => '200'], + 'axles' => [['position' => '0', 'max_load' => ['value' => '700', 'unit' => 'g']], + ['position' => '1000', 'max_load' => ['value' => '305', 'unit' => 'g']]]]], + ]); + $placements = array_merge(...array_map(static fn(array $c): array => $c['placements'], $result['containers'])); + self::assertCount(1, $placements, $profile); + $x = (float)$placements[0]['position']['x']['value']; + self::assertTrue($x >= 200 && $x <= 205, "{$profile}: x {$x}"); + } + } } diff --git a/tests/ConstraintTest.php b/tests/ConstraintTest.php index 8efdb23..ff39f64 100644 --- a/tests/ConstraintTest.php +++ b/tests/ConstraintTest.php @@ -10,7 +10,7 @@ use Packvium\Constraint\ContainerEligibilityConstraint; use Packvium\Constraint\FloorConstraint; use Packvium\Constraint\LoadCalculator; -use Packvium\Constraint\Internal\{LoadAnalysis,LoadSupportGraph}; +use Packvium\Constraint\Internal\{ConstraintActivity,LoadAnalysis,LoadSupportGraph}; use Packvium\Constraint\LoadUnit; use Packvium\Constraint\RouteOrderConstraint; use Packvium\Constraint\StopAccessibilityConstraint; @@ -233,6 +233,21 @@ public static function testTheCorridorCacheSeparatesContainersWithDifferentDoors self::assertTrue($throughPlus->allowed); } + public static function testTheSweepAsksTheInstanceForItsDoors(): void + { + // S17: the activity check read the configuration's doors, so a caller-supplied + // constraint built with its own doors was skipped in a container that states none. + // Python asks the instance; so does PHP now. + $doorless = Container::create('doorless', Dimensions::mm(100, 100, 100)); + $item = self::instance('i'); + self::assertFalse(ConstraintActivity::isInert(new StopAccessibilityConstraint(['-x']), $doorless, $item, true, true)); + self::assertTrue(ConstraintActivity::isInert(new StopAccessibilityConstraint(), $doorless, $item, true, true)); + self::assertTrue(ConstraintActivity::isInert(new StopAccessibilityConstraint(['-x']), $doorless, $item, true, false)); + $doored = Container::create('doored', Dimensions::mm(100, 100, 100), accessDirections: ['+x']); + self::assertSame(['+x'], (new StopAccessibilityConstraint(['-x']))->directionsFor($doored)); + self::assertSame(['-x'], (new StopAccessibilityConstraint(['-x']))->directionsFor($doorless)); + } + public static function testSweptVolumeRefusesAnUnknownDirectionAtThePrimitive(): void { // The constraint validates its doors at construction, but the primitive is public @@ -315,6 +330,16 @@ public static function testATowerPushesItsWholeWeightOntoTheBase(): void self::assertSame([200, 100, 0], LoadCalculator::topLoads($tower)); } + public static function testEverythingAboveAUnitIsRestingOnItNotOnlyItsDirectLoad(): void + { + $tower = [ + self::unit(0, 0, 0, 10, 10, 10, weight: 100, label: 'bottom'), + self::unit(0, 0, 10, 10, 10, 10, weight: 100, label: 'middle'), + self::unit(0, 0, 20, 10, 10, 10, weight: 100, label: 'top'), + ]; + self::assertSame([[1 => true, 2 => true], [2 => true], []], LoadCalculator::restingAbove($tower)); + } + public static function testAThreeLayerNestedColumnPropagatesLoadAndStackedCountDirectly(): void { $nested = [ @@ -937,6 +962,18 @@ public static function testAnItemRestingOnTwoSupportersCountsOnceForEach(): void self::assertSame([1, 1, 0], LoadCalculator::stackedCounts($supportersAndLoad)); } + public static function testAStackOfElevenHundredSheetsIsCountedWithoutRecursing(): void + { + // The audit's tall-stack reproduction (S3) at the constraint level. + $column = []; + for ($level = 0; $level < 1_100; $level++) { + $column[] = self::unit(0, 0, $level, 10, 10, 1, stackLimit: 5_000, label: "s{$level}"); + } + self::assertSame(array_map(static fn(int $level): int => 1_099 - $level, range(0, 1_099)), + LoadCalculator::stackedCounts($column)); + self::assertNull(LoadCalculator::stackLimitExceeded($column)); + } + public static function testNoStackLimitsMeansNoCheckToRun(): void { $column = [ @@ -1331,6 +1368,26 @@ public static function testCoveredIsSatisfiedWhenSupportersCoverAllFourCorners() self::assertTrue((new SupportConstraint(0.0))->evaluate($resting)->allowed); } + public static function testCoveredCountsOnlyBoxesTheCandidateActuallyRestsOn(): void + { + // The audit's three-box case (S4): `a` carries the front half of the candidate, + // `b` and `c` touch its two back corners with zero overlap area. Corners touched + // only by a zero-area neighbour hang, so this is refused, as the validators do. + [$front] = Item::create('a', Dimensions::mm(10, 5, 10))->instances(); + [$left] = Item::create('b', Dimensions::mm(10, 10, 10))->instances(); + [$right] = Item::create('c', Dimensions::mm(10, 10, 10))->instances(); + $candidate = self::instance('top', 10, 10, 10, ['groundContactRule' => 'covered']); + $resting = self::context($candidate, 10 * self::MM, [ + self::placed($front, 10 * self::MM, 0), + self::placed($left, 0, 10 * self::MM), + self::placed($right, 20 * self::MM, 10 * self::MM), + ], x: 10 * self::MM); + $result = (new SupportConstraint(0.0))->evaluate($resting); + self::assertFalse($result->allowed); + self::assertSame('ground_contact_violation', $result->code); + self::assertSame('covered: 1 supporter(s), not all four corners touched', $result->detail); + } + public static function testSingleRejectsACandidateSplitAcrossTwoSupporters(): void { [$left] = Item::create('left', Dimensions::mm(50, 100, 10))->instances(); @@ -1664,4 +1721,18 @@ public static function testTheBlockedItemAndItsBlockerAreBothNamed(): void self::assertTrue(str_contains($detail, 'base'), 'the blocked item is named'); self::assertTrue(str_contains($detail, 'top'), 'its blocker is named'); } + + public static function testTheFirstBlockerNamedIsTheLowestIndexNotTheFirstReached(): void + { + // `high` is reached first through `left`; both it and `right` block `base`. The + // lowest index is named so PHP and Python agree (S16). + $scene = [ + self::unit(0, 0, 0, 20, 10, 10, label: 'base'), + self::unit(0, 0, 10, 10, 10, 10, label: 'left'), + self::unit(10, 0, 10, 10, 10, 10, label: 'right'), + self::unit(0, 0, 20, 10, 10, 10, label: 'high'), + ]; + self::assertSame(['unloading_order_violation', 'base blocked by right'], + LoadCalculator::routeOrderViolated($scene, [0.0, 0.0, 1.0, 2.0])); + } } diff --git a/tests/FixedPlacementTest.php b/tests/FixedPlacementTest.php index 4ca1be5..8f1255e 100644 --- a/tests/FixedPlacementTest.php +++ b/tests/FixedPlacementTest.php @@ -159,7 +159,7 @@ public static function testAFixedPlacementOutOfShapeIsRefusedBeforeAnythingIsCoe ['fixed_placements[0] needs ["orientation"]', [array_diff_key($entry, ['orientation' => 0])]], ['fixed_placements[0].item_type is a non-empty string', [array_replace($entry, ['item_type' => ''])]], ['fixed_placements[0].container_type is a non-empty string', [array_replace($entry, ['container_type' => 5])]], - ['fixed_placements[0].orientation is one of the six codes', [array_replace($entry, ['orientation' => 'lwh'])]], + ['fixed_placements[0].orientation must be one of ["LWH","LHW","WLH","WHL","HLW","HWL"]', [array_replace($entry, ['orientation' => 'lwh'])]], ['fixed_placements[0].container_instance counts from 1', [array_replace($entry, ['container_instance' => '1'])]], ['fixed_placements[0].container_instance counts from 1', [array_replace($entry, ['container_instance' => true])]], ['fixed_placements[0].container_instance counts from 1', [array_replace($entry, ['container_instance' => 1.9])]], diff --git a/tests/PackingSequenceTest.php b/tests/PackingSequenceTest.php index 43712d7..e155ef9 100644 --- a/tests/PackingSequenceTest.php +++ b/tests/PackingSequenceTest.php @@ -509,6 +509,18 @@ public static function testASyntheticLoadingCycleIsDetected(): void self::assertFalse($graph->isAcyclic()); } + public static function testADependencyChainOfElevenHundredLevelsIsChecked(): void + { + // An 1100-sheet stack is an 1100-long chain; the old depth-first check recursed + // once per level. A cycle behind a tail is still found. + $chain = []; + for ($level = 0; $level < 1_099; $level++) { $chain[$level] = [$level + 1 => true]; } + $chain[1_099] = []; + self::assertTrue((new UnloadingDependencyGraph($chain))->isAcyclic()); + self::assertTrue((new LoadingDependencyGraph($chain))->isAcyclic()); + self::assertFalse((new UnloadingDependencyGraph([0 => [1 => true], 1 => [2 => true], 2 => [1 => true]]))->isAcyclic()); + } + public static function testAnUnknownDirectionIsRejectedNotTreatedAsMinusZ(): void { // The concrete bug the audit reopened this over: an unrecognised direction diff --git a/tests/RequestErrorTest.php b/tests/RequestErrorTest.php index bf7eb2d..022ae87 100644 --- a/tests/RequestErrorTest.php +++ b/tests/RequestErrorTest.php @@ -182,8 +182,9 @@ public static function testAWellFormedRateTablePassesTheRules(): void public static function testWhatTheRulesDoNotNameIsStillARequestError(): void { $request = self::request(); - $request['items'][0]['allowed_rotations'] = ['XYZ']; - $error = self::refusal($request, 'unknown rotation'); + // A model rule the schema does not have: rate brackets out of order. + $request['containers'][0]['rate_table'] = ['weight_brackets_g' => [5000, 1000], 'prices_minor' => [500, 900]]; + $error = self::refusal($request, 'descending rate brackets'); self::assertSame(['invalid_value', ''], [$error->reason(), $error->field()]); self::assertTrue(str_starts_with($error->getMessage(), 'invalid_request: '), $error->getMessage()); } @@ -250,6 +251,17 @@ private static function refusal($request, string $name): InvalidRequestException throw new RuntimeException("{$name}: the request was packed"); } + /**: with no output block, the result is in the request unit spelt as its schema code. */ + public static function testWithoutAnOutputBlockTheResultIsInTheRequestUnitSpeltAsItsCode(): void + { + foreach (['cm' => 'cm', 'MM' => 'mm', 'IN' => 'in', 'Inches' => 'in', 'millimeter' => 'mm', 'tick' => 'mm'] as $unit => $code) { + $request = self::request(); + $request['units'] = ['length' => $unit]; + $result = ArrayCodec::pack($request); + self::assertSame($code, $result['containers'][0]['inner_dimensions']['length']['unit'], $unit); + } + } + /** @return array */ private static function request(): array { diff --git a/tests/RequestObjectsCorpusTest.php b/tests/RequestObjectsCorpusTest.php new file mode 100644 index 0000000..d2258b5 --- /dev/null +++ b/tests/RequestObjectsCorpusTest.php @@ -0,0 +1,268 @@ + 'a request that is not an object has no objects', + 'items-missing' => 'Packer::pack takes the items as an argument', + 'items-not-list' => 'Packer::pack takes the items as a list of Item', + 'item-not-object' => 'an item that is not an object is not an Item', + 'containers-missing' => 'Packer::pack takes the containers as an argument', + 'configuration-not-object' => 'a configuration that is not an object is not a PackingConfig', + 'effort-not-object' => 'an effort budget that is not an object is not an EffortBudget', + 'container-made-to-measure-not-object' => 'a machine that is not an object is not a MadeToMeasure', + 'container-deformable-boundary-not-object' => 'the object holds the bag\'s kind, not a block', + 'container-deformable-boundary-kind-missing' => 'the object holds the bag\'s kind, not a block', + 'item-id-missing' => 'Item requires an id', + 'item-dimensions-missing' => 'Item requires dimensions', + 'item-side-missing' => 'Dimensions requires all three sides', + 'container-made-to-measure-minimum-missing' => 'MadeToMeasure requires a minimum', + 'container-made-to-measure-increment-missing' => 'MadeToMeasure requires an increment', + 'rate-brackets-not-list' => 'RateTable holds its brackets as a list', + 'solver-profile-unknown' => 'SolverProfile has no such case', + 'configuration-key-unknown-before-bad-value' => 'SolverProfile has no such case, and ' . self::UNKNOWN_KEY, + 'configuration-key-unknown' => self::UNKNOWN_KEY, + 'configuration-key-unknown-null' => self::UNKNOWN_KEY, + 'configuration-key-unknown-escaped' => self::UNKNOWN_KEY, + 'configuration-keys-unknown-first-in-code-point-order' => self::UNKNOWN_KEY, + 'effort-key-unknown' => self::UNKNOWN_KEY, + 'container-deformable-boundary-key-unknown' => self::UNKNOWN_KEY, + 'container-made-to-measure-key-unknown' => self::UNKNOWN_KEY, + 'unknown-configuration-key-before-its-values' => self::UNKNOWN_KEY, + 'unsupported-before-units' => 'an unsupported field has no object form', + 'unsupported-before-an-item' => 'an unsupported field has no object form', + 'container-flat-bag-with-access-directions' => 'an empty list is how an object leaves the field out', + 'item-id-number' => self::COERCED, + 'item-quantity-text' => self::COERCED, + 'container-access-directions-not-list' => self::COERCED, + 'effort-limit-text' => self::TYPED, + 'item-accepts-stacking-groups-not-list' => self::TYPED, + 'item-side-boolean' => self::TYPED, + 'item-side-fraction' => self::TYPED, + 'item-stacking-group-number' => self::TYPED, + 'fixed-position-unparsable' => 'a Point holds integer ticks, not text', + 'fixed_placements.position.x="-1"' => self::NEGATIVE_POSITION, + 'fixed_placements.position.x=-1' => self::NEGATIVE_POSITION, + 'fixed_placements.position.y="-1"' => self::NEGATIVE_POSITION, + 'fixed_placements.position.y=-1' => self::NEGATIVE_POSITION, + 'fixed_placements.position.z="-1"' => self::NEGATIVE_POSITION, + 'fixed_placements.position.z=-1' => self::NEGATIVE_POSITION, + // A closed vocabulary the object holds as an enum case cannot hold a stranger. + 'item-allowed-rotations-not-list' => self::TYPED, + 'item-allowed-rotation-unknown' => 'Rotation has no such case', + 'item-allowed-rotation-lowercase' => 'Rotation has no such case', + 'item-shape-type-unknown' => 'ShapeType has no such case', + 'fixed-orientation-unknown' => 'Rotation has no such case', + 'configuration-solvers-not-list' => self::TYPED, + 'output-not-object' => self::OUTPUT, + 'output-length-unit-unknown' => self::OUTPUT, + 'output-weight-unit-unknown' => self::OUTPUT, + 'output-before-configuration' => self::OUTPUT, + ]; + + /** Cases the object path answers differently on purpose (docs/ERRORS.md). */ + private const DIFFERENT_ON_PURPOSE = [ + 'configuration-objective-unknown' => 'an unknown objective keeps UnknownObjectiveException', + 'configuration-solver-unknown' => 'an unknown solver keeps UnknownSolverException', + 'container-access-direction-unknown' => 'an unknown direction keeps InvalidDirectionError', + 'item-accepts-stacking-groups-entry-empty' => 'a set\'s index counts in code-point order', + 'an-item-id-before-its-quantity' => self::CONSTRUCTOR_FIRST, + 'item-ids-before-containers' => self::CONSTRUCTOR_FIRST, + 'container-ids-before-fixed-placements' => self::CONSTRUCTOR_FIRST, + ]; + + /** Pinned, so the skip set cannot grow without this line changing too. */ + private const SKIPPED = 61; + + public static function testTheSkipSetIsPinnedAndNamesOnlyCorpusCases(): void + { + $names = \array_keys(self::corpus()); + self::assertSame([], \array_intersect_key(self::NOT_OBJECTS, self::DIFFERENT_ON_PURPOSE)); + self::assertSame([], \array_diff(\array_keys(self::skips()), $names), 'a skip names no corpus case'); + self::assertCount(self::SKIPPED, self::skips()); + self::assertGreaterThan(100, \count($names) - self::SKIPPED, 'the corpus quietly emptied itself'); + } + + public static function testTheObjectPathRefusesAsTheJsonPathDoes(): void + { + $differences = []; + foreach (self::corpus() as $name => $request) { + if (isset(self::skips()[$name])) { + continue; + } + [$json, $objects, $stage] = self::outcomes($request); + if (!self::sameRefusal($json, $objects, $stage)) { + $differences[] = "{$name}: json " . self::describe($json) . "; objects at {$stage} " . self::describe($objects); + } + } + self::assertTrue($differences === [], \implode("\n", $differences)); + } + + public static function testASkippedCaseStillDiffers(): void + { + $matching = []; + foreach (self::corpus() as $name => $request) { + if (!isset(self::skips()[$name])) { + continue; + } + [$json, $objects, $stage] = self::outcomes($request); + if (self::sameRefusal($json, $objects, $stage)) { + $matching[] = $name; + } + } + self::assertTrue($matching === [], 'a skip that matches has been fixed, and must leave its list: ' + . \implode(', ', $matching)); + } + + /** @return array case name => request */ + private static function corpus(): array + { + // A cross-language fixture kept one level above this package; a published copy does + // not carry it. + $path = \dirname(__DIR__, 2) . '/conformance/request_errors/corpus.json'; + if (!\is_file($path)) { + self::skip('the shared request-error corpus is not part of this package'); + } + $decoded = \json_decode((string)\file_get_contents($path), true, 512, \JSON_THROW_ON_ERROR); + self::assertSame('packvium-request-error-corpus/v1', $decoded['format']); + $cases = []; + foreach ($decoded['cases'] as $case) { + $cases[$case['name']] = $case['request']; + } + return $cases; + } + + /** @return array */ + private static function skips(): array + { + return self::NOT_OBJECTS + self::DIFFERENT_ON_PURPOSE; + } + + /** + * The JSON path's refusal, the object path's outcome, and where the object path ended. + * + * @param mixed $request + * @return array{0:Throwable,1:?Throwable,2:string} + */ + private static function outcomes($request): array + { + $json = null; + try { + ArrayCodec::pack($request); + } catch (Throwable $error) { + $json = $error; + } + self::assertNotNull($json, 'the JSON path answered a malformed request'); + // A key the codec reads and the request lacks is a warning to PHP; here it means the + // objects cannot be built, so it is thrown like every other failure to build them. + \set_error_handler(static function (int $severity, string $message): bool { + throw new \ErrorException($message, 0, $severity); + }); + try { + [$config, $items, $containers, $fixed] = self::objects($request); + } catch (Throwable $error) { + // What the objects could not be built from is the finding. + return [$json, $error, 'constructor']; + } finally { + \restore_error_handler(); + } + try { + (new Packer($config))->pack($items, $containers, $fixed); + } catch (Throwable $error) { + return [$json, $error, 'pack']; + } + return [$json, null, 'pack']; + } + + /** + * `ArrayCodec`'s model without the JSON rules: its builders, and its fixed placements + * without `FixedPlacementShape` in front of them. + * + * @param mixed $request + * @return array{0:mixed,1:mixed,2:mixed,3:list} + */ + private static function objects($request): array + { + $data = $request; + unset($data['fixed_placements']); + [$config, , , $items, $containers] = self::codec('model', $data); + $unit = (string)($request['units']['length'] ?? 'mm'); + $fixed = []; + foreach ($request['fixed_placements'] ?? [] as $raw) { + $position = self::codec('point', $raw['position'] ?? [], $unit); + $fixed[] = new FixedPlacement($raw['item_type'], $raw['container_type'], $position, + Rotation::from($raw['orientation']), $raw['container_instance'] ?? 1); + } + return [$config, $items, $containers, $fixed]; + } + + /** @return mixed */ + private static function codec(string $method, ...$arguments) + { + $builder = new ReflectionMethod(ArrayCodec::class, $method); + $builder->setAccessible(true); + return $builder->invoke(null, ...$arguments); + } + + private static function sameRefusal(Throwable $json, ?Throwable $objects, string $stage): bool + { + if (!$objects instanceof InvalidRequestException || !$json instanceof InvalidRequestException + || !\is_a($objects, \get_class($json))) { + return false; + } + if ([$objects->errorCode(), $objects->reason()] !== [$json->errorCode(), $json->reason()]) { + return false; + } + if ($stage === 'constructor') { + return $objects->field() === ''; + } + return [$objects->field(), $objects->getMessage()] === [$json->field(), $json->getMessage()]; + } + + private static function describe(?Throwable $error): string + { + if ($error === null) { + return 'accepted'; + } + if ($error instanceof InvalidRequestException) { + return \sprintf('%s(%s, %s, %s, %s)', \get_class($error), $error->errorCode(), $error->reason(), + $error->field(), $error->getMessage()); + } + return \get_class($error) . ': ' . $error->getMessage(); + } +} diff --git a/tests/RequestObjectsTest.php b/tests/RequestObjectsTest.php new file mode 100644 index 0000000..1f929f7 --- /dev/null +++ b/tests/RequestObjectsTest.php @@ -0,0 +1,216 @@ + ['length' => '100', 'width' => '100', 'height' => '100'], + 'increment' => ['length' => '50', 'width' => '50', 'height' => '50']]; + + public static function testARequestOfObjectsIsRefusedWithTheJsonReasonAndField(): void + { + $cases = [ + 'quantity past 2^53 - 1' => [self::packed([self::cube(quantity: self::TOO_LARGE)]), + static function (array &$r): void { $r['items'][0]['quantity'] = self::TOO_LARGE; }], + 'repeated item id' => [self::packed([self::cube(), self::cube()]), + static function (array &$r): void { $r['items'][] = $r['items'][0]; }], + 'repeated container id' => [self::packed(null, [self::box(), self::box()]), + static function (array &$r): void { $r['containers'][] = $r['containers'][0]; }], + 'empty stacking group' => [self::packed([self::cube(stackingGroup: '')]), + static function (array &$r): void { $r['items'][0]['stacking_group'] = ''; }], + 'max_stacked_items past 2^53 - 1' => [self::packed([self::cube(maxStackedItems: self::TOO_LARGE)]), + static function (array &$r): void { $r['items'][0]['max_stacked_items'] = self::TOO_LARGE; }], + 'container cost past 2^53 - 1' => [self::packed(null, [self::box(costMinor: self::TOO_LARGE)]), + static function (array &$r): void { $r['containers'][0]['cost_minor'] = self::TOO_LARGE; }], + 'tag limit past 2^53 - 1' => [self::packed(null, [self::box(tagLimits: ['fragile' => self::TOO_LARGE])]), + static function (array &$r): void { $r['containers'][0]['tag_limits'] = ['fragile' => self::TOO_LARGE]; }], + 'rate table price past 2^53 - 1' => [self::packed(null, [self::box(rateTable: new RateTable([1000], [self::TOO_LARGE]))]), + static function (array &$r): void { $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000], 'prices_minor' => [self::TOO_LARGE]]; }], + 'time limit past 2^53 - 1' => [self::packed(null, null, PackingConfig::fast(self::TOO_LARGE)), + static function (array &$r): void { $r['configuration']['time_limit_ms'] = self::TOO_LARGE; }], + 'effort limit past 2^53 - 1' => [self::packed(null, null, new PackingConfig(SolverProfile::Fast, effortBudget: new EffortBudget(maxRestarts: self::TOO_LARGE))), + static function (array &$r): void { $r['configuration']['effort_budget'] = ['max_restarts' => self::TOO_LARGE]; }], + 'made to measure beside outer dimensions' => [self::packed(null, [self::madeToMeasureBox(self::machine(), Dimensions::mm(210, 110, 210))]), + static function (array &$r): void { + $r['containers'][0]['made_to_measure'] = self::JSON_MACHINE; + $r['containers'][0]['outer_dimensions'] = ['length' => '210', 'width' => '110', 'height' => '210']; + }], + 'made to measure priced past 2^53 - 1' => [self::packed(null, [self::madeToMeasureBox(self::machine(10 ** 18))]), + static function (array &$r): void { $r['containers'][0]['made_to_measure'] = self::JSON_MACHINE + ['cost_per_square_metre_minor' => 10 ** 18]; }], + ]; + foreach ($cases as $name => [$build, $edit]) { + $fromObjects = self::refusal($build, $name); + $fromJson = self::jsonRefusal($edit, $name); + self::assertSame(self::identity($fromJson), self::identity($fromObjects), $name); + self::assertSame($fromJson->getMessage(), $fromObjects->getMessage(), $name); + } + } + + public static function testAnObjectRefusesWithTheJsonReasonAndNoField(): void + { + $cases = [ + 'zero quantity' => [static fn() => self::cube(quantity: 0), + static function (array &$r): void { $r['items'][0]['quantity'] = 0; }], + 'negative side' => [static fn() => Dimensions::mm('-1', 100, 100), + static function (array &$r): void { $r['items'][0]['dimensions']['length'] = '-1'; }], + 'unknown unit' => [static fn() => Length::of(1, 'furlong'), + static function (array &$r): void { $r['units'] = ['length' => 'furlong']; }], + 'support ratio above one' => [static fn() => self::cube(minimumSupportRatio: 2.0), + static function (array &$r): void { $r['items'][0]['minimum_support_ratio'] = 2; }], + 'zero container quantity' => [static fn() => self::box(quantity: 0), + static function (array &$r): void { $r['containers'][0]['quantity'] = 0; }], + 'too few candidate points' => [static fn() => new PackingConfig(SolverProfile::Fast, maxCandidatePoints: 8), + static function (array &$r): void { $r['configuration']['max_candidate_points'] = 8; }], + 'zero effort limit' => [static fn() => new EffortBudget(maxRestarts: 0), + static function (array &$r): void { $r['configuration']['effort_budget'] = ['max_restarts' => 0]; }], + ]; + foreach ($cases as $name => [$build, $edit]) { + $fromObjects = self::refusal($build, $name); + $fromJson = self::jsonRefusal($edit, $name); + self::assertSame([$fromJson->errorCode(), $fromJson->reason(), ''], self::identity($fromObjects), $name); + } + } + + /** It used to be expanded into that many instances, which never finished. */ + /**: the bag exclusion `Container` itself does not refuse, and an empty fixed placement id. */ + public static function testTheRulesOnlyARequestCanCheckAreRefusedAsOnTheJsonPath(): void + { + $bag = new Container('box', Dimensions::mm(200, 100, 200), deformableBoundary: 'flat_bag', madeToMeasure: self::machine()); + $unnamed = new FixedPlacement('', 'box', new Point(0, 0, 0), Rotation::LWH); + $cases = [ + 'made to measure beside a flat bag' => [self::packed(null, [$bag]), + static function (array &$r): void { + $r['containers'][0]['deformable_boundary'] = ['kind' => 'flat_bag']; + $r['containers'][0]['made_to_measure'] = self::JSON_MACHINE; + }], + 'fixed placement without an item type' => [ + static fn() => (new Packer(PackingConfig::fast()))->pack([self::cube()], [self::box()], [$unnamed]), + static function (array &$r): void { + $r['fixed_placements'] = [['item_type' => '', 'container_type' => 'box', 'container_instance' => 1, + 'position' => ['x' => '0', 'y' => '0', 'z' => '0'], 'orientation' => 'LWH']]; + }], + ]; + foreach ($cases as $name => [$build, $edit]) { + $fromObjects = self::refusal($build, $name); + $fromJson = self::jsonRefusal($edit, $name); + self::assertSame(self::identity($fromJson), self::identity($fromObjects), $name); + self::assertSame($fromJson->getMessage(), $fromObjects->getMessage(), $name); + } + } + + public static function testAQuantityPastTheExactRangeIsRefusedBeforeAnySolve(): void + { + $error = self::refusal(self::packed([self::cube(quantity: self::TOO_LARGE)]), 'quantity'); + self::assertSame(['above_maximum', '/items/0/quantity'], [$error->reason(), $error->field()]); + } + + /** A set has no order, so insertion order must not pick which value an error names. */ + public static function testAcceptedStackingGroupsAreCheckedInCodePointOrder(): void + { + $error = self::refusal(self::packed([self::cube(acceptsStackingGroups: ['pallet', '', 'box'])]), 'groups'); + self::assertSame(['invalid_value', '/items/0/accepts_stacking_groups/0'], [$error->reason(), $error->field()]); + } + + /** A wrapper that quotes the text (a commerce document) reads what it always read. */ + public static function testAConstructorRefusalKeepsItsOwnMessage(): void + { + $error = self::refusal(static fn() => self::cube(quantity: 0), 'zero quantity'); + self::assertSame('Item quantity must be positive', $error->getMessage()); + } + + /** A model rule the JSON table lacks is answered as every engine answers it. */ + public static function testTheJsonPathStillReportsWhatItsRulesDoNotNameAsInvalidValue(): void + { + $error = self::jsonRefusal(static function (array &$r): void { + $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [5000, 1000], 'prices_minor' => [500, 900]]; + }, 'descending brackets'); + self::assertSame(['invalid_value', ''], [$error->reason(), $error->field()]); + self::assertSame('invalid_request: rate_table weight brackets must be strictly ascending', $error->getMessage()); + } + + /** @return array{0:string,1:string,2:string} */ + private static function identity(InvalidRequestException $error): array + { + return [$error->errorCode(), $error->reason(), $error->field()]; + } + + private static function cube(mixed ...$fields): Item + { + return Item::create('cube', Dimensions::mm(100, 100, 100), ...$fields); + } + + private static function box(mixed ...$fields): Container + { + return Container::create('box', Dimensions::mm(200, 100, 200), ...$fields); + } + + private static function madeToMeasureBox(MadeToMeasure $machine, ?Dimensions $outer = null): Container + { + return new Container('box', Dimensions::mm(200, 100, 200), $outer, madeToMeasure: $machine); + } + + private static function machine(int $cost = 0): MadeToMeasure + { + $minimum = Length::mm(100)->ticks; + $increment = Length::mm(50)->ticks; + return new MadeToMeasure([$minimum, $minimum, $minimum], [$increment, $increment, $increment], $cost); + } + + /** + * @param list|null $items + * @param list|null $containers + */ + private static function packed(?array $items = null, ?array $containers = null, ?PackingConfig $config = null): callable + { + return static fn() => (new Packer($config ?? PackingConfig::fast()))->pack($items ?? [self::cube()], $containers ?? [self::box()]); + } + + private static function refusal(callable $build, string $name): InvalidRequestException + { + try { + $build(); + } catch (InvalidRequestException $error) { + return $error; + } + throw new RuntimeException("{$name}: the objects were accepted"); + } + + private static function jsonRefusal(callable $edit, string $name): InvalidRequestException + { + $request = [ + 'items' => [['id' => 'cube', 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '200', 'width' => '100', 'height' => '200']]], + 'configuration' => ['solver_profile' => 'fast'], + ]; + $edit($request); + return self::refusal(static fn() => ArrayCodec::pack($request), "{$name} (JSON)"); + } +} diff --git a/tests/ResultValidationCorpusTest.php b/tests/ResultValidationCorpusTest.php new file mode 100644 index 0000000..9b97085 --- /dev/null +++ b/tests/ResultValidationCorpusTest.php @@ -0,0 +1,140 @@ + $case) { + $reason = self::disagreement($case['expected'], self::outcome($case['request'], $case['result'])); + if ($reason !== null) { + $disagreements[] = "case {$index}: {$reason}"; + } + } + self::assertSame([], $disagreements); + } + + public static function testTheCorpusReachesEveryIssueCodeAndRefusalKind(): void + { + $codes = []; + $refusals = []; + foreach (self::corpus() as $case) { + foreach ($case['expected']['issues'] ?? [] as $issue) { + $codes[$issue['code']] = true; + } + if (isset($case['expected']['refusal'])) { + $refusals[$case['expected']['refusal']['kind']] = true; + } + } + self::assertGreaterThan(70, \count($codes), 'the corpus quietly lost issue codes'); + self::assertSame(['contract', 'shape'], self::sortedKeys($refusals)); + } + + /** @return array{issues: list}|array{refusal: array{kind: string, message: string}} */ + private static function outcome(string $requestText, string $resultText): array + { + try { + $request = \json_decode($requestText, true, 512, \JSON_THROW_ON_ERROR); + $result = \json_decode($resultText, true, 512, \JSON_THROW_ON_ERROR); + if (!\is_array($request) || !\is_array($result)) { + throw MalformedResult::shape('a document is not a JSON object'); + } + $issues = []; + foreach (validate($request, $result) as $issue) { + $issues[] = ['code' => $issue->code, 'detail' => $issue->detail]; + } + return ['issues' => $issues]; + } catch (MalformedResult $refusal) { + return ['refusal' => ['kind' => $refusal->kind, 'message' => $refusal->getMessage()]]; + } catch (JsonException $refusal) { + return ['refusal' => ['kind' => 'shape', 'message' => 'not JSON: ' . $refusal->getMessage()]]; + } + } + + /** + * @param array $expected + * @param array $actual + */ + private static function disagreement(array $expected, array $actual): ?string + { + if (isset($expected['issues'])) { + if (($actual['issues'] ?? null) === $expected['issues']) { + return null; + } + return isset($actual['refusal']) + ? "refused ({$actual['refusal']['message']}) where the reference found issues" + : 'a different issue list: ' . \json_encode($actual['issues']); + } + $reference = $expected['refusal']; + if (!isset($actual['refusal'])) { + return "answered where the reference refused ({$reference['message']})"; + } + if ($reference['kind'] === 'contract' && !self::sameRefusal($reference, $actual['refusal'])) { + return "refused with {$actual['refusal']['kind']}: {$actual['refusal']['message']} " + . "where the reference raised MalformedResult({$reference['message']})"; + } + return null; + } + + /** + * @param array{kind: string, message: string} $expected + * @param array{kind: string, message: string} $actual + */ + private static function sameRefusal(array $expected, array $actual): bool + { + if ($actual['kind'] !== $expected['kind']) { + return false; + } + if (\preg_match(self::QUOTES_PYTHON_ERROR, $expected['message'], $quoted) === 1) { + return \str_starts_with($actual['message'], $quoted[1]); + } + return $actual['message'] === $expected['message']; + } + + /** @return list}> */ + private static function corpus(): array + { + $path = \dirname(__DIR__, 2) . '/conformance/result_validation/corpus.json'; + if (!\is_file($path)) { + self::skip('the shared result-validation corpus is not part of this package'); + } + $decoded = \json_decode((string)\file_get_contents($path), true, 512, \JSON_THROW_ON_ERROR); + self::assertSame('packvium-result-validation-corpus/v1', $decoded['format']); + return $decoded['cases']; + } + + /** + * @param array $set + * @return list + */ + private static function sortedKeys(array $set): array + { + $keys = \array_keys($set); + \sort($keys); + return $keys; + } +} diff --git a/tests/ResultValidationTest.php b/tests/ResultValidationTest.php new file mode 100644 index 0000000..754d9b1 --- /dev/null +++ b/tests/ResultValidationTest.php @@ -0,0 +1,359 @@ + [['id' => 'cube', 'quantity' => 2, 'dimensions' => ['length' => '10', 'width' => '10', 'height' => '10']]], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '20', 'width' => '10', 'height' => '10']]], + ]; + + /** The engine packages the validator may use: integer primitives and its own public types. */ + private const ALLOWED = [ + 'Packvium\\Support\\BigInt', 'Packvium\\Support\\SignedBigInt', 'Packvium\\Support\\ShortestFloat', + 'Packvium\\Validation\\MalformedResult', 'Packvium\\Validation\\ResultIssue', + ]; + + public static function testTheValidatorImportsNothingFromTheEngine(): void + { + $imported = []; + foreach (\glob(\dirname(__DIR__) . '/src/Support/ResultValidation/*.php') ?: [] as $file) { + \preg_match_all('/^use (Packvium\\\\[^;\s]+);/m', (string)\file_get_contents($file), $uses); + foreach ($uses[1] as $class) { + if (\strncmp($class, 'Packvium\\Support\\ResultValidation\\', 34) !== 0 && !\in_array($class, self::ALLOWED, true)) { + $imported[] = \basename($file) . ': ' . $class; + } + } + } + self::assertSame([], $imported); + } + + public static function testAResultTheEnginePackedIsValid(): void + { + self::assertSame([], validate(self::REQUEST, ArrayCodec::pack(self::REQUEST))); + } + + public static function testTwoItemsInOnePlaceAreACollisionNamedAsTheReferenceNamesIt(): void + { + $result = ArrayCodec::pack(self::REQUEST); + $result['containers'][0]['placements'][1]['position'] = $result['containers'][0]['placements'][0]['position']; + $issues = validate(self::REQUEST, $result); + self::assertCount(1, $issues); + self::assertTrue($issues[0] instanceof ResultIssue); + self::assertSame('collision: cube#1 with cube#2 in box#1', (string)$issues[0]); + } + + /**: the audit's scene, where B rests on exactly half its base at a ratio that rounds down to 500000 ppm. */ + public static function testTheAuditReproductionIsPackedAndValid(): void + { + $request = [ + 'configuration' => ['minimum_support_ratio' => 0.5000001, 'solver_profile' => 'fast'], + 'items' => [ + ['id' => 'A', 'quantity' => 1, 'priority' => 10, 'allowed_rotations' => ['LWH'], 'dimensions' => ['length' => '100', 'width' => '50', 'height' => '50']], + ['id' => 'B', 'quantity' => 1, 'allowed_rotations' => ['LWH'], 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '50']], + ], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]], + ]; + $result = ArrayCodec::pack($request); + self::assertSame('feasible', $result['status']); + self::assertSame([], validate($request, $result)); + } + + /** + * Support is judged by the solvers' ppm rule, `floor(base * ppm / 10^6)` with + * `ppm = floor(ratio * 10^6 + 0.5)` in doubles, not by the exact rational. On a 10^7 tick + * base each ratio's ppm floor is admitted and one tick less is refused. + */ + public static function testSupportIsJudgedByTheSolversPpmRule(): void + { + $base = 10000000; + $bar = ['length' => '1', 'width' => (string)$base, 'height' => '1']; + $request = [ + 'units' => ['length' => 'tick'], + 'items' => [ + ['id' => 'lower', 'quantity' => 1, 'allowed_rotations' => ['LWH'], 'dimensions' => $bar], + ['id' => 'upper', 'quantity' => 1, 'allowed_rotations' => ['LWH'], 'dimensions' => $bar], + ], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '1', 'width' => (string)(2 * $base), 'height' => '2']]], + ]; + $floor = ArrayCodec::pack($request); + $insufficient = static function (float $ratio, int $supported) use ($request, $floor, $base): array { + $result = $floor; + foreach ($result['containers'][0]['placements'] as &$placement) { + if ($placement['item_type'] === 'upper') { + $placement['position']['y'] = ['ticks' => $base - $supported, 'value' => (string)($base - $supported), 'unit' => 'tick']; + $placement['position']['z'] = ['ticks' => 1, 'value' => '1', 'unit' => 'tick']; + } + } + unset($placement); + $request['configuration'] = ['minimum_support_ratio' => $ratio]; + $details = []; + foreach (validate($request, $result) as $issue) { + if ($issue->code === 'insufficient_support') { + $details[] = $issue->detail; + } + } + return $details; + }; + // 0.0001245 is 124 ppm in doubles where the exact decimal rounds to 125. + foreach ([[0.5000001, 5000000], [0.0001245, 1240], [0.9999996, 10000000], [0.25, 2500000]] as [$ratio, $threshold]) { + self::assertSame([], $insufficient($ratio, $threshold), "ratio {$ratio}"); + self::assertCount(1, $insufficient($ratio, $threshold - 1), "ratio {$ratio}"); + } + self::assertSame(['upper#1: 0.500000 < 0.500000'], $insufficient(0.5000001, 4999999)); + } + + /** + * (audit F5): the void-fill reserve goes through the same conversion, reserving + * `floor(volume * ppm / 10^6)`. On a 10^7 cubic tick container the engine reports that + * reserve, a bar filling exactly the usable volume is valid and one tick wider is refused. + */ + public static function testTheVoidFillReserveIsJudgedByTheSolversPpmRule(): void + { + $volume = 10000000; + $request = static function (float $ratio, int $width) use ($volume): array { + return [ + 'units' => ['length' => 'tick'], + 'items' => [['id' => 'bar', 'quantity' => 1, 'allowed_rotations' => ['LWH'], 'dimensions' => ['length' => '1', 'width' => (string)$width, 'height' => '1']]], + 'containers' => [['id' => 'box', 'void_fill_reserve_ratio' => $ratio, 'inner_dimensions' => ['length' => '1', 'width' => (string)$volume, 'height' => '1']]], + ]; + }; + $oneTick = ArrayCodec::pack($request(0.0, 1)); + $reserveIssues = static function (float $ratio, int $width, int $reserve) use ($request, $oneTick): array { + $result = $oneTick; + $result['containers'][0]['placements'][0]['dimensions']['width'] = ['ticks' => $width, 'value' => (string)$width, 'unit' => 'tick']; + $result['containers'][0]['used_volume_ticks3'] = (string)$width; + $result['containers'][0]['void_fill_reserve_ticks3'] = (string)$reserve; + $issues = []; + foreach (validate($request($ratio, $width), $result) as $issue) { + if (\strncmp($issue->code, 'void_fill_reserve', 17) === 0) { + $issues[] = (string)$issue; + } + } + return $issues; + }; + // 0.0001245 is 124 ppm in doubles where the exact decimal rounds to 125. + foreach ([[0.0001245, 1240], [0.0002445, 2440], [0.5000001, 5000000], [0.9999994, 9999990], [0.25, 2500000]] as [$ratio, $reserve]) { + $packed = ArrayCodec::pack($request($ratio, 1)); + self::assertSame((string)$reserve, (string)$packed['containers'][0]['void_fill_reserve_ticks3'], "ratio {$ratio}"); + self::assertSame([], validate($request($ratio, 1), $packed), "ratio {$ratio}"); + self::assertSame([], $reserveIssues($ratio, $volume - $reserve, $reserve), "ratio {$ratio}"); + self::assertCount(1, $reserveIssues($ratio, $volume - $reserve + 1, $reserve), "ratio {$ratio}"); + } + self::assertSame(['void_fill_reserve_exceeded: box#1: used 9998761 > usable 9998760'], $reserveIssues(0.0001245, 9998761, 1240)); + } + + /** + * `compression_ratio` goes through the same conversion. A 5 kg brick holds a 1 m + * compressible pad at half its 10 kPa limit, where one ppm moves the occupied height by + * about eight ticks: the engine compresses by the double's ppm and the validator agrees. + */ + public static function testCompressionIsJudgedByTheSolversPpmRule(): void + { + $request = static function (float $ratio): array { + return [ + 'items' => [ + ['id' => 'pad', 'quantity' => 1, 'must_be_on_floor' => true, 'allowed_rotations' => ['LWH'], 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '1000'], 'shape_type' => 'compressible', 'compression_ratio' => $ratio, 'max_compression_pressure_kpa' => 10], + ['id' => 'brick', 'quantity' => 1, 'allowed_rotations' => ['LWH'], 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '10'], 'weight' => ['value' => '5', 'unit' => 'kg']], + ], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '100', 'width' => '100', 'height' => '2000']]], + ]; + }; + $used = static function (float $ratio) use ($request): string { + return (string)ArrayCodec::pack($request($ratio))['containers'][0]['used_volume_ticks3']; + }; + // 0.0001245 is 124 ppm in doubles where the exact decimal rounds to 125. + foreach ([[0.0001245, 0.000124], [0.0002445, 0.000244], [0.5000001, 0.5], [0.25, 0.25]] as [$ratio, $ppmRatio]) { + $result = ArrayCodec::pack($request($ratio)); + self::assertSame([], validate($request($ratio), $result), "ratio {$ratio}"); + self::assertSame($used($ppmRatio), (string)$result['containers'][0]['used_volume_ticks3'], "ratio {$ratio}"); + } + self::assertNotSame($used(0.000125), $used(0.0001245)); + } + + public static function testAResultOfTheWrongShapeIsRefusedRatherThanJudged(): void + { + try { + validate(self::REQUEST, ['containers' => 'none']); + self::assertTrue(false, 'a result without the documented shape must be refused'); + } catch (MalformedResult $refusal) { + self::assertSame(MalformedResult::CONTRACT, $refusal->kind); + self::assertSame("result is missing 'status'", $refusal->getMessage()); + } + } + + public static function testIntegersStayExactPastSixtyFourBits(): void + { + $volume = Exact::mul(Exact::mul(9600000000, 9600000000), 9600000000); + self::assertSame('884736000000000000000000000000', $volume); + self::assertSame(-4, Exact::floorDiv(-7, 2)); + self::assertSame(2, Exact::mod(-7, 3)); + self::assertSame(4, Exact::ceilDiv(7, 2)); + self::assertSame(Exact::negate('884736000000000000'), Exact::floorDiv(Exact::negate($volume), '1000000000000')); + } + + public static function testADocumentIntegerPastSixtyFourBitsIsRefusedNotJudged(): void + { + // `json_decode` has turned it into a float (or a string) before the validator sees it, + // so it cannot be judged exactly; the reference would judge it, and the contract names + // the departure (docs/VALIDATION-CONTRACT.md). + $result = ArrayCodec::pack(self::REQUEST); + $result['containers'][0]['placements'][0]['position']['x']['ticks'] = 'SEVENTY_BITS'; + $big = \str_replace('"SEVENTY_BITS"', '1180591620717411303424', (string)\json_encode($result)); + foreach ([0, \JSON_BIGINT_AS_STRING] as $flags) { + $message = null; + try { + validate(self::REQUEST, \json_decode($big, true, 512, $flags)); + } catch (MalformedResult $refusal) { + $message = $refusal->getMessage(); + } + self::assertTrue(\is_string($message) && \str_contains($message, 'ticks must be an integer'), + 'a 70-bit tick must be refused, not judged'); + } + } + + public static function testFractionsParseAsPythonReadsThem(): void + { + $cases = ['1_000' => [1000, 1], '.5' => [1, 2], '5.' => [5, 1], '1e3' => [1000, 1], '1E-2' => [1, 100], + ' 3/16 ' => [3, 16], '+.5e1' => [5, 1], '1_0.0_1' => [1001, 100], '-0.25' => [-1, 4]]; + foreach ($cases as $text => [$numerator, $denominator]) { + $ratio = Units::parseFraction((string)$text); + self::assertSame([$numerator, $denominator], [$ratio->numerator, $ratio->denominator], (string)$text); + } + foreach (['1 / 2', '0x10', '', '.', '1__0', '_1', '1/0', 'None'] as $bad) { + self::assertThrows(MalformedResult::class, static function () use ($bad): void { Units::parseFraction($bad); }, $bad); + } + } + + public static function testMeasuresRoundHalfToEven(): void + { + self::assertSame(152400 + 12 * 406400, Units::toTicks('12 3/8 in', 'mm', Units::LENGTH)); + self::assertSame(-24000, Units::toTicks('-1 1/2 mm', 'mm', Units::LENGTH)); + self::assertSame(1600000, Units::toTicks('10 CM', 'mm', Units::LENGTH)); + self::assertSame(0, Units::toTicks('0.00003125', 'mm', Units::LENGTH)); + self::assertSame(2, Units::toTicks('0.00009375', 'mm', Units::LENGTH)); + } + + public static function testValuesPrintAsPythonPrintsThem(): void + { + $floats = [[1e16, '1e+16'], [1e-5, '1e-05'], [0.0001, '0.0001'], [123456789012345678.0, '1.2345678901234568e+17'], + [0.1, '0.1'], [-0.0, '-0.0'], [5.0, '5.0'], [1e15, '1000000000000000.0'], [2.5e-6, '2.5e-06']]; + foreach ($floats as [$value, $expected]) { + self::assertSame($expected, PyFormat::floatRepr($value)); + } + self::assertSame("\"it's\"", PyFormat::stringRepr("it's")); + self::assertSame("'a\\nb\\\\'", PyFormat::stringRepr("a\nb\\")); + self::assertSame("'\\x07é\\u200b'", PyFormat::stringRepr("\u{7}é\u{200b}")); + self::assertSame("'\\U000e0001\\u0600'", PyFormat::stringRepr("\u{e0001}\u{600}")); + self::assertSame("'\\u0378\\ue000é'", PyFormat::stringRepr("\u{378}\u{e000}é")); + self::assertSame("{'a': [1, None, True], 'b': 'x'}", PyFormat::repr(['a' => [1, null, true], 'b' => 'x'])); + self::assertSame('(7,)', PyFormat::intTuple([7])); + self::assertSame('0.000003', PyFormat::fixed6(Ratio::of(5, 2000000)->toFloat())); + } + + public static function testFloatConversionIsCorrectlyRounded(): void + { + self::assertSame(2.5e-6, Ratio::of(5, 2000000)->toFloat()); + self::assertSame(2.0 ** 60, Ratio::integer((1 << 60) + 1)->toFloat()); + self::assertSame((float)((1 << 54) + 4), Ratio::integer((1 << 54) + 3)->toFloat()); + self::assertSame(1.0 / 3.0, Ratio::of('300000000000000000000', '900000000000000000000')->toFloat()); + } + + /**: the Python values the reference compares, orders and hashes, beyond what the corpus reaches. */ + public static function testJsonValuesCompareAsPythonComparesThem(): void + { + self::assertSame(1, Json::compare([1, 2], [1])); + self::assertSame(-1, Json::compare([1], [1, 2])); + self::assertSame(-1, Json::compare(1.5, 2)); + self::assertTrue(Json::equals([1, [2.0]], [true, [2]])); + self::assertFalse(Json::equals([1, 2], [1, 3])); + self::assertSame('null', Json::hashKey(null)); + self::assertSame(['null', 'a boolean', 'an integer', 'a list', 'an object'], + [Json::kind(null), Json::kind(false), Json::kind(1), Json::kind([1]), Json::kind([])]); + self::assertSame([2, -2, 1, '10000000000000000000'], + [Json::pyInt(2.7, 'x'), Json::pyInt(-2.7, 'x'), Json::pyInt(true, 'x'), Json::pyInt(1e19, 'x')]); + self::assertSame(1, Json::int(true, 'x')); + self::assertFalse(Json::isList(5)); + $refusals = [ + static function (): void { Json::compare([1], 'a'); }, + static function (): void { Json::hashKey([1]); }, + static function (): void { Json::pyInt([], 'x'); }, + static function (): void { Json::get(5, 'x'); }, + static function (): void { Json::items('x', 'x'); }, + static function (): void { Json::text(1, 'x'); }, + ]; + foreach ($refusals as $index => $refusal) { + self::assertThrows(MalformedResult::class, $refusal, "refusal {$index}"); + } + } + + public static function testExactArithmeticCoversItsEdges(): void + { + self::assertSame(12, Exact::normalize('12')); + self::assertSame('18446744073709551616', Exact::powerOfTwo(64)); + self::assertThrows(MalformedResult::class, static function (): void { Exact::floorDiv(1, 0); }); + $negative = Ratio::of(3, -4); + self::assertSame([-3, 4], [$negative->numerator, $negative->denominator]); + self::assertSame(1.0 / 3.0, Ratio::of(1, 3)->toFloat()); + self::assertSame(0.1, Ratio::of(1, 10)->toFloat()); + self::assertSame(3.0e-300, Ratio::of(3, Exact::normalize('1' . \str_repeat('0', 300)))->toFloat()); + } + + public static function testGeometryAndUnitsRefuseWhatTheyCannotRead(): void + { + self::assertSame([0, 0, 0], Geometry::primitiveAxis([0, 0, 0])); + // WLH is an odd permutation, so the hull is mirrored back into a proper rotation + // (`_rotate_hull` gives ((1, 0, 0), (1, 2, 0), (0, 0, 0)) for the same three vertices). + self::assertSame([[1, 0, 0], [1, 2, 0], [0, 0, 0]], + Geometry::rotateHull([[0, 0, 0], [2, 0, 0], [0, 1, 0]], Geometry::axes('WLH'))); + $refusals = [ + static function (): void { Geometry::axes('XYZ'); }, + static function (): void { Geometry::rotateHull([], [0, 1, 2]); }, + static function (): void { Units::perUnit(Units::LENGTH, 'furlong'); }, + static function (): void { Units::parseFraction('1e999'); }, + ]; + foreach ($refusals as $index => $refusal) { + self::assertThrows(MalformedResult::class, $refusal, "refusal {$index}"); + } + } + + /** The reference prints a missing id as `?`; the port refuses an issue it would have to name so. */ + public static function testAnIssueOnAContainerWithoutAnIdIsRefused(): void + { + $label = new Label(['container_type' => 'box']); + self::assertSame('?', (string)$label); + self::assertThrows(MalformedResult::class, static function () use ($label): void { $label->verify(); }); + } + + public static function testSpecialValuesPrintAsPythonPrintsThem(): void + { + self::assertSame(['nan', 'inf', '-inf', '1.5'], + [PyFormat::floatRepr(\NAN), PyFormat::floatRepr(\INF), PyFormat::floatRepr(-\INF), PyFormat::floatRepr(1.5)]); + self::assertSame("'a\\tb\\rc'", PyFormat::stringRepr("a\tb\rc")); + self::assertSame("'a\\'b\"'", PyFormat::stringRepr("a'b\"")); + self::assertSame("'\\x85'", PyFormat::stringRepr("\u{85}")); + self::assertSame("'\\U000f0000'", PyFormat::stringRepr("\u{f0000}")); + } +} diff --git a/tests/SerializationTest.php b/tests/SerializationTest.php index 3068f5e..a9ff47f 100644 --- a/tests/SerializationTest.php +++ b/tests/SerializationTest.php @@ -320,6 +320,16 @@ public static function testTheSolverProfileAndSeedArePlumbedThrough(): void self::assertSame(7, $result['algorithm']['seed']); } + public static function testANegativeSeedPacksUnderQuality(): void + { + // A negative remainder once reached the multi-start shuffle as a negative index. + $items = array_map(static fn(int $side) => self::cube("c{$side}", $side), [20, 25, 30, 35, 40, 45]); + $result = ArrayCodec::pack(self::request($items, [self::box('c')], + ['configuration' => ['solver_profile' => 'quality', 'seed' => -7]])); + self::assertSame(-7, $result['algorithm']['seed']); + self::assertSame([], $result['unpacked_items']); + } + public static function testAnUnknownProfileIsRejectedRatherThanSilentlyDefaulted(): void { try { @@ -354,8 +364,15 @@ public static function testExplicitSolverOrderIsPreservedInStartRecords(): void public static function testAnUnknownSolverNameIsRejectedRatherThanSilentlyDefaulted(): void { - self::assertThrows(\Packvium\Algorithm\UnknownSolverException::class, static fn() => ArrayCodec::pack( - self::request([self::cube('a', 50)], [self::box('c')], ['configuration' => ['solvers' => ['brute_force']]]))); + try { + ArrayCodec::pack(self::request([self::cube('a', 50)], [self::box('c')], + ['configuration' => ['solvers' => ['brute_force']]])); + } catch (\Packvium\Serialization\InvalidRequestException $error) { + // Refused by the request rules, at the unknown name, as every engine does. + self::assertSame(['not_allowed', '/configuration/solvers/0'], [$error->reason(), $error->field()]); + return; + } + self::fail('an unknown solver name was packed'); } public static function testAnEffortBudgetIsPlumbedThroughAndActuallyBoundsTheSearch(): void diff --git a/tests/SolverTest.php b/tests/SolverTest.php index ceff652..3c432b6 100644 --- a/tests/SolverTest.php +++ b/tests/SolverTest.php @@ -29,6 +29,7 @@ use Packvium\Constraint\ConstraintSet; use Packvium\Constraint\LoadCalculator; use Packvium\Domain\AxisAlignedBox; +use Packvium\Domain\Axle; use Packvium\Domain\Container; use Packvium\Domain\Dimensions; use Packvium\Domain\Item; @@ -342,7 +343,11 @@ public static function testMoreBlockSearchEffortCannotWorsenTheObjective(): void self::assertPhysicallySound($high->state); } - /** One 60x60x40 base and three 40x60x50 tops in a 100 mm crate: the base ends on two tops and overhangs them. */ + /** + * One 60x60x40 base and three 40x60x50 tops in a 100 mm crate. The greedy block pass, which + * `balanced` runs, ends the base on two tops so that it overhangs them; `quality`'s lookahead + * finds a layout with nothing overhanging. + */ private static function aBaseAndThreeTops(): array { return [...self::instances('base',60,60,40),...self::instances('top',40,60,50,['quantity'=>3])]; @@ -364,7 +369,7 @@ private static function restingShare(array $placements,Placement $placement): fl public static function testABlockSetOnASmallerOneReportsTheSupportItReallyHas(): void { $box=Container::create('crate',Dimensions::mm(100,100,100),quantity:1); - $solution=(new HomogeneousBlockSolver())->packOne($box,1,self::aBaseAndThreeTops(),PackingConfig::quality(),new SearchStats(),self::generous()); + $solution=(new HomogeneousBlockSolver())->packOne($box,1,self::aBaseAndThreeTops(),self::greedyBlocks(),new SearchStats(),self::generous()); $placements=$solution->state->placements; $base=array_values(array_filter($placements,static fn(Placement $p):bool=>$p->instance->item->id==='base'))[0]; self::assertTrue($base->envelopeOrigin->z>0); @@ -372,6 +377,23 @@ public static function testABlockSetOnASmallerOneReportsTheSupportItReallyHas(): self::assertSame(self::restingShare($placements,$base),$base->supportRatio); } + /** The block solver without `quality`'s lookahead: one greedy pass per mode. */ + private static function greedyBlocks(): PackingConfig + { + return new PackingConfig(profile:SolverProfile::Balanced,containerPlanNodeLimit:100_000); + } + + public static function testTheQualityLookaheadFindsALayoutWithNothingOverhanging(): void + { + $box=Container::create('crate',Dimensions::mm(100,100,100),quantity:1); + $greedy=(new HomogeneousBlockSolver())->packOne($box,1,self::aBaseAndThreeTops(),self::greedyBlocks(),new SearchStats(),self::generous()); + $looked=(new HomogeneousBlockSolver())->packOne($box,1,self::aBaseAndThreeTops(),PackingConfig::quality(),new SearchStats(),self::generous()); + self::assertSame([],$looked->unpacked); + self::assertTrue(!$looked->timeLimitReached); + foreach($looked->state->placements as $placement)self::assertSame(1.0,$placement->supportRatio); + self::assertTrue($looked->state->maxZ<$greedy->state->maxZ); + } + public static function testTheBlockSolverLeavesARequestThatAsksForSupportToThePerItemSearch(): void { $box=Container::create('crate',Dimensions::mm(100,100,100),quantity:1); @@ -954,6 +976,29 @@ public static function testSpaceAndNodeMetricsCountTheirOwnSolverWork(): void self::assertGreaterThan(0,$stats->searchNodesExpanded); } + public static function testAxleBalancedPointsScanFloorRowsInAscendingY(): void + { + // Python and Rust sort the floor y-values; PHP scanned them in insertion order, + // which moved where a counted stop landed (S12). + $container = Container::create('axled', Dimensions::mm(1000, 100, 100), + axles: [new Axle(Length::mm(100), Weight::of(300, 'kg')), new Axle(Length::mm(900), Weight::of(300, 'kg'))]); + $state = new ContainerState($container, 1); + $mm = Length::mm(1)->ticks; + $state->points = ['a' => new Point(0, 50 * $mm, 0), 'b' => new Point(0, 0, 0), + 'c' => new Point(0, 20 * $mm, 0), 'd' => new Point(0, 70 * $mm, 10 * $mm)]; + [$item] = Item::create('i', Dimensions::mm(200, 10, 10), '400 kg')->instances(); + $dims = $item->item->dimensions; + $forms = [[Rotation::LWH, $dims, $dims, 200 * $mm, 10 * $mm, 10 * $mm]]; + $method = new ReflectionMethod(CandidateFinder::class, 'axleBalancedPoints'); + $method->setAccessible(true); + $points = $method->invoke(null, $state, $item, $forms, 1000 * $mm); + // 400 kg over axles 800 mm apart reaches a 300 kg limit with its centre at 300 or 700 mm. + self::assertSame([200 * $mm, 200 * $mm, 200 * $mm, 600 * $mm, 600 * $mm, 600 * $mm], + array_map(static fn(Point $point): int => $point->x, $points)); + foreach (array_chunk($points, 3) as $row) + self::assertSame([0, 20 * $mm, 50 * $mm], array_map(static fn(Point $point): int => $point->y, $row)); + } + // ------------------------------------------------------------ seeded randomness public static function testTheSameSeedReplaysTheSameSequence(): void @@ -1020,6 +1065,16 @@ public static function testTheSequenceMatchesPythonForTheSameSeed(): void self::assertSame([1, 2, 4, 3, 5, 0], (new DeterministicRandom(7))->shuffled(range(0, 5))); } + public static function testANegativeSeedShufflesAsPythonDoes(): void + { + // Python reduces a negative seed to its non-negative residue modulo 2^31; PHP's + // remainder keeps the sign and once indexed negative keys under `quality`. + $values = range(0, 9); + self::assertSame([5, 0, 3, 4, 8, 7, 6, 9, 2, 1], (new DeterministicRandom(-7))->shuffled($values)); + self::assertSame((new DeterministicRandom(2_147_483_641))->shuffled($values), + (new DeterministicRandom(-7))->shuffled($values)); + } + // ----------------------------------------------------------------- group batches public static function testUngroupedItemsAreOfferedOneAtATime(): void