From 9f483d530208887a2cf374ee22657f6d4af843c1 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 4 Oct 2026 14:29:55 -0400 Subject: [PATCH] chore(release): 1.5.0 --- CHANGELOG.md | 34 +++ CITATION.cff | 25 ++ README.md | 227 ++++++++++++++--- codemeta.json | 31 +++ composer.json | 12 +- docs/GUARANTEES.md | 20 +- docs/UNITS-AND-NUMERICS.md | 2 +- examples/errors.php | 232 ++++++++++++++++++ examples/execution.php | 2 +- examples/extensions.php | 204 +++++++++++++++ examples/fixed_placements.php | 129 ++++++++++ examples/limits.php | 153 ++++++++++++ examples/objectives.php | 3 +- examples/reproducibility.php | 155 ++++++++++++ examples/serialization.php | 79 +++--- examples/trucking.php | 230 +++++++++++++++++ src-legacy/Algorithm/BeamPacker.php | 64 +++-- .../Algorithm/HomogeneousBlockSolver.php | 25 +- src-legacy/Algorithm/MaximalSpaceSolver.php | 28 ++- src-legacy/Algorithm/SpatialIndex.php | 25 +- src-legacy/Artifacts/OperationalArtifact.php | 2 +- src-legacy/Support/FixedPlacementShape.php | 4 +- src-legacy/Support/RationalParser.php | 33 ++- src-legacy/Support/RequestRules.php | 48 ++++ src/Algorithm/BeamPacker.php | 60 +++-- src/Algorithm/HomogeneousBlockSolver.php | 25 +- src/Algorithm/MaximalSpaceSolver.php | 28 ++- src/Algorithm/SpatialIndex.php | 25 +- src/Artifacts/OperationalArtifact.php | 2 +- src/Support/FixedPlacementShape.php | 4 +- src/Support/RationalParser.php | 33 ++- src/Support/RequestRules.php | 48 ++++ tests/AccessDirectionsTest.php | 6 + tests/AxleLoadTest.php | 17 ++ tests/DomainTest.php | 9 + tests/ExtensionTest.php | 82 +++++++ tests/FixedPlacementTest.php | 4 +- tests/InvariantTest.php | 37 ++- tests/IrregularItemsTest.php | 42 ++++ tests/ObjectiveBoundsTest.php | 6 + tests/PackingSequenceTest.php | 18 ++ tests/PlanRevisionTest.php | 2 +- tests/RationalParserTest.php | 39 +++ tests/RebalanceTest.php | 40 +++ tests/RequestErrorTest.php | 23 ++ tests/SerializationTest.php | 32 +++ tests/SolverTest.php | 105 ++++++++ tests/SpatialIndexTest.php | 73 ++++++ 48 files changed, 2337 insertions(+), 190 deletions(-) create mode 100644 CITATION.cff create mode 100644 codemeta.json create mode 100644 examples/errors.php create mode 100644 examples/extensions.php create mode 100644 examples/fixed_placements.php create mode 100644 examples/limits.php create mode 100644 examples/reproducibility.php create mode 100644 examples/trucking.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 9496884..26ba317 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ 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.5.0] + +No API changes. The beam search is faster with identical placements, a block answer reports +its real support, and a misspelt configuration key is now refused (see *Fixed*). + +### Changed + +- **Beam search 18–24% faster, same results.** The bound that ranks beam nodes reads prefix + sums built once per step, one binary search per node instead of a `BigInt` addition per + future item, and expansions that cannot beat the best plan so far are skipped early. + +### Fixed + +- **A block answer reports the support each item really has.** `HomogeneousBlockSolver` wrote + `supportRatio` 1.0 for every item, including those of a block set on a smaller one, which + overhang it. The bottom layer of each block now reports the share of its base that rests on + something. With `minimumSupportRatio` above zero the block solver is no longer tried at all; + its answer was built and then discarded by validation. +- **A misspelt `configuration` key is refused.** A key the request schema does not declare in + `configuration` or its `effort_budget` (`profile` for `solver_profile`, `top_k` for + `alternatives`) was silently ignored, so the request ran on defaults. `ArrayCodec::pack` now + throws `InvalidRequestException` with reason `not_allowed` and the key's pointer, for example + `/configuration/profile`. +- **A number past PHP's integer range is refused instead of changed.** A length or weight of + `9223372036854775808` became `9223372036854775807`, and a decimal whose scaled value overflowed + became a float, so the request was solved for a different size than the one sent. Both now + throw `InvalidArgumentException` ("Scaled unit value exceeds integer range"). +- **An unknown `objective` or access direction is refused with its pointer.** It was + `invalid_value` with an empty field; it is now `not_allowed` with, for example, + `/configuration/objective`. +- **Compressible items are no longer laid out as rigid blocks** by `HomogeneousBlockSolver`. +- **Refusal messages match the documentation**, e.g. a fixed placement with unknown keys says it + `cannot carry` them. + ## [1.4.0] Replanning a job that has already started, and container ids that match the other engines. diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000..e11c019 --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,25 @@ +cff-version: 1.2.0 +message: "If you use Packvium in your research, please cite it as below." +title: "Packvium for PHP" +type: software +authors: + - name: "Packvium contributors" + website: "https://packvium.com" +version: "1.5.0" +license: MIT +url: "https://packvium.com" +repository-code: "https://github.com/toxakara/packvium-php" +repository-artifact: "https://packagist.org/packages/packvium/packvium" +abstract: >- + Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results. +keywords: + - 3d-bin-packing + - bin-packing + - 3d-packing + - cartonization + - container-loading + - pallet-packing + - truck-loading + - packing-algorithm + - logistics + - deterministic diff --git a/README.md b/README.md index f20bd21..04da502 100644 --- a/README.md +++ b/README.md @@ -3,18 +3,27 @@ Deterministic 3D cartonization and rectangular bin packing. Pure PHP, **no runtime dependencies**, exact integer geometry. +Use it to pick the smallest carton for an order, build a pallet, load a shipping container, +or load a truck within its axle ratings and delivery-stop order. Every answer comes back as +coordinates and rotations for each item, with a reason for anything that did not fit. + Full documentation, the constraint reference and benchmarks live at [packvium.com](https://packvium.com). -> **Version 1.4.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.5.0 — the public API is frozen.** Field names, status codes and the > objective vector do not change without a major version, so any `1.x` is a safe upgrade > from any earlier `1.x`. -> Read [docs/GUARANTEES.md](docs/GUARANTEES.md) before relying on a result. +> Read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-php/blob/main/docs/GUARANTEES.md) +> before relying on a result. ```bash composer require packvium/packvium ``` +The library runs on PHP 7.3 and newer. The quick start below and the shipped examples are +written for **PHP 8.2 or newer**; [Older PHP](#older-php-73-to-81) shows what changes below +that. + ## Quick start ```php @@ -23,8 +32,8 @@ use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, Dimensions, Item}; use Packvium\Packer; -$result = (new Packer(PackingConfig::balanced()))->pack( - [Item::create('book', Dimensions::mm('210', '140', '30'), quantity: 4)], +$result = (new Packer(PackingConfig::balanced(timeLimitMs: 60000)))->pack( + [Item::create('book', Dimensions::mm('210', '140', '30'), '450 g', quantity: 4)], [Container::create('box', Dimensions::mm('400', '300', '250'))], ); @@ -36,13 +45,24 @@ foreach ($result->containers as $container) { } ``` -Fractional inches are exact, not approximated: +The same request can be written as a plain array, the JSON document every Packvium +engine reads. This form works unchanged on every supported PHP version: ```php -Dimensions::inches('12 3/8', '8 1/2', '3/4'); +use Packvium\Serialization\ArrayCodec; + +$result = ArrayCodec::pack([ + 'units' => ['length' => 'mm'], + 'configuration' => ['time_limit_ms' => 60000], + 'items' => [['id' => 'book', 'quantity' => 4, 'weight' => '450 g', + 'dimensions' => ['length' => '210', 'width' => '140', 'height' => '30']]], + 'containers' => [['id' => 'box', + 'inner_dimensions' => ['length' => '400', 'width' => '300', 'height' => '250']]], +]); +echo $result['status'], PHP_EOL; // feasible ``` -There is also a CLI that reads a JSON request on standard input: +There is also a CLI that reads the same JSON request on standard input: ```bash echo '{"items":[{"id":"box","quantity":8,"dimensions":{"length":"50","width":"50","height":"50"}}], @@ -53,10 +73,60 @@ echo '{"items":[{"id":"box","quantity":8,"dimensions":{"length":"50","width":"50 The library is framework-independent: no facades, no static state, no container bindings. Construct a `Packer` and call it. +## Units + +Every length is an integer number of ticks of 1/16000 mm, and every weight an integer +number of 1/8 µg. Nothing on the path from request to score is a float, so no placement +decision depends on rounding, and an imperial spec sheet and a metric container agree +without a tolerance: + +```php +Dimensions::inches('12 3/8', '8 1/2', '3/4'); // exact: fractions, mixed fractions, decimals +Dimensions::mm('210', '140', '30'); +Item::create('mug', Dimensions::mm('100', '100', '120'), '12 oz'); +``` + +Lengths accept `mm`, `cm`, `m`, `in`, `ft` and ticks; weights `mg`, `g`, `kg`, `oz` and `lb`. +Pass numbers as strings or integers — the API has no float parameters for a measure. Round +item exteriors outward and container interiors inward before building the request. +Volumes that exceed `PHP_INT_MAX` are handled in exact decimal-string arithmetic rather +than losing precision. See +[docs/UNITS-AND-NUMERICS.md](https://github.com/toxakara/packvium-php/blob/main/docs/UNITS-AND-NUMERICS.md) +and [`units.php`](https://github.com/toxakara/packvium-php/blob/main/examples/units.php). + +## Determinism + +The same request, seed and budget give the same result. The one thing that can break that +is the wall clock: `time_limit_ms` (`timeLimitMs`) stops the search when time runs out, and +how far a search gets in that time depends on the machine and its load. A search that +finishes inside its limit is reproducible; one the clock stopped is not. + +`effort_budget` bounds the search by counted work instead — candidates evaluated, +placements attempted, search nodes expanded, portfolio restarts — so it stops at the same +point everywhere. Keep `time_limit_ms` as a generous safety fuse beside it: + +```php +$result = ArrayCodec::pack([ + 'configuration' => [ + 'effort_budget' => ['max_search_nodes' => 20000], + 'time_limit_ms' => 60000, + ], + // items, containers ... +]); +$result['termination']['code']; // "complete", "effort_limit" or "time_limit" +``` + +`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. +[`reproducibility.php`](https://github.com/toxakara/packvium-php/blob/main/examples/reproducibility.php) +shows all three outcomes. + ## Errors -A request that no engine may answer throws `Packvium\Serialization\InvalidRequestException`, an -`InvalidArgumentException`, before anything is solved. It names the problem instead of +A request that no engine may answer throws `Packvium\Serialization\InvalidRequestException`, +an `InvalidArgumentException`, before anything is solved. It names the problem instead of describing it: ```php @@ -69,21 +139,38 @@ try { $e->errorCode(); // "invalid_request" $e->reason(); // "below_minimum" $e->field(); // "/items/0/quantity" -- a JSON Pointer into your request + $e->detail(); // "must be at least 1" $e->getMessage(); // "invalid_request: /items/0/quantity: must be at least 1" } ``` -`reason()` is one of `missing_field`, `wrong_type`, `below_minimum`, `above_maximum`, `negative_measure`, `invalid_unit`, `duplicate_id`, `not_allowed` or `invalid_value`. `FixedPlacementException` extends it, with code -`invalid_fixed_placement` and reason `malformed` or `cannot_hold`. -The message is the same in every Packvium engine. Branch on `reason` and `field`; show the -message to a person. A request that is valid but does not fit completely is not an error: the -result lists what was left out, and why, in `unpacked_items`. +- `reason()` is one of `missing_field`, `wrong_type`, `below_minimum`, `above_maximum`, + `negative_measure`, `invalid_unit`, `duplicate_id`, `not_allowed` or `invalid_value`. + Branch on `reason()` and `field()`; show the message to a person. The message is the + same in every Packvium engine. When a request breaks several rules, the first is + reported, in a fixed order: units, configuration, items, containers, fixed placements. +- `Packvium\Validation\FixedPlacementException` extends it, with code + `invalid_fixed_placement` and reason `malformed` (an entry is not the right shape) or + `cannot_hold` (the fixed items are not a valid packing on their own). +- `Packvium\Serialization\UnsupportedFeatureException` (code `unsupported_feature`) is a + separate type: the request uses a field this engine has not implemented yet, and it is + refused rather than silently ignored. +- An unknown `objective` or `access_directions` value in a request raises + `InvalidRequestException` with reason `not_allowed` and a `field()` pointing to + the bad value. Direct domain constructors may raise their own argument errors. + +A request that is valid but does not fit completely is not an error: the result lists what +was left out, and why, in `unpacked_items`. +[`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. ## Examples -Runnable, in [`examples/`](examples). Each one is a single file you can read top to bottom -and execute without a project around it. Every one of them is executed by the test suite -on each release, so none of them can quietly stop working. +Runnable, in [`examples/`](https://github.com/toxakara/packvium-php/tree/main/examples). Each +one is a single file you can read top to bottom and execute without a project around it. +Every one of them is executed by the test suite on each release, so none of them can +quietly stop working. They are PHP 8.2 code (named arguments, enums); run them on 8.2 or +newer. New here? Read `basic.php`, then `objectives.php` — between them they cover what most callers need. `units.php` and `serialization.php` explain the two design choices that @@ -91,14 +178,20 @@ surprise people. | File | What it shows | | --- | --- | -| [`basic.php`](examples/basic.php) | The smallest useful call: items in, placements out — and the three details in it that are easy to miss. | -| [`objectives.php`](examples/objectives.php) | All six objectives on scenes where they genuinely disagree, including the rate card that makes the heavier shipment the cheaper one. | -| [`constraints.php`](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. | -| [`units.php`](examples/units.php) | Why there are no floats anywhere: fractional inches, exact ticks, and the one-tick difference between a fit and a refusal. | -| [`serialization.php`](examples/serialization.php) | The same request as JSON, the result in full, and exactly which mistakes are refused and which are silently ignored. | +| [`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. | +| [`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. | +| [`serialization.php`](https://github.com/toxakara/packvium-php/blob/main/examples/serialization.php) | The same request as JSON, the result in full, runners-up via `alternatives`, and exactly which mistakes are refused and which are silently ignored. | +| [`errors.php`](https://github.com/toxakara/packvium-php/blob/main/examples/errors.php) | A web handler that turns every refusal into a 422 naming the item and the value: each `InvalidRequestException` reason, the fixed-placement refusals, and the oversize order that is not an error at all. | +| [`reproducibility.php`](https://github.com/toxakara/packvium-php/blob/main/examples/reproducibility.php) | `effortBudget` against `timeLimitMs` on four simulated hosts: a clock-stopped search that answers differently on each, a budget that answers the same on all of them, and how to read `termination`. | +| [`trucking.php`](https://github.com/toxakara/packvium-php/blob/main/examples/trucking.php) | A van with two axle ratings, a rear door and three stops: the route-legal plan, axle loads, the unloading and loading order, what the driver can reach at the first stop, and what goes wrong without `stopIndex`. | +| [`fixed_placements.php`](https://github.com/toxakara/packvium-php/blob/main/examples/fixed_placements.php) | Pack a trailer that already has four pallets on board: packing around them, the cost of one left in the wrong place, and the refusals when the record is impossible. | | [`shapes.php`](https://github.com/toxakara/packvium-php/blob/main/examples/shapes.php) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, and a cushion that compresses under load until the crush limit refuses it. | -| [`nested.php`](examples/nested.php) | Units into cartons, cartons onto a pallet, in one call. | -| [`commerce.php`](examples/commerce.php) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | +| [`nested.php`](https://github.com/toxakara/packvium-php/blob/main/examples/nested.php) | Units into cartons, cartons onto a pallet, in one call. | +| [`extensions.php`](https://github.com/toxakara/packvium-php/blob/main/examples/extensions.php) | Rules the request has no field for: a custom placement constraint and container selector through `ExtensionRegistry`, a custom solution scorer — and why a rule everyone must obey belongs in the request instead. | +| [`commerce.php`](https://github.com/toxakara/packvium-php/blob/main/examples/commerce.php) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | | [`execution.php`](https://github.com/toxakara/packvium-php/blob/main/examples/execution.php) | Turn a result into dock instructions: solver facts kept apart from screen text, and a step order that is injected or honestly absent — byte-identical to the other three engines. | | [`artifacts.php`](https://github.com/toxakara/packvium-php/blob/main/examples/artifacts.php) | Hand a result to a system with no engine: one document with the plan, geometry and the request that produced it, exported as CSV and a printable HTML work order — byte-identical to the other three engines. | | [`revisions.php`](https://github.com/toxakara/packvium-php/blob/main/examples/revisions.php) | Replan a half-loaded job: a missing item and a locked placement recorded against the approved plan, a replan that keeps the locked item in place, and a hash-chained record that notices an edit — the same digests as the other three engines. | @@ -107,27 +200,36 @@ surprise people. php examples/objectives.php ``` -`constraints.php` and `nested.php` print byte-for-byte what their Python counterparts -print, which is the cross-language contract this port is held to, not a coincidence. +`limits.php`, `fixed_placements.php`, `nested.php` and `shapes.php` print byte for byte +what their [Python counterparts](https://github.com/toxakara/packvium-python/tree/main/examples) +print. `trucking.php`, `errors.php`, `reproducibility.php` and `constraints.php` differ only +where a line names a PHP spelling (`stopIndex`, `allowedRotations`, `true`) or a +language's own exception class. That is the cross-language contract this port is held to — +identical placements for the same request — not a coincidence. The other examples print +PHP values (`[0,1,180]` where Python prints `(0, 1, 180)`), so their text differs even +where their answers agree. ## What it does - **Exact arithmetic.** Length is measured in ticks of 1/16000 mm and weight in 1/8 µg. - No coordinate is ever a float, so no placement decision depends on rounding. Volumes - that exceed `PHP_INT_MAX` are handled in exact decimal-string arithmetic rather than - losing precision. + No coordinate is ever a float, so no placement decision depends on rounding. - **Real constraints.** Weight and payload limits, permitted rotations, keep-upright, - floor-only, non-stackable, top-load limits, minimum support ratio, tag incompatibility, - clearance and rectangular obstacles. + floor-only, non-stackable, top-load limits, minimum support ratio, tag incompatibility + and per-container tag limits, item-count limits, clearance, obstacles built from unions + of boxes, two-axle load limits, delivery stops and door access. - **A solver portfolio, not one algorithm.** Regular-grid, layer, extreme-point, maximal-space and bounded exact search, selected by problem shape and profile. - **Answers you can check.** Every solution is re-validated by logic independent of the search. Unplaced items come back with a reason code, not silently missing. -- **Deterministic.** The same input and seed produce the same result, always. +- **Deterministic.** The same input, seed and effort budget produce the same result, and + the result says when a clock, not the budget, stopped the search. - **Multi-container and nested.** Split across containers, or pack containers into containers. - **Extensible.** Register your own constraints, item orderings, candidate scorers, container selectors or complete solvers. +- **Loading and unloading order.** `Packvium\Sequence` answers which placements a door can + reach right now and gives a safe loading order, or an unloading order that empties each + stop before the next. - **Work orders and portable artifacts.** `Packvium\Execution\Plan` turns a result into an operator's step list. `Packvium\Artifacts\OperationalArtifact` wraps that plan with geometry, display values and the request that produced it, and `ArtifactExports` writes it @@ -143,9 +245,10 @@ print, which is the cross-language contract this port is held to, not a coincide | Document | Covers | | --- | --- | -| [docs/GUARANTEES.md](docs/GUARANTEES.md) | What is promised and what is not. Start here. | -| [docs/PUBLIC-API.md](docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | -| [docs/UNITS-AND-NUMERICS.md](docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | +| [docs/GUARANTEES.md](https://github.com/toxakara/packvium-php/blob/main/docs/GUARANTEES.md) | What is promised and what is not. Start here. | +| [docs/PUBLIC-API.md](https://github.com/toxakara/packvium-php/blob/main/docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | +| [docs/UNITS-AND-NUMERICS.md](https://github.com/toxakara/packvium-php/blob/main/docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | +| [docs/COMMERCE-API.md](https://github.com/toxakara/packvium-php/blob/main/docs/COMMERCE-API.md) | Carrier rating, policy evaluation and catalog versions. | ## Requirements @@ -164,6 +267,35 @@ PHP 7.3, 7.4, 8.0 and 8.1 are end-of-life and receive no upstream security fixes runs there so that an upgrade does not have to block your project — not so that it can be postponed. +### Older PHP (7.3 to 8.1) + +Two things differ from the quick start: one is PHP syntax your version does not have, the +other is how the downgraded tree represents enums. + +- **No named arguments** (they need PHP 8.0). Pass arguments positionally, filling the + defaults you skip: `Item::create('book', $dimensions, '450 g', 4)`. +- **Enums are strings.** Below 8.2 `PackingStatus`, `Rotation`, `SolverProfile`, + `ShapeType` and `Rounding` are classes of string constants, so `$result->status` is the + string `'feasible'` itself — there is no `->value`. `Rotation::LWH` is the string `'LWH'`. + +```php +$result = (new Packer(PackingConfig::balanced(60000)))->pack( + [Item::create('book', Dimensions::mm('210', '140', '30'), '450 g', 4)], + [Container::create('box', Dimensions::mm('400', '300', '250'))] +); + +echo $result->status, PHP_EOL; // feasible +foreach ($result->containers as $container) { + foreach ($container->placements as $placement) { + echo $placement->instance->id(), ' ', $placement->rotation, PHP_EOL; + } +} +``` + +The array API (`ArrayCodec::pack`) takes and returns plain arrays of strings and integers, +so code written against it is the same on every version. The shipped examples are 8.2 +code and are not meant to run below it. + ## The Packvium family One request and result contract, implemented independently in four engines (Rust, @@ -185,9 +317,28 @@ Documentation, the constraint reference and the benchmarks are at ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md). Security reports go through the process in -[SECURITY.md](SECURITY.md), not public issues. +See [CONTRIBUTING.md](https://github.com/toxakara/packvium-php/blob/main/CONTRIBUTING.md). +Security reports go through the process in +[SECURITY.md](https://github.com/toxakara/packvium-php/blob/main/SECURITY.md), not public +issues. + +## Citation + +If Packvium supports your research, cite it as software. GitHub's **Cite this repository** +button reads [`CITATION.cff`](https://github.com/toxakara/packvium-php/blob/main/CITATION.cff), and +[`codemeta.json`](https://github.com/toxakara/packvium-php/blob/main/codemeta.json) carries the same record in +CodeMeta form. + +```bibtex +@software{packvium_php, + author = {{Packvium contributors}}, + title = {Packvium for PHP}, + version = {1.5.0}, + license = {MIT}, + url = {https://packvium.com} +} +``` ## License -MIT. See [LICENSE](LICENSE). +MIT. See [LICENSE](https://github.com/toxakara/packvium-php/blob/main/LICENSE). diff --git a/codemeta.json b/codemeta.json new file mode 100644 index 0000000..93173ab --- /dev/null +++ b/codemeta.json @@ -0,0 +1,31 @@ +{ + "@context": "https://w3id.org/codemeta/3.0", + "@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.5.0", + "license": "https://spdx.org/licenses/MIT", + "author": [ + { + "@type": "Organization", + "name": "Packvium contributors", + "url": "https://packvium.com" + } + ], + "url": "https://packvium.com", + "codeRepository": "https://github.com/toxakara/packvium-php", + "issueTracker": "https://github.com/toxakara/packvium-php/issues", + "programmingLanguage": "PHP", + "keywords": [ + "3d-bin-packing", + "bin-packing", + "3d-packing", + "cartonization", + "container-loading", + "pallet-packing", + "truck-loading", + "packing-algorithm", + "logistics", + "deterministic" + ] +} diff --git a/composer.json b/composer.json index ad8b5f3..64a8285 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "packvium/packvium", - "description": "Deterministic, extensible 3D cartonization and container packing library with exact metric and imperial units.", + "description": "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", "type": "library", "suggest": { "packvium/native-bridge": "Routes solves through the Rust core over FFI when a shared library is available, with identical results." @@ -14,13 +14,19 @@ ], "keywords": [ "3d-bin-packing", + "bin-packing", + "3d-packing", "cartonization", "container-loading", - "packing", - "logistics" + "pallet-packing", + "truck-loading", + "packing-algorithm", + "logistics", + "deterministic" ], "homepage": "https://packvium.com", "support": { + "docs": "https://packvium.com/docs", "issues": "https://github.com/toxakara/packvium-php/issues", "source": "https://github.com/toxakara/packvium-php", "security": "https://github.com/toxakara/packvium-php/blob/main/SECURITY.md" diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 11d9696..6f2b855 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -15,7 +15,9 @@ After a result reports `feasible` or `optimal` and passes independent validation 1/8 µg for weight. No coordinate is ever a binary floating-point number, so no placement decision depends on rounding; - **determinism** — identical input and identical seed produce an identical result, on - any platform and in any of the implementations; + any platform, when the search completes or stops on `configuration.effort_budget`. A + search stopped by `time_limit_ms` stops where the host's speed let it, so it may differ + between runs; the result says which limit stopped it; - **complete accounting** — every requested item instance appears exactly once, either placed or listed as unpacked with a reason code. @@ -31,9 +33,10 @@ After a result reports `feasible` or `optimal` and passes independent validation - **That your inputs are right.** Dimensions, weights and clearances are taken as given. Round item exteriors outward, container interiors inward, and clearance outward before you build the request. -- **Support for non-rectangular shapes.** Items and containers are rigid axis-aligned - cuboids; obstacles are rectangular. No cylinders, deformable bags, meshes or - irregular geometry. +- **Arbitrary shapes.** Containers are axis-aligned cuboids. An item is a cuboid, a convex + hull of vertices, or a cuboid that compresses by a declared ratio; obstacles are cuboids + or unions of them. Concave meshes, curved surfaces and free-form deformable bags are not + modelled — approximate them with a convex hull or a bounding cuboid. - **A result before the deadline.** With a time limit set, the search may return `time_limit` with a partial packing, or nothing placed at all. - **Full load propagation.** Top-load limits are enforced against what rests *directly* @@ -41,14 +44,15 @@ After a result reports `feasible` or `optimal` and passes independent validation ## Not modelled at all -Deformable goods, dynamic shipping physics, contact-load propagation through arbitrary -support graphs, pallet-overhang standards, axle loads, unloading-route optimization, and -carrier tariff or rating catalogs. None of these are built in, and none are approximated +Dynamic shipping physics, contact-load propagation through arbitrary support graphs, +pallet-overhang standards, and route optimization. Axle loads, the unloading order of a +given stop sequence (`stop_index`, `access_directions`) and carrier rate tables are +modelled; choosing the route itself is not. None of the unmodelled items is approximated silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.4.0` freezes the public API. Field names, status codes, the objective +Version `1.5.0` freezes the public API. Field names, status codes, the objective vector, the numeric policy and the validation rules do not change without a major version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde constraint on `1.0` is enough; an exact pin is no longer required. diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index 1badad2..272c4ee 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -8,7 +8,7 @@ One internal length tick is `1/16000 mm`. - `1 international inch = 25.4 mm = 406,400 ticks` - common fractional inches through at least `1/128 in` are exact integers -Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. Binary floating-point input is intentionally rejected by the Python API; PHP type declarations accept only integer/string/structured values. +Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. A binary float with a fractional part is intentionally rejected by the Python API, by `Length` and `Weight` alike (`TypeError`); an integral float such as `100.0` is exact, and is what JavaScript sends for `100`, so it is accepted as that integer. PHP type declarations accept only integer/string/structured values. ## Weight diff --git a/examples/errors.php b/examples/errors.php new file mode 100644 index 0000000..8a6bf39 --- /dev/null +++ b/examples/errors.php @@ -0,0 +1,232 @@ +: `, the same text in every Packvium + * engine, fit for a log line. + * + * `FixedPlacementException` is a subclass for items already in place that cannot be where + * the request says. And a request that is valid but does not fit completely is not an + * error at all: it is a result with `unpacked_items`. + */ +declare(strict_types=1); + +require dirname(__DIR__) . '/autoload.php'; + +use Packvium\Serialization\{ArrayCodec, InvalidRequestException}; +use Packvium\Validation\FixedPlacementException; + +$order = [ + 'units' => ['length' => 'mm'], + 'configuration' => ['time_limit_ms' => 60000, 'effort_budget' => ['max_restarts' => 4]], + 'items' => [ + ['id' => 'mug', 'quantity' => 2, 'weight' => '380 g', + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '120']], + ['id' => 'teapot', 'quantity' => 1, 'weight' => '1.2 kg', + 'dimensions' => ['length' => '220', 'width' => '160', 'height' => '180']], + ], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '300', 'width' => '250', 'height' => '200']]], +]; + +/** + * Every value along a JSON Pointer, root first, so a message can name the item by id. + * + * @param mixed $document + * @return list + */ +function resolve($document, string $pointer): array +{ + $values = [$document]; + foreach (array_slice(explode('/', $pointer), 1) as $token) { + $key = str_replace(['~1', '~0'], ['/', '~'], $token); + $current = end($values); + if (!is_array($current) || !array_key_exists($key, $current)) { + break; + } + $values[] = $current[$key]; + } + return $values; +} + +/** + * `/items/1/dimensions/width` becomes `item "teapot", dimensions/width`. + * + * The pointer is exact but written for programs. People know their items by id, so the + * nearest object that has one names the place, and the rest of the pointer says which + * value in it. + */ +function where(array $request, string $pointer): string +{ + $tokens = array_slice(explode('/', $pointer), 1); + $values = resolve($request, $pointer); + for ($depth = count($values) - 1; $depth > 0; $depth--) { + $value = $values[$depth]; + if (is_array($value) && isset($value['id'])) { + $kind = rtrim($tokens[$depth - 2], 's'); + $rest = implode('/', array_slice($tokens, $depth)); + return sprintf('%s "%s"', $kind, $value['id']) . ($rest === '' ? '' : ", {$rest}"); + } + } + return $pointer === '' ? 'the request' : $pointer; +} + +/** + * What a POST /pack endpoint would do: a status code and a JSON body. + * + * @return array{0:int,1:array} + */ +function handle(string $body): array +{ + $request = json_decode($body, true, 512, JSON_THROW_ON_ERROR); + try { + $result = ArrayCodec::pack($request); + } catch (FixedPlacementException $error) { + // A subclass of InvalidRequestException, so it must be caught first. Its detail + // names the physical problem (a collision, too much weight), which is what a dock + // operator needs to hear. + return [422, ['code' => $error->errorCode(), 'reason' => $error->reason(), 'field' => $error->field(), + 'message' => "The items already loaded cannot stay as recorded: {$error->detail()}."]]; + } catch (InvalidRequestException $error) { + return [422, ['code' => $error->errorCode(), 'reason' => $error->reason(), 'field' => $error->field(), + 'message' => 'Please check ' . where($request, $error->field()) . ": {$error->detail()}."]]; + } + // Not an error: the caller gets the plan, and a clear list of what is not in it. + $leftOut = array_column($result['unpacked_items'], 'item_id'); + return [200, ['status' => $result['status'], 'boxes' => count($result['containers']), 'left_out' => $leftOut]]; +} + +/** + * JSON with a space after each separator, the way the other Packvium examples print it. + * + * @param mixed $value + */ +function spaced($value): string +{ + if (!is_array($value)) { + return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); + } + if ($value === [] || array_keys($value) === range(0, count($value) - 1)) { + return '[' . implode(', ', array_map('spaced', $value)) . ']'; + } + $pairs = []; + foreach ($value as $key => $entry) { + $pairs[] = spaced((string)$key) . ': ' . spaced($entry); + } + return '{' . implode(', ', $pairs) . '}'; +} + +function show(string $label, array $request): void +{ + [$status, $body] = handle(json_encode($request, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION)); + echo " {$label}\n"; + echo " HTTP {$status} ", spaced($body), "\n"; +} + +/** A copy of `$request` with `$change` applied to it. */ +function broken(array $request, callable $change): array +{ + $change($request); + return $request; +} + +function section(string $title): void +{ + echo "\n", str_repeat('=', 78), "\n", $title, "\n", str_repeat('=', 78), "\n"; +} + +// -------------------------------------------------------------------------------------- +section('1. Refused before solving: one reason, one pointer, one message'); + +show('a valid order', $order); +show('quantity 0', + broken($order, static function (array &$r): void { $r['items'][0]['quantity'] = 0; })); +show('a negative width', + broken($order, static function (array &$r): void { $r['items'][1]['dimensions']['width'] = '-160'; })); +show('a missing height', + broken($order, static function (array &$r): void { unset($r['items'][1]['dimensions']['height']); })); +show('a float where a measure belongs', + broken($order, static function (array &$r): void { $r['items'][1]['dimensions']['width'] = 160.5; })); +show('the same container id twice', + broken($order, static function (array &$r): void { $r['containers'][] = $r['containers'][0]; })); +show('an unknown solver profile', + broken($order, static function (array &$r): void { $r['configuration']['solver_profile'] = 'turbo'; })); +echo ' + A float is refused as a measure on purpose: binary floating point cannot hold most + decimal lengths exactly, and every length here is exact. Send "160.5" as a string. + When several values are wrong, the first is reported, in a fixed order every + engine shares: units, configuration, items, containers, fixed placements. +'; + +// -------------------------------------------------------------------------------------- +section('2. Items already in place that cannot be there'); + +// Turned (`WLH`: its width along the box's length) so the mugs still fit beside it. +$onBoard = ['item_type' => 'teapot', 'container_type' => 'box', 'orientation' => 'WLH', + 'position' => ['x' => '0', 'y' => '0', 'z' => '0']]; +show('a teapot already in the box, packed around', + broken($order, static function (array &$r) use ($onBoard): void { $r['fixed_placements'] = [$onBoard]; })); +show('a teapot recorded at x = 200 mm, hanging out of a 300 mm box', + broken($order, static function (array &$r) use ($onBoard): void { + $r['fixed_placements'] = [array_merge($onBoard, ['position' => ['x' => '200']])]; + })); +show('a mug and the teapot recorded in the same place', + broken($order, static function (array &$r) use ($onBoard): void { + $r['fixed_placements'] = [$onBoard, ['item_type' => 'mug', 'container_type' => 'box', 'orientation' => 'LWH']]; + })); +show('an orientation code that does not exist', + broken($order, static function (array &$r) use ($onBoard): void { + $r['fixed_placements'] = [array_merge($onBoard, ['orientation' => 'XYZ'])]; + })); +echo ' + `cannot_hold` means the fixed set is well formed but is not a valid packing on its + own, and `field` is the whole list. `malformed` points at the one bad value. +'; + +// -------------------------------------------------------------------------------------- +section('3. Not an error: a valid order that does not fit'); + +show('a teapot too tall for any box', + broken($order, static function (array &$r): void { $r['items'][1]['dimensions']['height'] = '450'; })); +echo ' + The caller asked a fair question and got an answer: the rest of the order is + packed, and `unpacked_items` says what is not and why. Retrying it will not help, + and neither will treating it as a 4xx. +'; + +// -------------------------------------------------------------------------------------- +section('4. Two refusals that do not carry a pointer'); + +foreach ([ + 'an unknown objective' => static function (array &$r): void { $r['configuration']['objective'] = 'cheapest'; }, + 'an unknown door' => static function (array &$r): void { $r['containers'][0]['access_directions'] = ['rear']; }, +] as $label => $change) { + try { + ArrayCodec::pack(broken($order, $change)); + } catch (InvalidRequestException $error) { + printf(" %s: InvalidRequestException, reason %s, field \"%s\": %s\n", + $label, $error->reason(), $error->field(), substr($error->getMessage(), 0, 50)); + } catch (InvalidArgumentException $error) { + $class = substr(strrchr(get_class($error), '\\') ?: get_class($error), 1); + printf(" %s: %s: %s\n", $label, $class, substr($error->getMessage(), 0, 70)); + } +} +echo ' + Both are `InvalidArgumentException`s, so a handler that ends with + `catch (InvalidArgumentException $e)` still turns them into a 422 -- but neither + has a field to highlight. The objective is refused by the objective registry with + a message only; the door reaches the request error with reason `invalid_value` and + an empty pointer, which means the request as a whole. +'; diff --git a/examples/execution.php b/examples/execution.php index f85d8b0..3b6920e 100644 --- a/examples/execution.php +++ b/examples/execution.php @@ -34,7 +34,7 @@ 'units' => ['length' => 'mm'], 'configuration' => [ 'objective' => 'default', - 'profile' => 'balanced', + 'solver_profile' => 'balanced', 'seed' => 42, // A safety fuse, not a target -- nothing in this scene comes close to it. 'time_limit_ms' => 60000, diff --git a/examples/extensions.php b/examples/extensions.php new file mode 100644 index 0000000..d661eed --- /dev/null +++ b/examples/extensions.php @@ -0,0 +1,204 @@ +tag, $context->item->item->tags, true)) { + return ConstraintResult::allow(); + } + // `Point` carries raw tick counts, not `Length` objects: it is built once per + // candidate and this is the hot path. + if ($context->point->z <= $this->limit->ticks) { + return ConstraintResult::allow(); + } + // The code is yours. It travels into the unpacked reason, so make it something a + // person reading a failed order will understand. + return ConstraintResult::reject( + 'fragile_too_high', + sprintf('base at %smm is above the %smm limit for %s items', + (new Length($context->point->z))->decimal('mm'), $this->limit->decimal('mm'), $this->tag) + ); + } +} + +// The footprint is only as wide as one crate, so the column has to grow upwards and the +// rule has something to refuse. A rule that never fires teaches nothing. +$items = [ + Item::create('crate', Dimensions::mm('400', '400', '300'), '12 kg', quantity: 3), + Item::create('vase', Dimensions::mm('400', '400', '200'), '2 kg', 2, $anyOrientation, tags: ['fragile']), +]; +$column = [Container::create('column', Dimensions::mm('400', '400', '1300'), maxPayload: '200 kg', quantity: 1)]; + +$vaseHeights = static function (array $containers): array { + $heights = []; + foreach ($containers as $container) { + foreach ($container->placements as $placement) { + if ($placement->instance->item->id === 'vase') { + $heights[] = (new Length($placement->position->z))->decimal('mm'); + } + } + } + sort($heights, SORT_NUMERIC); + return $heights; +}; + +$unrestricted = (new Packer(config()))->pack($items, $column); +$heights = $vaseHeights($unrestricted->containers); +echo 'without the rule, the highest vase sits at ', end($heights), " mm\n"; + +$restricted = (new Packer(config(), new ExtensionRegistry([new FragileHeightLimit(Length::mm('400'))])))->pack($items, $column); +printf("with a 400mm limit, vases sit at %s and %d were left behind\n", + json_encode($vaseHeights($restricted->containers)), count($restricted->unpacked)); + +// ----------------------------------------------------------------------------------- +// A custom solution scorer. The six built-in objectives rank by space, packaging cost, +// billed weight, landed money, stack height or value. None of them cares whether the +// weight is spread *evenly across the containers* -- which is what a two-person lift or a +// van's balance depends on, and is nowhere in the request. +// +// Return exact integers, lower is better, compared left to right. Keep the unpacked count +// first unless you really mean "leave items behind to score better", and fall back to the +// default vector for everything your rule does not care about -- otherwise two equally +// balanced solutions are ranked by luck. +// ----------------------------------------------------------------------------------- +final class EvenlyLoadedContainers implements SolutionScorer +{ + public function score(RawSolution $solution): ObjectiveScore + { + $loads = array_map(static fn($container): int => $container->payloadWeight()->ticks, $solution->containers); + $spread = $loads === [] ? 0 : max($loads) - min($loads); + $default = (new DefaultSolutionScorer())->score($solution)->components; + return new ObjectiveScore(array_merge([count($solution->unpacked), $spread], array_slice($default, 1))); + } +} + +// Two heavy items and two light ones, two boxes, two slots each. Every arrangement uses the +// same volume, so the built-in objectives are indifferent -- and put both anvils in one box. +$lopsided = [ + Item::create('anvil', Dimensions::mm('200', '200', '200'), '10 kg', quantity: 2), + Item::create('pillow', Dimensions::mm('200', '200', '200'), '1 kg', quantity: 2), +]; +$twoBoxes = [Container::create('box', Dimensions::mm('400', '200', '200'), maxPayload: '50 kg', quantity: 2)]; + +echo "\n"; +foreach (['default' => null, 'evenly loaded' => new EvenlyLoadedContainers()] as $label => $scorer) { + $result = (new Packer(config(), new ExtensionRegistry(), $scorer))->pack($lopsided, $twoBoxes); + $contents = []; + $weights = []; + foreach ($result->containers as $container) { + $ids = array_map(static fn($placement): string => $placement->instance->item->id, $container->placements); + sort($ids); + $contents[] = $ids; + $weights[] = $container->payloadWeight()->decimal('kg') . ' kg'; + } + printf("%15s: %s -> %s\n", $label, json_encode($contents), json_encode($weights)); +} + +// ----------------------------------------------------------------------------------- +// A custom container selector. When several container types are offered, the search asks +// the selector which one to open next, comparing each type's best single-container fill. +// The default opens whichever holds the most items, then the cheapest. This one keeps +// "most items" first -- drop it and the search happily opens box after box that each +// hold one item -- and then prefers the *smallest* box, however much it costs, because +// shipping air costs more than cardboard. +// ----------------------------------------------------------------------------------- +final class SmallestBoxFirst implements ContainerSelector +{ + public function score(Container $container, SingleContainerSolution $solution): array + { + $default = (new DefaultContainerSelector())->score($container, $solution); + // Whole cubic millimetres are plenty to rank boxes by and stay inside an int; + // the exact volume in ticks does not. + $size = $container->innerDimensions; + $cubicMm = intdiv($size->length->ticks, Length::TICKS_PER_MM) + * intdiv($size->width->ticks, Length::TICKS_PER_MM) + * intdiv($size->height->ticks, Length::TICKS_PER_MM); + return [$default[0], $cubicMm, $container->id]; + } +} + +$books = [Item::create('book', Dimensions::mm('210', '140', '30'), '450 g', quantity: 4)]; +$cartons = [ + Container::create('mailer', Dimensions::mm('220', '150', '130'), costMinor: 190), + Container::create('carton', Dimensions::mm('400', '300', '250'), costMinor: 120), +]; + +echo "\n"; +foreach (['default' => null, 'smallest box first' => new SmallestBoxFirst()] as $label => $selector) { + $registry = new ExtensionRegistry([], [], [], null, $selector); + $result = (new Packer(config(), $registry))->pack($books, $cartons); + $opened = array_map(static fn($container): string => $container->container->id, $result->containers); + printf("%18s: opens %s, packaging cost %d\n", $label, json_encode($opened), + array_sum(array_map(static fn($container): int => $container->container->costMinor, $result->containers))); +} + +echo "\n"; +echo "None of these rules exists in the JSON request. Hand the same request to another\n"; +echo "Packvium engine and you get the unrestricted answer -- which is exactly why a rule\n"; +echo "everyone must obey belongs in the request as data, not in a class.\n"; diff --git a/examples/fixed_placements.php b/examples/fixed_placements.php new file mode 100644 index 0000000..a26a000 --- /dev/null +++ b/examples/fixed_placements.php @@ -0,0 +1,129 @@ + 'returns-pallet', 'container_type' => 'trailer', 'orientation' => $orientation, + 'position' => ['x' => $x, 'y' => $y, 'z' => '0']]; +} + +$request = [ + 'units' => ['length' => 'mm'], + // Counted work decides the answer, not the clock (see reproducibility.php); the time + // limit is a fuse far above what this solve needs. + 'configuration' => ['time_limit_ms' => 60000, 'effort_budget' => ['max_restarts' => 8]], + 'items' => [ + ['id' => 'returns-pallet', 'quantity' => 4, 'weight' => '350 kg', 'keep_upright' => true, 'stackable' => false, + 'dimensions' => ['length' => '1200', 'width' => '800', 'height' => '1500']], + ['id' => 'store-pallet', 'quantity' => 14, 'weight' => '500 kg', 'keep_upright' => true, + 'dimensions' => ['length' => '1200', 'width' => '800', 'height' => '1100']], + ], + 'containers' => [['id' => 'trailer', 'max_payload' => '9000 kg', + 'inner_dimensions' => ['length' => '7200', 'width' => '2400', 'height' => '2400']]], + // Three across the nose, and one turned behind them. + 'fixed_placements' => [onBoard('0', '0'), onBoard('0', '800'), onBoard('0', '1600'), + onBoard('1200', '0', 'WLH')], +]; + +/** Solve a copy of the request with `$change` applied to it. */ +function solve(array $request, ?callable $change = null): array +{ + if ($change !== null) { + $change($request); + } + return ArrayCodec::pack($request); +} + +function show(array $result): void +{ + $trailer = $result['containers'][0]; + $fixed = array_values(array_filter($trailer['placements'], static fn(array $p): bool => !empty($p['fixed']))); + $added = array_values(array_filter($trailer['placements'], static fn(array $p): bool => empty($p['fixed']))); + $payload = (new Weight($trailer['payload_weight']['ticks']))->decimal('kg', 1); + printf(" status %s, payload %s kg, left out %d\n", $result['status'], $payload, count($result['unpacked_items'])); + echo ' already on board, unmoved: ', implode(', ', array_column($fixed, 'item_id')), "\n"; + printf(" added: %d store pallets\n", count($added)); + foreach ($added as $placement) { + if ($placement['position']['z']['value'] !== '0') { + printf(" %s is stacked, at z = %s mm\n", $placement['item_id'], $placement['position']['z']['value']); + } + } +} + +function section(string $title): void +{ + echo "\n", str_repeat('=', 78), "\n", $title, "\n", str_repeat('=', 78), "\n"; +} + +// -------------------------------------------------------------------------------------- +section('1. Packed around the pallets already on board'); + +show(solve($request)); +echo ' + The returns pallets keep their ids, positions and orientations. They took the + first four instances of `returns-pallet`, so none are left for the engine to + place; ask for five and it would place one more. +'; + +// -------------------------------------------------------------------------------------- +section('2. One pallet was left in the middle of the floor'); + +show(solve($request, static function (array &$r): void { + $r['fixed_placements'][3]['position'] = ['x' => '1200', 'y' => '400', 'z' => '0']; +})); +echo ' + The fourth returns pallet stands 400 mm off the side wall, and no pallet fits in + the strip it leaves. The plan still takes all fourteen store pallets, but it has + to put one on top of another to do it. Whether that is acceptable is + your call; the plan shows you the price of not moving that pallet. +'; + +// -------------------------------------------------------------------------------------- +section('3. What is on board cannot be where the record says'); + +foreach ([ + 'two pallets recorded in the same place' => static function (array &$r): void { + $r['fixed_placements'][3]['position'] = ['x' => '600', 'y' => '0', 'z' => '0']; + }, + 'a 1000 kg trailer limit, already exceeded by the returns' => static function (array &$r): void { + $r['containers'][0]['max_payload'] = '1000 kg'; + }, +] as $label => $change) { + try { + solve($request, $change); + } catch (FixedPlacementException $refusal) { + echo " {$label}:\n"; + echo " {$refusal->reason()}, {$refusal->field()}: {$refusal->getMessage()}\n"; + } +} +echo ' + Nothing is solved when the starting point is impossible: a plan built on a + collision or an overweight trailer would be wrong before the first pallet moved. + `cannot_hold` names the fixed set as a whole; the detail says what is wrong. +'; diff --git a/examples/limits.php b/examples/limits.php new file mode 100644 index 0000000..49b3f79 --- /dev/null +++ b/examples/limits.php @@ -0,0 +1,153 @@ + ['length' => 'mm'], + // Counted work decides the answer, not the clock (see reproducibility.php); the time + // limit is a fuse far above what this solve needs. + 'configuration' => ['time_limit_ms' => 60000, 'effort_budget' => ['max_restarts' => 8]], + 'items' => [ + ['id' => 'frozen-tote', 'quantity' => 3, 'weight' => '15 kg', + 'dimensions' => ['length' => '600', 'width' => '400', 'height' => '300'], + 'eligible_container_tags' => ['refrigerated']], + ['id' => 'lithium-battery', 'quantity' => 3, 'weight' => '12 kg', + 'dimensions' => ['length' => '400', 'width' => '300', 'height' => '250'], + 'tags' => ['dangerous_goods']], + ['id' => 'parcel', 'quantity' => 24, 'weight' => '8 kg', + 'dimensions' => ['length' => '500', 'width' => '400', 'height' => '400']], + ], + 'containers' => [ + ['id' => 'cargo-bike', 'quantity' => 3, 'cost_minor' => 900, 'max_items' => 4, 'max_payload' => '100 kg', + 'inner_dimensions' => ['length' => '1000', 'width' => '800', 'height' => '900']], + ['id' => 'reefer-van', 'quantity' => 1, 'cost_minor' => 4000, + 'inner_dimensions' => ['length' => '1800', 'width' => '1400', 'height' => '1200'], + 'tags' => ['refrigerated'], + 'tag_limits' => ['dangerous_goods' => 1], + 'obstacles' => [ + ['id' => 'fridge-unit', 'origin' => ['x' => '0', 'y' => '0', 'z' => '800'], + 'dimensions' => ['length' => '400', 'width' => '1400', 'height' => '400']], + ['id' => 'wheel-arches', 'origin' => ['x' => '700', 'y' => '0', 'z' => '0'], + 'dimensions' => ['length' => '800', 'width' => '200', 'height' => '350'], + 'additional_boxes' => [['origin' => ['x' => '700', 'y' => '1200', 'z' => '0'], + 'dimensions' => ['length' => '800', 'width' => '200', 'height' => '350']]]], + ]], + ], +]; + +/** Solve a copy of the request with `$change` applied to it. */ +function solve(array $request, ?callable $change = null): array +{ + if ($change !== null) { + $change($request); + } + return ArrayCodec::pack($request); +} + +function show(array $result): void +{ + echo " status: {$result['status']}\n"; + foreach ($result['containers'] as $container) { + $contents = array_count_values(array_column($container['placements'], 'item_type')); + ksort($contents); + $listed = []; + foreach ($contents as $name => $count) { + $listed[] = "{$count} {$name}"; + } + printf(" %-14s %s\n", $container['id'], implode(', ', $listed)); + } + // One line per kind of refusal: a reader needs "five parcels, no room", not five lines. + $refusals = []; + foreach ($result['unpacked_items'] as $unpacked) { + $key = implode("\0", [$unpacked['item_type'], $unpacked['reason'], $unpacked['proof']['level']]); + $refusals[$key] = ($refusals[$key] ?? 0) + 1; + } + ksort($refusals); + foreach ($refusals as $key => $number) { + [$name, $reason, $level] = explode("\0", $key); + echo " left out: {$number} {$name}, {$reason} ({$level})\n"; + } +} + +function placedCount(array $result, string $containerId, string $itemType): int +{ + $total = 0; + foreach ($result['containers'] as $container) { + if ($container['id'] !== $containerId) { + continue; + } + $total += count(array_keys(array_column($container['placements'], 'item_type'), $itemType, true)); + } + return $total; +} + +function section(string $title): void +{ + echo "\n", str_repeat('=', 78), "\n", $title, "\n", str_repeat('=', 78), "\n"; +} + +// -------------------------------------------------------------------------------------- +section('1. The plan'); + +$plan = solve($request); +show($plan); +echo ' + All three frozen totes are in the van, because nothing else is refrigerated. Only + one battery rides in the van; the other two go by bike. The bike takes four items, + its `max_items`, although there is room and payload for more. +'; + +// -------------------------------------------------------------------------------------- +section('2. What the obstacles cost'); + +$openVan = solve($request, static function (array &$r): void { unset($r['containers'][1]['obstacles']); }); +printf(" parcels in the van with the fridge unit and arches: %d\n", placedCount($plan, 'reefer-van#1', 'parcel')); +printf(" parcels in the van if it were an empty box: %d\n", placedCount($openVan, 'reefer-van#1', 'parcel')); +echo ' + An obstacle is exact space, not a hint. Model what is really there, or the plan + will put a parcel where the wheel arch is. +'; + +// -------------------------------------------------------------------------------------- +section('3. `max_containers`: the plan may use one vehicle'); + +show(solve($request, static function (array &$r): void { $r['configuration']['max_containers'] = 1; })); +echo ' + The cap is honoured, and what does not fit is listed rather than silently sent in + a vehicle you did not allow. The reason is `observed`, not `proven`: the search + found no room for these, which is not a claim that no arrangement has room. +'; + +// -------------------------------------------------------------------------------------- +section('4. `eligible_container_tags`: the van is off the road today'); + +show(solve($request, static function (array &$r): void { array_splice($r['containers'], 1, 1); })); +echo ' + The frozen totes cannot go anywhere, and their reason is `proven`: no container in + the request carries the tag they need, which is a fact about the request rather + than about how far the search got. The rest is `observed`: three bikes of four + items each were all the request offered, and the search ran out of them. +'; diff --git a/examples/objectives.php b/examples/objectives.php index 38128d1..267d1c8 100644 --- a/examples/objectives.php +++ b/examples/objectives.php @@ -14,7 +14,8 @@ * * The score is always a lexicographic vector of exact integers, never a float, and its * first key is always the unpacked count: no objective will ever leave an item behind to - * save money. See docs/OBJECTIVE.md for the full key ordering. + * save money. Every line below prints the whole vector, so each objective's key order + * is on the page. */ declare(strict_types=1); diff --git a/examples/reproducibility.php b/examples/reproducibility.php new file mode 100644 index 0000000..13408ea --- /dev/null +++ b/examples/reproducibility.php @@ -0,0 +1,155 @@ +pack($items, $boxes); +} + +/** + * Whether an artifact of this result could promise an exact replay: only when no clock + * stopped the search. It is the rule `Packvium\Artifacts\OperationalArtifact` applies. + */ +function replayLevel(PackingResult $result): string +{ + return $result->toArray()['algorithm']['time_limit_reached'] ? 'not_guaranteed' : 'exact'; +} + +function describe(PackingResult $result): string +{ + $opened = implode(',', array_map(static fn($packed): string => $packed->container->id, $result->containers)); + return sprintf('%-6s left out %2d termination %-12s replay %s', + $opened, count($result->unpacked), $result->termination->code, replayLevel($result)); +} + +function section(string $title): void +{ + echo "\n", str_repeat('=', 78), "\n", $title, "\n", str_repeat('=', 78), "\n"; +} + +// -------------------------------------------------------------------------------------- +section('1. A clock-limited search answers differently on different machines'); + +// The same 100 ms limit on four simulated hosts. +foreach (['fast host' => 10000, 'busy host' => 50000, 'slower host' => 200000, 'overloaded' => 1000000] as $label => $step) { + printf(" %-12s %s\n", $label, describe(solveOn(config(100), $step, $items, $boxes))); +} +echo ' + Same request, four answers. Each is a valid packing of what the search reached + before the clock ran out, and the items it never reached are listed as left out, + but none can be reproduced: run it again on a different day and you get whichever + one the machine allows. `termination` says + `time_limit`, and the replay level refuses to promise a replay. +'; + +// -------------------------------------------------------------------------------------- +section('2. An effort budget answers the same everywhere'); + +$enough = new EffortBudget(5000); +foreach (['fast host' => 10000, 'slower host' => 200000, 'overloaded' => 1000000] as $label => $step) { + printf(" %-12s %s\n", $label, describe(solveOn(config(FUSE_MS, $enough), $step, $items, $boxes))); +} +echo ' + The budget is large enough that the search finishes, so `termination` is + `complete`, and it would stop at the same count on any machine if it were not. +'; + +// -------------------------------------------------------------------------------------- +section('3. A budget that is too small is still reproducible, and says so'); + +$tooSmall = new EffortBudget(500); +foreach (['fast host' => 10000, 'overloaded' => 1000000] as $label => $step) { + printf(" %-12s %s\n", $label, describe(solveOn(config(FUSE_MS, $tooSmall), $step, $items, $boxes))); +} +echo ' + The search stopped early and left items out -- `termination` is `effort_limit`, + not `complete` -- but it stopped at the same point on both hosts, so the answer + can be replayed exactly. Raise the budget until the answer is good enough, then + keep it fixed. +'; + +// -------------------------------------------------------------------------------------- +section('4. Reading `termination`'); + +$termination = (new Packer(config(FUSE_MS, new EffortBudget(null, null, null, 4)))) + ->pack($items, $boxes)->toArray()['termination']; +echo " code: {$termination['code']}\n"; +foreach ($termination['starts'] as $start) { + echo rtrim(sprintf(' %-28s completed=%-5s%s', $start['id'], $start['completed'] ? 'true' : 'false', + $start['selected'] ? ' <- selected' : '')), "\n"; +} +echo ' + `maxRestarts` caps how many portfolio starts run -- here four -- which bounds the + work of a large request as well as fixing it. `code` describes the selected start: + a losing start that was cut short leaves it `complete`, and shows up in its own + record and in `all_required_starts_completed` instead. Over JSON, the same budget + is `configuration.effort_budget`. +'; diff --git a/examples/serialization.php b/examples/serialization.php index 801ca44..e47e40b 100644 --- a/examples/serialization.php +++ b/examples/serialization.php @@ -16,10 +16,9 @@ * * - lengths and weights travel as *decimal strings*, never as floats, so "12 3/8 in" * survives the trip intact (see units.php for why that matters); - * - a field this engine has deliberately not implemented is refused by name, but a key - * the parser simply does not recognise is ignored. The last section shows both -- the - * refusal through the guard's own test hook, because this engine has caught up and now - * refuses nothing of its own. + * - a field this engine has deliberately not implemented yet is refused by name, never + * quietly ignored -- but a key the parser does not recognise on an item *is* ignored. + * The difference matters, and the last section shows both. */ declare(strict_types=1); @@ -39,16 +38,16 @@ 'dimensional_weight_divisor' => 5000, 'dimensional_weight_length_unit' => 'cm', 'dimensional_weight_weight_unit' => 'kg', - 'profile' => 'balanced', + 'solver_profile' => 'balanced', 'seed' => 42, - 'top_k' => 2, - // An example must not change answer merely because the machine is busy. `top_k` - // asks the portfolio for runners-up, and how many it finds is bounded by the - // *wall clock* unless a budget says otherwise -- so without this line two runs on - // a loaded host can print a different number of alternatives, which is - // exactly. gave every conformance fixture an explicit budget for this - // reason; the examples were not part of that sweep. The value is a safety fuse, - // not a target: nothing here comes close to it. + // Up to two complete answers: the winner and one runner-up. + 'alternatives' => 2, + // A wall clock is a fact about the machine, not about the request: how many + // runners-up a clock-bounded search finds depends on how busy the host is. The + // effort budget counts work instead, so it stops at the same point on every + // machine, and the time limit is only a safety fuse far above what this needs. + // reproducibility.php shows what happens when the clock does decide. + 'effort_budget' => ['max_search_nodes' => 20000], 'time_limit_ms' => 60000, ], 'items' => [ @@ -103,25 +102,31 @@ echo substr(json_encode($result['containers'][0]['placements'][0], JSON_PRETTY_PRINT), 0, 320), " ...\n"; // ----------------------------------------------------------------------------------- -// `top_k` asks for runners-up: real alternative arrangements, already scored and already -// validated. Two of them can share a score and still differ in geometry, so compare -// placements rather than scores when showing a human a choice. +// `alternatives` asks for runners-up. They are real alternative arrangements, already +// scored and already validated -- useful when you want to show a human a choice rather +// than a verdict. The count includes the winner, so `2` means at most one runner-up, and +// an empty list is normal: a search that found nothing else worth ranking says so. // ----------------------------------------------------------------------------------- +// Two alternatives can share a score and still be different arrangements -- equal cost, +// different geometry. Compare their placements, not their scores, when showing a choice. echo "\nalternatives: ", count($result['alternatives'] ?? []), "\n"; foreach ($result['alternatives'] ?? [] as $alternative) { - $first = $alternative['containers'][0]['placements'][0]; - printf(" score %s first placement %s at x=%s\n", - json_encode($alternative['score']), $first['item_id'], $first['position']['x']['value']); + $positions = []; + foreach ($alternative['containers'] as $container) { + foreach ($container['placements'] as $placement) { + $positions[] = [$placement['item_id'], $placement['position']['x']['value']]; + } + } + printf(" score %s first two placements %s\n", + json_encode($alternative['score']), json_encode(array_slice($positions, 0, 2))); } // ----------------------------------------------------------------------------------- // What is refused, and what is not. The two look alike from the outside. // -// A key the parser does not recognise is *ignored*. Misspell `keep_upright` and you get -// a silently unrotated mug, not an error -- the strictness lives in the request JSON -// Schema, which sets `additionalProperties: false` and ships with the project rather -// than with this package. Validate against it if you want typo protection. -// See docs/SERIALIZATION.md. +// A key the parser does not recognise on an item is *ignored*. Misspell `keep_upright` +// and you get a silently rotatable mug, not an error. If typos in item fields matter to +// you, check keys against the field list in docs/PUBLIC-API.md before calling the engine. // ----------------------------------------------------------------------------------- $typo = $request; $typo['items'][1]['keep_uprght'] = true; @@ -139,33 +144,25 @@ printf("unknown objective: %s\n", substr($refusal->getMessage(), 0, 100)); } -// And a field this engine names as not-yet-implemented is refused explicitly, so a -// request written for a newer engine fails loudly instead of being half-honoured. The -// list below is the engine's own constant, and it is empty: implemented -// `convex_hull` and `compressible`, the last reserved names left on it, so this engine -// now serves every field and every `shape_type` value the schema defines. +// And a field the schema reserves but this engine has not implemented yet is refused by +// name, so a request written for a newer engine fails loudly instead of being +// half-honoured. The list is the engine's own constant. $refused = array_filter(ArrayCodec::UNSUPPORTED_FIELDS); printf("fields this engine refuses by name: %s\n", $refused === [] ? 'none' : json_encode($refused)); -// Caught up is the right state and a poor demonstration, so the guard takes its lists as -// parameters -- the same hook its own tests use. Passing the value retired shows -// the refusal a caller still gets from an engine that is behind, and shows it naming the -// *value* rather than the field: `rigid_cuboid` is the default and is implemented, so a -// caller who spells the default out must be served, not refused. -$behind = $request; -$behind['items'][0]['shape_type'] = 'convex_hull'; +$ahead = $request; +$ahead['containers'][0]['pallet_overhang_limit'] = ['length' => '50', 'width' => '50']; try { - ArrayCodec::rejectUnsupported($behind, null, ['convex_hull']); + ArrayCodec::pack($ahead); } catch (UnsupportedFeatureException $refusal) { - printf(" what one looks like, from an engine that is not: %s\n", - substr($refusal->getMessage(), 0, 110)); + printf(" sending one anyway: %s\n", substr($refusal->getMessage(), 0, 100)); } // ----------------------------------------------------------------------------------- // The same document drives the command line, which reads a request on stdin and writes -// a result on stdout -- which is how the cross-language conformance harness talks to -// every engine: +// a result on stdout -- which is how the engines are checked against each other, and how +// you would call this from a language with no binding yet: // // echo '' | php bin/packvium // ----------------------------------------------------------------------------------- diff --git a/examples/trucking.php b/examples/trucking.php new file mode 100644 index 0000000..5579ad3 --- /dev/null +++ b/examples/trucking.php @@ -0,0 +1,230 @@ + */ +function manifest(bool $withRoute = true): array +{ + $stop = static fn(int $index): ?int => $withRoute ? $index : null; + // Every orientation is offered and `keepUpright` narrows it. Naming the list keeps the + // later named arguments valid for the PHP 7.3 build of this package. + $any = [Rotation::LWH, Rotation::LHW, Rotation::WLH, Rotation::WHL, Rotation::HLW, Rotation::HWL]; + return [ + Item::create('bakery-rack', Dimensions::mm('800', '600', '1700'), '90 kg', 2, $any, + keepUpright: true, stopIndex: $stop(0)), + Item::create('drinks-pallet', Dimensions::mm('1200', '800', '1100'), '420 kg', 1, $any, + keepUpright: true, mustBeOnFloor: true, stopIndex: $stop(1)), + Item::create('parcel', Dimensions::mm('600', '400', '400'), '18 kg', 6, $any, stopIndex: $stop(2)), + Item::create('dry-goods-pallet', Dimensions::mm('1200', '800', '1400'), '260 kg', 1, $any, + keepUpright: true, stopIndex: $stop(2)), + ]; +} + +// The effort budget decides where the search stops, so every run gives this same plan; +// the time limit is only a fuse far above what this needs (see reproducibility.php). +// `maxContainers: 1` because there is one van: anything that does not fit is reported, +// not sent in a second vehicle. +$config = new PackingConfig( + SolverProfile::Balanced, timeLimitMs: 60000, maxContainers: 1, + effortBudget: new EffortBudget(null, null, null, 8), +); + +function section(string $title): void +{ + echo "\n", str_repeat('=', 78), "\n", $title, "\n", str_repeat('=', 78), "\n"; +} + +function millimetres(int $ticks): string +{ + return (new Length($ticks))->decimal('mm', 1); +} + +/** + * The exact axle reactions from the result document, shown in kilograms. + * + * They arrive as a numerator over a shared denominator so no engine has to round them; + * rounding happens here, for display only. The numerator is a decimal string because + * weight ticks times length ticks outgrows a 64-bit integer, so it is divided digit by + * digit, then rounded half to even like every other value Packvium renders. + * + * @return array{0:string,1:string} + */ +function axleLoadsKg(PackingResult $result): array +{ + $reactions = $result->toArray()['containers'][0]['axle_reactions']; + $denominator = (int)$reactions['denominator']; + $kilograms = static function (string $numerator) use ($denominator): string { + $quotient = 0; + $remainder = 0; + foreach (str_split($numerator) as $digit) { + $remainder = $remainder * 10 + (int)$digit; + $quotient = $quotient * 10 + intdiv($remainder, $denominator); + $remainder %= $denominator; + } + $twice = 2 * $remainder; + if ($twice > $denominator || ($twice === $denominator && $quotient % 2 === 1)) { + $quotient++; + } + return (new Weight($quotient))->decimal('kg', 1); + }; + return [$kilograms($reactions['front_numerator']), $kilograms($reactions['rear_numerator'])]; +} + +// -------------------------------------------------------------------------------------- +section("1. The plan: nothing for a later stop stands in an earlier stop's way out"); + +$result = (new Packer($config))->pack(manifest(), [van($frontAxle, $rearAxle)]); +$packed = $result->containers[0]; +$placements = $packed->placements; +printf(" status: %s, left behind: %d\n", $result->status->value, count($result->unpacked)); +$byPosition = $placements; +usort($byPosition, static fn($a, $b): int => [$a->position->x, $a->position->y, $a->position->z] + <=> [$b->position->x, $b->position->y, $b->position->z]); +foreach ($byPosition as $placement) { + printf(" stop %d %-20s x=%6s mm y=%6s mm\n", $placement->instance->item->stopIndex, + $placement->instance->id(), millimetres($placement->position->x), millimetres($placement->position->y)); +} +echo " + x is the distance from the bulkhead, so the rear doors are at x = 4200 mm. The + bakery racks sit at the front, but the aisle beside them runs clear to the doors: + the rule is that nothing due later blocks every way out, not that stop 0 is last in. +"; + +// -------------------------------------------------------------------------------------- +section('2. Axle loads against their ratings'); + +[$front, $rear] = axleLoadsKg($result); +printf(" payload: %s kg of 1300 kg allowed\n", $packed->payloadWeight()->decimal('kg', 1)); +printf(" front axle: %s kg of %s kg\n", $front, $frontAxle->maxLoad->decimal('kg', 1)); +printf(" rear axle: %s kg of %s kg\n", $rear, $rearAxle->maxLoad->decimal('kg', 1)); + +$tightAxle = new Axle(Length::mm('600'), Weight::parse('1450 kg')); +$tight = (new Packer($config))->pack(manifest(), [van($tightAxle, $rearAxle)]); +echo "\n the same load with a 1450 kg front axle rating:\n"; +foreach ($tight->unpacked as $unpacked) { + printf(" left behind: %s, reason %s (%s)\n", $unpacked->instance->id(), $unpacked->reason, $unpacked->proof->level); +} +echo " + The axle rule refuses a placement rather than reporting an overload afterwards. + Note the reason: an item the axles cannot carry is reported as the generic + `no_feasible_placement`, not as an axle problem, so when a load comes up short on + a vehicle with axle ratings, check the reactions before shopping for a bigger van. +"; + +// -------------------------------------------------------------------------------------- +section('3. Unloading order along the route, and the loading order it implies'); + +$boxes = array_map(static fn($placement) => $placement->envelopeBox(), $placements); +$stops = array_map(static fn($placement): ?int => $placement->instance->item->stopIndex, $placements); +$inside = $packed->container->innerDimensions; + +$unloading = UnloadingDependencyGraph::safeRouteRemovalOrder($boxes, $stops, $inside, REAR_DOORS); +foreach ($unloading as $step => $index) { + printf(" off %2d: stop %d %s\n", $step + 1, $stops[$index], $placements[$index]->instance->id()); +} + +// Loading is unloading played backwards: whatever comes off last goes on first. +// `replayLoadingOrder` checks that independently -- every item supported by what is +// already in, and each one able to travel in through the doors -- and throws if not. +$loading = array_reverse($unloading); +LoadingDependencyGraph::replayLoadingOrder($boxes, $inside, $loading, REAR_DOORS); +echo "\n load in this order: ", + implode(', ', array_map(static fn(int $index): string => $placements[$index]->instance->id(), $loading)), "\n"; + +// -------------------------------------------------------------------------------------- +section('4. What the driver can reach on opening the doors at stop 0'); + +foreach (UnloadingDependencyGraph::placementReachability($boxes, $inside, $stops, REAR_DOORS) as $reach) { + if ($stops[$reach->index] !== 0) { + continue; + } + $blockers = array_map( + static fn(int $index): string => $placements[$index]->instance->id(), + array_keys($reach->blockedByNeighbors + $reach->blockedBySupport) + ); + sort($blockers); + printf(" %s: reachable=%s%s\n", $placements[$reach->index]->instance->id(), + $reach->reachable ? 'true' : 'false', $blockers === [] ? '' : ', behind ' . implode(', ', $blockers)); +} +echo " + Reachability is a snapshot, not a plan: one rack is behind the other, which is + fine because both are for this stop and the first one comes off first. +"; + +// -------------------------------------------------------------------------------------- +section('5. The same goods without `stopIndex`'); + +$unrouted = (new Packer($config))->pack(manifest(false), [van($frontAxle, $rearAxle)]); +$unroutedPlacements = $unrouted->containers[0]->placements; +$due = ['bakery-rack' => 0, 'drinks-pallet' => 1, 'parcel' => 2, 'dry-goods-pallet' => 2]; +try { + UnloadingDependencyGraph::safeRouteRemovalOrder( + array_map(static fn($placement) => $placement->envelopeBox(), $unroutedPlacements), + array_map(static fn($placement): int => $due[$placement->instance->item->id], $unroutedPlacements), + $inside, + REAR_DOORS + ); +} catch (RouteSequenceError $stuck) { + $names = array_map(static fn(int $index): string => $unroutedPlacements[$index]->instance->id(), $stuck->stuck); + sort($names); + printf(" status %s, every item packed -- and at stop %d the driver cannot get these out: %s\n", + $unrouted->status->value, $stuck->stop, implode(', ', $names)); +} +echo " + Without the route the plan is still a valid packing, and still within the axle + ratings; it just cannot be delivered in order. The route is only enforced when + you state it. +"; diff --git a/src-legacy/Algorithm/BeamPacker.php b/src-legacy/Algorithm/BeamPacker.php index 9c5b965..9a93cbc 100644 --- a/src-legacy/Algorithm/BeamPacker.php +++ b/src-legacy/Algorithm/BeamPacker.php @@ -52,6 +52,8 @@ public static function pack(Container $container,int $sequence,array $items,Pack $futureCount=count($future); foreach($expansions as [$state,$unplaced]){ $unplacedCount=count($unplaced)+$futureCount; + // More unplaced items loses on the key's first component; skip building a signature that cannot win. + if($unplacedCount>$incumbentKey[0])continue; $used=$state->usedVolume;$signature=[]; foreach($state->placements as $p){ $signature[]=$p->instance->id().'@'.$p->envelopeOrigin->x.','.$p->envelopeOrigin->y.','.$p->envelopeOrigin->z; @@ -63,7 +65,7 @@ public static function pack(Container $container,int $sequence,array $items,Pack if($candidateKey<$incumbentKey){$incumbent=[$state,array_merge($unplaced,$future)];$incumbentKey=$candidateKey;} } if($expansions===[])break; - $futureInfo=self::precomputeFuture($future,$container->maxPayload!==null); + $futureInfo=self::precomputeFuture($future,($nullsafeVariable1 = $container->maxPayload) ? $nullsafeVariable1->ticks : null); $beam=array_slice(StableSorter::sortBy($expansions,static function (array $node) use ($futureInfo): array { return self::nodeKeyPrecomputed($node,$futureInfo); }),0,$width); @@ -142,34 +144,46 @@ public static function extended(ContainerState $state,ItemInstance $item,Candida return $child; } - /** @param list $sortedCosts */ - private static function countWithVolumeCapacity(array $sortedCosts,string $capacity):int + /** @param list $cumulativeVolumes */ + private static function countWithVolumeCapacity(array $cumulativeVolumes,string $capacity):int { - $used='0';$count=0; - foreach($sortedCosts as $cost){ - $next=BigInt::add($used,$cost); - if(BigInt::compare($next,$capacity)>0)break; - $used=$next;$count++; - } - return $count; + return self::countWithin($cumulativeVolumes,static function (string $used) use ($capacity): bool { + return BigInt::compare($used,$capacity)<=0; + }); + } + + /** @param list $cumulativeWeights */ + private static function countWithWeightCapacity(array $cumulativeWeights,int $capacity):int + { + return self::countWithin($cumulativeWeights,static function (?int $used) use ($capacity): bool { + return $used!==null&&$used<=$capacity; + }); } - /** @param list $sortedWeights */ - private static function countWithWeightCapacity(array $sortedWeights,int $capacity):int + /** + * How many of the cheapest costs fit, read off their prefix sums. Costs are + * non-negative, so the sums never decrease and the count is one binary search: + * O(log f) per node instead of the O(f) walk. + * + * @template T + * @param list $cumulative + * @param callable(T):bool $fits + */ + private static function countWithin(array $cumulative,callable $fits):int { - $used=0;$count=0; - foreach($sortedWeights as $weight){ - if($used+$weight>$capacity)break; - $used+=$weight;$count++; + $low=0;$high=count($cumulative); + while($low<$high){ + $middle=intdiv($low+$high,2); + if($fits($cumulative[$middle]))$low=$middle+1;else $high=$middle; } - return $count; + return $low; } /** * @param list $future - * @return array{count:int,volumes:?list,weights:?list} + * @return array{count:int,volumes:?list,weights:?list} */ - private static function precomputeFuture(array $future,bool $hasMaxPayload):array + private static function precomputeFuture(array $future,?int $maxPayloadTicks):array { $count=count($future); if($count===0)return ['count'=>0,'volumes'=>null,'weights'=>null]; @@ -185,13 +199,23 @@ private static function precomputeFuture(array $future,bool $hasMaxPayload):arra usort($volumes,static function (string $a, string $b): int { return BigInt::compare($a,$b); }); + $used='0'; + foreach($volumes as $index=>$volume)$volumes[$index]=$used=BigInt::add($used,$volume); } $weights=null; - if($hasMaxPayload){ + if($maxPayloadTicks!==null){ $weights=array_map(static function (ItemInstance $item): int { return $item->weight()->ticks; },$future); sort($weights,SORT_NUMERIC); + // Null means a prefix exceeds the payload. Compare before adding so neither + // the sum nor payload + 1 can overflow a native int, even at PHP_INT_MAX. + $used=0; + foreach($weights as $index=>$weight){ + if($used===null||$weight>$maxPayloadTicks-$used){$used=null;} + else $used+=$weight; + $weights[$index]=$used; + } } return ['count'=>$count,'volumes'=>$volumes,'weights'=>$weights]; } diff --git a/src-legacy/Algorithm/HomogeneousBlockSolver.php b/src-legacy/Algorithm/HomogeneousBlockSolver.php index cf5b258..7d9e223 100644 --- a/src-legacy/Algorithm/HomogeneousBlockSolver.php +++ b/src-legacy/Algorithm/HomogeneousBlockSolver.php @@ -3,8 +3,9 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; +use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Constraint\PlacementConstraint; -use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Placement,Point}; +use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Placement,Point,ShapeType}; use Packvium\Extension\CandidateScorer; use Packvium\Support\BigInt; use Packvium\Unit\Length; @@ -34,7 +35,7 @@ public function orderInsensitive():bool{return true;} public function packOne(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):SingleContainerSolution { - if(!$this->supports($container,$items)) + if(!$this->supports($container,$items,$config)) return (new ExtremePointSolver($this->constraints))->packOne($container,$sequence,$items,$config,$stats,$deadline); $best=null;$reached=false; foreach(['count','volume'] as $mode){ @@ -47,16 +48,27 @@ public function packOne(Container $container,int $sequence,array $items,PackingC return new SingleContainerSolution($best->state,$best->unpacked,false,$reached); } - private function supports(Container $container,array $items):bool + private function supports(Container $container,array $items,PackingConfig $config):bool { + // A block set on a smaller one overhangs it, so a request that asks for support + // is left to the per-item search. + if($config->minimumSupportRatio>0)return false; if($this->constraints!==[]||$container->obstacles!==[]||$container->preloaded!==[]||$container->axles!==null||$container->tagLimits!==[]||$container->maxStackDensity!==null||$container->voidFillReserveRatio>0)return false; foreach($items as $instance){ $item=$instance->item; - if($item->group!==null||$item->tags!==[]||$item->incompatibleTags!==[]||$item->eligibleContainerTags!==[]||!$item->stackable||$item->mustBeOnFloor||$item->maxTopLoad!==null||$item->maxStackedItems!==null||$item->minimumSupportRatio!=0.0||!in_array($item->groundContactRule,[null,'free'],true)||$item->nestingHeight!==null||$item->stopIndex!==null)return false; + if($item->shapeType!==ShapeType::RIGID_CUBOID||$item->group!==null||$item->tags!==[]||$item->incompatibleTags!==[]||$item->eligibleContainerTags!==[]||!$item->stackable||$item->mustBeOnFloor||$item->maxTopLoad!==null||$item->maxStackedItems!==null||$item->minimumSupportRatio!=0.0||!in_array($item->groundContactRule,[null,'free'],true)||$item->nestingHeight!==null||$item->stopIndex!==null)return false; } return true; } + /** The share of a member's base that rests on the floor or on a box beneath it. */ + private static function memberSupport(ContainerState $state,ItemInstance $instance,Point $point,Dimensions $envelope):float + { + if($point->z===0)return 1.0; + $support=LoadSupportGraph::candidateView($state->placements,$instance,new AxisAlignedBox($point,$envelope)); + return $support->supportingArea/$envelope->baseAreaTicks(); + } + private function solutionKey(SingleContainerSolution $solution):array { $signature=[]; @@ -118,7 +130,10 @@ private function packMode(Container $container,int $sequence,array $items,Packin 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); - $state->addDirect(new Placement($chosen[$index++],$position,$best['rotation'],$best['physical'],$point,$best['envelope'],1.0)); + // 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)); diff --git a/src-legacy/Algorithm/MaximalSpaceSolver.php b/src-legacy/Algorithm/MaximalSpaceSolver.php index 9fd6990..5b48136 100644 --- a/src-legacy/Algorithm/MaximalSpaceSolver.php +++ b/src-legacy/Algorithm/MaximalSpaceSolver.php @@ -151,15 +151,7 @@ public static function subtractAll(array $spaces,array $boxes,?SearchStats $stat },$kept); $result=[]; foreach($kept as $index=>[$space,$isNew]){ - if($isNew){ - [$x1,$y1,$z1,$x2,$y2,$z2]=$extents[$index]; - $dominated=false; - foreach($extents as $other=>$extent){ - if($other===$index)continue; - if($extent[0]<=$x1&&$extent[1]<=$y1&&$extent[2]<=$z1&&$x2<=$extent[3]&&$y2<=$extent[4]&&$z2<=$extent[5]){$dominated=true;break;} - } - if($dominated)continue; - } + if($isNew&&self::isContained($extents,$index))continue; $result[]=$space; } if(count($result)>self::MAX_MAXIMAL_SPACES){ @@ -175,4 +167,22 @@ static function (Space $space): array { } return $result; } + + /** + * Whether another extent contains `$extents[$index]`, for extents ordered by origin z. + * + * A container starts at or below what it contains, so the scan stops at the first + * extent that starts higher: O(prefix) instead of O(s), with no index to build. + * + * @param list $extents + */ + private static function isContained(array $extents,int $index):bool + { + [$x1,$y1,$z1,$x2,$y2,$z2]=$extents[$index]; + foreach($extents as $other=>$extent){ + if($extent[2]>$z1)return false; + if($other!==$index&&$extent[0]<=$x1&&$extent[1]<=$y1&&$x2<=$extent[3]&&$y2<=$extent[4]&&$z2<=$extent[5])return true; + } + return false; + } } diff --git a/src-legacy/Algorithm/SpatialIndex.php b/src-legacy/Algorithm/SpatialIndex.php index 064f5cd..31165af 100644 --- a/src-legacy/Algorithm/SpatialIndex.php +++ b/src-legacy/Algorithm/SpatialIndex.php @@ -14,11 +14,8 @@ * Safety property the whole design leans on: a grid cell assignment only needs to be a * superset of "boxes this query could possibly intersect" — `query()` returns bound * *indices*, and the caller (unchanged from before this class existed) still runs the - * exact 6-comparison AABB test on each one before trusting it. A bug here can only make - * the index slower (over-inclusive buckets) or, if under-inclusive, is caught immediately - * by the differential property tests in SpatialIndexTest.php, which compare every query - * against a naive O(n) scan across many random configurations. It can never by itself - * cause a false "no collision" silently, because the exact check is still the final word. + * exact AABB test on each one. Over-inclusive buckets cost time; omitted candidates + * cannot be recovered by the exact check. Differential tests guard that invariant. */ final class SpatialIndex { @@ -43,6 +40,10 @@ final class SpatialIndex * @var array>>> */ private $cells = []; + /** Every live search state owns its cache; 64 held the 1.4.0 peak where 1024 cost +26%. */ + private const QUERY_CACHE_LIMIT = 64; + /** @var array> Per-state, bounded; PHP copy-on-write isolates forks. */ + private $queryCache = []; public function __construct(int $lengthTicks, int $widthTicks, int $heightTicks, int $cellsPerAxis = 8) { @@ -81,6 +82,7 @@ private function cellRange(int $x1, int $y1, int $z1, int $x2, int $y2, int $z2) /** @param array{0:int,1:int,2:int,3:int,4:int,5:int} $bound */ public function add(int $index, array $bound): void { + $this->queryCache = []; [$x1, $y1, $z1, $x2, $y2, $z2] = $bound; [$ix1, $ix2, $iy1, $iy2, $iz1, $iz2] = $this->cellRange($x1, $y1, $z1, $x2, $y2, $z2); for ($ix = $ix1; $ix < $ix2; $ix++) { @@ -99,6 +101,19 @@ public function query(int $x1, int $y1, int $z1, int $x2, int $y2, int $z2): arr if ($ix2 === $ix1 + 1 && $iy2 === $iy1 + 1 && $iz2 === $iz1 + 1) { return $this->cells[$ix1][$iy1][$iz1] ?? []; } + $key = "$ix1:$ix2:$iy1:$iy2:$iz1:$iz2"; + if (isset($this->queryCache[$key])) { + return $this->queryCache[$key]; + } + if (count($this->queryCache) >= self::QUERY_CACHE_LIMIT) { + $this->queryCache = []; + } + return $this->queryCache[$key] = $this->collect($ix1, $ix2, $iy1, $iy2, $iz1, $iz2); + } + + /** @return list */ + private function collect(int $ix1, int $ix2, int $iy1, int $iy2, int $iz1, int $iz2): array + { // Cells are visited in (x, y, z) order and an index keeps its first position, so // the sequence is a deterministic function of the contents. A box touching a // single occupied cell gets that bucket back as-is. diff --git a/src-legacy/Artifacts/OperationalArtifact.php b/src-legacy/Artifacts/OperationalArtifact.php index b076211..644ad60 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.4.0'; + public const SUITE_VERSION = '1.5.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/Support/FixedPlacementShape.php b/src-legacy/Support/FixedPlacementShape.php index 37d2746..b6701a0 100644 --- a/src-legacy/Support/FixedPlacementShape.php +++ b/src-legacy/Support/FixedPlacementShape.php @@ -62,7 +62,7 @@ public static function requirePoint($point, string $where, string $field, callab } $unknown = JsonValue::namesOutside($point, self::AXES); if ($unknown !== []) { - throw $refuse("{$where} does not carry " . CanonicalJson::spelling($unknown), $field); + throw $refuse("{$where} cannot carry " . CanonicalJson::spelling($unknown), $field); } foreach (self::AXES as $axis) { $value = JsonValue::get($point, $axis); @@ -80,7 +80,7 @@ private static function requireEntry($entry, string $where, string $field, strin } $unknown = JsonValue::namesOutside($entry, self::FIELDS); if ($unknown !== []) { - throw self::malformed("{$where} does not carry " . CanonicalJson::spelling($unknown), $field); + throw self::malformed("{$where} cannot carry " . CanonicalJson::spelling($unknown), $field); } $missing = \array_values(\array_filter(self::REQUIRED, static function (string $name) use ($entry): bool { return !JsonValue::has($entry, $name); diff --git a/src-legacy/Support/RationalParser.php b/src-legacy/Support/RationalParser.php index 6302966..312f3cf 100644 --- a/src-legacy/Support/RationalParser.php +++ b/src-legacy/Support/RationalParser.php @@ -21,19 +21,29 @@ public static function parse($value): array $text = trim(str_replace("\u{00A0}", ' ', $value)); $negative = strncmp($text, '-', strlen('-')) === 0; if (preg_match('/^([+-]?\d+)\s+(\d+)\s*\/\s*(\d+)$/', $text, $m)) { - $whole = (int)$m[1]; $n = (int)$m[2]; $d = (int)$m[3]; self::assertDenominator($d); + $whole = self::parseWhole($m[1]); $n = self::parseWhole($m[2]); $d = self::parseWhole($m[3]); self::assertDenominator($d); + if ($whole !== 0 && abs($whole) > intdiv(PHP_INT_MAX - $n, $d)) { + throw new InvalidArgumentException('Scaled unit value exceeds integer range'); + } $magnitude = abs($whole) * $d + $n; return [$negative ? -$magnitude : $magnitude, $d]; } if (preg_match('/^([+-]?\d+)\s*\/\s*(\d+)$/', $text, $m)) { - $d = (int)$m[2]; self::assertDenominator($d); return [(int)$m[1], $d]; + $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}"); } $fraction = $m[3] ?? ''; - if ($fraction === '') { return [$negative ? -(int)$m[2] : (int)$m[2], 1]; } + 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'); } $den = 10 ** strlen($fraction); - $num = (int)$m[2] * $den + (int)$fraction; + $intPart = self::parseWhole($m[2]); + if ($intPart !== 0 && $intPart > intdiv(PHP_INT_MAX - (int)$fraction, $den)) { + throw new InvalidArgumentException('Scaled unit value exceeds integer range'); + } + $num = $intPart * $den + (int)$fraction; return [$negative ? -$num : $num, $den]; } @@ -43,6 +53,7 @@ public static function parse($value): array public static function scaled($value, int $multiplier, string $rounding): int { [$n, $d] = self::parse($value); + if ($n === PHP_INT_MIN || $multiplier === PHP_INT_MIN) { throw new InvalidArgumentException('Scaled unit value exceeds integer range'); } // Cancel the denominator against the multiplier before multiplying. A value like // "1.123456789012345678" mm would otherwise overflow on n * 16000 even though the // exact result is a small integer number of ticks. @@ -113,5 +124,19 @@ private static function round(int $n, int $d, string $rounding): int private static function gcd(int $a, int $b): int { while ($b !== 0) { [$a, $b] = [$b, $a % $b]; } return max(1, $a); } + private static function parseWhole(string $s): int + { + $sign = strncmp($s, '-', strlen('-')) === 0 ? '-' : ''; + $digits = ltrim($s, '+-'); + $trimmed = ltrim($digits, '0') ?: '0'; + if ($sign === '-' && $trimmed === '9223372036854775808') { + return PHP_INT_MIN; + } + if ((string)(int)$trimmed !== $trimmed) { + throw new InvalidArgumentException('Scaled unit value exceeds integer range'); + } + return (int)$s; + } + private static function assertDenominator(int $d): void { if ($d <= 0) { throw new InvalidArgumentException('Fraction denominator must be positive'); } } } diff --git a/src-legacy/Support/RequestRules.php b/src-legacy/Support/RequestRules.php index ff5ecb0..a949fca 100644 --- a/src-legacy/Support/RequestRules.php +++ b/src-legacy/Support/RequestRules.php @@ -21,6 +21,8 @@ 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']; + public const ACCESS_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; private const CONFIGURATION_INTEGERS = [ 'time_limit_ms' => 1, 'alternatives' => 1, 'max_containers' => 1, 'exact_item_limit' => 1, @@ -28,6 +30,14 @@ final class RequestRules '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']; + /** 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', + 'dimensional_weight_divisor', 'dimensional_weight_length_unit', 'dimensional_weight_weight_unit', + 'effort_budget', 'exact_item_limit', 'max_candidate_points', 'max_candidates_per_item', 'max_containers', + 'minimum_support_ratio', 'multi_start_orders', 'objective', 'require_placement_coordinates', 'seed', + 'solver_profile', 'solvers', 'time_limit_ms', + ]; private const SIDES = ['length', 'width', 'height']; private const WEIGHT_UNIT = 'g'; @@ -86,11 +96,17 @@ 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)); + } foreach (self::CONFIGURATION_INTEGERS as $name => $minimum) { self::optionalInteger($configuration, $name, $where, $minimum); } @@ -99,6 +115,7 @@ private static function configuration($raw, string $unit): void $effort = JsonValue::get($configuration, 'effort_budget'); if ($effort !== null) { $budget = self::objectAt($effort, "{$where}/effort_budget"); + self::knownFields($budget, "{$where}/effort_budget", self::EFFORT_LIMITS); foreach (self::EFFORT_LIMITS as $name) { self::optionalInteger($budget, $name, "{$where}/effort_budget", 1); } @@ -140,6 +157,10 @@ private static function container($raw, string $where, string $unit): void self::optionalInteger($container, 'max_items', $where, 1); self::optionalInteger($container, 'cost_minor', $where, 0); self::optionalRatio($container, 'void_fill_reserve_ratio', $where, 1); + $accessDirections = JsonValue::get($container, 'access_directions'); + if ($accessDirections !== null) { + self::accessDirections($accessDirections, "{$where}/access_directions"); + } $tagLimits = JsonValue::get($container, 'tag_limits'); if ($tagLimits !== null) { self::tagLimits($tagLimits, "{$where}/tag_limits"); @@ -154,6 +175,18 @@ private static function container($raw, string $where, string $unit): void } } + /** @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)); + } + } + } + /** @param mixed $raw */ private static function dimensions($raw, string $where, string $unit): void { @@ -305,6 +338,21 @@ private static function isMeasureObject($value): bool return $value instanceof stdClass || (\is_array($value) && !JsonValue::isList($value)); } + /** + * The schema closes this object: a key it does not name is refused, never ignored. The + * first unknown key in code-point order is named, the order every engine can share. + * + * @param stdClass|array $object + * @param list $known + */ + private static function knownFields($object, string $where, array $known): void + { + $unknown = JsonValue::namesOutside($object, $known); + if ($unknown !== []) { + throw self::refuse('not_allowed', self::pointer($where, $unknown[0]), 'is not a known field'); + } + } + /** * @param mixed $value * @return stdClass|array diff --git a/src/Algorithm/BeamPacker.php b/src/Algorithm/BeamPacker.php index 8fc65c8..c4df07b 100644 --- a/src/Algorithm/BeamPacker.php +++ b/src/Algorithm/BeamPacker.php @@ -52,6 +52,8 @@ public static function pack(Container $container,int $sequence,array $items,Pack $futureCount=count($future); foreach($expansions as [$state,$unplaced]){ $unplacedCount=count($unplaced)+$futureCount; + // More unplaced items loses on the key's first component; skip building a signature that cannot win. + if($unplacedCount>$incumbentKey[0])continue; $used=$state->usedVolume;$signature=[]; foreach($state->placements as $p){ $signature[]=$p->instance->id().'@'.$p->envelopeOrigin->x.','.$p->envelopeOrigin->y.','.$p->envelopeOrigin->z; @@ -61,7 +63,7 @@ public static function pack(Container $container,int $sequence,array $items,Pack if($candidateKey<$incumbentKey){$incumbent=[$state,array_merge($unplaced,$future)];$incumbentKey=$candidateKey;} } if($expansions===[])break; - $futureInfo=self::precomputeFuture($future,$container->maxPayload!==null); + $futureInfo=self::precomputeFuture($future,$container->maxPayload?->ticks); $beam=array_slice(StableSorter::sortBy($expansions,static fn(array $node):array=>self::nodeKeyPrecomputed($node,$futureInfo)),0,$width); if($exhausted){ [$state,$unplaced]=$incumbent; @@ -134,34 +136,42 @@ public static function extended(ContainerState $state,ItemInstance $item,Candida return $child; } - /** @param list $sortedCosts */ - private static function countWithVolumeCapacity(array $sortedCosts,string $capacity):int + /** @param list $cumulativeVolumes */ + private static function countWithVolumeCapacity(array $cumulativeVolumes,string $capacity):int { - $used='0';$count=0; - foreach($sortedCosts as $cost){ - $next=BigInt::add($used,$cost); - if(BigInt::compare($next,$capacity)>0)break; - $used=$next;$count++; - } - return $count; + return self::countWithin($cumulativeVolumes,static fn(string $used):bool=>BigInt::compare($used,$capacity)<=0); + } + + /** @param list $cumulativeWeights */ + private static function countWithWeightCapacity(array $cumulativeWeights,int $capacity):int + { + return self::countWithin($cumulativeWeights,static fn(?int $used):bool=>$used!==null&&$used<=$capacity); } - /** @param list $sortedWeights */ - private static function countWithWeightCapacity(array $sortedWeights,int $capacity):int + /** + * How many of the cheapest costs fit, read off their prefix sums. Costs are + * non-negative, so the sums never decrease and the count is one binary search: + * O(log f) per node instead of the O(f) walk. + * + * @template T + * @param list $cumulative + * @param callable(T):bool $fits + */ + private static function countWithin(array $cumulative,callable $fits):int { - $used=0;$count=0; - foreach($sortedWeights as $weight){ - if($used+$weight>$capacity)break; - $used+=$weight;$count++; + $low=0;$high=count($cumulative); + while($low<$high){ + $middle=intdiv($low+$high,2); + if($fits($cumulative[$middle]))$low=$middle+1;else $high=$middle; } - return $count; + return $low; } /** * @param list $future - * @return array{count:int,volumes:?list,weights:?list} + * @return array{count:int,volumes:?list,weights:?list} */ - private static function precomputeFuture(array $future,bool $hasMaxPayload):array + private static function precomputeFuture(array $future,?int $maxPayloadTicks):array { $count=count($future); if($count===0)return ['count'=>0,'volumes'=>null,'weights'=>null]; @@ -173,11 +183,21 @@ private static function precomputeFuture(array $future,bool $hasMaxPayload):arra if(!$hasNesting){ $volumes=array_map(static fn(ItemInstance $item):string=>$item->dimensions()->volumeString(),$future); usort($volumes,static fn(string $a,string $b):int=>BigInt::compare($a,$b)); + $used='0'; + foreach($volumes as $index=>$volume)$volumes[$index]=$used=BigInt::add($used,$volume); } $weights=null; - if($hasMaxPayload){ + if($maxPayloadTicks!==null){ $weights=array_map(static fn(ItemInstance $item):int=>$item->weight()->ticks,$future); sort($weights,SORT_NUMERIC); + // Null means a prefix exceeds the payload. Compare before adding so neither + // the sum nor payload + 1 can overflow a native int, even at PHP_INT_MAX. + $used=0; + foreach($weights as $index=>$weight){ + if($used===null||$weight>$maxPayloadTicks-$used){$used=null;} + else $used+=$weight; + $weights[$index]=$used; + } } return ['count'=>$count,'volumes'=>$volumes,'weights'=>$weights]; } diff --git a/src/Algorithm/HomogeneousBlockSolver.php b/src/Algorithm/HomogeneousBlockSolver.php index 5a2af05..8b9ee35 100644 --- a/src/Algorithm/HomogeneousBlockSolver.php +++ b/src/Algorithm/HomogeneousBlockSolver.php @@ -3,8 +3,9 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; +use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Constraint\PlacementConstraint; -use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Placement,Point}; +use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Placement,Point,ShapeType}; use Packvium\Extension\CandidateScorer; use Packvium\Support\BigInt; use Packvium\Unit\Length; @@ -27,7 +28,7 @@ public function orderInsensitive():bool{return true;} public function packOne(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):SingleContainerSolution { - if(!$this->supports($container,$items)) + if(!$this->supports($container,$items,$config)) return (new ExtremePointSolver($this->constraints))->packOne($container,$sequence,$items,$config,$stats,$deadline); $best=null;$reached=false; foreach(['count','volume'] as $mode){ @@ -40,16 +41,27 @@ public function packOne(Container $container,int $sequence,array $items,PackingC return new SingleContainerSolution($best->state,$best->unpacked,false,$reached); } - private function supports(Container $container,array $items):bool + private function supports(Container $container,array $items,PackingConfig $config):bool { + // A block set on a smaller one overhangs it, so a request that asks for support + // is left to the per-item search. + if($config->minimumSupportRatio>0)return false; if($this->constraints!==[]||$container->obstacles!==[]||$container->preloaded!==[]||$container->axles!==null||$container->tagLimits!==[]||$container->maxStackDensity!==null||$container->voidFillReserveRatio>0)return false; foreach($items as $instance){ $item=$instance->item; - if($item->group!==null||$item->tags!==[]||$item->incompatibleTags!==[]||$item->eligibleContainerTags!==[]||!$item->stackable||$item->mustBeOnFloor||$item->maxTopLoad!==null||$item->maxStackedItems!==null||$item->minimumSupportRatio!=0.0||!in_array($item->groundContactRule,[null,'free'],true)||$item->nestingHeight!==null||$item->stopIndex!==null)return false; + if($item->shapeType!==ShapeType::RIGID_CUBOID||$item->group!==null||$item->tags!==[]||$item->incompatibleTags!==[]||$item->eligibleContainerTags!==[]||!$item->stackable||$item->mustBeOnFloor||$item->maxTopLoad!==null||$item->maxStackedItems!==null||$item->minimumSupportRatio!=0.0||!in_array($item->groundContactRule,[null,'free'],true)||$item->nestingHeight!==null||$item->stopIndex!==null)return false; } return true; } + /** The share of a member's base that rests on the floor or on a box beneath it. */ + private static function memberSupport(ContainerState $state,ItemInstance $instance,Point $point,Dimensions $envelope):float + { + if($point->z===0)return 1.0; + $support=LoadSupportGraph::candidateView($state->placements,$instance,new AxisAlignedBox($point,$envelope)); + return $support->supportingArea/$envelope->baseAreaTicks(); + } + private function solutionKey(SingleContainerSolution $solution):array { $signature=[]; @@ -107,7 +119,10 @@ private function packMode(Container $container,int $sequence,array $items,Packin 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); - $state->addDirect(new Placement($chosen[$index++],$position,$best['rotation'],$best['physical'],$point,$best['envelope'],1.0)); + // 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)); diff --git a/src/Algorithm/MaximalSpaceSolver.php b/src/Algorithm/MaximalSpaceSolver.php index 312a9a0..79d74ed 100644 --- a/src/Algorithm/MaximalSpaceSolver.php +++ b/src/Algorithm/MaximalSpaceSolver.php @@ -131,15 +131,7 @@ public static function subtractAll(array $spaces,array $boxes,?SearchStats $stat ],$kept); $result=[]; foreach($kept as $index=>[$space,$isNew]){ - if($isNew){ - [$x1,$y1,$z1,$x2,$y2,$z2]=$extents[$index]; - $dominated=false; - foreach($extents as $other=>$extent){ - if($other===$index)continue; - if($extent[0]<=$x1&&$extent[1]<=$y1&&$extent[2]<=$z1&&$x2<=$extent[3]&&$y2<=$extent[4]&&$z2<=$extent[5]){$dominated=true;break;} - } - if($dominated)continue; - } + if($isNew&&self::isContained($extents,$index))continue; $result[]=$space; } if(count($result)>self::MAX_MAXIMAL_SPACES){ @@ -151,4 +143,22 @@ public static function subtractAll(array $spaces,array $boxes,?SearchStats $stat } return $result; } + + /** + * Whether another extent contains `$extents[$index]`, for extents ordered by origin z. + * + * A container starts at or below what it contains, so the scan stops at the first + * extent that starts higher: O(prefix) instead of O(s), with no index to build. + * + * @param list $extents + */ + private static function isContained(array $extents,int $index):bool + { + [$x1,$y1,$z1,$x2,$y2,$z2]=$extents[$index]; + foreach($extents as $other=>$extent){ + if($extent[2]>$z1)return false; + if($other!==$index&&$extent[0]<=$x1&&$extent[1]<=$y1&&$x2<=$extent[3]&&$y2<=$extent[4]&&$z2<=$extent[5])return true; + } + return false; + } } diff --git a/src/Algorithm/SpatialIndex.php b/src/Algorithm/SpatialIndex.php index dd68363..3ea7ead 100644 --- a/src/Algorithm/SpatialIndex.php +++ b/src/Algorithm/SpatialIndex.php @@ -14,11 +14,8 @@ * Safety property the whole design leans on: a grid cell assignment only needs to be a * superset of "boxes this query could possibly intersect" — `query()` returns bound * *indices*, and the caller (unchanged from before this class existed) still runs the - * exact 6-comparison AABB test on each one before trusting it. A bug here can only make - * the index slower (over-inclusive buckets) or, if under-inclusive, is caught immediately - * by the differential property tests in SpatialIndexTest.php, which compare every query - * against a naive O(n) scan across many random configurations. It can never by itself - * cause a false "no collision" silently, because the exact check is still the final word. + * exact AABB test on each one. Over-inclusive buckets cost time; omitted candidates + * cannot be recovered by the exact check. Differential tests guard that invariant. */ final class SpatialIndex { @@ -31,6 +28,10 @@ final class SpatialIndex * @var array>>> */ private array $cells = []; + /** Every live search state owns its cache; 64 held the 1.4.0 peak where 1024 cost +26%. */ + private const QUERY_CACHE_LIMIT = 64; + /** @var array> Per-state, bounded; PHP copy-on-write isolates forks. */ + private array $queryCache = []; public function __construct(int $lengthTicks, int $widthTicks, int $heightTicks, int $cellsPerAxis = 8) { @@ -69,6 +70,7 @@ private function cellRange(int $x1, int $y1, int $z1, int $x2, int $y2, int $z2) /** @param array{0:int,1:int,2:int,3:int,4:int,5:int} $bound */ public function add(int $index, array $bound): void { + $this->queryCache = []; [$x1, $y1, $z1, $x2, $y2, $z2] = $bound; [$ix1, $ix2, $iy1, $iy2, $iz1, $iz2] = $this->cellRange($x1, $y1, $z1, $x2, $y2, $z2); for ($ix = $ix1; $ix < $ix2; $ix++) { @@ -87,6 +89,19 @@ public function query(int $x1, int $y1, int $z1, int $x2, int $y2, int $z2): arr if ($ix2 === $ix1 + 1 && $iy2 === $iy1 + 1 && $iz2 === $iz1 + 1) { return $this->cells[$ix1][$iy1][$iz1] ?? []; } + $key = "$ix1:$ix2:$iy1:$iy2:$iz1:$iz2"; + if (isset($this->queryCache[$key])) { + return $this->queryCache[$key]; + } + if (count($this->queryCache) >= self::QUERY_CACHE_LIMIT) { + $this->queryCache = []; + } + return $this->queryCache[$key] = $this->collect($ix1, $ix2, $iy1, $iy2, $iz1, $iz2); + } + + /** @return list */ + private function collect(int $ix1, int $ix2, int $iy1, int $iy2, int $iz1, int $iz2): array + { // Cells are visited in (x, y, z) order and an index keeps its first position, so // the sequence is a deterministic function of the contents. A box touching a // single occupied cell gets that bucket back as-is. diff --git a/src/Artifacts/OperationalArtifact.php b/src/Artifacts/OperationalArtifact.php index b076211..644ad60 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.4.0'; + public const SUITE_VERSION = '1.5.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/Support/FixedPlacementShape.php b/src/Support/FixedPlacementShape.php index faf7281..c566d35 100644 --- a/src/Support/FixedPlacementShape.php +++ b/src/Support/FixedPlacementShape.php @@ -62,7 +62,7 @@ public static function requirePoint($point, string $where, string $field, callab } $unknown = JsonValue::namesOutside($point, self::AXES); if ($unknown !== []) { - throw $refuse("{$where} does not carry " . CanonicalJson::spelling($unknown), $field); + throw $refuse("{$where} cannot carry " . CanonicalJson::spelling($unknown), $field); } foreach (self::AXES as $axis) { $value = JsonValue::get($point, $axis); @@ -80,7 +80,7 @@ private static function requireEntry($entry, string $where, string $field, strin } $unknown = JsonValue::namesOutside($entry, self::FIELDS); if ($unknown !== []) { - throw self::malformed("{$where} does not carry " . CanonicalJson::spelling($unknown), $field); + throw self::malformed("{$where} cannot carry " . CanonicalJson::spelling($unknown), $field); } $missing = \array_values(\array_filter(self::REQUIRED, static fn(string $name): bool => !JsonValue::has($entry, $name))); if ($missing !== []) { diff --git a/src/Support/RationalParser.php b/src/Support/RationalParser.php index 5d97f32..b23a5cf 100644 --- a/src/Support/RationalParser.php +++ b/src/Support/RationalParser.php @@ -20,25 +20,36 @@ public static function parse(int|string $value): array $text = trim(str_replace("\u{00A0}", ' ', $value)); $negative = str_starts_with($text, '-'); if (preg_match('/^([+-]?\d+)\s+(\d+)\s*\/\s*(\d+)$/', $text, $m)) { - $whole = (int)$m[1]; $n = (int)$m[2]; $d = (int)$m[3]; self::assertDenominator($d); + $whole = self::parseWhole($m[1]); $n = self::parseWhole($m[2]); $d = self::parseWhole($m[3]); self::assertDenominator($d); + if ($whole !== 0 && abs($whole) > intdiv(PHP_INT_MAX - $n, $d)) { + throw new InvalidArgumentException('Scaled unit value exceeds integer range'); + } $magnitude = abs($whole) * $d + $n; return [$negative ? -$magnitude : $magnitude, $d]; } if (preg_match('/^([+-]?\d+)\s*\/\s*(\d+)$/', $text, $m)) { - $d = (int)$m[2]; self::assertDenominator($d); return [(int)$m[1], $d]; + $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}"); } $fraction = $m[3] ?? ''; - if ($fraction === '') { return [$negative ? -(int)$m[2] : (int)$m[2], 1]; } + 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'); } $den = 10 ** strlen($fraction); - $num = (int)$m[2] * $den + (int)$fraction; + $intPart = self::parseWhole($m[2]); + if ($intPart !== 0 && $intPart > intdiv(PHP_INT_MAX - (int)$fraction, $den)) { + throw new InvalidArgumentException('Scaled unit value exceeds integer range'); + } + $num = $intPart * $den + (int)$fraction; return [$negative ? -$num : $num, $den]; } public static function scaled(int|string $value, int $multiplier, Rounding $rounding): int { [$n, $d] = self::parse($value); + if ($n === PHP_INT_MIN || $multiplier === PHP_INT_MIN) { throw new InvalidArgumentException('Scaled unit value exceeds integer range'); } // Cancel the denominator against the multiplier before multiplying. A value like // "1.123456789012345678" mm would otherwise overflow on n * 16000 even though the // exact result is a small integer number of ticks. @@ -106,5 +117,19 @@ private static function round(int $n, int $d, Rounding $rounding): int private static function gcd(int $a, int $b): int { while ($b !== 0) { [$a, $b] = [$b, $a % $b]; } return max(1, $a); } + private static function parseWhole(string $s): int + { + $sign = str_starts_with($s, '-') ? '-' : ''; + $digits = ltrim($s, '+-'); + $trimmed = ltrim($digits, '0') ?: '0'; + if ($sign === '-' && $trimmed === '9223372036854775808') { + return PHP_INT_MIN; + } + if ((string)(int)$trimmed !== $trimmed) { + throw new InvalidArgumentException('Scaled unit value exceeds integer range'); + } + return (int)$s; + } + private static function assertDenominator(int $d): void { if ($d <= 0) { throw new InvalidArgumentException('Fraction denominator must be positive'); } } } diff --git a/src/Support/RequestRules.php b/src/Support/RequestRules.php index 82ea6b3..77ecc60 100644 --- a/src/Support/RequestRules.php +++ b/src/Support/RequestRules.php @@ -21,6 +21,8 @@ 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']; + public const ACCESS_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; private const CONFIGURATION_INTEGERS = [ 'time_limit_ms' => 1, 'alternatives' => 1, 'max_containers' => 1, 'exact_item_limit' => 1, @@ -28,6 +30,14 @@ final class RequestRules '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']; + /** 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', + 'dimensional_weight_divisor', 'dimensional_weight_length_unit', 'dimensional_weight_weight_unit', + 'effort_budget', 'exact_item_limit', 'max_candidate_points', 'max_candidates_per_item', 'max_containers', + 'minimum_support_ratio', 'multi_start_orders', 'objective', 'require_placement_coordinates', 'seed', + 'solver_profile', 'solvers', 'time_limit_ms', + ]; private const SIDES = ['length', 'width', 'height']; private const WEIGHT_UNIT = 'g'; @@ -86,11 +96,17 @@ 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)); + } foreach (self::CONFIGURATION_INTEGERS as $name => $minimum) { self::optionalInteger($configuration, $name, $where, $minimum); } @@ -99,6 +115,7 @@ private static function configuration($raw, string $unit): void $effort = JsonValue::get($configuration, 'effort_budget'); if ($effort !== null) { $budget = self::objectAt($effort, "{$where}/effort_budget"); + self::knownFields($budget, "{$where}/effort_budget", self::EFFORT_LIMITS); foreach (self::EFFORT_LIMITS as $name) { self::optionalInteger($budget, $name, "{$where}/effort_budget", 1); } @@ -140,6 +157,10 @@ private static function container($raw, string $where, string $unit): void self::optionalInteger($container, 'max_items', $where, 1); self::optionalInteger($container, 'cost_minor', $where, 0); self::optionalRatio($container, 'void_fill_reserve_ratio', $where, 1); + $accessDirections = JsonValue::get($container, 'access_directions'); + if ($accessDirections !== null) { + self::accessDirections($accessDirections, "{$where}/access_directions"); + } $tagLimits = JsonValue::get($container, 'tag_limits'); if ($tagLimits !== null) { self::tagLimits($tagLimits, "{$where}/tag_limits"); @@ -154,6 +175,18 @@ private static function container($raw, string $where, string $unit): void } } + /** @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)); + } + } + } + /** @param mixed $raw */ private static function dimensions($raw, string $where, string $unit): void { @@ -303,6 +336,21 @@ private static function isMeasureObject($value): bool return $value instanceof stdClass || (\is_array($value) && !JsonValue::isList($value)); } + /** + * The schema closes this object: a key it does not name is refused, never ignored. The + * first unknown key in code-point order is named, the order every engine can share. + * + * @param stdClass|array $object + * @param list $known + */ + private static function knownFields($object, string $where, array $known): void + { + $unknown = JsonValue::namesOutside($object, $known); + if ($unknown !== []) { + throw self::refuse('not_allowed', self::pointer($where, $unknown[0]), 'is not a known field'); + } + } + /** * @param mixed $value * @return stdClass|array diff --git a/tests/AccessDirectionsTest.php b/tests/AccessDirectionsTest.php index 7f116a6..9447f17 100644 --- a/tests/AccessDirectionsTest.php +++ b/tests/AccessDirectionsTest.php @@ -81,6 +81,10 @@ public static function testOneBadDirectionRefusesTheWholeList(): void // ------------------------------------------------ the same rules through a request + /** Counted work, not a clock, decides where the search stops: under the default wall-clock + * limit a loaded host truncated one of two otherwise identical solves, and the + * comparisons below reported the host rather than the engine. The time limit is only + * a fuse, far above what one cube needs. */ private static function request(?array $doors): array { $container = ['id' => 'van', @@ -89,6 +93,8 @@ private static function request(?array $doors): array $container['access_directions'] = $doors; } return ['units' => ['length' => 'mm'], + 'configuration' => ['effort_budget' => ['max_search_nodes' => 20000], + 'time_limit_ms' => 60000], 'items' => [['id' => 'cube', 'quantity' => 1, 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]], 'containers' => [$container]]; diff --git a/tests/AxleLoadTest.php b/tests/AxleLoadTest.php index 36808d5..9c06df2 100644 --- a/tests/AxleLoadTest.php +++ b/tests/AxleLoadTest.php @@ -103,4 +103,21 @@ public static function testALoadOutsideTheAxleSpanHasANegativeOppositeReaction() self::assertTrue(str_starts_with($reaction['front_numerator'], '-')); self::assertFalse(str_starts_with($reaction['rear_numerator'], '-')); } + + public static function testTheBalancedOriginsAccountForTheLoadAlreadyAboard(): void + { + // Axles at 100 and 900, each limited to 500. A 400-tick unit already sits with its + // centre at 100, right over the front axle. For a further 400-tick item 200 long, + // front reaches its limit with the item's centre at 700 (origin 600): 400 + 400*200/800. + // Rear reaches its limit with the centre at 1100 (origin 1000): 0 + 400*1000/800. + $axles = [new Axle(new Length(100), new Weight(500)), new Axle(new Length(900), new Weight(500))]; + $aboard = [self::unit(400, 0, 200)]; + self::assertSame([600, 1000], AxleLoad::axleBalancedOrigins($axles, $aboard, 0, 0, 400, 200)); + + // Both origins land exactly on a limit, which `exceeded` still admits. + $atFront = self::unit(400, 600, 200, 'item'); + $atRear = self::unit(400, 1000, 200, 'item'); + self::assertNull(AxleLoad::exceeded($axles, [...$aboard, $atFront])); + self::assertNull(AxleLoad::exceeded($axles, [...$aboard, $atRear])); + } } diff --git a/tests/DomainTest.php b/tests/DomainTest.php index f0dbf3e..3501d9e 100644 --- a/tests/DomainTest.php +++ b/tests/DomainTest.php @@ -145,6 +145,15 @@ public static function testAContainerMaxItemsBelowOneIsRefused(): void self::assertSame(1, Container::create('c', Dimensions::mm(1, 1, 1), maxItems: 1)->maxItems); } + public static function testTheBaseAreaKeysOrderTheLargestFootprintFirst(): void + { + $wide = Dimensions::mm(30, 20, 1); + $narrow = Dimensions::mm(10, 10, 50); + self::assertSame(30.0 * 20 * 16_000 * 16_000, $wide->baseAreaScore()); + self::assertSame([-$wide->baseAreaTicks()], $wide->descendingBaseAreaKey()); + self::assertTrue($wide->descendingBaseAreaKey() < $narrow->descendingBaseAreaKey()); + } + public static function testOuterDimensionsCannotBeSmallerThanInner(): void { self::assertThrows(InvalidArgumentException::class, static fn() => Container::create( diff --git a/tests/ExtensionTest.php b/tests/ExtensionTest.php index da88d95..9499b01 100644 --- a/tests/ExtensionTest.php +++ b/tests/ExtensionTest.php @@ -10,6 +10,7 @@ use Packvium\Algorithm\SearchStats; use Packvium\Algorithm\SingleContainerSolution; use Packvium\Algorithm\SingleContainerSolver; +use Packvium\Algorithm\TimeLimitReached; use Packvium\Config\PackingConfig; use Packvium\Config\SolverProfile; use Packvium\Constraint\ConstraintContext; @@ -17,8 +18,11 @@ use Packvium\Constraint\PlacementConstraint; use Packvium\Domain\Container; use Packvium\Domain\Dimensions; +use Packvium\Domain\FixedPlacement; use Packvium\Domain\ItemInstance; +use Packvium\Domain\Placement; use Packvium\Domain\Point; +use Packvium\Domain\Rotation; use Packvium\Extension\CandidateScorer; use Packvium\Extension\ContainerSelector; use Packvium\Extension\ExtensionRegistry; @@ -26,6 +30,7 @@ use Packvium\Objective\ObjectiveScore; use Packvium\Objective\SolutionScorer; use Packvium\Packer; +use Packvium\Result\PackingStatus; /** * The extension points: placement constraints, item orderings, solvers and the @@ -219,6 +224,83 @@ public function packOne(Container $container, int $sequence, array $items, self::assertFalse(str_starts_with($result->algorithm->solver, 'nothing')); } + public static function testACustomSolverThatBreaksAPhysicalRuleNeverWins(): void + { + // Every item stacked into the same corner fits the count perfectly and overlaps + // everything. The independent validator must mark that start invalid so a built-in + // start wins instead, however well the overlapping answer scores. + $overlapping = new class implements SingleContainerSolver { + public function name(): string + { + return 'overlapping'; + } + + public function packOne(Container $container, int $sequence, array $items, + PackingConfig $config, SearchStats $stats, Deadline $deadline): SingleContainerSolution + { + $state = new ContainerState($container, $sequence); + $origin = new Point(0, 0, 0); + foreach ($items as $item) { + $dimensions = $item->dimensions(); + $state->add(new Placement($item, $origin, Rotation::LWH, $dimensions, $origin, $dimensions)); + } + return new SingleContainerSolution($state, []); + } + }; + $items = [Support::item('a', 40, 40, 40, ['quantity' => 4])]; + $containers = [Support::box('c', 100, 100, 100)]; + $result = (new Packer(new PackingConfig(topK: 8), new ExtensionRegistry([], [], [$overlapping]))) + ->pack($items, $containers); + + self::assertNotSame(PackingStatus::InvalidResult, $result->status); + self::assertFalse(str_starts_with($result->algorithm->solver, 'overlapping')); + self::assertSame([], Support::problems($result, $items, $containers)); + foreach ($result->alternatives as $alternative) { + self::assertNotSame(PackingStatus::InvalidResult, $alternative->status); + } + } + + public static function testASolverThatRunsOutOfTimeOnAFixedContainerStillKeepsIt(): void + { + // A start whose solver gives up while filling a container that already holds a + // fixed item keeps that container with the fixed item alone -- dropping it would + // drop an item the request says is already loaded. + $givesUp = new class implements SingleContainerSolver { + public function name(): string + { + return 'gives_up'; + } + + public function packOne(Container $container, int $sequence, array $items, + PackingConfig $config, SearchStats $stats, Deadline $deadline): SingleContainerSolution + { + throw new TimeLimitReached('this solver never finishes'); + } + }; + $items = [Support::item('a', 40, 40, 40, ['quantity' => 3])]; + $containers = [Support::box('c', 100, 100, 100)]; + $fixed = [new FixedPlacement('a', 'c', new Point(0, 0, 0), Rotation::LWH)]; + $result = (new Packer(new PackingConfig(topK: 8), new ExtensionRegistry([], [], [$givesUp]))) + ->pack($items, $containers, $fixed); + + // The packer validates every start against the request, fixed placements included. + self::assertTrue($result->complete()); + self::assertNotSame(PackingStatus::InvalidResult, $result->status); + self::assertSame([], $result->warnings); + $keptAlone = false; + foreach ([$result, ...$result->alternatives] as $candidate) { + if (!str_starts_with($candidate->algorithm->solver, 'gives_up')) { + continue; + } + self::assertCount(1, $candidate->containers); + self::assertSame(['a#1'], array_map(static fn($p): string => $p->instance->id(), $candidate->containers[0]->placements)); + self::assertTrue($candidate->containers[0]->placements[0]->fixed); + self::assertCount(2, $candidate->unpacked); + $keptAlone = true; + } + self::assertTrue($keptAlone, 'the giving-up start was never ranked'); + } + // --------------------------------------------------------------------- scoring public static function testACustomCandidateScorerRanksThePlacements(): void diff --git a/tests/FixedPlacementTest.php b/tests/FixedPlacementTest.php index e83bad1..0cd8068 100644 --- a/tests/FixedPlacementTest.php +++ b/tests/FixedPlacementTest.php @@ -141,7 +141,7 @@ public static function testAFixedPlacementOutOfShapeIsRefusedBeforeAnythingIsCoe ['fixed_placements[0] is an object', [5]], ['fixed_placements[1] is an object', [$entry, [1, 2]]], ['fixed_placements[0] needs ["item_type","container_type","orientation"]', [[]]], - ['fixed_placements[0] does not carry ["5","note"]', [$entry + ['note' => 'strapped', 5 => 1]]], + ['fixed_placements[0] cannot carry ["5","note"]', [$entry + ['note' => 'strapped', 5 => 1]]], ['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])]], @@ -154,7 +154,7 @@ public static function testAFixedPlacementOutOfShapeIsRefusedBeforeAnythingIsCoe ['fixed_placements[0].position is a point object', [array_replace($entry, ['position' => ['100', '0', '0']])]], ['fixed_placements[0].position is a point object', [array_replace($entry, ['position' => null])]], ['fixed_placements[0].position is a point object', [array_replace($entry, ['position' => '100'])]], - ['fixed_placements[0].position does not carry ["w"]', [array_replace($entry, ['position' => ['x' => '100', 'w' => '5']])]], + ['fixed_placements[0].position cannot carry ["w"]', [array_replace($entry, ['position' => ['x' => '100', 'w' => '5']])]], ['fixed_placements[0].position.x is a measure', [array_replace($entry, ['position' => ['x' => true]])]], ['fixed_placements[0].position.y is a measure', [array_replace($entry, ['position' => ['y' => null]])]], ['fixed_placements[0].position.z is a measure', [array_replace($entry, ['position' => ['z' => ['1']]])]], diff --git a/tests/InvariantTest.php b/tests/InvariantTest.php index 798ff4b..8bc53a4 100644 --- a/tests/InvariantTest.php +++ b/tests/InvariantTest.php @@ -326,7 +326,7 @@ public static function testRaisingTheTimeLimitNeverLowersTheChosenRank(): void public static function testConcurrentStartsReproduceTheSequentialAnswerUnderAnAmpleBudget(): void { if (!function_exists('pcntl_fork')) { - self::markTestSkipped('pcntl extension not available'); + self::skip('pcntl extension not available'); } for ($seed = 0; $seed < 4; $seed++) { [$items, $containers] = self::generate($seed); @@ -350,7 +350,7 @@ public static function testConcurrentStartsReproduceTheSequentialAnswerUnderAnAm public static function testConcurrentStartsAreBitIdenticalUnderABitingEffortBudget(): void { if (!function_exists('pcntl_fork')) { - self::markTestSkipped('pcntl extension not available'); + self::skip('pcntl extension not available'); } [$items, $containers] = self::generate(7); $effort = new EffortBudget(maxCandidatesEvaluated: 40, maxPlacementAttempts: 40, maxSearchNodes: 20, maxRestarts: 4); @@ -365,6 +365,39 @@ public static function testConcurrentStartsAreBitIdenticalUnderABitingEffortBudg } } + public static function testConcurrentStartsReportAnEffortStopAsEffortNotTime(): void + { + // A budget small enough to stop the in-process first start and every forked one. + // Each side relabels the items it left behind from `time_limit` to `effort_limit` + // on its own, so both must do it for the answer to say why the search stopped. + if (!function_exists('pcntl_fork')) { + self::skip('pcntl extension not available'); + } + $items = []; + for ($index = 0; $index < 6; $index++) { + $items[] = Support::item("i{$index}", 30 + 5 * $index, 20 + 3 * $index, 15 + 2 * $index, ['quantity' => 3]); + } + $containers = [Support::box('c', 100, 100, 100, ['quantity' => 3])]; + $config = new PackingConfig( + SolverProfile::Balanced, timeLimitMs: 60_000, seed: 1, effortBudget: new EffortBudget(maxSearchNodes: 3), + multiStartOrders: 4, solvers: ['extreme_points', 'layer'], parallelStarts: 4, + ); + + $result = Support::pack($items, $containers, $config); + self::assertTrue($result->algorithm->effortLimitReached); + self::assertFalse($result->complete()); + foreach ($result->unpacked as $unpacked) { + self::assertSame('effort_limit', $unpacked->reason); + } + foreach ($result->alternatives as $alternative) { + foreach ($alternative->unpacked as $unpacked) { + self::assertSame('effort_limit', $unpacked->reason); + } + } + self::assertSame(self::chosenAnswer($result->toArray()), + self::chosenAnswer(Support::pack($items, $containers, $config)->toArray())); + } + public static function testParallelStartsFallsBackToSequentialWithAnInjectedClock(): void { // An injected test clock has no meaning across a fork boundary (see diff --git a/tests/IrregularItemsTest.php b/tests/IrregularItemsTest.php index c49529f..a8e7682 100644 --- a/tests/IrregularItemsTest.php +++ b/tests/IrregularItemsTest.php @@ -72,6 +72,48 @@ public static function testTheDocumentedCompressionExamples(): void self::assertSame(75, Compression::effectiveHeight(100, 250000, 100, ['100', '1'])); } + public static function testAnItemWithNoPressureHeadroomDoesNotCompress(): void + { + // A zero limit admits only zero pressure, so the item keeps its full height -- and + // the division by the limit below that early answer is never reached. + self::assertSame(100, Compression::effectiveHeight(100, 250000, 0, ['0', '1'])); + self::assertSame(100, Compression::effectiveHeight(100, 250000, 0, ['100', '1'])); + } + + public static function testAVertexPartWayAlongAnEdgeIsWalkedPast(): void + { + // (5,0,0) lies on the cube's bottom front edge: collinear with two corners, so the + // face walk must step over it to the farther corner rather than turn back. The hull + // is the cube, with the cube's own volume, axes and contacts. + $withMidpoint = HullShape::of([ + [0, 0, 0], [10, 0, 0], [0, 10, 0], [10, 10, 0], + [0, 0, 10], [10, 0, 10], [0, 10, 10], [10, 10, 10], [5, 0, 0], + ]); + $cube = self::cube(10); + self::assertSame($cube->volume, $withMidpoint->volume); + self::assertSame($cube->faceAxes, $withMidpoint->faceAxes); + self::assertSame($cube->edgeDirections, $withMidpoint->edgeDirections); + self::assertTrue(HullShape::collide($withMidpoint, [0, 0, 0], $cube, [9, 0, 0])); + self::assertFalse(HullShape::collide($withMidpoint, [0, 0, 0], $cube, [10, 0, 0])); + } + + public static function testTheRotatedShapeMemoIsBoundedAndAnswersTheSameAfterClearing(): void + { + // More distinct shapes than the memo holds: it is cleared rather than grown, and a + // shape built again after that is the same shape. + $wedge = self::lowerWedge(); + $before = HullShape::shapeFor($wedge, Rotation::HWL); + self::assertTrue($before === HullShape::shapeFor($wedge, Rotation::HWL), 'a repeated request is memoised'); + for ($stretch = 1; $stretch <= 1025; $stretch++) { + HullShape::shapeFor([[0, 0, 0], [$stretch, 0, 0], [0, 1, 0], [0, 0, 1]], Rotation::LWH); + } + $after = HullShape::shapeFor($wedge, Rotation::HWL); + self::assertSame($before->volume, $after->volume); + self::assertSame($before->vertices, $after->vertices); + self::assertSame($before->faceAxes, $after->faceAxes); + self::assertSame($before->edgeDirections, $after->edgeDirections); + } + public static function testTheCrushBoundaryIsInclusive(): void { self::assertFalse(Compression::exceeds(['100', '1'], 100), 'the limit itself is admissible'); diff --git a/tests/ObjectiveBoundsTest.php b/tests/ObjectiveBoundsTest.php index 8c6dcf0..1d83179 100644 --- a/tests/ObjectiveBoundsTest.php +++ b/tests/ObjectiveBoundsTest.php @@ -201,6 +201,12 @@ public static function testAContainerWithNoRoomBoundsNothingRatherThanDividingBy 'payload' => null, 'max_items' => null, 'quantity' => 1, 'cost_minor' => 0]; self::assertSame(0, ObjectiveBounds::fromNormalised([$item], [$noFloor])[4]); self::assertSame(0, ObjectiveBounds::fromNormalised([$item], [$noHeight])[4]); + + // A container so tall that the placed volume, stood on its widest floor, reaches + // less than one part per million of it: the height bound has nothing to claim. + $tall = ['usable' => '1000000000', 'inner' => '1000000000', 'base_area' => 100, 'height' => 10_000_000, + 'payload' => null, 'max_items' => null, 'quantity' => 1, 'cost_minor' => 0]; + self::assertSame(0, ObjectiveBounds::fromNormalised([$item], [$tall])[4]); } /** diff --git a/tests/PackingSequenceTest.php b/tests/PackingSequenceTest.php index 3a593fc..c593659 100644 --- a/tests/PackingSequenceTest.php +++ b/tests/PackingSequenceTest.php @@ -354,6 +354,14 @@ public static function testAnEmptyDirectionSetLeavesEveryPlacementUnreachableWit self::assertSame([], $reachability[0]->blockedByNeighbors); } + public static function testReachabilityNeedsOneStopEntryPerPlacement(): void + { + $container = Dimensions::mm(20, 10, 10); + $boxes = [self::box(0, 0, 0, 10, 10, 10), self::box(10, 0, 0, 10, 10, 10)]; + self::assertThrows(\InvalidArgumentException::class, + static fn() => UnloadingDependencyGraph::placementReachability($boxes, $container, [0])); + } + public static function testReachabilityIsReportedForEveryPlacementInInputOrder(): void { $container = Dimensions::mm(30, 10, 10); @@ -952,6 +960,16 @@ public static function testComposedSafeLoadingApiCannotReturnAnOverloadedOrder() }); } + public static function testComposedSafeLoadingApiReturnsTheOrderEveryRuleAdmits(): void + { + $bottom = Item::create('bottom', Dimensions::mm(10, 10, 5), weight: '1kg'); + $top = Item::create('top', Dimensions::mm(10, 10, 5), weight: '1kg'); + // Listed top first: the order must still load the supporting item before it. + $placements = [self::stackedPlacement($top, 0, 0, 5), self::stackedPlacement($bottom, 0, 0, 0)]; + $container = Container::create('c', Dimensions::mm(10, 10, 20)); + self::assertSame([1, 0], LoadingDependencyGraph::safeLoadingOrderForPlacements($placements, $container)); + } + public static function testAMalformedBusinessRuleOrderIsRejectedBeforeAnyRuleCheck(): void { $item = Item::create('a', Dimensions::mm(10, 10, 5)); diff --git a/tests/PlanRevisionTest.php b/tests/PlanRevisionTest.php index 2bcec7b..cacebc5 100644 --- a/tests/PlanRevisionTest.php +++ b/tests/PlanRevisionTest.php @@ -286,7 +286,7 @@ public static function testRefusalsQuoteValuesByCanonicalJson(): void 'a placement does not carry ["item_id"]' => array_replace($lock, ['placement' => array_replace($placement, ['item_id' => 'x'])]), 'placement.container_instance counts from 1' => array_replace($lock, ['placement' => array_replace($placement, ['container_instance' => '1'])]), 'placement.position is a point object' => array_replace($lock, ['placement' => array_replace($placement, ['position' => [0, 0, 0]])]), - 'placement.position does not carry ["w"]' => array_replace($lock, ['placement' => array_replace($placement, ['position' => ['w' => '5']])]), + 'placement.position cannot carry ["w"]' => array_replace($lock, ['placement' => array_replace($placement, ['position' => ['w' => '5']])]), 'placement.position.x is a measure' => array_replace($lock, ['placement' => array_replace($placement, ['position' => ['x' => true]])]), 'placement.position.z is a measure' => array_replace($lock, ['placement' => array_replace($placement, ['position' => ['z' => null]])]), 'placement.position.y is a measure' => array_replace($lock, ['placement' => array_replace($placement, ['position' => ['y' => ['1']]])]), diff --git a/tests/RationalParserTest.php b/tests/RationalParserTest.php index 86540b0..d9f544c 100644 --- a/tests/RationalParserTest.php +++ b/tests/RationalParserTest.php @@ -94,6 +94,22 @@ public static function testScalingRefusesValuesBeyondIntegerRange(): void static fn() => RationalParser::scaled('9223372036854775807', 16_000, Rounding::Nearest)); } + public static function testParsingRefusesValuesBeyondIntegerRange(): void + { + self::assertThrows(InvalidArgumentException::class, + static fn() => RationalParser::parse('99999999999999999999')); + self::assertThrows(InvalidArgumentException::class, + static fn() => RationalParser::parse('-99999999999999999999')); + self::assertThrows(InvalidArgumentException::class, + static fn() => RationalParser::scaled('99999999999999999999', 1, Rounding::Nearest)); + } + + public static function testScalingRefusesNativeIntegerMinimumCleanly(): void + { + self::assertThrows(InvalidArgumentException::class, + static fn() => RationalParser::scaled(PHP_INT_MIN, 1, Rounding::Nearest)); + } + public static function testRoundingModesAgreeWithPython(): void { self::assertSame(1, RationalParser::scaled('1.4', 1, Rounding::Floor)); @@ -125,6 +141,16 @@ public static function testDecimalStringIsExactLongDivision(): void self::assertSame('-25.4', RationalParser::decimalString(-406_400, 16_000, 8)); } + public static function testDecimalStringCarriesARoundUpIntoTheWholePart(): void + { + // Every fractional digit is a nine, so rounding up carries out of the fraction. + self::assertSame('1', RationalParser::decimalString(999_999_999, 1_000_000_000, 8)); + self::assertSame('-1', RationalParser::decimalString(-999_999_999, 1_000_000_000, 8)); + // With no fractional digits the tie rounds the whole part itself to even. + self::assertSame('2', RationalParser::decimalString(3, 2, 0)); + self::assertSame('2', RationalParser::decimalString(5, 2, 0)); + } + public static function testDecimalStringRoundsTiesToEvenAtTheRequestedPrecision(): void { self::assertSame('0.33', RationalParser::decimalString(1, 3, 2)); @@ -149,4 +175,17 @@ public static function testDecimalStringRoundsUpOnAnExactHalfWithOddPrecedingDig // 7/4 to 1 place is exactly 1.75 -> last kept digit 7 is odd, rounds up to '1.8'. self::assertSame('1.8', RationalParser::decimalString(7, 4, 1)); } + + public static function testScalingPastTheIntegerRangeIsRefusedNotWrapped(): void + { + foreach (['9223372036854775807 1/2', '9223372036854775807.5'] as $text) { + self::assertThrows(InvalidArgumentException::class, + static fn() => RationalParser::parse($text), "accepted '{$text}'"); + } + } + + public static function testTheMostNegativeIntegerIsAValidNumerator(): void + { + self::assertSame([PHP_INT_MIN, 1], RationalParser::parse('-9223372036854775808/1')); + } } diff --git a/tests/RebalanceTest.php b/tests/RebalanceTest.php index d83778c..e55aba8 100644 --- a/tests/RebalanceTest.php +++ b/tests/RebalanceTest.php @@ -192,6 +192,46 @@ public static function testAMoveThatWouldStrandASupportedItemIsDeclined(): void self::assertValid($request, $outcome->containers, [], $config); } + public static function testAWeightlessItemIsNeverMovedToBalanceWeight(): void + { + // Moving the 5 kg item only flips the imbalance, and moving the weightless one + // cannot narrow it at all, so it is not even tried: nothing moves. + $heavy = Support::item('heavy', 40, 40, 40, ['weight' => '5000 g']); + $feather = Support::item('feather', 40, 40, 40); + $alone = Support::item('alone', 40, 40, 40, ['weight' => '1000 g']); + $boxType = Support::box('box', 200, 200, 200); + $request = new PackingRequest([$heavy, $feather, $alone], [$boxType]); + $packed = [ + new PackedContainer($boxType, 1, [self::floorPlacement($heavy, 1, 0, 0), self::floorPlacement($feather, 1, 50 * Support::MM, 0)]), + new PackedContainer($boxType, 2, [self::floorPlacement($alone, 1, 0, 0)]), + ]; + $outcome = WeightRebalancer::rebalance($request, $packed, [], new PackingConfig()); + self::assertSame([], $outcome->moves); + self::assertSame(self::weights($packed), self::weights($outcome->containers)); + } + + public static function testAMoveIntoAContainerWithNoRoomIsDeclined(): void + { + // Moving the 1 kg item would narrow the spread from 5 kg to 3 kg, but the only + // other container is already full, so there is nowhere in it to put the item. + $heavy = Support::item('heavy', 40, 40, 40, ['weight' => '5000 g']); + $light = Support::item('light', 40, 40, 40, ['weight' => '1000 g']); + $alone = Support::item('alone', 40, 40, 40, ['weight' => '1000 g']); + $roomy = Support::box('roomy', 200, 200, 200); + $snug = Support::box('snug', 40, 40, 40); + $request = new PackingRequest([$heavy, $light, $alone], [$roomy, $snug]); + $packed = [ + new PackedContainer($roomy, 1, [self::floorPlacement($heavy, 1, 0, 0), self::floorPlacement($light, 1, 50 * Support::MM, 0)]), + new PackedContainer($snug, 1, [self::floorPlacement($alone, 1, 0, 0)]), + ]; + $config = new PackingConfig(); + $outcome = WeightRebalancer::rebalance($request, $packed, [], $config); + self::assertSame([], $outcome->moves); + self::assertSame(self::weights($packed), self::weights($outcome->containers)); + self::assertAccountingHolds($request, $outcome->containers, []); + self::assertValid($request, $outcome->containers, [], $config); + } + public static function testASingleContainerHasNothingToRebalance(): void { $solo = Support::item('solo', 40, 40, 40, ['weight' => '500 g']); diff --git a/tests/RequestErrorTest.php b/tests/RequestErrorTest.php index a0ed88f..fc5342e 100644 --- a/tests/RequestErrorTest.php +++ b/tests/RequestErrorTest.php @@ -67,6 +67,14 @@ public static function testEachRuleNamesTheValueItBroke(): void 'above_maximum', '/configuration/minimum_support_ratio', 'must be at most 1'], 'unknown profile' => [static function (array &$r): void { $r['configuration']['solver_profile'] = 7; }, 'not_allowed', '/configuration/solver_profile', 'must be one of ["fast","balanced","quality","exact_small"]'], + 'unknown objective' => [static function (array &$r): void { $r['configuration']['objective'] = 'cheapest'; }, + 'not_allowed', '/configuration/objective', 'must be one of ["default","lowest_cost","shipping_cost","lowest_landed_cost","open_dimension_height","maximum_value"]'], + 'unknown access direction' => [static function (array &$r): void { $r['containers'][0]['access_directions'] = ['upwards']; }, + 'not_allowed', '/containers/0/access_directions/0', 'must be one of ["+x","-x","+y","-y","+z","-z"]'], + 'unknown configuration key' => [static function (array &$r): void { $r['configuration']['top_k'] = 2; $r['configuration']['profile'] = 'balanced'; }, + 'not_allowed', '/configuration/profile', 'is not a known field'], + 'unknown effort key' => [static function (array &$r): void { $r['configuration']['effort_budget'] = ['max_nodes' => 1]; }, + 'not_allowed', '/configuration/effort_budget/max_nodes', 'is not a known field'], 'configuration a list' => [static function (array &$r): void { $r['configuration'] = [1]; }, 'wrong_type', '/configuration', 'must be an object'], 'tag escaped' => [static function (array &$r): void { $r['containers'][0]['tag_limits'] = ['a/b~c' => 0]; }, @@ -103,6 +111,12 @@ public static function testEachRuleNamesTheValueItBroke(): void 'below_minimum', '/containers/0/rate_table/fuel_surcharge_permille', 'must be at least 0'], 'catalog reference not an object' => [static function (array &$r): void { $r['catalog_versions_used'] = [5]; }, 'invalid_value', '', 'catalog_versions_used[0] must be an object'], + 'catalog reference missing a field' => [static function (array &$r): void { $r['catalog_versions_used'] = [['catalog_id' => 'cartons', 'version' => 1]]; }, + 'invalid_value', '', 'catalog_versions_used[0] must contain exactly the canonical fields'], + 'catalog id empty' => [static function (array &$r): void { $r['catalog_versions_used'] = [['catalog_id' => '', 'version' => 1, 'effective_at' => 0, 'resolved_at' => 0]]; }, + 'invalid_value', '', 'catalog_versions_used[0].catalog_id must be non-empty'], + 'catalog version below one' => [static function (array &$r): void { $r['catalog_versions_used'] = [['catalog_id' => 'cartons', 'version' => 0, 'effective_at' => 0, 'resolved_at' => 0]]; }, + 'invalid_value', '', 'catalog_versions_used[0].version must be >= 1'], ]; foreach ($cases as $name => [$edit, $reason, $field, $detail]) { $request = self::request(); @@ -146,6 +160,15 @@ public static function testAnIntegralFloatPassesTheRulesAsTheIntegerItIs(): void self::assertTrue(true); } + public static function testAWellFormedRateTablePassesTheRules(): void + { + $request = self::request(); + $request['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000, 5000], 'prices_minor' => [500, 900], + 'minimum_charge_minor' => 100, 'fuel_surcharge_permille' => 50]; + RequestRules::check($request); + self::assertContains(ArrayCodec::pack($request)['status'], ['feasible', 'optimal']); + } + public static function testWhatTheRulesDoNotNameIsStillARequestError(): void { $request = self::request(); diff --git a/tests/SerializationTest.php b/tests/SerializationTest.php index 59c05f6..5025697 100644 --- a/tests/SerializationTest.php +++ b/tests/SerializationTest.php @@ -100,6 +100,38 @@ public static function testTheThreeResultAxesAreIndependentOfTheLegacyStatus(): self::assertSame(['code'=>'not_proven'],$result['optimality']); } + public static function testAProvenInfeasibleAndAnInvalidResultEachSayWhichAxisTheyAffect(): void + { + $infeasible=(new PackingResult(PackingStatus::Infeasible,[],[],new AlgorithmReport('quality','test',1,42),[0]))->toArray(); + self::assertSame(['code'=>'infeasible'],$infeasible['feasibility']); + self::assertSame('complete',$infeasible['termination']['code']); + self::assertSame(['code'=>'proven_infeasible'],$infeasible['optimality']); + + $invalid=(new PackingResult(PackingStatus::InvalidResult,[],[],new AlgorithmReport('quality','test',1,42),[0]))->toArray(); + self::assertSame(['code'=>'unknown'],$invalid['feasibility']); + self::assertSame('error',$invalid['termination']['code']); + } + + public static function testAFactNeedsANonEmptyCode(): void + { + self::assertThrows(\InvalidArgumentException::class, static fn() => new ResultFact('')); + self::assertThrows(\InvalidArgumentException::class, static fn() => ResultFact::fromArray(['limit'=>1])); + self::assertThrows(\InvalidArgumentException::class, static fn() => ResultFact::fromArray(['code'=>''])); + self::assertThrows(\InvalidArgumentException::class, static fn() => ResultFact::fromArray(['code'=>7])); + } + + public static function testTerminationNeedsExactlyOneSelectedStart(): void + { + self::assertThrows(\InvalidArgumentException::class, static fn() => TerminationSummary::aggregate([])); + self::assertThrows(\InvalidArgumentException::class, static fn() => TerminationSummary::aggregate([ + new StartRecord('a', true, true, false), + ])); + self::assertThrows(\InvalidArgumentException::class, static fn() => TerminationSummary::aggregate([ + new StartRecord('a', true, true, false, true), + new StartRecord('b', true, true, false, true), + ])); + } + public static function testAnUnknownFutureFactCodeRoundTripsVerbatim(): void { self::assertSame( diff --git a/tests/SolverTest.php b/tests/SolverTest.php index 0e35a01..414ce25 100644 --- a/tests/SolverTest.php +++ b/tests/SolverTest.php @@ -38,9 +38,11 @@ use Packvium\Domain\Placement; use Packvium\Domain\Point; use Packvium\Domain\Rotation; +use Packvium\Domain\ShapeType; use Packvium\Extension\DefaultCandidateScorer; use Packvium\Support\BigInt; use Packvium\Unit\Length; +use Packvium\Unit\Weight; /** * The search machinery: time budgets, seeded randomness, free-space bookkeeping and @@ -338,6 +340,45 @@ 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. */ + private static function aBaseAndThreeTops(): array + { + return [...self::instances('base',60,60,40),...self::instances('top',40,60,50,['quantity'=>3])]; + } + + /** The share of a placement's base on the floor or on a top face, from geometry alone. */ + private static function restingShare(array $placements,Placement $placement): float + { + $box=$placement->envelopeBox(); + if($box->origin->z===0)return 1.0; + $resting=0; + foreach($placements as $other){ + $below=$other->envelopeBox(); + if($below->z2()===$box->origin->z)$resting+=$below->overlapAreaXY($box); + } + return $resting/$placement->envelopeDimensions->baseAreaTicks(); + } + + 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()); + $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); + self::assertTrue(abs($base->supportRatio-5/6)<1e-9); + self::assertSame(self::restingShare($placements,$base),$base->supportRatio); + } + + public static function testTheBlockSolverLeavesARequestThatAsksForSupportToThePerItemSearch(): void + { + $box=Container::create('crate',Dimensions::mm(100,100,100),quantity:1); + $config=new PackingConfig(profile:SolverProfile::Quality,minimumSupportRatio:1.0,multiStartOrders:24,maxCandidatesPerItem:16,containerPlanBeamWidth:16,containerPlanNodeLimit:100_000); + $solution=(new HomogeneousBlockSolver())->packOne($box,1,self::aBaseAndThreeTops(),$config,new SearchStats(),self::generous()); + self::assertTrue($solution->state->placements!==[]); + foreach($solution->state->placements as $placement)self::assertSame(1.0,self::restingShare($solution->state->placements,$placement)); + } + public static function testBlockSearchFallsBackWhenABusinessRuleCanDistinguishPlacements(): void { $box=Container::create('box',Dimensions::mm(100,100,200),quantity:1); @@ -348,6 +389,21 @@ public static function testBlockSearchFallsBackWhenABusinessRuleCanDistinguishPl self::assertPhysicallySound($solution->state); } + public static function testBlockSearchFallsBackForCompressibleItems(): void + { + $box=Container::create('box',Dimensions::mm(100,100,200),quantity:1); + $items=self::instances('sponge',100,100,100,[ + 'quantity'=>2, + 'shapeType'=>ShapeType::COMPRESSIBLE, + 'compressionRatioPpm'=>200_000, + 'maxCompressionPressureKpa'=>50, + ]); + $solution=(new HomogeneousBlockSolver())->packOne($box,1,$items,PackingConfig::quality(),new SearchStats(),self::generous()); + self::assertCount(2,$solution->state->placements); + self::assertCount(0,$solution->unpacked); + self::assertPhysicallySound($solution->state); + } + public static function testBeamPackerPrecomputedFutureMatchesStandardEvaluation(): void { $box = Container::create('box', Dimensions::mm(300, 200, 200), quantity: 1); @@ -367,6 +423,16 @@ public static function testBeamPackerPrecomputedFutureBoundsByPayload(): void self::assertPhysicallySound($solution->state); } + public static function testBeamWeightBoundStaysExactAtIntegerMaximum(): void + { + $small = new ItemInstance(new Item('small', Dimensions::mm(1, 1, 1), new Weight(1)), 1); + $large = new ItemInstance(new Item('large', Dimensions::mm(1, 1, 1), new Weight(PHP_INT_MAX)), 1); + $future = (new ReflectionMethod(BeamPacker::class, 'precomputeFuture'))->invoke(null, [$small, $large], PHP_INT_MAX); + $count = new ReflectionMethod(BeamPacker::class, 'countWithWeightCapacity'); + self::assertSame(1, $count->invoke(null, $future['weights'], PHP_INT_MAX)); + self::assertSame(0, $count->invoke(null, $future['weights'], 0)); + } + public static function testBeamPackerPrecomputedFutureDropsTheVolumeBoundForNesting(): void { $box = Container::create('box', Dimensions::mm(300, 200, 200), quantity: 1); @@ -376,6 +442,36 @@ public static function testBeamPackerPrecomputedFutureDropsTheVolumeBoundForNest self::assertPhysicallySound($solution->state); } + public static function testBeamPackerKeepsTheGreedyPrefixWhenEffortRunsOutMidGreedy(): void + { + // The greedy seed pass itself runs out of effort: every batch it had not placed is + // reported unplaced, and what it had placed stays physically sound. + $box = Container::create('box', Dimensions::mm(300, 200, 200), quantity: 1); + $items = self::instances('small', 50, 50, 50, ['quantity' => 10]); + $stats = new SearchStats(); + $deadline = self::generous()->withEffort(new EffortBudget(maxCandidatesEvaluated: 1), $stats); + $config = new PackingConfig(profile: SolverProfile::Quality, maxCandidatesPerItem: 4, containerPlanBeamWidth: 4, containerPlanNodeLimit: 20); + $solution = (new ExtremePointSolver())->packOne($box, 1, $items, $config, $stats, $deadline); + self::assertSame(10, count($solution->state->placements) + count($solution->unpacked)); + self::assertTrue($solution->unpacked !== [], 'a one-candidate budget cannot place all ten'); + self::assertPhysicallySound($solution->state); + } + + public static function testContainerPlanSearchBoundsTheContainersStillNeededByPayload(): void + { + // Every container has a payload ceiling, so the plan search's lower bound on the + // containers still to open counts weight as well as volume. Only one 600 g item fits + // under each 1 kg ceiling: three items need three containers. + $items = [Item::create('heavy', Dimensions::mm(40, 40, 40), weight: '600 g', quantity: 3)]; + $containers = [Container::create('box', Dimensions::mm(100, 100, 100), maxPayload: '1 kg', quantity: 5)]; + $config = new PackingConfig(timeLimitMs: 60_000, seed: 1, effortBudget: new EffortBudget(maxSearchNodes: 100_000), + containerPlanBeamWidth: 4, containerPlanNodeLimit: 64); + $result = (new \Packvium\Packer($config))->pack($items, $containers); + self::assertTrue($result->complete()); + self::assertCount(3, $result->containers); + self::assertSame([], Support::problems($result, $items, $containers)); + } + private static function assertPhysicallySound(ContainerState $state): void { $boundary = new AxisAlignedBox(new Point(0, 0, 0), $state->container->innerDimensions); @@ -497,6 +593,15 @@ public static function testAnExhaustedDeadlineRaisesRatherThanReturningQuietly() self::assertThrows(TimeLimitReached::class, static fn() => $expired->check()); } + public static function testADeadlineUntilAnAbsoluteInstantHonoursThatInstant(): void + { + // The forked starts share one absolute instant rather than a sliced budget. + self::assertTrue(Deadline::until(hrtime(true) - 1)->expired(), 'an instant already passed is expired'); + $ample = Deadline::until(hrtime(true) + 60_000_000_000); + self::assertFalse($ample->expired()); + self::assertTrue($ample->usesRealClock()); + } + public static function testASliceIsNeverTooSmallToPlaceAnything(): void { // A long multi-start list would otherwise hand out budgets no solver can use. diff --git a/tests/SpatialIndexTest.php b/tests/SpatialIndexTest.php index e48e1db..6ec4a6d 100644 --- a/tests/SpatialIndexTest.php +++ b/tests/SpatialIndexTest.php @@ -48,6 +48,79 @@ private static function randomBound(DeterministicRandom $rng, int $span): array return [$x1, $y1, $z1, $x2, $y2, $z2]; } + public static function testRepeatedRangesAreCachedAndDetachedOnMutation(): void + { + $index = new SpatialIndex(800, 800, 800); + $index->add(0, [0, 0, 0, 150, 150, 150]); + $query = [0, 0, 0, 160, 160, 160]; + self::assertSame([0], $index->query(...$query)); + $cache = new \ReflectionProperty(SpatialIndex::class, 'queryCache'); + self::assertSame(1, count($cache->getValue($index))); + $fork = $index->copy(); + $returned = $index->query(...$query); + $returned[] = 999; + $index->add(1, [100, 100, 100, 180, 180, 180]); + self::assertSame([0, 1], $index->query(...$query)); + self::assertSame([0], $fork->query(...$query)); + $fork->add(2, [100, 100, 100, 180, 180, 180]); + self::assertSame([0, 2], $fork->query(...$query)); + self::assertSame([0, 1], $index->query(...$query)); + } + + public static function testQueryCacheHasABoundedRetention(): void + { + $index = new SpatialIndex(800, 800, 800); + $first = [0, 0, 0, 150, 150, 150]; + $index->add(0, $first); + $queries = []; + for ($i = 0; $i < 1100; $i++) { + $query = [$i * 100, 0, 0, $i * 100 + 150, 150, 150]; + $queries[] = $query; + $index->query(...$query); + } + $cache = new \ReflectionProperty(SpatialIndex::class, 'queryCache'); + self::assertTrue(count($cache->getValue($index)) <= 64); + $fork = $index->copy(); + $inserted = [100, 100, 100, 180, 180, 180]; + $forkInserted = [700, 100, 100, 780, 180, 180]; + $index->add(1, $inserted); + $fork->add(1, $forkInserted); + $fresh = SpatialIndex::build([$first, $inserted], 800, 800, 800); + $freshFork = SpatialIndex::build([$first, $forkInserted], 800, 800, 800); + foreach ([...$queries, $inserted, $forkInserted] as $query) { + self::assertSame($fresh->query(...$query), $index->query(...$query)); + self::assertSame($freshFork->query(...$query), $fork->query(...$query)); + } + self::assertTrue(count($cache->getValue($index)) <= 64); + self::assertTrue(count($cache->getValue($fork)) <= 64); + } + + public static function testCachedQueriesMatchFreshIndexesAfterDivergentForks(): void + { + for ($seed = 0; $seed < 5; $seed++) { + $rng = new DeterministicRandom($seed); + $index = new SpatialIndex(800, 800, 800); + $bounds = []; + $queries = []; + for ($q = 0; $q < 20; $q++) { $queries[] = self::randomBound($rng, 800); } + for ($step = 0; $step < 20; $step++) { + foreach ($queries as $query) { $index->query(...$query); } + $fork = $index->copy(); + $originalBound = self::randomBound($rng, 800); + $forkBound = self::randomBound($rng, 800); + $fork->add($step, $forkBound); + $freshFork = SpatialIndex::build([...$bounds, $forkBound], 800, 800, 800); + $bounds[] = $originalBound; + $index->add($step, $originalBound); + $fresh = SpatialIndex::build($bounds, 800, 800, 800); + foreach ($queries as $query) { + self::assertSame($fresh->query(...$query), $index->query(...$query)); + self::assertSame($freshFork->query(...$query), $fork->query(...$query)); + } + } + } + } + public static function testAnEmptyIndexFindsNothing(): void { $index = new SpatialIndex(1000, 1000, 1000);