From ff00286bedd127215b286c101c401d25563b4f4d Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 8 Nov 2026 08:18:28 -0500 Subject: [PATCH] chore(release): 1.10.0 --- .github/DISCUSSION_TEMPLATE/q-a.yml | 2 +- .github/DISCUSSION_TEMPLATE/show-and-tell.yml | 2 +- .github/ISSUE_TEMPLATE/bug_report.yml | 4 +- .github/ISSUE_TEMPLATE/feature_request.yml | 2 +- CHANGELOG.md | 61 +++ CITATION.cff | 2 +- README.md | 34 +- bin/packvium | 5 +- codemeta.json | 2 +- docs/GUARANTEES.md | 2 +- docs/PUBLIC-API.md | 103 ++++- examples/execution.php | 4 +- examples/nested.php | 5 +- examples/objectives.php | 21 + examples/packaging.php | 190 ++++++++ examples/revisions.php | 60 +++ examples/serialization.php | 55 ++- examples/units.php | 18 + scripts/build_php74.py | 15 +- src-legacy/Algorithm/CandidateFinder.php | 114 +++-- src-legacy/Algorithm/ContainerState.php | 10 +- .../Algorithm/FixedPlacementAdmission.php | 12 +- src-legacy/Algorithm/GridSolver.php | 8 + .../Algorithm/HomogeneousBlockSolver.php | 2 +- .../Algorithm/Internal/MadeToMeasureTrial.php | 16 +- src-legacy/Algorithm/Internal/PalletTrial.php | 103 +++++ src-legacy/Algorithm/MaximalSpaceSolver.php | 7 +- src-legacy/Algorithm/ObjectiveBoundScope.php | 6 +- src-legacy/Algorithm/ObjectiveBounds.php | 203 ++++++++- src-legacy/Algorithm/SolverOrchestrator.php | 26 +- src-legacy/Algorithm/SupportCalculator.php | 7 +- src-legacy/Artifacts/ArtifactExports.php | 28 +- src-legacy/Artifacts/OperationalArtifact.php | 36 +- src-legacy/Constraint/ContactGraph.php | 13 +- .../Constraint/Internal/LoadSupportGraph.php | 57 ++- .../Constraint/Internal/PlacedSupportBase.php | 425 +++++++++++++++++- .../Constraint/RouteOrderConstraint.php | 12 +- src-legacy/Constraint/SupportConstraint.php | 24 +- src-legacy/Constraint/TopLoadConstraint.php | 18 +- src-legacy/Domain/Container.php | 81 +++- src-legacy/Domain/Deck.php | 44 ++ src-legacy/Domain/Dimensions.php | 3 + src-legacy/Domain/FixedPlacement.php | 9 +- src-legacy/Domain/FlatBag.php | 18 +- src-legacy/Domain/HullShape.php | 49 +- src-legacy/Domain/Item.php | 3 +- src-legacy/Domain/Orientations.php | 93 ++++ src-legacy/Domain/OverhangLimit.php | 27 ++ src-legacy/Domain/PackedContainer.php | 9 +- src-legacy/Domain/PackingRequest.php | 8 +- src-legacy/Domain/PalletOverhang.php | 125 ++++++ src-legacy/Domain/Placement.php | 19 + src-legacy/Domain/RateTable.php | 11 +- src-legacy/Domain/Rotation.php | 6 +- src-legacy/Execution/Plan.php | 28 +- src-legacy/Nested/NestedPacker.php | 210 ++++++++- src-legacy/Packer.php | 26 +- src-legacy/Result/PackingResult.php | 111 +++-- src-legacy/Revisions/PlanRevision.php | 364 ++++++++++++++- src-legacy/Serialization/ArrayCodec.php | 89 +++- src-legacy/Support/FixedPlacementShape.php | 97 +++- .../Support/Internal/RareRequestRules.php | 70 ++- src-legacy/Support/PrettyJsonStream.php | 46 +- src-legacy/Support/RationalParser.php | 4 +- src-legacy/Support/RequestObjects.php | 72 ++- src-legacy/Support/RequestRules.php | 131 +++++- .../Support/ResultValidation/Accounting.php | 4 +- src-legacy/Support/ResultValidation/Bound.php | 77 +++- .../ResultValidation/ContainerCheck.php | 84 +++- .../ResultValidation/ContainerSpec.php | 14 + .../Support/ResultValidation/Geometry.php | 57 ++- .../ResultValidation/ObjectiveCheck.php | 2 +- .../Support/ResultValidation/PlacementIds.php | 81 ++++ src-legacy/Support/ResultValidation/Spec.php | 69 ++- .../Support/ResultValidation/Stacking.php | 42 +- src-legacy/Support/ResultValidation/Units.php | 13 + .../Support/ResultValidation/Validator.php | 18 + .../IndependentSolutionValidator.php | 66 ++- src/Algorithm/CandidateFinder.php | 104 +++-- src/Algorithm/ContainerState.php | 10 +- src/Algorithm/FixedPlacementAdmission.php | 12 +- src/Algorithm/GridSolver.php | 8 + src/Algorithm/HomogeneousBlockSolver.php | 2 +- src/Algorithm/Internal/MadeToMeasureTrial.php | 16 +- src/Algorithm/Internal/PalletTrial.php | 103 +++++ src/Algorithm/MaximalSpaceSolver.php | 7 +- src/Algorithm/ObjectiveBoundScope.php | 6 +- src/Algorithm/ObjectiveBounds.php | 201 ++++++++- src/Algorithm/SolverOrchestrator.php | 26 +- src/Algorithm/SupportCalculator.php | 7 +- src/Artifacts/ArtifactExports.php | 28 +- src/Artifacts/OperationalArtifact.php | 36 +- src/Constraint/ContactGraph.php | 13 +- src/Constraint/Internal/LoadSupportGraph.php | 57 ++- src/Constraint/Internal/PlacedSupportBase.php | 403 ++++++++++++++++- src/Constraint/RouteOrderConstraint.php | 12 +- src/Constraint/SupportConstraint.php | 23 +- src/Constraint/TopLoadConstraint.php | 18 +- src/Domain/Container.php | 63 ++- src/Domain/Deck.php | 18 + src/Domain/Dimensions.php | 3 +- src/Domain/FixedPlacement.php | 3 +- src/Domain/FlatBag.php | 18 +- src/Domain/HullShape.php | 34 +- src/Domain/Item.php | 3 +- src/Domain/Orientations.php | 93 ++++ src/Domain/OverhangLimit.php | 13 + src/Domain/PackedContainer.php | 9 +- src/Domain/PackingRequest.php | 2 +- src/Domain/PalletOverhang.php | 124 +++++ src/Domain/Placement.php | 19 + src/Domain/RateTable.php | 3 + src/Domain/Rotation.php | 16 +- src/Execution/Plan.php | 28 +- src/Nested/NestedPacker.php | 188 +++++++- src/Packer.php | 23 +- src/Result/PackingResult.php | 103 +++-- src/Revisions/PlanRevision.php | 364 ++++++++++++++- src/Serialization/ArrayCodec.php | 87 +++- src/Support/FixedPlacementShape.php | 95 +++- src/Support/Internal/RareRequestRules.php | 70 ++- src/Support/PrettyJsonStream.php | 46 +- src/Support/RationalParser.php | 4 +- src/Support/RequestObjects.php | 66 ++- src/Support/RequestRules.php | 131 +++++- src/Support/ResultValidation/Accounting.php | 4 +- src/Support/ResultValidation/Bound.php | 77 +++- .../ResultValidation/ContainerCheck.php | 84 +++- .../ResultValidation/ContainerSpec.php | 14 + src/Support/ResultValidation/Geometry.php | 57 ++- .../ResultValidation/ObjectiveCheck.php | 2 +- src/Support/ResultValidation/PlacementIds.php | 81 ++++ src/Support/ResultValidation/Spec.php | 69 ++- src/Support/ResultValidation/Stacking.php | 42 +- src/Support/ResultValidation/Units.php | 13 + src/Support/ResultValidation/Validator.php | 18 + .../IndependentSolutionValidator.php | 66 ++- tests/BoundLoadingTest.php | 4 +- tests/ConstraintTest.php | 181 ++++++++ tests/CurrencyTest.php | 146 ++++++ tests/EffectiveRotationValidationTest.php | 33 ++ tests/EffortBoundaryTest.php | 20 + tests/FlatBagTest.php | 2 +- tests/GussetedBagTest.php | 200 +++++++++ tests/InvariantTest.php | 47 ++ tests/IrregularItemsTest.php | 24 + tests/MadeToMeasureTest.php | 89 +++- tests/MeasureReadingTest.php | 10 + tests/NestedTest.php | 239 ++++++++++ tests/ObjectiveBoundsTest.php | 114 ++++- tests/OperationalArtifactTest.php | 26 ++ tests/PackingSequenceTest.php | 28 ++ tests/PalletOverhangTest.php | 390 ++++++++++++++++ tests/PlacementIdTest.php | 293 ++++++++++++ tests/PlanRevisionTest.php | 94 ++++ tests/PrettyJsonStreamTest.php | 34 ++ tests/RequestErrorTest.php | 4 +- tests/RequestObjectsCorpusTest.php | 31 +- tests/ResultValidationBoundTest.php | 44 +- tests/ResultValidationEdgesTest.php | 274 +++++++++++ tests/ResultValidationTest.php | 37 +- tests/SerializationTest.php | 3 +- tests/SignedRotationsTest.php | 255 +++++++++++ tests/StockCutIndexTest.php | 91 ++++ tests/Support.php | 16 + 165 files changed, 9204 insertions(+), 764 deletions(-) create mode 100644 examples/packaging.php create mode 100644 src-legacy/Algorithm/Internal/PalletTrial.php create mode 100644 src-legacy/Domain/Deck.php create mode 100644 src-legacy/Domain/Orientations.php create mode 100644 src-legacy/Domain/OverhangLimit.php create mode 100644 src-legacy/Domain/PalletOverhang.php create mode 100644 src-legacy/Support/ResultValidation/PlacementIds.php create mode 100644 src/Algorithm/Internal/PalletTrial.php create mode 100644 src/Domain/Deck.php create mode 100644 src/Domain/Orientations.php create mode 100644 src/Domain/OverhangLimit.php create mode 100644 src/Domain/PalletOverhang.php create mode 100644 src/Support/ResultValidation/PlacementIds.php create mode 100644 tests/CurrencyTest.php create mode 100644 tests/EffectiveRotationValidationTest.php create mode 100644 tests/GussetedBagTest.php create mode 100644 tests/PalletOverhangTest.php create mode 100644 tests/PlacementIdTest.php create mode 100644 tests/ResultValidationEdgesTest.php create mode 100644 tests/SignedRotationsTest.php create mode 100644 tests/StockCutIndexTest.php diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml index 0bb59bc..196b437 100644 --- a/.github/DISCUSSION_TEMPLATE/q-a.yml +++ b/.github/DISCUSSION_TEMPLATE/q-a.yml @@ -10,7 +10,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium/packvium 1.9.0 (PHP)" + placeholder: "packvium/packvium 1.10.0 (PHP)" validations: required: true - type: textarea diff --git a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml index e91fe0b..ccf74c3 100644 --- a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml +++ b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml @@ -16,7 +16,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium/packvium 1.9.0 (PHP)" + placeholder: "packvium/packvium 1.10.0 (PHP)" validations: required: false - type: textarea diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 0014acf..2de712d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -33,8 +33,8 @@ body: id: version attributes: label: Package version - description: The exact version installed, for example 1.9.0. - placeholder: "1.9.0" + description: The exact version installed, for example 1.10.0. + placeholder: "1.10.0" validations: required: true - type: input diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 9310929..c3cf3a1 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -29,7 +29,7 @@ body: id: version attributes: label: Package version - placeholder: "1.9.0" + placeholder: "1.10.0" validations: required: true - type: textarea diff --git a/CHANGELOG.md b/CHANGELOG.md index a95713e..b026519 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,67 @@ 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.10.0] + +Overhanging pallets, gusseted bags, 24 rotations for a hull, a declared currency, an id on every +placement, a nested packer that compares carton sets, and bounds under three more objectives. +One stricter refusal: a `units` key other than `length` (see *Changed*). + +### Added + +- **`container.pallet_overhang_limit`** (`Packvium\Domain\OverhangLimit`): a load may pass the + deck by the stated length at each end and width at each side. Positions are measured from the + corner of the overhang zone, only the deck bears weight, and the packed pallet reports + `achieved_dimensions`, at which it is billed and handed up. Refused beside `access_directions`, + `axles`, `made_to_measure`, `obstacles`, a non-zero `void_fill_reserve_ratio` or a + `stop_index`. +- **Gusseted bags:** `deformable_boundary.kind: "gusseted_bag"` with `side_gusset_depth`; + `Container::create()` and the constructor take a trailing `?Length $sideGussetDepth`. +- **18 signed rotations for a `convex_hull` item** (`Rotation::NL_NW_PH` is `-L-W+H`), 24 in all, + in `allowedRotations`, a placement's orientation, `fixed_placements` and revision events; + `Rotation::every()`, `isSigned()`, `isUpright()`. `Rotation::all()` is unchanged, and a signed + code on any other item is `invalid_request` / `invalid_value`. +- **`placement_id` on every placement**, the canonical JSON of `[container id, x, y, z, + item_type, orientation]` in ticks. A fixed placement or a locked revision event may quote it, + the execution plan copies it, and `validate` reports `placement_id_mismatch` and + `duplicate_placement_id`. +- **`currency`** on the request and each `rate_table`, echoed as the result's `currency`; it + never changes the packing. `PackingRequest`, `Packer::pack()` and `RateTable` take a trailing + `?string $currency`, and `validate` reports `currency_mismatch`. +- **`optimality.lower_bound` and the gap under `maximum_value`, `open_dimension_height` and + `maximum_volume`**, besides `default` and `lowest_cost`; `validate` checks them. +- **`new NestedPacker(int $levelBeamWidth = 1)`** carries the K best carton sets up a level and + lets the outermost level's score choose; 1 is the greedy chain, answer for answer. +- **A made-to-measure box may keep a `void_fill_reserve_ratio`**: when the box cut tight to the + load would break the reserve, a larger one is cut. +- **`PlanRevision::stockCutBoxes()`**, and the revision issue `artifact_required`. +- **`examples/packaging.php`**: an overhanging pallet, a gusseted mailer, a cut box with a + reserve and a nested beam. + +### Changed + +- **`units` refuses every key but `length`**: `invalid_request` / `not_allowed` at + `/units/`. 1.9 read a bare weight as grams whatever `units.weight` said; write the unit + on each weight instead. +- **`PlanRevision::derive()` stocks a box already cut to measure** that holds a locked or + verified placement, as `@#` at its cut size, price and tare, where + 1.9 derived a request every engine refused. `verifyChain()` checks that revision only when + given its approved artifact. +- **`keep_upright` narrows an explicit `allowed_rotations` list** in `validate`, not only the + default list. + +### Fixed + +- **An explicit rotation list emptied by `keep_upright` is refused at `allowed_rotations`**, + with the same named request error the independent validator checks. +- **Stocking cut boxes indexes artifact lookups once** and reports malformed consumed + machine fields as structured `invalid_revision` errors. +- **An artifact export refuses an integer past `2^53 - 1`** with `number_out_of_range`, where it + printed one up to `PHP_INT_MAX` that other engines read differently. +- **A compressible item no longer joins a rigid item's grid lattice.** +- **A mixed fraction whose whole part is `PHP_INT_MIN`** is refused as a negative measure, + where it failed later as a type error. + ## [1.9.0] No API change, but admission is stricter: some requests 1.8 accepted are now refused (see the diff --git a/CITATION.cff b/CITATION.cff index 7c2cac4..05482d3 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,7 +5,7 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.9.0" +version: "1.10.0" license: MIT url: "https://packvium.com" repository-code: "https://github.com/toxakara/packvium-php" diff --git a/README.md b/README.md index 0df626b..16be37a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ coordinates and rotations for each item, with a reason for anything that did not Full documentation, the constraint reference and benchmarks live at [packvium.com](https://packvium.com). -> **Version 1.9.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.10.0 — the public API is frozen.** Field names, status codes and the > objective vector do not change without a major version, so any `1.x` is a safe upgrade > from any earlier `1.x`. > Read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-php/blob/main/docs/GUARANTEES.md) @@ -97,7 +97,7 @@ Pass numbers as strings or integers — the API has no float parameters for a me 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. A JSON request's `units` sets only the length unit; a weight takes its -unit from the measure or is grams, and `units.weight` is ignored today. See +unit from the measure or is grams; any other `units` key, `weight` included, is refused. 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). @@ -172,6 +172,8 @@ try { - Since 1.8.0, `keep_upright`, `stackable`, `must_be_on_floor` and `require_placement_coordinates` must be JSON booleans: `"no"`, `0` or `1` raises `InvalidRequestException` with reason `wrong_type`. +- Since 1.10.0, a `units` key other than `length` is `not_allowed` at `/units/`, and so + is a `rate_table.currency` that differs from the request's `currency`. 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`. @@ -216,22 +218,23 @@ surprise people. | File | What it shows | | --- | --- | | [`basic.php`](https://github.com/toxakara/packvium-php/blob/main/examples/basic.php) | The smallest useful call: items in, placements out — and the three details in it that are easy to miss. | -| [`objectives.php`](https://github.com/toxakara/packvium-php/blob/main/examples/objectives.php) | Six of the seven objectives (all but `maximum_volume`) on scenes where they genuinely disagree, including the rate card that makes the heavier shipment the cheaper one. | +| [`objectives.php`](https://github.com/toxakara/packvium-php/blob/main/examples/objectives.php) | Six of the seven objectives (all but `maximum_volume`) on scenes where they genuinely disagree, including the rate card that makes the heavier shipment the cheaper one — and the lower bound a result states, loose or attained. | | [`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. | +| [`serialization.php`](https://github.com/toxakara/packvium-php/blob/main/examples/serialization.php) | The same request as JSON, the result in full with its `currency` and each `placement_id`, runners-up via `alternatives`, the signed rotations only a hull may use, 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`](https://github.com/toxakara/packvium-php/blob/main/examples/nested.php) | Units into cartons, cartons onto a pallet, in one call. | +| [`packaging.php`](https://github.com/toxakara/packvium-php/blob/main/examples/packaging.php) | Packaging that is not a rigid box: a crate overhanging its pallet deck, a gusseted mailer that holds a layer a flat one cannot, a box cut to measure that keeps room for void fill, and `new NestedPacker(2)` letting the outer level choose the cartons. | | [`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. | +| [`revisions.php`](https://github.com/toxakara/packvium-php/blob/main/examples/revisions.php) | Replan a half-loaded job: a missing item and a placement locked by its `placement_id`, a replan that keeps the locked item in place, a hash-chained record that notices an edit — the same digests as the other three engines — and a box already cut to measure offered back as stock. | ```bash php examples/objectives.php @@ -254,18 +257,22 @@ where their answers agree. 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. +- **Packaging that is not a rigid box.** Flat and gusseted bags, boxes cut to measure (with a + void-fill reserve if you ask for one), pallets a load may overhang by a stated margin, and + convex-hull items in all 24 orientations. - **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. -- **A proof, or the distance to one.** Under the `default` and `lowest_cost` objectives every - result states `optimality.lower_bound`. A complete result that attains it reports `optimal`, - which proves no packing obeying the request's rules scores better; any other carries the gap - to the bound (`gap_key`, `absolute_gap`, `relative_gap`). +- **A proof, or the distance to one.** Under every objective but `shipping_cost` and + `lowest_landed_cost`, every result states `optimality.lower_bound`. A complete result that + attains it reports `optimal`, which proves no packing obeying the request's rules scores + better; any other carries the gap to the bound (`gap_key`, `absolute_gap`, `relative_gap`). - **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. + containers; `new NestedPacker(K)` carries the K best carton sets up a + level, so the pallet decides between them. - **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 @@ -278,7 +285,8 @@ where their answers agree. Rust and JavaScript packages write. - **Items already in place, and replanning around them.** A request's `fixed_placements` pins items to known positions before the solve: they keep their place, carry weight and - support, and come back marked `fixed: true`. `Packvium\Revisions\PlanRevision` records what + support, and come back marked `fixed: true`. Every placement carries a `placement_id` the + same in every engine, which a fixed placement or a lock may quote. `Packvium\Revisions\PlanRevision` records what changed on the dock — a missing item, a substituted container, a lock, a verification — as an append-only chain linked by SHA-256, and derives the request the next plan solves. @@ -367,7 +375,7 @@ Documentation, the constraint reference and the benchmarks are at | --- | --- | --- | | Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/toxakara/packvium-python) | | PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/toxakara/packvium-php) | -| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.9"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.10"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | | Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/toxakara/packvium-node) | | Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/toxakara/packvium-wasm) | | PHP FFI bridge — [`packvium/native-bridge`](https://packagist.org/packages/packvium/native-bridge) | `composer require packvium/native-bridge` | [packvium-php-bridge](https://github.com/toxakara/packvium-php-bridge) | @@ -391,7 +399,7 @@ CodeMeta form. @software{packvium_php, author = {{Packvium contributors}}, title = {Packvium for PHP}, - version = {1.9.0}, + version = {1.10.0}, license = {MIT}, url = {https://packvium.com} } diff --git a/bin/packvium b/bin/packvium index 1f08ddf..2f385c2 100755 --- a/bin/packvium +++ b/bin/packvium @@ -6,6 +6,7 @@ use Packvium\Serialization\ArrayCodec; use Packvium\Support\PrettyJsonStream; $input = stream_get_contents(STDIN); if ($input === false || trim($input) === '') { fwrite(STDERR, "Expected packing JSON on stdin\n"); exit(2); } -// Streamed, not `echo json_encode(...)`: the encoded result is never held next to its array. -try { $result=ArrayCodec::pack(json_decode($input,true,512,JSON_THROW_ON_ERROR)); PrettyJsonStream::write($result,STDOUT); fwrite(STDOUT,"\n"); } +// Streamed, not `echo json_encode(...)`: the encoded result is never held next to its array, +// and its placements are built as they are written, never all at once. +try { $result=ArrayCodec::packStreamed(json_decode($input,true,512,JSON_THROW_ON_ERROR)); PrettyJsonStream::write($result,STDOUT); fwrite(STDOUT,"\n"); } catch(Throwable $e){ fwrite(STDERR,$e->getMessage()."\n"); exit(1); } diff --git a/codemeta.json b/codemeta.json index 12fec4a..2bf1dcf 100644 --- a/codemeta.json +++ b/codemeta.json @@ -3,7 +3,7 @@ "@type": "SoftwareSourceCode", "name": "Packvium for PHP", "description": "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", - "version": "1.9.0", + "version": "1.10.0", "license": "https://spdx.org/licenses/MIT", "author": [ { diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 0d40bf9..f0b05e9 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -61,7 +61,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.9.0` freezes the public API. Field names, status codes, the objective +Version `1.10.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/PUBLIC-API.md b/docs/PUBLIC-API.md index 7eb418e..c0f98e6 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -32,6 +32,15 @@ pack validly but less densely; any such difference is pinned in `conformance/native-quality-budget.json` rather than left to drift. + **24 rotations for a hull (1.10).** `allowed_rotations` and a placement's `orientation` + take 24 codes: the six legacy codes, unchanged and still the default list, then 18 signed + codes such as `-L-W+H` -- per output axis a sign and the declared side -- that only a + `convex_hull` may list (elsewhere `invalid_request` / `invalid_value` at + `/items//allowed_rotations/`). `keep_upright` keeps the codes whose z entry is `+H`. + Python's `Rotation` enum gains the 18 members in canonical table order (`NL_NW_PH = + "-L-W+H"`, ...), `Rotation.every()` for all 24 and the `is_signed` / `is_upright` + properties; `Rotation.all()` and `Rotation.upright()` keep returning the legacy six and two. + Where they are implemented: a `convex_hull` item's collisions are decided by an exact integer separating-axis test rather than by its box, and its occupied volume is the hull's own — two complementary wedges share a crate that fits one of their bounding boxes. A @@ -54,7 +63,8 @@ statics, rejected as a constraint rather than merely reported), and an optional `rate_table` carrier tariff (ascending `weight_brackets_g` paired with `prices_minor`, an optional `minimum_charge_minor` floor and an optional - `fuel_surcharge_permille`). The rate card is request data rather than a registered + `fuel_surcharge_permille`, and since 1.10 an optional `currency`, which must equal the + request's). The rate card is request data rather than a registered scorer precisely so all four engines can be held to the same price; only the `lowest_landed_cost` objective reads it, and a request that omits it behaves exactly as it did before the field existed. @@ -75,6 +85,14 @@ `billedDimensions()`, Rust `Container::deformable_boundary: Option` with `PackedContainer::achieved_dimensions()` / `billed_dimensions()`, and the TypeScript request type. +- **Gusseted bags (1.10).** `deformable_boundary: {"kind": "gusseted_bag", "side_gusset_depth": G}` + is a flat bag whose side gussets open to depth `G`, a length measure in the request's units, + required for this kind, positive and at most `inner_dimensions.width`; a `flat_bag` refuses the + key as an unknown field. The width girth becomes `b + c <= W + G`; the frame (`b <= W`), the + length girth, billing on `achieved_dimensions`, the refused fields, the solver fallbacks and + the validator issue `bag_girth_exceeded` are the flat bag's. Bottom gussets are not modelled. + Python's `Container` keeps `deformable_boundary: str` (`"gusseted_bag"`) and gains a trailing + `side_gusset_depth: Length | None = None`, refused unless the kind is `gusseted_bag`. - **Made-to-measure containers.** `made_to_measure` (absent or `null`: a stock container) makes the container an on-demand box machine whose largest box is `inner_dimensions`: `minimum` and `increment` per axis (required; `minimum` equal to @@ -87,12 +105,33 @@ and `tare_weight` (declared tare plus the board, rounded up the same way), both inside every objective and `gross_weight`; `achieved_dimensions` reports the extent before rounding. `outer_dimensions` or `deformable_boundary` next to it is `invalid_request` / `not_allowed`; - `axles`, non-empty `obstacles`, a positive `void_fill_reserve_ratio` or a fixed placement in - the container is `unsupported_feature`; a largest box priced above `2^53 - 1` is + `axles`, non-empty `obstacles` or a fixed placement in the container is + `unsupported_feature`. A positive `void_fill_reserve_ratio` is kept in the box that ships: when + the box cut tight to the load would break it, the box is the solving envelope instead. + A largest box priced above `2^53 - 1` is `invalid_value`. The engines expose it as Python `Container.made_to_measure` (a `packvium.MadeToMeasure`, last field), PHP the trailing constructor parameter `?MadeToMeasure $madeToMeasure` (`Packvium\Domain\MadeToMeasure`), Rust `Container::made_to_measure: Option`, and the TypeScript request type. +- **Pallet overhang.** `pallet_overhang_limit: {length, width}` (both required, + non-negative lengths, no default; zero forbids overhang) lets a load pass the deck, the + container's `inner_dimensions`, by `length` at each end and `width` at each side. Positions + are measured from the corner of the overhang zone, so the deck lies at `[length, length + L]` + by `[width, width + W]`, fixed placements included. Only the deck bears weight: a floor + placement's `support_ratio` is the share of its base on the deck, held to + `minimum_support_ratio` and the centre-of-gravity rule like any support. A load the deck + holds is never overhung; one that needs the overhang is seated with the least of it. The + packed pallet reports its declared `inner_dimensions` and `outer_dimensions` (else inner), + `achieved_dimensions` -- the deck grown by the overhang used, at the load's height -- and its + `volume_utilization` against the widened frame; it is billed, and handed to an outer nesting + level, at the larger of its declared footprint and `achieved_dimensions` per horizontal axis + and its declared height. Beside non-empty `access_directions`, `axles`, `made_to_measure`, + non-empty `obstacles`, a positive `void_fill_reserve_ratio` or any item with a `stop_index` + it is `unsupported_feature` (`container.pallet_overhang_limit+`); beside + `deformable_boundary` it is `invalid_request` / `not_allowed`; a frame past the admission + ceiling is `above_maximum`. Python `Container.pallet_overhang_limit` (a + `packvium.OverhangLimit`, last field); the object APIs refuse the same combinations as + `not_allowed`. - `PackingConfig`: solver profile, deadline, alternatives, deterministic seed, clearance, support threshold (`minimum_support_ratio`, default 0: support is not required, and an item may rest on nothing above the floor; set it above 0 to require that share of the @@ -135,7 +174,18 @@ search with `invalid_fixed_placement`. Python `Packer.pack(items, containers, fixed_placements)` and PHP `Packer::pack($items, $containers, $fixedPlacements)` take `FixedPlacement` values; Rust takes them in `PackingRequest.fixed_placements`, and every - JSON entry point reads the field; all four engines implement it. + JSON entry point reads the field; all four engines implement it. Since 1.10 an entry may + restate the result placement's `placement_id`, the canonical JSON of + `["#", x, y, z, "", ""]` with the + position in ticks; any other string is refused as `invalid_fixed_placement` / `invalid_value` at + `/fixed_placements//placement_id`, and `null` is absent. Python's `FixedPlacement` takes it + as a trailing `placement_id: str | None = None`. +- `currency` (1.10): optional ISO 4217 code, three capital letters, that every money + field of the request is in. It is echoed by the result and never priced, converted or + ranked by; a `rate_table.currency` must equal it. Python takes it as the trailing + `currency=None` of `Packer.pack(items, containers, fixed_placements, currency)` and of + `PackingRequest`, and `RateTable` gains a trailing `currency=None`; the object path refuses + it with the JSON path's reason and field. - `catalog_versions_used`: optional immutable catalog references resolved before packing. Each reference has exactly `catalog_id`, positive `version`, non-negative `published_at_epoch_ms`, and `content_digest`; catalog IDs are unique. @@ -163,7 +213,8 @@ request field. extension point remains open: closing the object would make a previously valid producer fail a validator, which is a breaking change. Every engine emits these fields since, on the primary result and on each alternative, for the `default` and - `lowest_cost` objectives; a complete result that attains its bound reports `status: + `lowest_cost` objectives, and since 1.10.0 also for `maximum_value`, + `open_dimension_height` and `maximum_volume`; a complete result that attains its bound reports `status: optimal` and `code: proven_optimal`, and nothing else does; - legacy `status`: `optimal`, `feasible`, `best_found`, `time_limit`, `infeasible`, or `invalid_result`; - packed containers with exact coordinates, dimensions, rotations, and a @@ -179,6 +230,14 @@ request field. - objective score — a five-key lexicographic vector of exact integers, lower is better, computed by the same formula in every implementation — and solver statistics. Under the default objective the keys are `unpacked_count`, `container_count`, `total_cost_minor`, `unused_volume_ppm` (per container `floor((V - used) x 10^6 / V)` of inner volume `V`) and `stack_height_ppm` (per container `floor(top x 10^6 / H)` of inner height `H`); `configuration.objective` selects one of seven orderings (`default`, `lowest_cost`, `shipping_cost`, `lowest_landed_cost`, `open_dimension_height`, `maximum_value`, `maximum_volume`), and the result echoes it in `objective`; - the exact `catalog_versions_used` lineage from the request (an empty array when no catalog was involved), preserved by Python, PHP, Rust and JavaScript; +- a `placement_id` on every placement of the answer and every alternative (1.10): + the canonical JSON of `[container id, x, y, z, item_type, orientation]` with the position in + ticks, for example `["truck#1",0,0,1600000,"crate","LWH"]`, a pure function of the placement; + `validate` reports a missing or wrong one as `placement_id_mismatch` and a repeat as + `duplicate_placement_id`; +- the request's `currency`, present exactly when the request declares one, on the answer and + every alternative (1.10); `validate` reports a missing, extra or different one as + `currency_mismatch`; - warnings and top-K alternatives. With `minimum_support_ratio` at its default 0, a result with a placement resting on nothing above the floor carries one `unsupported_placements: N placement(s) rest on nothing above the container floor; ...` @@ -246,7 +305,10 @@ Metrics are diagnostics: they never participate in feasibility, ranking or the objective vector. `algorithm.time_limit_reached` and `algorithm.effort_limit_reached` identify distinct, -mutually exclusive causes. The former is only a wall-clock deadline. The latter means +mutually exclusive causes. The former is only a wall-clock deadline, read when the start +ends: it says the deadline had passed by then, not that the clock cut work, so a start that +finished its search just as the clock passed reads it too, in every engine, as +`global_deadline_reached`, which requires it, does. The latter means the selected start was stopped by one of the request's counted-work boundaries: the search had more work to do and the budget refused it. A start that finished having used exactly its budget was not stopped, and reports neither flag. No counter in `algorithm.metrics` ends @@ -645,7 +707,10 @@ otherwise refuse**, and the strongest thing it can do is reserve its own slot. A solve cannot honour comes back on `LockedResolve` as unpreserved and names the lock — it is an outcome, not an exception — while a lock set that contradicts itself, by overlapping or by naming an item the request does not contain, is refused with `LockSetError` before any -solve runs. +solve runs. Since 1.10 a lock read by `locks_from_plan` carries its reference's +`placement_id` (`PlacementLock` gains a trailing `placement_id: str | None = None`), and +preservation is checked by it rather than by `container_index`, the emitted container order +a re-solve need not repeat. Python only, and deliberately so: a lock has no representation in the request schema, since that field is held for the next contract freeze, so there is nothing to hand another engine. @@ -702,14 +767,15 @@ approved operational artifact and its events, and calls no solver or clock. | Language | Surface | | --- | --- | -| Python | `packvium.revisions.root_revision(request)`, `.derive_revision(parent, approved_artifact, events)`, `.verify_revision_chain(revisions, artifacts=None)`, `.document_digest(document)`, `.canonical_revision_json(document)`; `packvium.revision_outcomes.record_revision(ledger, revision, decision_id, recorded_at)` | +| Python | `packvium.revisions.root_revision(request)`, `.derive_revision(parent, approved_artifact, events)`, `.apply_events(request, events)`, `.stock_cut_boxes(request, approved_artifact, revision)`, `.verify_revision_chain(revisions, artifacts=None)`, `.document_digest(document)`, `.canonical_revision_json(document)`; `packvium.revision_outcomes.record_revision(ledger, revision, decision_id, recorded_at)` | | Rust | `packvium_core::revisions::root_revision_json(request)`, `derive_revision_json(parent, artifact, events)`, `apply_events_json(request, events)`, `verify_revision_chain_json(revisions, artifacts)`, `document_digest_json(document)`, `canonical_revision_json(document)`; SHA-256 from the `sha2` crate, so the WASM package hashes too | | JavaScript | `rootRevision`, `deriveRevision`, `applyEvents`, `verifyRevisionChain`, `documentDigest`, `canonicalRevisionJson` from `@packvium/engine`'s `revisions.js`; SHA-256 from `node:crypto` | | PHP | `Packvium\Revisions\PlanRevision::root($request)`, `::derive($parent, $approvedArtifact, $events)`, `::verifyChain($revisions, $artifacts)`, `::digest($document)`, `::canonicalJson($document)`, `::parse($json)`. Documents are `stdClass` trees, so `{}` and `[]` keep their digests | Digests are SHA-256 over the RFC 8785 canonical bytes. The audit reports `revision_number`, -`parent_mismatch`, `sequence_gap`, `request_mismatch` and `artifact_mismatch` without -stopping at the first. Refusals use `invalid_revision`, `invalid_event`, `event_conflict`, +`parent_mismatch`, `sequence_gap`, `request_mismatch`, `artifact_mismatch` and +`artifact_required` (a revision that stocks a made-to-measure box, audited without its +artifact) without stopping at the first. Refusals use `invalid_revision`, `invalid_event`, `event_conflict`, `invalid_artifact` and the canonical-form codes. ## Scenario and recommendation API @@ -746,12 +812,10 @@ credited to the treatment. paired cohort is too small. Neither writes to a registry: publishing goes only through `approve_catalog` / `approve_policy`, and a proposal is handed no registry to write to. -**Supported, and not yet frozen.** This surface and `packvium.locks` are reached by -importing the submodule, which puts them outside the frozen API snapshot the packing and -commerce surfaces are held to. They work, they are tested, and they will not be withdrawn -inside 1.x — but a parameter may be renamed or a returned value gain a field in a minor -release, announced in the changelog rather than blocked by a gate. Pin the version if you -depend on the exact shape. +**Frozen since 1.10.0.** The six modules `packvium.simulation`, `packvium.recommendations`, +`packvium.outcomes`, `packvium.holdout`, `packvium.pareto` and `packvium.locks` each declare +`__all__` and are held to the API snapshot, as the packing and commerce surfaces are. From 1.2.0 +to 1.9.0 they were supported but provisional, so a signature could change in a minor release. ## JSON API @@ -762,7 +826,6 @@ Python, PHP, Rust and the JavaScript fallback accept the same top-level keys: `u `units` holds one key, `length`: the unit of every length written without one, millimetres when `units`, or `units.length`, is absent or `null`. There is no request-wide weight unit. A weight takes its unit from the measure itself (`"2.5 kg"`, `{"value": "2.5", "unit": "kg"}`), and a -bare number is grams. `units.weight` is not a field: today every engine ignores it without an -error, so `{"length": "cm", "weight": "kg"}` still reads a bare weight `2` as 2 g. Write the unit -on each weight instead. A future release that changes the request schema will refuse unknown -keys in `units`, as it already refuses them in `configuration`. +bare number is grams. `units` is closed: since 1.10.0 a key other than `length` is refused as +`not_allowed` at `/units/` (docs/ERRORS.md), so `{"length": "cm", "weight": "kg"}`, which +used to read a bare weight `2` as 2 g without a word, is an error. Write the unit on each weight. diff --git a/examples/execution.php b/examples/execution.php index 3b6920e..f16180c 100644 --- a/examples/execution.php +++ b/examples/execution.php @@ -141,8 +141,8 @@ echo ' It does not follow that four engines packing the same *request* agree. Python', PHP_EOL; echo ' and PHP are held to identical placements, which is why this file and', PHP_EOL; echo ' examples/execution.py print the same byte count; Rust and JavaScript are held to', PHP_EOL; -echo ' a valid answer at or above the objective floor, and the Node example prints 1280', PHP_EOL; -echo ' bytes rather than 1877 for that reason.', PHP_EOL; +echo ' a valid answer at or above the objective floor, and the Node example prints', PHP_EOL; +echo ' another byte count for that reason.', PHP_EOL; echo PHP_EOL; echo ' Operator locks continue this story and are Python-only: a lock has no', PHP_EOL; echo ' representation in the request schema, so there is nothing to hand another engine.', PHP_EOL; diff --git a/examples/nested.php b/examples/nested.php index fecc156..c5a36f1 100644 --- a/examples/nested.php +++ b/examples/nested.php @@ -14,8 +14,9 @@ * * The levels stay independent on purpose. Level two does not reach back and repack level * one to get a better pallet, because that would make the carton contents depend on the - * pallet, and a carton you already taped shut cannot be repacked. If you want that - * trade-off explored, run the packer yourself with different carton sets and compare. + * pallet, and a carton you already taped shut cannot be repacked. To explore that + * trade-off, `new NestedPacker(3)` carries the three best carton sets + * up a level and keeps the one whose pallet scores best. */ declare(strict_types=1); diff --git a/examples/objectives.php b/examples/objectives.php index 267d1c8..78b5ba8 100644 --- a/examples/objectives.php +++ b/examples/objectives.php @@ -25,6 +25,7 @@ use Packvium\Domain\{Container, Dimensions, Item, RateTable}; use Packvium\Domain\UnratedWeightException; use Packvium\Packer; +use Packvium\Result\PackingResult; // An example must not change answer merely because the host was busy. These solves need // a fraction of the budget; the generous wall-clock value is only a safety fuse, so a @@ -139,3 +140,23 @@ sort($kept); sort($left); printf("%-18s packed=%s left behind=%s\n", 'maximum_value', json_encode($kept), json_encode($left)); + +// ----------------------------------------------------------------------------------- +// Most objectives' results also say how far they can be from the best possible answer +// (`shipping_cost` and `lowest_landed_cost` do not yet): `optimality.lower_bound` is a +// score no packing that obeys the request can beat, computed from the request alone. A +// complete result that attains it reports `proven_optimal`; any other carries the gap, +// and one that leaves items behind says `best_found` even at a gap of 0. +// The bound is cheap and so it can be loose -- the shortest stack is bounded by the +// load's volume spread over the largest floor -- but no packing ever beats it. +// ----------------------------------------------------------------------------------- +$bound = static function (PackingResult $result): string { + $optimality = $result->toArray()['optimality']; + return sprintf('%s score=%s bound=%s gap=%s', $optimality['code'], json_encode($result->score), + json_encode($optimality['lower_bound']), json_encode($optimality['absolute_gap'] ?? 0)); +}; +echo "\n"; +printf("%-18s %s\n", 'open_dimension_height', $bound((new Packer( + new PackingConfig(objective: 'open_dimension_height', timeLimitMs: SAFETY_FUSE_MS) +))->pack($widgets, [$snug, $roomy]))); +printf("%-18s %s\n", 'maximum_value', $bound($result)); diff --git a/examples/packaging.php b/examples/packaging.php new file mode 100644 index 0000000..24697c4 --- /dev/null +++ b/examples/packaging.php @@ -0,0 +1,190 @@ + ['max_search_nodes' => 20000], 'time_limit_ms' => 60000]; +const RULE = '=============================================================================='; + +function section(string $title): void +{ + echo "\n", RULE, "\n", $title, "\n", RULE, "\n"; +} + +/** @param array> $dimensions */ +function size(array $dimensions): string +{ + return "{$dimensions['length']['value']} x {$dimensions['width']['value']} x {$dimensions['height']['value']} mm"; +} + +/** @param array $result */ +function placedCount(array $result): int +{ + $placed = 0; + foreach ($result['containers'] as $container) { + $placed += count($container['placements']); + } + return $placed; +} + +// -------------------------------------------------------------------------------------- +section('1. A crate wider than the pallet deck'); + +$pallet = [ + 'units' => ['length' => 'mm'], + 'configuration' => CONFIGURATION, + 'items' => [ + ['id' => 'crate', 'quantity' => 1, 'weight' => '40 kg', + 'dimensions' => ['length' => '1250', 'width' => '850', 'height' => '600']], + ], + 'containers' => [ + ['id' => 'euro', 'max_payload' => '1000 kg', + 'inner_dimensions' => ['length' => '1200', 'width' => '800', 'height' => '1000']], + ], +]; +$deckOnly = ArrayCodec::pack($pallet); +printf(" deck only: %s, %d placed, crate refused: %s\n", + $deckOnly['status'], placedCount($deckOnly), $deckOnly['unpacked_items'][0]['reason']); + +$pallet['containers'][0]['pallet_overhang_limit'] = ['length' => '50', 'width' => '50']; +$overhung = ArrayCodec::pack($pallet); +$loaded = $overhung['containers'][0]; +$crate = $loaded['placements'][0]; +printf(" 50 mm overhang: %s, %d placed\n", $overhung['status'], placedCount($overhung)); +printf(" declared deck: %s\n", size($loaded['inner_dimensions'])); +printf(" achieved footprint: %s\n", size($loaded['achieved_dimensions'])); +printf(" crate at x=%s y=%s mm, %s of its base on the deck\n", + $crate['position']['x']['value'], $crate['position']['y']['value'], $crate['support_ratio']); +echo << ['length' => 'mm'], + 'configuration' => CONFIGURATION, + 'items' => [ + ['id' => 'book', 'quantity' => 3, 'weight' => '300 g', 'allowed_rotations' => ['LWH'], + 'dimensions' => ['length' => '200', 'width' => '100', 'height' => '20']], + ], + 'containers' => [ + ['id' => 'mailer', 'quantity' => 1, 'deformable_boundary' => ['kind' => 'flat_bag'], + 'inner_dimensions' => ['length' => '300', 'width' => '150', 'height' => '100']], + ], +]; +$flat = ArrayCodec::pack($mailer); +printf(" flat bag: %s, %d of 3 books\n", $flat['status'], placedCount($flat)); + +$mailer['containers'][0]['deformable_boundary'] = ['kind' => 'gusseted_bag', 'side_gusset_depth' => '25']; +$gusseted = ArrayCodec::pack($mailer); +printf(" 25 mm side gussets: %s, %d of 3 books, filled to %s\n", + $gusseted['status'], placedCount($gusseted), size($gusseted['containers'][0]['achieved_dimensions'])); +echo << ['length' => 'mm'], + 'configuration' => CONFIGURATION, + 'items' => [ + ['id' => 'cube', 'quantity' => 8, 'weight' => '100 g', + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']], + ], + 'containers' => [ + ['id' => 'machine', 'cost_minor' => 40, + 'inner_dimensions' => ['length' => '1510', 'width' => '1510', 'height' => '1510'], + 'made_to_measure' => [ + 'minimum' => ['length' => '60', 'width' => '60', 'height' => '60'], + 'increment' => ['length' => '25', 'width' => '25', 'height' => '25'], + 'outer_allowance' => ['length' => '3', 'width' => '3', 'height' => '3'], + 'cost_per_square_metre_minor' => 1000, + 'tare_per_square_metre' => '500', + ]], + ], +]; +foreach ([0.0, 0.5] as $reserve) { + $cut['containers'][0]['void_fill_reserve_ratio'] = $reserve; + $box = ArrayCodec::pack($cut)['containers'][0]; + printf(" reserve %.1f: cut to %s, costs %d, %s of it filled\n", + $reserve, size($box['inner_dimensions']), $box['made_to_measure']['cost_minor'], + $box['volume_utilization']); +} +echo <<pack($jars, $levels); + $cartons = array_map(static fn ($packed): string => $packed->id(), $chain->levels[0]->containers); + printf(" new NestedPacker(%d): cartons %s, locker %s\n", + $width, json_encode($cartons), $chain->levels[1]->complete() ? 'complete' : 'leaves a carton out'); +} +echo <<request))['containers'][0]['placements'][0]; $events = [ + // `placement_id` quotes the placement the operator saw on the plan. It must agree with + // the fields beside it, so a lock copied from the wrong line is refused, not applied. ['sequence' => 1, 'type' => 'placement_locked', 'placement' => [ + 'placement_id' => $loaded['placement_id'], 'item_type' => 'cube', 'container_type' => 'tote', 'container_instance' => 1, 'position' => [ 'x' => $loaded['position']['x']['value'], @@ -112,6 +115,7 @@ function approve(array $request): array . "..., replay {$revision->approved->replay->level}\n"; echo " slabs still to pack: {$revision->request->items[1]->quantity}\n"; echo ' fixed placements: ' . count($revision->request->fixed_placements) . "\n"; +echo " locked by id: {$loaded['placement_id']}\n"; echo << ['length' => 'mm'], + 'configuration' => $request['configuration'], + 'items' => [ + ['id' => 'cube', 'quantity' => 8, 'weight' => '100 g', + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']], + ], + 'containers' => [ + ['id' => 'machine', 'cost_minor' => 40, + 'inner_dimensions' => ['length' => '1510', 'width' => '1510', 'height' => '1510'], + 'made_to_measure' => [ + 'minimum' => ['length' => '60', 'width' => '60', 'height' => '60'], + 'increment' => ['length' => '25', 'width' => '25', 'height' => '25'], + 'outer_allowance' => ['length' => '3', 'width' => '3', 'height' => '3'], + 'cost_per_square_metre_minor' => 1000, + 'tare_per_square_metre' => '500', + ]], + ], +]; +$cutRoot = PlanRevision::root($cut); +$cutArtifact = approve(plain($cutRoot->request)); +$first = ArrayCodec::pack(plain($cutRoot->request))['containers'][0]['placements'][0]; +$cutRevision = PlanRevision::derive($cutRoot, $cutArtifact, [ + ['sequence' => 1, 'type' => 'placement_locked', 'placement' => [ + 'placement_id' => $first['placement_id'], + 'item_type' => 'cube', 'container_type' => 'machine', 'container_instance' => 1, + 'position' => [ + 'x' => $first['position']['x']['value'], + 'y' => $first['position']['y']['value'], + 'z' => $first['position']['z']['value'], + ], + 'orientation' => $first['orientation'], + ]], +]); +$derived = plain($cutRevision->request); +echo ' containers offered: ' . implode(', ', array_column($derived['containers'], 'id')) . "\n"; +echo " the lock now points at {$derived['fixed_placements'][0]['container_type']}\n"; +foreach (ArrayCodec::pack($derived)['containers'] as $container) { + echo ' replanned into: ' . count($container['placements']) + . " cubes in a {$container['container_type']}, {$container['inner_dimensions']['length']['value']} mm a side\n"; +} +echo ' audit without the artifact: ' . $codes(PlanRevision::verifyChain([$cutRoot, $cutRevision])) . "\n"; +echo ' audit with it: ' + . $codes(PlanRevision::verifyChain([$cutRoot, $cutRevision], [null, $cutArtifact])) . "\n"; +echo << ['length' => 'mm'], + 'currency' => 'EUR', 'configuration' => [ 'objective' => 'lowest_landed_cost', 'dimensional_weight_divisor' => 5000, @@ -75,6 +79,7 @@ 'prices_minor' => [890, 1240, 2050], 'minimum_charge_minor' => 650, 'fuel_surcharge_permille' => 78, + 'currency' => 'EUR', ], ], ], @@ -97,7 +102,11 @@ printf("containers %s\n", json_encode(array_column($result['containers'], 'container_type'))); printf("placed %d\n", $placed); printf("unplaced %s\n", json_encode($result['unpacked_items'] ?? [])); +printf("currency %s <- the request's own, echoed; it never changes the score\n", $result['currency']); +// `placement_id` is the placement's own identity: the canonical JSON of its container, +// position in ticks, item type and orientation. It is the same in every engine, so a +// fixed placement or a lock can quote it instead of matching coordinates by hand. echo "\none placement, in full:\n"; echo substr(json_encode($result['containers'][0]['placements'][0], JSON_PRETTY_PRINT), 0, 320), " ...\n"; @@ -144,15 +153,59 @@ printf("unknown objective: %s\n", substr($refusal->getMessage(), 0, 100)); } +// A rate card priced in another currency than the request is refused, at its own +// pointer, rather than added to a total in the wrong money. +$dollars = $request; +$dollars['containers'][0]['rate_table']['currency'] = 'USD'; +try { + ArrayCodec::pack($dollars); +} catch (Throwable $refusal) { + printf("rate card in USD: %s\n", $refusal->getMessage()); +} + +// The rotation vocabulary has 24 codes. The six letter codes turn a box; the 18 signed +// ones, such as `-L-W+H`, are the extra turns only a non-box shape can tell apart, so +// they are accepted on a `convex_hull` item and refused on anything else. +$signed = $request; +$signed['items'][0]['allowed_rotations'] = ['LWH', '-L-W+H']; +try { + ArrayCodec::pack($signed); +} catch (Throwable $refusal) { + printf("signed rotation on a box: %s\n", $refusal->getMessage()); +} +$wedges = [ + 'units' => ['length' => 'mm'], + 'configuration' => ['effort_budget' => ['max_search_nodes' => 20000], 'time_limit_ms' => 60000], + 'items' => [[ + 'id' => 'wedge', 'quantity' => 2, 'weight' => '1 kg', 'shape_type' => 'convex_hull', + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100'], + // Half of the cube, cut along a vertical diagonal. Its partner is the same wedge + // turned half a turn about the vertical, `-L-W+H`, which no letter code names. + 'hull_vertices' => [ + ['x' => '0', 'y' => '0', 'z' => '0'], ['x' => '100', 'y' => '0', 'z' => '0'], + ['x' => '0', 'y' => '100', 'z' => '0'], ['x' => '0', 'y' => '0', 'z' => '100'], + ['x' => '100', 'y' => '0', 'z' => '100'], ['x' => '0', 'y' => '100', 'z' => '100'], + ], + 'allowed_rotations' => ['LWH', '-L-W+H'], + ]], + 'containers' => [['id' => 'crate', 'quantity' => 1, + 'inner_dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]], +]; +$pair = ArrayCodec::pack($wedges); +printf("two wedges in one crate: %s, orientations %s\n", $pair['status'], + json_encode(array_column($pair['containers'][0]['placements'], 'orientation'))); + // 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. +// half-honoured. The list is the engine's own constant, empty while it is caught up; a +// combination of implemented fields that has no defined meaning is refused the same way. $refused = array_filter(ArrayCodec::UNSUPPORTED_FIELDS); printf("fields this engine refuses by name: %s\n", $refused === [] ? 'none' : json_encode($refused)); $ahead = $request; $ahead['containers'][0]['pallet_overhang_limit'] = ['length' => '50', 'width' => '50']; +$ahead['containers'][0]['axles'] = [['position' => '0'], ['position' => '100']]; try { ArrayCodec::pack($ahead); } catch (UnsupportedFeatureException $refusal) { diff --git a/examples/units.php b/examples/units.php index b8b8eb1..6f637c2 100644 --- a/examples/units.php +++ b/examples/units.php @@ -21,6 +21,8 @@ use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, Dimensions, Item}; use Packvium\Packer; +use Packvium\Serialization\ArrayCodec; +use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\{Length, Weight}; // ----------------------------------------------------------------------------------- @@ -81,6 +83,22 @@ json_encode(Length::parse('12 3/8 in')->toArray()), json_encode(Weight::parse('2 3/4 lb')->toArray('g'))); +// A JSON request's `units` sets the length unit and nothing else. A weight names its own +// unit or is grams, so `units.weight` would have to override what the weight says -- it +// is refused instead of being read either way. +try { + ArrayCodec::pack([ + 'units' => ['length' => 'mm', 'weight' => 'kg'], + 'configuration' => ['time_limit_ms' => 60000], + 'items' => [['id' => 'tin', 'weight' => '450', + 'dimensions' => ['length' => '80', 'width' => '80', 'height' => '110']]], + 'containers' => [['id' => 'carton', + 'inner_dimensions' => ['length' => '200', 'width' => '200', 'height' => '200']]], + ]); +} catch (InvalidRequestException $refusal) { + printf("\nunits.weight: %s (%s)\n", $refusal->getMessage(), $refusal->reason()); +} + // An example must not change answer merely because the host was busy. This solve needs // a fraction of the budget below; the generous wall-clock value is only a safety fuse, so // a loaded machine cannot cut the multi-start portfolio short and let a different start win. diff --git a/scripts/build_php74.py b/scripts/build_php74.py index 9a4ec2b..6b368f9 100644 --- a/scripts/build_php74.py +++ b/scripts/build_php74.py @@ -222,9 +222,20 @@ def _patch_downgraded_enums() -> None: "use InvalidArgumentException;\n" "final class Rotation\n{\n" " public const LWH='LWH', LHW='LHW', WLH='WLH', WHL='WHL', HLW='HLW', HWL='HWL';\n" - " public static function cases():array{return [self::LWH,self::LHW,self::WLH,self::WHL,self::HLW,self::HWL];}\n" - " public static function all():array{return self::cases();}\n" + # The 18 signed codes only a convex hull may name (1.10), in table order. + " public const PL_NW_NH='+L-W-H', NL_PW_NH='-L+W-H', NL_NW_PH='-L-W+H', " + "PL_NH_PW='+L-H+W', PL_PH_NW='+L+H-W', NL_NH_NW='-L-H-W', " + "PW_NL_PH='+W-L+H', PW_PL_NH='+W+L-H', NW_NL_NH='-W-L-H', " + "PW_NH_NL='+W-H-L', NW_PH_NL='-W+H-L', NW_NH_PL='-W-H+L', " + "PH_NL_NW='+H-L-W', NH_PL_NW='-H+L-W', NH_NL_PW='-H-L+W', " + "PH_NW_PL='+H-W+L', PH_PW_NL='+H+W-L', NH_NW_NL='-H-W-L';\n" + " public static function cases():array{return [self::LWH,self::LHW,self::WLH,self::WHL,self::HLW,self::HWL," + "self::PL_NW_NH,self::NL_PW_NH,self::NL_NW_PH,self::PL_NH_PW,self::PL_PH_NW,self::NL_NH_NW," + "self::PW_NL_PH,self::PW_PL_NH,self::NW_NL_NH,self::PW_NH_NL,self::NW_PH_NL,self::NW_NH_PL," + "self::PH_NL_NW,self::NH_PL_NW,self::NH_NL_PW,self::PH_NW_PL,self::PH_PW_NL,self::NH_NW_NL];}\n" + " public static function all():array{return [self::LWH,self::LHW,self::WLH,self::WHL,self::HLW,self::HWL];}\n" " public static function upright():array{return [self::LWH,self::WLH];}\n" + " public static function every():array{return self::cases();}\n" " public static function from(string $value):string{if(!in_array($value,self::cases(),true))" "throw new InvalidArgumentException('Unknown rotation '.$value);return $value;}\n" "}\n" diff --git a/src-legacy/Algorithm/CandidateFinder.php b/src-legacy/Algorithm/CandidateFinder.php index 0a88c58..aa457a3 100644 --- a/src-legacy/Algorithm/CandidateFinder.php +++ b/src-legacy/Algorithm/CandidateFinder.php @@ -18,9 +18,63 @@ final class CandidateFinder */ public static function find(ContainerState $state,ItemInstance $item,PackingConfig $config,array $constraints,SearchStats $stats,Deadline $deadline,CandidateScorer $scorer,?int $max=null,?array $points=null):array { + $prepared=self::prepare($state,$item,$config,$constraints,$scorer); + if($prepared===null)return []; + $forms=$prepared[3]; + $limitX=$prepared[19]; $container=$state->container; - if($container->maxItems!==null&&count($state->placements)>=$container->maxItems)return []; - if($container->maxPayload!==null&&$state->payloadTicks+$item->weight()->ticks>$container->maxPayload->ticks)return []; + if($points===null){ + if($item->item->nestingHeight===null)$scan=array_slice($state->orderedPoints,0,$config->maxCandidatePoints); + else{ + $merged=[]; + foreach(array_merge($state->orderedPoints, self::nestingPoints($state,$item)) as $candidatePoint) + $merged["{$candidatePoint->x}:{$candidatePoint->y}:{$candidatePoint->z}"]=$candidatePoint; + $scan=array_values($merged); + usort($scan,static function (Point $a, Point $b): int { + return [$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]; + }); + $scan=array_slice($scan,0,$config->maxCandidatePoints); + } + if($container->axles!==null)$scan=self::appendUnseen($scan,self::axleBalancedPoints($state,$item,$forms,$limitX)); + }else{ + $scan=$points; + if(count($scan)>1)usort($scan,static function (Point $a, Point $b): int { + return [$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]; + }); + } + $fixedVerdicts=[]; + return self::scanPoints($prepared,$scan,$max,$stats,$deadline,$fixedVerdicts); + } + + /** + * Evaluate `$spaces` in order, preparing item-invariant forms and constraints once. + * + * @param list $spaces + * @param list $constraints + */ + public static function chooseInSpaces(ContainerState $state,array $spaces,ItemInstance $item,PackingConfig $config,array $constraints,SearchStats $stats,Deadline $deadline,CandidateScorer $scorer):?Candidate + { + if($spaces===[])return null; + $prepared=self::prepare($state,$item,$config,$constraints,$scorer); + if($prepared===null){ + foreach($spaces as $_)$deadline->check(); + return null; + } + $fixedVerdicts=[]; + foreach($spaces as $space){ + $deadline->check(); + foreach(self::scanPoints($prepared,[$space->origin],null,$stats,$deadline,$fixedVerdicts) as $candidate) + if($candidate->envelopeDimensions->fitsInside($space->dimensions))return $candidate; + } + return null; + } + + /** @param list $constraints */ + private static function prepare(ContainerState $state,ItemInstance $item,PackingConfig $config,array $constraints,CandidateScorer $scorer):?array + { + $container=$state->container; + if($container->maxItems!==null&&count($state->placements)>=$container->maxItems)return null; + if($container->maxPayload!==null&&$state->payloadTicks+$item->weight()->ticks>$container->maxPayload->ticks)return null; $compressionSensitive=$state->compressionSensitive ||$item->item->shapeType===ShapeType::COMPRESSIBLE; $reserveNeedsCandidate=$item->item->nestingHeight!==null @@ -28,14 +82,16 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf ||$compressionSensitive; if($container->voidFillReserveRatio>0&&!$reserveNeedsCandidate){ $projected=BigInt::add($state->usedVolume,$item->dimensions()->volumeString()); - if(BigInt::compare($projected,$state->usableVolume())>0)return []; + if(BigInt::compare($projected,$state->usableVolume())>0)return null; } $inner=$container->innerDimensions; $limitX=$inner->length->ticks;$limitY=$inner->width->ticks;$limitZ=$inner->height->ticks; - // A flat bag also needs a + c <= L and b + c <= W over the running extents grown by - // the candidate: O(1), and the extents only grow, so no verdict flips. + // A bag also needs a + c <= L and b + c <= W + G over the running extents grown by + // the candidate (G is a gusseted bag's side gusset, 0 for a flat one): O(1), + // and the extents only grow, so no verdict flips. W + G is summed once per call. $bag=$container->isFlatBag(); $bagX=$state->maxX;$bagY=$state->maxY;$bagZ=$state->maxZ; + $girthY=$limitY+$container->sideGussetTicks(); $clearance=$config->clearance->ticks; // Envelope and extents depend only on the rotation, so they are built once // instead of once per (point, rotation) pair. @@ -76,29 +132,27 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf } $inertSupportChecks=count($active); $defaultScorer=get_class($scorer)===\Packvium\Extension\DefaultCandidateScorer::class; - // A rule that reads no position answers the same at every (point, rotation) of this - // search, so it is asked once, by the first position that reaches it. - // Keyed by chain position; the stored value is the verdict's `allowed`. - $fixedVerdicts=[]; - if($points===null){ - if($item->item->nestingHeight===null)$scan=array_slice($state->orderedPoints,0,$config->maxCandidatePoints); - else{ - $merged=[]; - foreach(array_merge($state->orderedPoints, self::nestingPoints($state,$item)) as $candidatePoint) - $merged["{$candidatePoint->x}:{$candidatePoint->y}:{$candidatePoint->z}"]=$candidatePoint; - $scan=array_values($merged); - usort($scan,static function (Point $a, Point $b): int { - return [$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]; - }); - $scan=array_slice($scan,0,$config->maxCandidatePoints); - } - if($container->axles!==null)$scan=self::appendUnseen($scan,self::axleBalancedPoints($state,$item,$forms,$limitX)); - }else{ - $scan=$points; - if(count($scan)>1)usort($scan,static function (Point $a, Point $b): int { - return [$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]; - }); - } + return [ + $state,$container,$item,$forms,$placed,$stackSensitive,$routeSensitive, + $bounds,$hullShapes,$index,$nesting,$reserveCheck,$usable,$compressionSensitive, + $active,$inertChain,$inertSupportChecks,$defaultScorer,$scorer, + $limitX,$limitY,$limitZ,$bag,$bagX,$bagY,$bagZ,$girthY,$clearance, + ]; + } + + /** + * @param list $scan + * @param array $fixedVerdicts + * @return list + */ + private static function scanPoints(array $prepared,array $scan,?int $max,SearchStats $stats,Deadline $deadline,array &$fixedVerdicts):array + { + [ + $state,$container,$item,$forms,$placed,$stackSensitive,$routeSensitive, + $bounds,$hullShapes,$index,$nesting,$reserveCheck,$usable,$compressionSensitive, + $active,$inertChain,$inertSupportChecks,$defaultScorer,$scorer, + $limitX,$limitY,$limitZ,$bag,$bagX,$bagY,$bagZ,$girthY,$clearance, + ]=$prepared; $out=[];$best=null; $retained=$max!==null&&$max>1?new \SplPriorityQueue():null; $placementOffset=count($bounds)-count($placed); @@ -118,7 +172,7 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf if($bag){ // Ternaries rather than max(): the call made this test dearer (44 ns against 74 ns). $thickness=$z2>$bagZ?$z2:$bagZ; - if(($x2>$bagX?$x2:$bagX)+$thickness>$limitX||($y2>$bagY?$y2:$bagY)+$thickness>$limitY)continue; + if(($x2>$bagX?$x2:$bagX)+$thickness>$limitX||($y2>$bagY?$y2:$bagY)+$thickness>$girthY)continue; } $tentative=null; if($nesting){ @@ -184,7 +238,7 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf $upperBound=BigInt::add($state->usedVolume,Nesting::occupiedVolume($reservePlacement)); $projected=BigInt::compare($upperBound,$usable)<=0 ?$upperBound - :Nesting::usedVolume(TopLoadAssigner::assign(array_merge($placed, [$reservePlacement]))); + :Nesting::usedVolume(TopLoadAssigner::assign(array_merge(is_array($placed) ? $placed : iterator_to_array(is_array($placed) ? new \ArrayIterator($placed) : $placed), [$reservePlacement]))); }else{ $projected=BigInt::add($state->usedVolume,Nesting::usedVolumeDelta($placed,$reservePlacement)); } diff --git a/src-legacy/Algorithm/ContainerState.php b/src-legacy/Algorithm/ContainerState.php index dba8d42..12222bb 100644 --- a/src-legacy/Algorithm/ContainerState.php +++ b/src-legacy/Algorithm/ContainerState.php @@ -3,7 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Constraint\VolumeReserve; use Packvium\Config\PackingConfig; -use Packvium\Domain\{AxisAlignedBox,Container,FlatBag,ItemInstance,LatticeSummary,Nesting,Placement,Point,ShapeType}; +use Packvium\Domain\{AxisAlignedBox,Container,FlatBag,ItemInstance,LatticeSummary,Nesting,PalletOverhang,Placement,Point,ShapeType}; use Packvium\Support\BigInt; /** * Placed boxes plus the candidate points they expose. @@ -242,8 +242,10 @@ private function extendExtent(int $x2,int $y2,int $z2):void * The dimensional weight, in weight ticks, a carrier bills for this container as filled. * * A flat bag is billed on its running extents, the parcel a carrier measures; an empty bag - * has no parcel yet and bills nothing by volume. A rigid container is billed on its declared - * outer size, else its inner size. O(1). + * has no parcel yet and bills nothing by volume. A pallet is billed at the footprint its load + * reached. A rigid container is billed on its declared outer size, else its inner + * size. O(1) but for a pallet, O(p): the state tracks no lowest corner, and pallets are + * deck-first trials of few boxes each. */ public function billedDimensionalWeight(PackingConfig $config):int { @@ -251,6 +253,8 @@ public function billedDimensionalWeight(PackingConfig $config):int if($container->isFlatBag()){ if($this->placements===[])return 0; $dimensions=FlatBag::asDimensions([$this->maxX,$this->maxY,$this->maxZ]); + }elseif($container->deck!==null){ + $dimensions=PalletOverhang::billedDimensions($container,$container->deck,$this->placements); }else{ $dimensions=$container->outerDimensions??$container->innerDimensions; } diff --git a/src-legacy/Algorithm/FixedPlacementAdmission.php b/src-legacy/Algorithm/FixedPlacementAdmission.php index adabc3e..073a081 100644 --- a/src-legacy/Algorithm/FixedPlacementAdmission.php +++ b/src-legacy/Algorithm/FixedPlacementAdmission.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Packvium\Algorithm; use Packvium\Constraint\Internal\LoadSupportGraph; -use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,FixedPlacement,Item,ItemInstance,PackedContainer,PackingRequest,Placement,Point}; +use Packvium\Domain\{AxisAlignedBox,Container,Deck,Dimensions,FixedPlacement,Item,ItemInstance,PackedContainer,PackingRequest,PalletOverhang,Placement,Point}; use Packvium\Support\{CanonicalJson,ExactGeometry,ExactInteger}; use Packvium\Unit\{Length,Weight}; use Packvium\Validation\{FixedPlacementException,IndependentSolutionValidator}; @@ -39,7 +39,7 @@ public static function admit(PackingRequest $request,float $minimumSupportRatio, self::requireContiguousInstances($grouped,$containers,$maxContainers); $packed=[]; foreach($grouped as [$containerId,$sequence,$placements]) - $packed[]=new PackedContainer($containers[$containerId],$sequence,self::withSupportAndLoads($placements)); + $packed[]=new PackedContainer($containers[$containerId],$sequence,self::withSupportAndLoads($placements,$containers[$containerId]->deck)); self::requireValidAlone($request,$packed,$minimumSupportRatio,$clearance); $taken=[];foreach($packed as $container)foreach($container->placements as $placement)$taken[$placement->instance->id()]=true; $free=array_values(array_filter($request->instances(),static function (ItemInstance $instance) use ($taken): bool { @@ -148,22 +148,22 @@ private static function requireContiguousInstances(array $grouped,array $contain * * @param list $placements @return list */ - private static function withSupportAndLoads(array $placements):array + private static function withSupportAndLoads(array $placements,?Deck $deck):array { $supported=[]; foreach($placements as $index=>$placement){ $others=$placements;unset($others[$index]); $supported[]=new Placement($placement->instance,$placement->position,$placement->rotation,$placement->dimensions, - $placement->envelopeOrigin,$placement->envelopeDimensions,self::supportRatio(array_values($others),$placement),new Weight(0),true); + $placement->envelopeOrigin,$placement->envelopeDimensions,self::supportRatio(array_values($others),$placement,$deck),new Weight(0),true); } return TopLoadAssigner::assign($supported); } /** @param list $others */ - private static function supportRatio(array $others,Placement $placement):float + private static function supportRatio(array $others,Placement $placement,?Deck $deck):float { - if($placement->envelopeOrigin->z===0)return 1.0; $box=new AxisAlignedBox($placement->envelopeOrigin,$placement->envelopeDimensions); + if($placement->envelopeOrigin->z===0)return PalletOverhang::floorSupportRatio($deck,$box); $support=LoadSupportGraph::candidateView($others,$placement->instance,$box); return ExactInteger::ratio($support->supportingArea,ExactGeometry::baseArea($placement->envelopeDimensions)); } diff --git a/src-legacy/Algorithm/GridSolver.php b/src-legacy/Algorithm/GridSolver.php index 787284d..02562b9 100644 --- a/src-legacy/Algorithm/GridSolver.php +++ b/src-legacy/Algorithm/GridSolver.php @@ -50,6 +50,10 @@ private static function latticeProfile(\Packvium\Domain\Item $item):string // A lattice joins same-type items only, so two types may share one exactly when // they share the stacking rule as well. $item->stackingGroup,$acceptsStackingGroups, + // packOne refuses a prototype that is not a rigid box, so the shape must be in the + // key too: otherwise a compressible type of the same size and weight joins a rigid + // prototype's lattice and is stacked with no crush check at all. + $item->shapeType, ]); } @@ -85,6 +89,10 @@ public function packOne(Container $container,int $sequence,array $items,PackingC // The lattice counts cells against the rigid frame alone; a bag's girth rule // couples the axes, which the per-candidate check applies exactly. return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); + if($container->deck!==null) + // The lattice rests every floor cell on the whole floor; a pallet's frame bears + // weight only on its deck, which the per-candidate support check reads. + return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); if($container->maxStackDensity!==null) // The single-layer heuristic below only ever reasons about one item // resting on one other, never the cumulative load a tall column presses diff --git a/src-legacy/Algorithm/HomogeneousBlockSolver.php b/src-legacy/Algorithm/HomogeneousBlockSolver.php index 35ff7de..319f5e1 100644 --- a/src-legacy/Algorithm/HomogeneousBlockSolver.php +++ b/src-legacy/Algorithm/HomogeneousBlockSolver.php @@ -102,7 +102,7 @@ public function supports(Container $container,array $items,PackingConfig $config // 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||$container->isFlatBag())return false; + if($this->constraints!==[]||$container->obstacles!==[]||$container->preloaded!==[]||$container->axles!==null||$container->tagLimits!==[]||$container->maxStackDensity!==null||$container->voidFillReserveRatio>0||$container->isFlatBag()||$container->deck!==null)return false; foreach($items as $instance){ $item=$instance->item; 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; diff --git a/src-legacy/Algorithm/Internal/MadeToMeasureTrial.php b/src-legacy/Algorithm/Internal/MadeToMeasureTrial.php index d8844e2..0ade76c 100644 --- a/src-legacy/Algorithm/Internal/MadeToMeasureTrial.php +++ b/src-legacy/Algorithm/Internal/MadeToMeasureTrial.php @@ -5,7 +5,9 @@ use Packvium\Config\PackingConfig; use Packvium\Domain\{Container,ItemInstance,MadeToMeasure}; use Packvium\Extension\{ContainerSelector,DefaultContainerSelector}; -use Packvium\Algorithm\{Deadline,SearchStats,SingleContainerSolution,SingleContainerSolver,TimeLimitReached}; +use Packvium\Algorithm\{ContainerState,Deadline,SearchStats,SingleContainerSolution,SingleContainerSolver,TimeLimitReached}; +use Packvium\Constraint\VolumeReserve; +use Packvium\Support\BigInt; /** * Trials of made-to-measure boxes, loaded only for a made-to-measure container. A part of `SolverOrchestrator` kept in its own file so PHP compiles it only when a @@ -43,6 +45,7 @@ public static function madeToMeasureTrial(\Closure $call,?ContainerSelector $con $last=$one; if($one->state->placementCount()>0){ $trial=$call('fabricated',$container,$one); + if(!self::keepsReserve($trial->state))$trial=$call('fabricated',$container,$one,$rung); if($one->state->placementCount()===count($items))return [$trial,$trials]; $key=$call('roundScore',$trial,$items,$config,$selector); if($best===null||($key<=>$bestKey)<0){$best=$trial;$bestKey=$key;} @@ -52,4 +55,15 @@ public static function madeToMeasureTrial(\Closure $call,?ContainerSelector $con $chosen=$best??$last; return [new SingleContainerSolution($chosen->state,$chosen->unpacked,$chosen->exhaustive,$chosen->timeLimitReached||$stopped,$chosen->dominantLattice),$trials]; } + + /** + * Whether a fabricated box keeps its void-fill reserve. The reserve is a share of the + * box that ships, so a box cut tight to its load can break a reserve the rung kept: the trial + * then cuts the rung itself, on the grid by construction and solved under its reserve. + */ + private static function keepsReserve(ContainerState $state):bool + { + $container=$state->container; + return $container->voidFillReserveRatio===0.0||BigInt::compare($state->usedVolume,VolumeReserve::usable($container))<=0; + } } diff --git a/src-legacy/Algorithm/Internal/PalletTrial.php b/src-legacy/Algorithm/Internal/PalletTrial.php new file mode 100644 index 0000000..d302bae --- /dev/null +++ b/src-legacy/Algorithm/Internal/PalletTrial.php @@ -0,0 +1,103 @@ + $items + * @return array{0:SingleContainerSolution,1:int} + */ + public static function palletTrial(\Closure $call,SingleContainerSolver $solver,Container $frame,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array + { + /** @var Deck $deck a solving frame always carries its deck */ + $deck=$frame->deck; + $rungConfig=$config->requirePlacementCoordinates?$config:$call('withCoordinates',$config); + $onDeck=$solver->packOne(PalletOverhang::deckAlone($frame),$sequence,$items,$rungConfig,$stats,$deadline); + if($onDeck->state->placementCount()===count($items)||$onDeck->timeLimitReached||$deadline->expired()) + return [self::moved($frame,$onDeck,$deck->x,$deck->y),1]; + try{ + $framed=$solver->packOne($frame,$sequence,$items,$rungConfig,$stats,$deadline); + }catch(TimeLimitReached $exception){ + return [self::withOutcome(self::moved($frame,$onDeck,$deck->x,$deck->y),true),1]; + } + if($framed->state->placementCount()>$onDeck->state->placementCount()){ + $seated=self::seated($frame,$framed,$config); + return [new SingleContainerSolution($seated->state,$seated->unpacked,false,$seated->timeLimitReached,$seated->dominantLattice),2]; + } + return [self::withOutcome(self::moved($frame,$onDeck,$deck->x,$deck->y),$framed->timeLimitReached),2]; + } + + /** The trial, never exhaustive, with the time limit as the second rung left it. */ + private static function withOutcome(SingleContainerSolution $one,bool $timeLimitReached):SingleContainerSolution + { + return new SingleContainerSolution($one->state,$one->unpacked,false,$timeLimitReached,$one->dominantLattice); + } + + /** + * A trial's whole load moved by `($dx, $dy)` on the frame, rebuilt so the state's points and + * index describe the frame. Relative geometry is unchanged, so only a floor placement's + * support -- its overlap with the deck -- is measured again. O(p) adds. + */ + private static function moved(Container $frame,SingleContainerSolution $one,int $dx,int $dy):SingleContainerSolution + { + $state=new ContainerState($frame,$one->state->sequence); + foreach($one->state->placements as $placement){ + $origin=self::shifted($placement->envelopeOrigin,$dx,$dy); + $support=$origin->z===0 + ?PalletOverhang::floorSupportRatio($frame->deck,new AxisAlignedBox($origin,$placement->envelopeDimensions)) + :$placement->supportRatio; + $state->add(new Placement($placement->instance,self::shifted($placement->position,$dx,$dy),$placement->rotation,$placement->dimensions, + $origin,$placement->envelopeDimensions,$support,$placement->topLoad,$placement->fixed)); + } + return new SingleContainerSolution($state,$one->unpacked,$one->exhaustive,$one->timeLimitReached,false); + } + + /** + * A frame trial moved to the least overhang (`PalletOverhang::centringOffset`), kept where + * the solver left it if the move would leave a floor placement short of support. O(p). + */ + private static function seated(Container $frame,SingleContainerSolution $one,PackingConfig $config):SingleContainerSolution + { + /** @var Deck $deck a solving frame always carries its deck */ + $deck=$frame->deck; + [$dx,$dy]=PalletOverhang::centringOffset($deck,$one->state->placements); + if($dx===0&&$dy===0)return $one; + $seated=self::moved($frame,$one,$dx,$dy); + $support=new SupportConstraint($config->minimumSupportRatio); + foreach($seated->state->placements as $placement){ + if($placement->envelopeOrigin->z!==0)continue; + $context=new ConstraintContext($frame,[],$placement->instance,$placement->envelopeOrigin,$placement->rotation,$placement->dimensions,$placement->envelopeDimensions); + if(!$support->evaluate($context)->allowed)return $one; + } + return $seated; + } + + private static function shifted(Point $point,int $dx,int $dy):Point + { + return new Point($point->x+$dx,$point->y+$dy,$point->z); + } +} diff --git a/src-legacy/Algorithm/MaximalSpaceSolver.php b/src-legacy/Algorithm/MaximalSpaceSolver.php index d1dcedb..7ad29d6 100644 --- a/src-legacy/Algorithm/MaximalSpaceSolver.php +++ b/src-legacy/Algorithm/MaximalSpaceSolver.php @@ -69,11 +69,6 @@ public function packOne(Container $container,int $sequence,array $items,PackingC /** @param list $spaces @param list $constraints */ private static function choose(ContainerState $state,array $spaces,ItemInstance $item,PackingConfig $config,array $constraints,SearchStats $stats,Deadline $deadline,CandidateScorer $scorer):?Candidate { - foreach($spaces as $space){ - $deadline->check(); - foreach(CandidateFinder::find($state,$item,$config,$constraints,$stats,$deadline,$scorer,null,[$space->origin]) as $candidate) - if($candidate->envelopeDimensions->fitsInside($space->dimensions))return $candidate; - } - return null; + return CandidateFinder::chooseInSpaces($state,$spaces,$item,$config,$constraints,$stats,$deadline,$scorer); } } diff --git a/src-legacy/Algorithm/ObjectiveBoundScope.php b/src-legacy/Algorithm/ObjectiveBoundScope.php index 4e5faa1..0f525fd 100644 --- a/src-legacy/Algorithm/ObjectiveBoundScope.php +++ b/src-legacy/Algorithm/ObjectiveBoundScope.php @@ -7,15 +7,19 @@ /** Request-only bound eligibility; keeps numeric bound code lazy. @internal */ final class ObjectiveBoundScope { + /** A name rather than a position is the one key only that objective ranks by. */ public const OBJECTIVE_ORDERS = [ 'default' => [0, 1, 2, 3, 4], 'lowest_cost' => [0, 2, 1, 3, 4], + 'maximum_value' => [0, 'value_forgone', 1, 2, 3], + 'open_dimension_height' => [0, 'achieved_height', 1, 2, 3], + 'maximum_volume' => ['unpacked_volume_ppm', 0, 1, 2, 3], ]; /** * O(containers) time, O(1) space; no instances or arithmetic are needed to refuse. * @param list $containers - * @return list|null + * @return list|null */ public static function order(array $containers, string $objective): ?array { diff --git a/src-legacy/Algorithm/ObjectiveBounds.php b/src-legacy/Algorithm/ObjectiveBounds.php index f89b92e..ac1ff9e 100644 --- a/src-legacy/Algorithm/ObjectiveBounds.php +++ b/src-legacy/Algorithm/ObjectiveBounds.php @@ -70,10 +70,11 @@ final class ObjectiveBounds public const MAX_BOUND_VALUE = '9007199254740991'; /** - * The objectives a bound is stated for, and where each reads the five bounds: the - * position in `compute`'s default-order vector of each of the objective's score keys. - * `lowest_cost` scores cost ahead of the container count, and the document shows the - * permuted vector is still a bound. Every other objective gets none. + * The objectives a bound is stated for, and where each reads its bounds: the position in + * `compute`'s default-order vector of each of the objective's score keys, or the name of + * the one key only that objective ranks by. `lowest_cost` scores cost ahead of + * the container count, and the document shows the permuted vector is still a bound. + * `shipping_cost` and `lowest_landed_cost` get none. */ public const OBJECTIVE_ORDERS = ObjectiveBoundScope::OBJECTIVE_ORDERS; @@ -84,7 +85,8 @@ final class ObjectiveBounds * (D13: the unused-volume key would read the machine maximum while the score * reads the fabricated box), and for a request past a declared ceiling. The last * withholds the bound and nothing else -- the pack is answered as it was before any - * bound existed, rather than failing with `BoundOverflowException` (finding F5). + * bound existed, rather than failing with `BoundOverflowException` (finding F5). An + * objective's own key past the portable ceiling withholds that objective's bound alone. * * @param list $instances every instance of the request, fixed ones included * @param list $containers @@ -97,15 +99,162 @@ public static function forRequest(array $instances, array $containers, string $o return null; } try { - $vector = self::compute($instances, $containers); + [$normalisedInstances, $normalisedContainers] = self::normalise($instances, $containers); + return self::objectiveVector($normalisedInstances, $normalisedContainers, $order); } catch (BoundOverflowException $refused) { return null; } - return array_map(static function (int $position) use ($vector): int { - return $vector[$position]; + } + + /** + * The bound in one objective's score order, from the normalised numbers `fromNormalised` + * reads plus each instance's `value`, throwing `BoundOverflowException` where a ceiling + * withholds it -- the one predicate's, or the objective's own key's. + * + * @param list $instances + * @param list $containers + * @param list $order an `OBJECTIVE_ORDERS` entry + * @return list + */ + public static function objectiveVector(array $instances, array $containers, array $order): array + { + $evaluated = self::evaluate($instances, $containers); + $vector = $evaluated['vector']; + return array_map(static function ($position) use ($vector, $instances, $evaluated): int { + return is_int($position) + ? $vector[$position] + : self::objectiveTerm($position, $instances, $evaluated); }, $order); } + /** + * The bound on the one key an objective ranks by and the default does not. + * + * Each is conditional on the keys before it, as `fromNormalised`'s are: the value and + * height terms hold for every packing that leaves exactly `L0` instances behind, and the + * volume term leads its objective and holds for every packing. + * + * No term sorts: `evaluate` already paid for the only volume sort (finding F6 doubled that + * cost once) and hands its ascending volumes and capacity total over, and the value term + * selects the `L0` smallest values with a bounded heap in `O(n log L0)`. With `O(c)` over + * the container types the request bound stays `O(n log n + c log c)`. + * + * @param list $instances + * @param array{vector:array{int,int,int,int,int},volumes:list,shrinks:bool,areas:list,capacity:?string} $evaluated + */ + private static function objectiveTerm(string $name, array $instances, array $evaluated): int + { + $unpacked = $evaluated['vector'][0]; + if ($name === 'value_forgone') { + return self::valueForgoneBound(array_column($instances, 'value'), $unpacked); + } + if ($name === 'achieved_height') { + return self::achievedHeightBound($evaluated['volumes'], $evaluated['shrinks'], + count($instances) - $unpacked, $evaluated['areas']); + } + return self::unpackedVolumeBound($evaluated['volumes'], $evaluated['shrinks'], + $evaluated['capacity']); + } + + /** + * `maximum_value`'s second key: whichever `$unpacked` instances are left behind, their + * value is at least that of the `$unpacked` least valuable. Values are non-negative, so + * the sum passes the portable ceiling exactly when some running sum does. + * + * @param list $values + */ + private static function valueForgoneBound(array $values, int $unpacked): int + { + return self::guardOutput(self::sumBig(array_map(\Closure::fromCallable('strval'), self::smallestValues($values, $unpacked))), + 'value forgone'); + } + + /** + * The `$count` smallest of `$values`, in no particular order, without sorting them all: a + * max-heap holding the smallest seen so far evicts its largest whenever it overfills. + * `O(n log count)` time, `O(count)` space. + * + * @param list $values + * @return list + */ + private static function smallestValues(array $values, int $count): array + { + if ($count <= 0) { + return []; + } + if ($count >= count($values)) { + return $values; + } + $kept = new \SplMaxHeap(); + foreach ($values as $value) { + $kept->insert($value); + if ($kept->count() > $count) { + $kept->extract(); + } + } + return iterator_to_array($kept, false); + } + + /** + * `open_dimension_height`'s second key, the summed tops in ticks. + * + * A container holding volume `v` on floor `A` stands at least `v / A` tall, because its + * placements are disjoint boxes inside `A x top`. Summed over the opened containers that + * is at least the placed volume over the widest floor, and the score is an integer. The + * placed volume is at least the `$placed` smallest. An instance that occupies less than + * its box breaks the disjoint-boxes step, so the term is dropped. + * + * @param list $volumes ascending + * @param list $areas square ticks, exact past a native int + */ + private static function achievedHeightBound(array $volumes, bool $shrinks, int $placed, + array $areas): int + { + $widest = array_reduce($areas, \Closure::fromCallable([ExactInteger::class, 'max']), 0); + if ($shrinks || $placed <= 0 || ExactInteger::sign($widest) <= 0) { + return 0; + } + return self::guardOutput( + self::ceilDivide(self::sumBig(array_slice($volumes, 0, $placed)), (string)$widest), + 'achieved height', + ); + } + + /** + * `maximum_volume`'s first key: the volume no inventory can hold, as the score's own + * rounded-up share of the requested volume. + * + * The packed volume is at most the summed usable capacity, so at least the rest is left + * behind whatever the geometry does. Unlimited inventory (a null capacity) holds + * everything, and an instance that occupies less than its box stops nominal volumes + * summing, so both give 0. The share is at most `PPM`, so it needs no output guard. + * + * @param list $volumes + */ + private static function unpackedVolumeBound(array $volumes, bool $shrinks, ?string $capacity): int + { + if ($shrinks || $capacity === null) { + return 0; + } + $requested = self::sumBig($volumes); + if (BigInt::compare($requested, $capacity) <= 0) { + return 0; + } + return (int)self::ceilDivide( + BigInt::multiply(BigInt::subtract($requested, $capacity), (string)self::PPM), + $requested, + ); + } + + /** `ceil(numerator / denominator)` for a non-negative numerator and positive denominator. */ + private static function ceilDivide(string $numerator, string $denominator): string + { + if (BigInt::compare($numerator, '0') === 0) { + return '0'; + } + return BigInt::divide(BigInt::add(BigInt::subtract($numerator, '1'), $denominator), $denominator); + } + /** * The `optimality` fields one result states against its request's bound * (OPTIMALITY-GAP.md § 1.1), or null where § 1.5 withholds them. @@ -193,6 +342,18 @@ private static function guardOutput(string $value, string $quantity): int * @return array{int,int,int,int,int} */ public static function compute(array $instances, array $containers): array + { + return self::fromNormalised(...self::normalise($instances, $containers)); + } + + /** + * The numbers the formulas consume, read once from the engine objects. + * + * @param list $instances + * @param list $containers + * @return array{0:list,1:list} + */ + private static function normalise(array $instances, array $containers): array { $normalisedInstances = []; foreach ($instances as $instance) { @@ -200,6 +361,7 @@ public static function compute(array $instances, array $containers): array 'volume' => $instance->item->dimensions->volumeString(), 'weight' => $instance->item->weight->ticks, 'shrinks' => self::occupiesLessThanItsBox($instance->item), + 'value' => $instance->item->value ?? 0, ]; } $normalisedContainers = []; @@ -215,7 +377,7 @@ public static function compute(array $instances, array $containers): array 'cost_minor' => $container->costMinor, ]; } - return self::fromNormalised($normalisedInstances, $normalisedContainers); + return [$normalisedInstances, $normalisedContainers]; } /** @@ -227,11 +389,28 @@ public static function compute(array $instances, array $containers): array * flag correctly for a `convex_hull` is asserted separately, in this engine's own tests, * so a port cannot pass the arithmetic check by copying a flag it never computes. * - * @param list $instances + * Each instance's `value` is not read here: only `objectiveVector`'s `maximum_value` key + * consumes it. + * + * @param list $instances * @param list $containers * @return array{int,int,int,int,int} */ public static function fromNormalised(array $instances, array $containers): array + { + return self::evaluate($instances, $containers)['vector']; + } + + /** + * `fromNormalised`'s vector, with the intermediates the objective-only keys reuse rather + * than recompute: the ascending volumes, the shrink flag, the floors and the volume + * capacity total (null when unbounded). + * + * @param list $instances + * @param list $containers + * @return array{vector:array{int,int,int,int,int},volumes:list,shrinks:bool,areas:list,capacity:?string} + */ + private static function evaluate(array $instances, array $containers): array { $volumes = []; $weights = []; @@ -291,13 +470,15 @@ public static function fromNormalised(array $instances, array $containers): arra $cost = self::costBound($costs, $quantities, $opened); $unused = self::unusedVolumeBound($volumes, $shrinks, $placed, $inner, $opened); $height = self::stackHeightBound($volumes, $shrinks, $placed, $areas, $heights, $opened); - return [ + $vector = [ self::guardOutput((string)$unpacked, 'unpacked count'), self::guardOutput((string)$opened, 'container count'), self::guardOutput((string)$cost, 'opening cost'), self::guardOutput((string)$unused, 'unused volume'), self::guardOutput((string)$height, 'stack height'), ]; + return ['vector' => $vector, 'volumes' => $volumes, 'shrinks' => $shrinks, + 'areas' => $areas, 'capacity' => $capacities['volume']]; } /** diff --git a/src-legacy/Algorithm/SolverOrchestrator.php b/src-legacy/Algorithm/SolverOrchestrator.php index 1cf644b..c2a04e8 100644 --- a/src-legacy/Algorithm/SolverOrchestrator.php +++ b/src-legacy/Algorithm/SolverOrchestrator.php @@ -9,7 +9,7 @@ use Packvium\Result\StartRecord; use Packvium\Support\{BigInt,ExactGeometry,ExactInteger,StableSorter}; use Packvium\Objective\{LandedCostSolutionScorer,ObjectiveRegistry}; -use Packvium\Algorithm\Internal\{ConcurrentStarts,ContainerPlanBeam,MadeToMeasureTrial,QualityStages}; +use Packvium\Algorithm\Internal\{ConcurrentStarts,ContainerPlanBeam,MadeToMeasureTrial,PalletTrial,QualityStages}; final class SolverOrchestrator { /** @@ -261,7 +261,7 @@ function ($i) use ($containers) { */ private static function fitsAlone(Container $container,Dimensions $dimensions):bool { - return $container->isFlatBag()?FlatBag::fitsAlone($container->innerDimensions,$dimensions):$dimensions->fitsInside($container->innerDimensions); + return $container->isFlatBag()?FlatBag::fitsAlone($container->innerDimensions,$dimensions,$container->sideGussetTicks()):$dimensions->fitsInside($container->innerDimensions); } /** @param list $containers */ @@ -689,21 +689,31 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem /** * One container's trial for a round, and how many single-container solves it spent. A * declared container is one solve; a made-to-measure one runs the rung chain and returns - * its trial already fabricated. + * its trial already fabricated; a pallet's frame without fixed items packs its + * deck first. * * @param list $items * @return array{0:SingleContainerSolution,1:int} */ private function trial(SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array { - if($container->madeToMeasure===null)return [$solver->packOne($container,$sequence,$items,$config,$stats,$deadline),1]; - return MadeToMeasureTrial::madeToMeasureTrial($this->bridge(),$this->containerSelector,$solver,$container,$sequence,$items,$config,$stats,$deadline); + if($container->madeToMeasure!==null) + return MadeToMeasureTrial::madeToMeasureTrial($this->bridge(),$this->containerSelector,$solver,$container,$sequence,$items,$config,$stats,$deadline); + if($container->deck!==null&&$container->preloaded===[]) + return PalletTrial::palletTrial($this->bridge(),$solver,$container,$sequence,$items,$config,$stats,$deadline); + return [$solver->packOne($container,$sequence,$items,$config,$stats,$deadline),1]; } - /** A rung trial as the box cut for it: the achieved extent of its placements, envelope far faces with clearance, rounded up onto the machine grid (D14). O(p). */ - private static function fabricated(Container $declared,SingleContainerSolution $one):SingleContainerSolution + /** + * A rung trial as the box cut for it: the achieved extent of its placements, envelope far faces + * with clearance, rounded up onto the machine grid (D14); or, given `$rung`, the rung itself, + * which is already on the grid. O(p). + * + * @param array{0:int,1:int,2:int}|null $rung + */ + private static function fabricated(Container $declared,SingleContainerSolution $one,?array $rung=null):SingleContainerSolution { - $box=$declared->fabricate(FlatBag::extentOf($one->state->placements)); + $box=$declared->fabricate($rung??FlatBag::extentOf($one->state->placements)); return new SingleContainerSolution($one->state->withContainer($box),$one->unpacked,false,$one->timeLimitReached,false); } diff --git a/src-legacy/Algorithm/SupportCalculator.php b/src-legacy/Algorithm/SupportCalculator.php index 7d710f4..d61d057 100644 --- a/src-legacy/Algorithm/SupportCalculator.php +++ b/src-legacy/Algorithm/SupportCalculator.php @@ -2,15 +2,16 @@ declare(strict_types=1); namespace Packvium\Algorithm; use Packvium\Constraint\Internal\LoadSupportGraph; -use Packvium\Domain\{AxisAlignedBox,ItemInstance}; +use Packvium\Domain\{AxisAlignedBox,ItemInstance,PalletOverhang}; use Packvium\Support\{ExactGeometry,ExactInteger}; final class SupportCalculator { - /** Reported support fraction, from resting contact with other placements only. */ + /** Reported support fraction, from resting contact with other placements, or on the floor with a pallet's deck. */ public static function ratio(ContainerState $state,ItemInstance $item,Candidate $c):float { - if($c->point->z===0)return 1.0; $box=new AxisAlignedBox($c->point,$c->envelopeDimensions); + // A floor without a deck is whole support; deciding it here keeps `PalletOverhang` unloaded. + if($c->point->z===0)return $state->container->deck===null?1.0:PalletOverhang::floorSupportRatio($state->container->deck,$box); $support=LoadSupportGraph::candidateView($state->placements,$item,$box); return ExactInteger::ratio($support->supportingArea,ExactGeometry::baseArea($c->envelopeDimensions)); } diff --git a/src-legacy/Artifacts/ArtifactExports.php b/src-legacy/Artifacts/ArtifactExports.php index 9acc487..08c793e 100644 --- a/src-legacy/Artifacts/ArtifactExports.php +++ b/src-legacy/Artifacts/ArtifactExports.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Artifacts; +use Packvium\Support\CanonicalJson; use Packvium\Support\JsonValue; /** @@ -312,10 +313,18 @@ private static function orDash($value): string */ private static function successor($index): string { + if (self::isIntegralFloat($index)) { + return self::text($index); + } if (!\is_int($index)) { throw new OperationalArtifactException('invalid_value', 'a container_index is not an integer'); } - return (string) ($index + 1); + // Checked before the addition, which past PHP_INT_MAX would turn into a float: the + // number shown is the index plus one, so 2^53 - 1 is already one past the ceiling. + if ($index >= CanonicalJson::MAX_EXACT_MAGNITUDE) { + throw new OperationalArtifactException('number_out_of_range', "container index {$index} is beyond what every engine holds exactly"); + } + return self::text($index + 1); } // ----------------------------------------------------------------------------- helpers @@ -335,6 +344,12 @@ private static function text($value): string if (\is_string($value)) { return $value; } + // Beyond 2^53 - 1 JavaScript has already rounded the integer, so its decimal would + // differ; past PHP_INT_MAX json_decode has made it a float, but it is still a whole number. + if (self::isIntegralFloat($value) + || (\is_int($value) && ($value > CanonicalJson::MAX_EXACT_MAGNITUDE || $value < -CanonicalJson::MAX_EXACT_MAGNITUDE))) { + throw new OperationalArtifactException('number_out_of_range', \json_encode($value) . ' is beyond what every engine holds exactly'); + } if (\is_int($value)) { return (string) $value; } @@ -342,6 +357,17 @@ private static function text($value): string throw new OperationalArtifactException('invalid_value', "a {$type} has no single rendering in a work order"); } + /** + * A whole number json_decode could only hold as a float, past PHP_INT_MAX. + * + * @param mixed $value + */ + private static function isIntegralFloat($value): bool + { + return \is_float($value) && \is_finite($value) && \floor($value) === $value + && \abs($value) > CanonicalJson::MAX_EXACT_MAGNITUDE; + } + /** * Python's truthiness for a JSON value: null, false, zero, an empty string, an empty array * and an empty object are false. PHP's own rule differs at `"0"`. diff --git a/src-legacy/Artifacts/OperationalArtifact.php b/src-legacy/Artifacts/OperationalArtifact.php index 5c8b0f1..7561c3c 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.9.0'; + public const SUITE_VERSION = '1.10.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']; @@ -168,12 +168,44 @@ public static function canonicalJson($artifact): string private static function plan($request, $result, array $loadingOrders): array { try { - return Plan::build($request, $result, $loadingOrders); + return Plan::build($request, self::withoutPlacementIds($result), $loadingOrders); } catch (ExecutionPlanException $error) { throw new OperationalArtifactException('invalid_plan_input', $error->getMessage(), $error); } } + /** + * The result as the v1 artifact reads it: every placement without its 1.10 `placement_id`. + * + * v1 is closed, and its embedded plan and placement references predate the id, so a plan + * built from a 1.10 result would otherwise gain a field inside a closed document. The id is + * recoverable from what v1 does carry: the canonical JSON of the result's + * `containers[container_index].id` and the reference's `position_ticks`, `item_type` and + * `orientation` (docs/OPERATIONAL-ARTIFACTS.md). Read after `requireObjects`, so every + * entry is an object; copies only what it changes, O(P). + * + * @param array|\stdClass $result + * @return array + */ + private static function withoutPlacementIds($result): array + { + $containers = []; + foreach (self::listOf(JsonValue::get($result, 'containers'), 'result.containers') as $index => $container) { + $placements = []; + foreach (self::placements($index, $container) as $placement) { + $placement = (array) $placement; + unset($placement['placement_id']); + $placements[] = $placement; + } + $container = (array) $container; + $container['placements'] = $placements; + $containers[] = $container; + } + $stripped = (array) $result; + $stripped['containers'] = $containers; + return $stripped; + } + // -------------------------------------------------------------------------- provenance /** diff --git a/src-legacy/Constraint/ContactGraph.php b/src-legacy/Constraint/ContactGraph.php index caaf463..e11e1e9 100644 --- a/src-legacy/Constraint/ContactGraph.php +++ b/src-legacy/Constraint/ContactGraph.php @@ -285,7 +285,18 @@ private function matches(array $buckets, array &$cache, int $plane, AxisAlignedB if (!isset($buckets[$plane])) { return []; } - $level = ($cache[$plane] = $cache[$plane] ?? new ContactLevelIndex($this->cell, $buckets[$plane])); + $entries = $buckets[$plane]; + if (count($entries) <= 32) { + $matches = []; + foreach ($entries as [$otherIndex, $other]) { + $area = ExactGeometry::overlapAreaXY($other, $box); + if ($area > 0) { + $matches[] = [$otherIndex, $area]; + } + } + return $matches; + } + $level = ($cache[$plane] = $cache[$plane] ?? new ContactLevelIndex($this->cell, $entries)); $matches = []; foreach ($level->near($box) as [$otherIndex, $other]) { $area = ExactGeometry::overlapAreaXY($other, $box); diff --git a/src-legacy/Constraint/Internal/LoadSupportGraph.php b/src-legacy/Constraint/Internal/LoadSupportGraph.php index 57d5ef7..183e599 100644 --- a/src-legacy/Constraint/Internal/LoadSupportGraph.php +++ b/src-legacy/Constraint/Internal/LoadSupportGraph.php @@ -35,6 +35,10 @@ final class LoadSupportGraph private $descending; /** @var list|null */ private $priorDescending; + /** @var array>|null */ + private $planeByTop; + /** @var array>|null */ + private $planeByBottom; /** @var list|null */ private static $cachedPlanePlacements; /** @var array> */ @@ -137,6 +141,8 @@ public function withUnit(LoadUnit $unit,int $cellHint=1):self $graph=clone $this; $graph->descending=null; $graph->priorDescending=$this->descendingIndices(); + $graph->planeByTop=null; + $graph->planeByBottom=null; $graph->face=$this->face->withBox($unit->box); $graph->units[]=$unit; // Without nesting this graph *is* the face graph, so read the edges straight off @@ -145,6 +151,55 @@ public function withUnit(LoadUnit $unit,int $cellHint=1):self return $graph; } + public function isNested():bool{return $this->nested;} + + /** @return list */ + public function contactsBelow(AxisAlignedBox $box):array + { + if($this->planeByTop===null)$this->buildPlaneExtents(); + $entries=$this->planeByTop[$box->origin->z]??[]; + if($entries===[])return []; + $bx1=$box->origin->x;$by1=$box->origin->y;$bx2=$box->x2();$by2=$box->y2(); + $out=[]; + foreach($entries as [$otherIndex,$ox1,$oy1,$ox2,$oy2]){ + $dx=($bx2<$ox2?$bx2:$ox2)-($bx1>$ox1?$bx1:$ox1); + if($dx<=0)continue; + $dy=($by2<$oy2?$by2:$oy2)-($by1>$oy1?$by1:$oy1); + if($dy>0)$out[]=new ContactEdge($otherIndex,ExactInteger::mul($dx,$dy)); + } + return $out; + } + + /** @return list */ + public function contactsAbove(AxisAlignedBox $box):array + { + if($this->planeByBottom===null)$this->buildPlaneExtents(); + $entries=$this->planeByBottom[$box->z2()]??[]; + if($entries===[])return []; + $bx1=$box->origin->x;$by1=$box->origin->y;$bx2=$box->x2();$by2=$box->y2(); + $out=[]; + foreach($entries as [$otherIndex,$ox1,$oy1,$ox2,$oy2]){ + $dx=($bx2<$ox2?$bx2:$ox2)-($bx1>$ox1?$bx1:$ox1); + if($dx<=0)continue; + $dy=($by2<$oy2?$by2:$oy2)-($by1>$oy1?$by1:$oy1); + if($dy>0)$out[]=new ContactEdge($otherIndex,ExactInteger::mul($dx,$dy)); + } + return $out; + } + + private function buildPlaneExtents():void + { + $byTop=[];$byBottom=[]; + foreach($this->units as $index=>$unit){ + $b=$unit->box; + $entry=[$index,$b->origin->x,$b->origin->y,$b->x2(),$b->y2()]; + $byTop[$b->z2()][]=$entry; + $byBottom[$b->origin->z][]=$entry; + } + $this->planeByTop=$byTop; + $this->planeByBottom=$byBottom; + } + /** @return list Canonical load order, shared across candidate siblings. */ public function descendingIndices():array { @@ -206,7 +261,7 @@ public function nonStackableFailure(array $placements,ItemInstance $item,int $ca } /** Why `$lower` refuses an item of `$upperGroup` resting directly on it, or null. O(1). */ - private static function stackingRefusal(Item $lower,?string $upperGroup):?string + public static function stackingRefusal(Item $lower,?string $upperGroup):?string { if(!$lower->stackable)return 'non_stackable'; if(!$lower->acceptsStackingGroup($upperGroup))return 'stacking_group_incompatible'; diff --git a/src-legacy/Constraint/Internal/PlacedSupportBase.php b/src-legacy/Constraint/Internal/PlacedSupportBase.php index bd02a74..c97d986 100644 --- a/src-legacy/Constraint/Internal/PlacedSupportBase.php +++ b/src-legacy/Constraint/Internal/PlacedSupportBase.php @@ -1,8 +1,9 @@ |null */ + private $baseLoads; + /** @var list|null */ + private $baseStackedCounts; /** - * `$placements`' units and graph with `$unit` appended at the last index. - * - * @param list $placements - * @return array{0:list,1:LoadSupportGraph} + * @var bool */ - public function withCandidate(array $placements,LoadUnit $unit):array - { - $box=$unit->box; - $base=$this->baseFor($placements,max($box->x2()-$box->origin->x,$box->y2()-$box->origin->y)); - $units=$this->baseUnits; - $units[]=$unit; - return [$units,$base->withUnit($unit,$this->hint)]; - } + private $baseHasMaxTop=false; + /** + * @var bool + */ + private $baseHasCrush=false; + /** + * @var bool + */ + private $baseHasMaxStacked=false; + /** + * @var bool|null + */ + private $baseBearingHolds; + /** + * @var int|null + */ + private $baseDensityChecked; + /** + * @var bool|null + */ + private $baseDensityHolds; + /** @var list|null */ + private $baseStops; + /** + * @var bool + */ + private $baseRouted=false; + /** @var list|null */ + private $baseMaxStopAbove; + /** + * @var bool|null + */ + private $baseRouteHolds; /** * The support graph over `$placements` alone, rebuilt only when it cannot serve. @@ -62,8 +88,375 @@ private function baseFor(array $placements,int $footprint):LoadSupportGraph if($same&&$footprint<=$this->hint)return $this->base; $this->hint=max($same?$this->hint:1,$footprint); $this->placements=$placements; - $this->baseUnits=LoadCalculator::units($placements); + if(!$same)$this->baseUnits=LoadCalculator::units($placements); $this->base=new LoadSupportGraph($this->baseUnits,$this->hint); + if(!$same){ + $this->baseLoads=null; + $this->baseStackedCounts=null; + $this->baseBearingHolds=null; + $this->baseDensityChecked=null; + $this->baseDensityHolds=null; + $this->baseStops=null; + $this->baseRouted=false; + $this->baseMaxStopAbove=null; + $this->baseRouteHolds=null; + } return $this->base; } + + private function settleBearing(?int $densityLimit):bool + { + assert($this->base!==null); + $baseUnits=$this->baseUnits; + if($this->baseBearingHolds===null){ + $hasMaxTop=false;$hasCrush=false;$hasMaxStacked=false; + foreach($baseUnits as $u){ + if($u->maxTopLoadTicks!==null)$hasMaxTop=true; + if($u->maxCompressionPressureKpa!==null)$hasCrush=true; + if($u->maxStackedItems!==null)$hasMaxStacked=true; + } + $this->baseHasMaxTop=$hasMaxTop; + $this->baseHasCrush=$hasCrush; + $this->baseHasMaxStacked=$hasMaxStacked; + $analysis=new LoadAnalysis($baseUnits,$this->base); + $loads=$analysis->topLoads(); + $this->baseLoads=$loads; + $holds=$analysis->overloaded()===null&&$analysis->crushed()===null; + if($hasMaxStacked){ + $counts=$analysis->stackedCounts(); + $this->baseStackedCounts=$counts; + if($holds){ + foreach($baseUnits as $idx=>$u) + if($u->maxStackedItems!==null&&$counts[$idx]>$u->maxStackedItems){$holds=false;break;} + } + } + $this->baseBearingHolds=$holds; + } + if(!$this->baseBearingHolds)return false; + if($densityLimit===null)return true; + if($this->baseDensityChecked!==$densityLimit||$this->baseDensityHolds===null){ + assert($this->baseLoads!==null); + $this->baseDensityChecked=$densityLimit; + $holds=true; + foreach($baseUnits as $idx=>$u){ + $total=$u->weightTicks+$this->baseLoads[$idx]; + $bearing=BigInt::multiply($total,LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($u->box->dimensions)); + if(BigInt::compare($bearing,$allowed)>0){$holds=false;break;} + } + $this->baseDensityHolds=$holds; + } + return $this->baseDensityHolds; + } + + public function evaluateTopLoad(ConstraintContext $c):ConstraintResult + { + $candidate=$c->envelopeBox(); + $item=$c->item->item; + $footprint=max($candidate->x2()-$candidate->origin->x,$candidate->y2()-$candidate->origin->y); + $base=$this->baseFor($c->placements,$footprint); + $baseUnits=$this->baseUnits; + $densityLimit=($nullsafeVariable1 = $c->container->maxStackDensity) ? $nullsafeVariable1->ticks : null; + if(!$base->isNested()&&$item->nestingHeight===null&&$this->settleBearing($densityLimit)){ + $below=$base->contactsBelow($candidate); + $above=$base->contactsAbove($candidate); + $upperGroup=$item->stackingGroup; + $placements=$c->placements; + foreach($below as $edge){ + $lower=$placements[$edge->index]->instance->item; + $code=LoadSupportGraph::stackingRefusal($lower,$upperGroup); + if($code!==null)return ConstraintResult::reject($code,$lower->id); + } + if(!$item->stackable||$item->acceptsStackingGroups!==[]){ + foreach($above as $edge){ + $code=LoadSupportGraph::stackingRefusal($item,$placements[$edge->index]->instance->item->stackingGroup); + if($code!==null)return ConstraintResult::reject($code,$item->id); + } + } + $hasMaxTop=$this->baseHasMaxTop||$item->maxTopLoad!==null; + $hasCrush=$this->baseHasCrush||$item->maxCompressionPressureKpa!==null; + $hasMaxStacked=$this->baseHasMaxStacked||$item->maxStackedItems!==null; + if(!$hasMaxTop&&!$hasCrush&&!$hasMaxStacked&&$densityLimit===null)return ConstraintResult::allow(); + if($below===[]&&$above===[]){ + if($densityLimit!==null){ + $bearing=BigInt::multiply($c->item->weight()->ticks,LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($candidate->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$c->item->id()); + } + return ConstraintResult::allow(); + } + if($above===[]){ + $baseLoads=$this->baseLoads; + assert($baseLoads!==null); + $allFloor=true; + foreach($below as $edge)if($base->supporters($edge->index)!==[]){$allFloor=false;break;} + if($allFloor){ + $downward=$c->item->weight()->ticks; + $totalArea=0; + foreach($below as $edge)$totalArea=ExactInteger::add($totalArea,$edge->area); + $assigned=0;$lastPos=count($below)-1; + $shares=[]; + foreach($below as $pos=>$edge){ + if($totalArea!==0&&$downward>0){ + $share=$pos===$lastPos?$downward-$assigned:ExactInteger::mulDiv($downward,$edge->area,$totalArea); + $assigned+=$share; + }else $share=0; + $shares[]=$share; + } + if($this->baseHasMaxTop){ + foreach($below as $pos=>$edge){ + $u=$edge->index; + $limitTicks=$baseUnits[$u]->maxTopLoadTicks; + if($limitTicks!==null&&$baseLoads[$u]+$shares[$pos]>$limitTicks) + return ConstraintResult::reject('top_load_exceeded',$baseUnits[$u]->label); + } + } + if($this->baseHasCrush){ + foreach($below as $pos=>$edge){ + $unitU=$baseUnits[$edge->index]; + $limitKpa=$unitU->maxCompressionPressureKpa; + if($limitKpa===null)continue; + $boxU=$unitU->box; + $fp=$unitU->footprintTicks2??ExactInteger::mul($boxU->x2()-$boxU->origin->x,$boxU->y2()-$boxU->origin->y); + if(Compression::exceeds(Compression::pressure($baseLoads[$edge->index]+$shares[$pos],$fp),$limitKpa)) + return ConstraintResult::reject('crush_violation',$unitU->label); + } + } + if($this->baseHasMaxStacked){ + assert($this->baseStackedCounts!==null); + foreach($below as $edge){ + $u=$edge->index; + $maxStacked=$baseUnits[$u]->maxStackedItems; + if($maxStacked!==null&&$this->baseStackedCounts[$u]+1>$maxStacked) + return ConstraintResult::reject('stacked_item_limit_exceeded',$baseUnits[$u]->label); + } + } + if($densityLimit!==null){ + foreach($below as $pos=>$edge){ + $u=$edge->index; + $unitU=$baseUnits[$u]; + $bearing=BigInt::multiply($unitU->weightTicks+$baseLoads[$u]+$shares[$pos],LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($unitU->box->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$unitU->label); + } + $bearing=BigInt::multiply($downward,LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($candidate->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$c->item->id()); + } + return ConstraintResult::allow(); + } + + $pending=[];$seenAffected=[]; + foreach($below as $edge){$pending[]=$edge->index;$seenAffected[$edge->index]=true;} + $idx=0; + while($idxsupporters($u) as $edge){ + if(!isset($seenAffected[$edge->index])){ + $seenAffected[$edge->index]=true; + $pending[]=$edge->index; + } + } + } + $deltaLoads=[]; + if($hasMaxTop||$hasCrush||$densityLimit!==null){ + $downward=$c->item->weight()->ticks; + $totalArea=0; + foreach($below as $edge)$totalArea=ExactInteger::add($totalArea,$edge->area); + if($totalArea!==0&&$downward>0){ + $assigned=0;$lastPos=count($below)-1; + foreach($below as $pos=>$edge){ + $share=$pos===$lastPos?$downward-$assigned:ExactInteger::mulDiv($downward,$edge->area,$totalArea); + $assigned+=$share; + $deltaLoads[$edge->index]=($deltaLoads[$edge->index]??0)+$share; + } + } + $order=array_keys($seenAffected); + usort($order,static function (int $a, int $b) use ($baseUnits): int { + return [-$baseUnits[$a]->box->z2(),-$baseUnits[$a]->box->origin->z,$a]<=>[-$baseUnits[$b]->box->z2(),-$baseUnits[$b]->box->origin->z,$b]; + }); + foreach($order as $u){ + $dLoad=$deltaLoads[$u]??0; + if($dLoad===0)continue; + $supports=$base->supporters($u); + if($supports===[])continue; + $totalArea=0; + foreach($supports as $edge)$totalArea=ExactInteger::add($totalArea,$edge->area); + if($totalArea===0)continue; + $oldDownward=$baseUnits[$u]->weightTicks+$baseLoads[$u]; + $newDownward=$oldDownward+$dLoad; + $oldAssigned=0;$newAssigned=0;$lastPos=count($supports)-1; + foreach($supports as $pos=>$edge){ + if($pos===$lastPos){ + $oldShare=$oldDownward-$oldAssigned; + $newShare=$newDownward-$newAssigned; + }else{ + $oldShare=ExactInteger::mulDiv($oldDownward,$edge->area,$totalArea); + $newShare=ExactInteger::mulDiv($newDownward,$edge->area,$totalArea); + $oldAssigned+=$oldShare; + $newAssigned+=$newShare; + } + $diff=$newShare-$oldShare; + if($diff!==0)$deltaLoads[$edge->index]=($deltaLoads[$edge->index]??0)+$diff; + } + } + } + $ascending=array_keys($seenAffected); + sort($ascending); + if($this->baseHasMaxTop){ + foreach($ascending as $u){ + $limitTicks=$baseUnits[$u]->maxTopLoadTicks; + if($limitTicks!==null&&$baseLoads[$u]+($deltaLoads[$u]??0)>$limitTicks) + return ConstraintResult::reject('top_load_exceeded',$baseUnits[$u]->label); + } + } + if($this->baseHasCrush){ + foreach($ascending as $u){ + $unitU=$baseUnits[$u]; + $limitKpa=$unitU->maxCompressionPressureKpa; + if($limitKpa===null)continue; + $boxU=$unitU->box; + $fp=$unitU->footprintTicks2??ExactInteger::mul($boxU->x2()-$boxU->origin->x,$boxU->y2()-$boxU->origin->y); + if(Compression::exceeds(Compression::pressure($baseLoads[$u]+($deltaLoads[$u]??0),$fp),$limitKpa)) + return ConstraintResult::reject('crush_violation',$unitU->label); + } + } + if($this->baseHasMaxStacked){ + assert($this->baseStackedCounts!==null); + foreach($ascending as $u){ + $maxStacked=$baseUnits[$u]->maxStackedItems; + if($maxStacked!==null&&$this->baseStackedCounts[$u]+1>$maxStacked) + return ConstraintResult::reject('stacked_item_limit_exceeded',$baseUnits[$u]->label); + } + } + if($densityLimit!==null){ + foreach($ascending as $u){ + $unitU=$baseUnits[$u]; + $bearing=BigInt::multiply($unitU->weightTicks+$baseLoads[$u]+($deltaLoads[$u]??0),LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($unitU->box->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$unitU->label); + } + $bearing=BigInt::multiply($c->item->weight()->ticks,LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($candidate->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$c->item->id()); + } + return ConstraintResult::allow(); + } + } + + $unit=new LoadUnit( + $candidate,$c->item->weight()->ticks,($nullsafeVariable2 = $item->maxTopLoad) ? $nullsafeVariable2->ticks : null,$item->maxStackedItems,$c->item->id(), + $item->nestingHeight===null?null:$item->id,($nullsafeVariable3 = $item->nestingHeight) ? $nullsafeVariable3->ticks : null, + $item->compressionRatioPpm,$item->maxCompressionPressureKpa, + ExactInteger::mul($c->dimensions->length->ticks,$c->dimensions->width->ticks), + ); + $units=$baseUnits; + $units[]=$unit; + $graph=$base->withUnit($unit,$this->hint); + $nonStackable=$graph->nonStackableFailure($c->placements,$c->item,count($units)-1); + if($nonStackable!==null)return ConstraintResult::reject($nonStackable[0],$nonStackable[1]); + $analysis=new LoadAnalysis($units,$graph); + $failure=$analysis->overloaded() + ??$analysis->crushed() + ??$analysis->stackLimitExceeded() + ??$analysis->stackDensityExceeded($densityLimit); + return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); + } + + /** @param list $placements */ + private function settleRoute(array $placements):void + { + assert($this->base!==null); + if($this->baseStops!==null)return; + $stops=[];$routed=false; + foreach($placements as $p){ + $stop=$p->instance->item->stopIndex===null?INF:(float)$p->instance->item->stopIndex; + if($stop!==INF)$routed=true; + $stops[]=$stop; + } + $this->baseStops=$stops; + $this->baseRouted=$routed; + $count=count($stops); + $maxStopAbove=$count===0?[]:array_fill(0,$count,-INF); + if($routed&&$count>0){ + foreach($this->base->descendingIndices() as $index){ + $best=-INF; + foreach($this->base->children($index) as $child){ + $childStop=$stops[$child]; + if($childStop>$best)$best=$childStop; + $childAbove=$maxStopAbove[$child]; + if($childAbove>$best)$best=$childAbove; + } + $maxStopAbove[$index]=$best; + } + $holds=true; + foreach($stops as $index=>$stop) + if($maxStopAbove[$index]>$stop){$holds=false;break;} + $this->baseRouteHolds=$holds; + }else{ + $this->baseRouteHolds=true; + } + $this->baseMaxStopAbove=$maxStopAbove; + } + + public function evaluateRouteOrder(ConstraintContext $c):ConstraintResult + { + $box=$c->envelopeBox(); + $footprint=max($box->x2()-$box->origin->x,$box->y2()-$box->origin->y); + $base=$this->baseFor($c->placements,$footprint); + $baseUnits=$this->baseUnits; + $this->settleRoute($c->placements); + assert($this->baseStops!==null&&$this->baseMaxStopAbove!==null); + $candidateStop=$c->item->item->stopIndex===null?INF:(float)$c->item->item->stopIndex; + if(!$this->baseRouted&&$candidateStop===INF)return ConstraintResult::allow(); + if(!$base->isNested()&&$c->item->item->nestingHeight===null&&$this->baseRouteHolds){ + $below=$base->contactsBelow($box); + $above=$base->contactsAbove($box); + if($below===[]&&$above===[])return ConstraintResult::allow(); + $baseStops=$this->baseStops; + $baseMaxAbove=$this->baseMaxStopAbove; + $violated=false; + foreach($below as $edge){ + if($candidateStop>$baseStops[$edge->index]){$violated=true;break;} + } + if(!$violated){ + foreach($above as $edge){ + $ch=$edge->index; + if($baseStops[$ch]>$candidateStop||$baseMaxAbove[$ch]>$candidateStop){$violated=true;break;} + } + } + if(!$violated)return ConstraintResult::allow(); + if($above===[]){ + $pending=[];$seen=[]; + foreach($below as $edge){$pending[]=$edge->index;$seen[$edge->index]=true;} + $idx=0;$offender=null; + while($idxsupporters($u) as $edge){ + if(!isset($seen[$edge->index])){ + $seen[$edge->index]=true; + $pending[]=$edge->index; + } + } + } + assert($offender!==null); + return ConstraintResult::reject( + 'unloading_order_violation', + $baseUnits[$offender]->label.' blocked by '.$c->item->id(), + ); + } + } + $candidate=new LoadUnit( + $box,$c->item->weight()->ticks,null,null,$c->item->id(), + $c->item->item->nestingHeight===null?null:$c->item->item->id,($nullsafeVariable4 = $c->item->item->nestingHeight) ? $nullsafeVariable4->ticks : null, + ); + $stops=$this->baseStops; + $stops[]=$candidateStop; + $units=$baseUnits; + $units[]=$candidate; + $graph=$base->withUnit($candidate,$this->hint); + $failure=(new LoadAnalysis($units,$graph))->routeOrderViolated($stops); + return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); + } } diff --git a/src-legacy/Constraint/RouteOrderConstraint.php b/src-legacy/Constraint/RouteOrderConstraint.php index 617fb95..faec103 100644 --- a/src-legacy/Constraint/RouteOrderConstraint.php +++ b/src-legacy/Constraint/RouteOrderConstraint.php @@ -22,16 +22,6 @@ final class RouteOrderConstraint implements PlacementConstraint public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->routeSensitive)return ConstraintResult::allow(); - $candidate=new LoadUnit( - $c->envelopeBox(),$c->item->weight()->ticks,null,null,$c->item->id(), - $c->item->item->nestingHeight===null?null:$c->item->item->id,($nullsafeVariable1 = $c->item->item->nestingHeight) ? $nullsafeVariable1->ticks : null, - ); - $stops=[]; - foreach($c->placements as $p)$stops[]=$p->instance->item->stopIndex===null?INF:(float)$p->instance->item->stopIndex; - $stops[]=$c->item->item->stopIndex===null?INF:(float)$c->item->item->stopIndex; - if(!LoadAnalysis::routed($stops))return ConstraintResult::allow(); - [$units,$graph]=($this->support = $this->support ?? new PlacedSupportBase())->withCandidate($c->placements,$candidate); - $failure=(new LoadAnalysis($units,$graph))->routeOrderViolated($stops); - return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); + return ($this->support = $this->support ?? new PlacedSupportBase())->evaluateRouteOrder($c); } } diff --git a/src-legacy/Constraint/SupportConstraint.php b/src-legacy/Constraint/SupportConstraint.php index a6bdcb2..c4c7211 100644 --- a/src-legacy/Constraint/SupportConstraint.php +++ b/src-legacy/Constraint/SupportConstraint.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Constraint\Internal\LoadSupportGraph; +use Packvium\Domain\{AxisAlignedBox,PalletOverhang}; use Packvium\Support\{ExactGeometry,ExactInteger}; /** * Support ratios arrive as floats from the public API but must never decide feasibility @@ -42,7 +43,7 @@ public function canReject(\Packvium\Domain\ItemInstance $item):bool public function evaluate(ConstraintContext $c):ConstraintResult { - if($c->point->z===0)return ConstraintResult::allow(); + if($c->point->z===0)return $this->onFloor($c); if(!$this->canReject($c->item))return ConstraintResult::allow(); $box=$c->envelopeBox(); $support=LoadSupportGraph::candidateView($c->placements,$c->item,$box); @@ -57,9 +58,28 @@ public function evaluate(ConstraintContext $c):ConstraintResult if($rule==='multiple'&&$count<2) return ConstraintResult::reject('ground_contact_violation',"multiple: rests on {$count} item(s)"); } + return $this->ratioAndCentroid($c,$box,$supporters,$support->supportingArea); + } + + /** + * A floor is whole support unless it is a pallet deck: then the deck is the one + * supporter, judged by the same ratio and centre-of-gravity rule. The ground contact rules + * name supporting items, and the floor is none, so they do not apply. + */ + private function onFloor(ConstraintContext $c):ConstraintResult + { + $deck=$c->container->deck; + if($deck===null)return ConstraintResult::allow(); + $box=$c->envelopeBox(); + return $this->ratioAndCentroid($c,$box,[$deck->asBox()],PalletOverhang::deckContactArea($deck,$box)); + } + + /** @param list $supporters + * @param int|string $area */ + private function ratioAndCentroid(ConstraintContext $c,AxisAlignedBox $box,array $supporters,$area):ConstraintResult + { $required=max($this->globalMinimum,$c->item->item->minimumSupportRatio); if($required<=0)return ConstraintResult::allow(); - $area=$support->supportingArea; $baseArea=ExactGeometry::baseArea($c->envelopeDimensions); if(ExactInteger::compare($area,self::exactRequiredArea($baseArea,self::scaled($required)))<0) return ConstraintResult::reject('insufficient_support',sprintf('%s/%s < %.6f',$area,$baseArea,$required)); diff --git a/src-legacy/Constraint/TopLoadConstraint.php b/src-legacy/Constraint/TopLoadConstraint.php index 7493d9a..0a6cf4d 100644 --- a/src-legacy/Constraint/TopLoadConstraint.php +++ b/src-legacy/Constraint/TopLoadConstraint.php @@ -22,22 +22,6 @@ final class TopLoadConstraint implements PlacementConstraint public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->stackSensitive)return ConstraintResult::allow(); - $item=$c->item->item; - $unit=new LoadUnit( - $c->envelopeBox(),$c->item->weight()->ticks,($nullsafeVariable1 = $item->maxTopLoad) ? $nullsafeVariable1->ticks : null,$item->maxStackedItems,$c->item->id(), - $item->nestingHeight===null?null:$item->id,($nullsafeVariable2 = $item->nestingHeight) ? $nullsafeVariable2->ticks : null, - $item->compressionRatioPpm,$item->maxCompressionPressureKpa, - ExactInteger::mul($c->dimensions->length->ticks,$c->dimensions->width->ticks), - ); - [$units,$graph]=($this->support = $this->support ?? new PlacedSupportBase())->withCandidate($c->placements,$unit); - $nonStackable=$graph->nonStackableFailure($c->placements,$c->item,count($units)-1); - if($nonStackable!==null)return ConstraintResult::reject($nonStackable[0],$nonStackable[1]); - $densityLimit=($nullsafeVariable3 = $c->container->maxStackDensity) ? $nullsafeVariable3->ticks : null; - $analysis=new LoadAnalysis($units,$graph); - $failure=$analysis->overloaded() - ??$analysis->crushed() - ??$analysis->stackLimitExceeded() - ??$analysis->stackDensityExceeded($densityLimit); - return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); + return ($this->support = $this->support ?? new PlacedSupportBase())->evaluateTopLoad($c); } } diff --git a/src-legacy/Domain/Container.php b/src-legacy/Domain/Container.php index da9cef4..c1da598 100644 --- a/src-legacy/Domain/Container.php +++ b/src-legacy/Domain/Container.php @@ -102,6 +102,21 @@ final class Container * @var \Packvium\Domain\MadeToMeasure|null */ public $madeToMeasure; + /** + * @readonly + * @var \Packvium\Domain\OverhangLimit|null + */ + public $palletOverhangLimit; + /** + * @readonly + * @var \Packvium\Domain\Deck|null + */ + public $deck; + /** + * @readonly + * @var \Packvium\Unit\Length|null + */ + public $sideGussetDepth; /** * Which walls this container can be unloaded through. * @@ -128,11 +143,18 @@ final class Container * carries the container with this emptied again (docs/PLAN-REVISIONS.md). * * `$deformableBoundary`: `'flat_bag'` makes this a flexible bag whose package conforms to its - * contents (`FlatBag`); null is a rigid container. + * contents (`FlatBag`); `'gusseted_bag'` is one whose width girth is widened by + * `$sideGussetDepth`, which that kind requires and every other container refuses (1.10). + * null is a rigid container. + * + * `$palletOverhangLimit`: how far a load may pass this pallet deck's edges (, + * `PalletOverhang`). `$deck`: the deck inside a solving frame, set only by + * `PalletOverhang::solvingFrame`, which widens `$innerDimensions` to the frame and drops the + * limit. * * @param list $obstacles @param list $tags @param array $tagLimits @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections @param list $preloaded */ - public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $outerDimensions=null,?Weight $tareWeight=null,?Weight $maxPayload=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],?Weight $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],array $preloaded=[],?string $deformableBoundary=null,?MadeToMeasure $madeToMeasure=null) + public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $outerDimensions=null,?Weight $tareWeight=null,?Weight $maxPayload=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],?Weight $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],array $preloaded=[],?string $deformableBoundary=null,?MadeToMeasure $madeToMeasure=null,?OverhangLimit $palletOverhangLimit=null,?Deck $deck=null,?Length $sideGussetDepth=null) {$tareWeight = $tareWeight ?? new Weight(0); $this->id = $id; $this->innerDimensions = $innerDimensions; @@ -153,7 +175,10 @@ public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $ $this->preloaded = $preloaded; $this->deformableBoundary = $deformableBoundary; $this->madeToMeasure = $madeToMeasure; - if($id==='')throw new ObjectRefusal('invalid_value','Container id is required');($nullsafeVariable1 = $madeToMeasure) ? $nullsafeVariable1->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]) : null;if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio);if($quantity!==null&&$quantity<=0)throw new ObjectRefusal('below_minimum','Container quantity must be positive');if($costMinor<0)throw new ObjectRefusal('below_minimum','Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new ObjectRefusal('below_minimum','Container max_items must be at least 1');if(!($voidFillReserveRatio>=0&&$voidFillReserveRatio<=1))throw ObjectRefusal::ratio($voidFillReserveRatio,'void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new ObjectRefusal('below_minimum','tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new ObjectRefusal('invalid_value','Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new ObjectRefusal('invalid_value',"Obstacle {$o->id} lies outside container"); + $this->palletOverhangLimit = $palletOverhangLimit; + $this->deck = $deck; + $this->sideGussetDepth = $sideGussetDepth; + if($id==='')throw new ObjectRefusal('invalid_value','Container id is required');($nullsafeVariable1 = $madeToMeasure) ? $nullsafeVariable1->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]) : null;if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$innerDimensions,$sideGussetDepth,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio,$palletOverhangLimit);elseif($sideGussetDepth!==null)throw new ObjectRefusal('not_allowed','side_gusset_depth requires deformable_boundary gusseted_bag');if($palletOverhangLimit!==null)self::requirePalletFields($obstacles,$axles,$accessDirections,$voidFillReserveRatio,$madeToMeasure);if($quantity!==null&&$quantity<=0)throw new ObjectRefusal('below_minimum','Container quantity must be positive');if($costMinor<0)throw new ObjectRefusal('below_minimum','Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new ObjectRefusal('below_minimum','Container max_items must be at least 1');if(!($voidFillReserveRatio>=0&&$voidFillReserveRatio<=1))throw ObjectRefusal::ratio($voidFillReserveRatio,'void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new ObjectRefusal('below_minimum','tag_limits must be at least 1');if($outerDimensions!==null&&!self::declaredInnerOf($innerDimensions,$deck)->fitsInside($outerDimensions))throw new ObjectRefusal('invalid_value','Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new ObjectRefusal('invalid_value',"Obstacle {$o->id} lies outside container"); if($axles!==null){[$front,$rear]=$axles;if($front->position->ticks>=$rear->position->ticks)throw new ObjectRefusal('invalid_value','The front axle must be strictly nearer the origin than the rear axle');if($front->position->ticks<0||$rear->position->ticks>$innerDimensions->length->ticks)throw new ObjectRefusal('invalid_value',"Axle positions must lie within the container's length");} foreach($accessDirections as $direction)if(!in_array($direction,SweptRegion::ALL_DIRECTIONS,true))throw new InvalidArgumentException("unknown movement direction {$direction}"); // Deduplicated into the canonical order rather than kept as given: two callers @@ -162,8 +187,21 @@ public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $ return in_array($d,$accessDirections,true); }));} /** The same container holding `$placements` before search. @param list $placements */ - public function withPreloaded(array $placements):self{return new self($this->id,$this->innerDimensions,$this->outerDimensions,$this->tareWeight,$this->maxPayload,$this->costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$placements,$this->deformableBoundary,$this->madeToMeasure);} + public function withPreloaded(array $placements):self{return new self($this->id,$this->innerDimensions,$this->outerDimensions,$this->tareWeight,$this->maxPayload,$this->costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$placements,$this->deformableBoundary,$this->madeToMeasure,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth);} public function isFlatBag():bool{return $this->deformableBoundary!==null;} + /** The side gusset depth G in ticks; 0 for a flat bag and every rigid container. */ + public function sideGussetTicks():int{return $this->sideGussetDepth===null?0:$this->sideGussetDepth->ticks;} + /** + * The same container packed in `$inner` with `$deck` as its only weight-bearing floor, and + * no overhang limit: how `PalletOverhang` builds a pallet's solving frame and its deck rung + *. A frame states no limit, so it is never widened twice. O(1). + * + * @internal + */ + public function framed(Dimensions $inner,?Deck $deck):self{return new self($this->id,$inner,$this->outerDimensions,$this->tareWeight,$this->maxPayload,$this->costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure,null,$deck,$this->sideGussetDepth);} + /** The inner size the caller declared: a solving frame's deck at its height, else `innerDimensions`. */ + public function declaredInner():Dimensions{return self::declaredInnerOf($this->innerDimensions,$this->deck);} + private static function declaredInnerOf(Dimensions $inner,?Deck $deck):Dimensions{return $deck===null?$inner:new Dimensions(new Length($deck->length),new Length($deck->width),$inner->height);} /** The declared container solved inside `$rung`: same id, everything else unchanged. @param array{0:int,1:int,2:int} $rung */ public function withEnvelope(array $rung):self{return $this->resized(self::dimensionsOf($rung),null,$this->costMinor,$this->tareWeight);} /** @@ -186,7 +224,7 @@ public function fabricate(array $achieved):self } return $this->resized(self::dimensionsOf($sides),self::dimensionsOf($outer),$machine->boxCostMinor($this->costMinor,$sides),new Weight($machine->boxTareTicks($this->tareWeight->ticks,$sides))); } - private function resized(Dimensions $inner,?Dimensions $outer,int $costMinor,Weight $tareWeight):self{return new self($this->id,$inner,$outer,$tareWeight,$this->maxPayload,$costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure);} + private function resized(Dimensions $inner,?Dimensions $outer,int $costMinor,Weight $tareWeight):self{return new self($this->id,$inner,$outer,$tareWeight,$this->maxPayload,$costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth);} /** @param array{0:int,1:int,2:int} $sides */ private static function dimensionsOf(array $sides):Dimensions{return new Dimensions(new Length($sides[0]),new Length($sides[1]),new Length($sides[2]));} /** @@ -196,16 +234,43 @@ private static function dimensionsOf(array $sides):Dimensions{return new Dimensi * * @param list $obstacles @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections */ - private static function requireBagFields(string $kind,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio):void + private static function requireBagFields(string $kind,Dimensions $inner,?Length $sideGussetDepth,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio,?OverhangLimit $palletOverhangLimit):void { if(!in_array($kind,FlatBag::KINDS,true))throw new ObjectRefusal('not_allowed',"unknown deformable_boundary kind {$kind}"); - $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'max_stack_density'=>$maxStackDensity!==null,'outer_dimensions'=>$outerDimensions!==null,'void_fill_reserve_ratio'=>$voidFillReserveRatio>0]; + self::requireGussetRule($kind===FlatBag::GUSSETED_BAG,$inner,$sideGussetDepth); + $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'max_stack_density'=>$maxStackDensity!==null,'outer_dimensions'=>$outerDimensions!==null,'void_fill_reserve_ratio'=>$voidFillReserveRatio>0,'pallet_overhang_limit'=>$palletOverhangLimit!==null]; foreach($present as $name=>$set)if($set)throw new ObjectRefusal('not_allowed',"{$name} cannot be combined with deformable_boundary"); } + /** + * A gusseted bag's side gusset is required, positive and no deeper than the bag is wide: a + * deeper fold would have no flat sheet left to fold from. A flat bag takes none. O(1). + */ + private static function requireGussetRule(bool $gusseted,Dimensions $inner,?Length $sideGussetDepth):void + { + if($sideGussetDepth===null){ + if($gusseted)throw new ObjectRefusal('missing_field','a gusseted_bag requires side_gusset_depth'); + return; + } + if(!$gusseted)throw new ObjectRefusal('not_allowed','side_gusset_depth requires deformable_boundary gusseted_bag'); + if($sideGussetDepth->ticks<=0)throw new ObjectRefusal('invalid_value','side_gusset_depth must be positive'); + if($sideGussetDepth->ticks>$inner->width->ticks)throw new ObjectRefusal('invalid_value','side_gusset_depth exceeds inner_dimensions width'); + } + /** + * The fields a pallet with an overhang limit refuses: each reads the declared frame or a wall + * the widened frame moves. The JSON path refuses the same combinations as + * `unsupported_feature` first. + * + * @param list $obstacles @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections + */ + private static function requirePalletFields(array $obstacles,?array $axles,array $accessDirections,float $voidFillReserveRatio,?MadeToMeasure $madeToMeasure):void + { + $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'void_fill_reserve_ratio'=>$voidFillReserveRatio>0,'made_to_measure'=>$madeToMeasure!==null]; + foreach($present as $name=>$set)if($set)throw new ObjectRefusal('not_allowed',"{$name} cannot be combined with pallet_overhang_limit"); + } /** * @param \Packvium\Unit\Weight|int|string|mixed[] $tareWeight * @param \Packvium\Unit\Weight|int|string|mixed[]|null $maxPayload * @param \Packvium\Unit\Weight|int|string|mixed[]|null $maxStackDensity */ - public static function create(string $id,Dimensions $innerDimensions,$tareWeight=0,$maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],$maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],?string $deformableBoundary=null):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections,[],$deformableBoundary);} + public static function create(string $id,Dimensions $innerDimensions,$tareWeight=0,$maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],$maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],?string $deformableBoundary=null,?Length $sideGussetDepth=null):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections,[],$deformableBoundary,null,null,null,$sideGussetDepth);} } diff --git a/src-legacy/Domain/Deck.php b/src-legacy/Domain/Deck.php new file mode 100644 index 0000000..7329eb9 --- /dev/null +++ b/src-legacy/Domain/Deck.php @@ -0,0 +1,44 @@ +x = $x; + $this->y = $y; + $this->length = $length; + $this->width = $width; + } + + public function x2():int{return $this->x+$this->length;} + public function y2():int{return $this->y+$this->width;} + + /** The deck as a one-tick slab on the floor: only its footprint is ever read. */ + public function asBox():AxisAlignedBox{return new AxisAlignedBox(new Point($this->x,$this->y,0),new Dimensions(new Length($this->length),new Length($this->width),new Length(1)));} +} diff --git a/src-legacy/Domain/Dimensions.php b/src-legacy/Domain/Dimensions.php index ff8b533..f78e45e 100644 --- a/src-legacy/Domain/Dimensions.php +++ b/src-legacy/Domain/Dimensions.php @@ -62,7 +62,10 @@ public function rotated(string $r):self{switch ($r) { return new self($this->height,$this->length,$this->width); case Rotation::HWL: return new self($this->height,$this->width,$this->length); + default: + return $this->signedRotated($r); }} + /** A signed code's box: its permutation, the signs being invisible on a cuboid (1.10). */ private function signedRotated(string $r):self{$sides=[$this->length,$this->width,$this->height];[$x,$y,$z]=Orientations::sourceAxes($r);return new self($sides[$x],$sides[$y],$sides[$z]);} /** @param list $allowed @return list */ public function uniqueRotations(array $allowed):array{$seen=[];$out=[];foreach($allowed as $r){$d=$this->rotated($r);$k=$d->length->ticks.':'.$d->width->ticks.':'.$d->height->ticks;if(!isset($seen[$k])){$seen[$k]=true;$out[]=[$r,$d];}}return $out;} public function fitsInside(self $o):bool{return $this->length->ticks<=$o->length->ticks&&$this->width->ticks<=$o->width->ticks&&$this->height->ticks<=$o->height->ticks;} public function expand(Length $c):self{$x=$c->ticks*2;return new self(new Length($this->length->ticks+$x),new Length($this->width->ticks+$x),new Length($this->height->ticks+$x));} diff --git a/src-legacy/Domain/FixedPlacement.php b/src-legacy/Domain/FixedPlacement.php index c225683..7c71685 100644 --- a/src-legacy/Domain/FixedPlacement.php +++ b/src-legacy/Domain/FixedPlacement.php @@ -35,17 +35,24 @@ final class FixedPlacement * @var int */ public $containerInstance = 1; + /** + * @readonly + * @var string|null + */ + public $placementId; /** * Every rule on these fields is checked where the placement sits in a request, by * `Packer::pack` (`RequestObjects::check`), with the JSON path's refusal and pointer. */ - public function __construct(string $itemId, string $containerId, Point $position, string $rotation, int $containerInstance=1) + /** `$placementId`: the result placement's id restated (1.10), refused unless it is this placement's. */ + public function __construct(string $itemId, string $containerId, Point $position, string $rotation, int $containerInstance=1, ?string $placementId=null) { $this->itemId = $itemId; $this->containerId = $containerId; $this->position = $position; $this->rotation = $rotation; $this->containerInstance = $containerInstance; + $this->placementId = $placementId; } public function packedContainerId():string{return "{$this->containerId}#{$this->containerInstance}";} diff --git a/src-legacy/Domain/FlatBag.php b/src-legacy/Domain/FlatBag.php index e5ea524..d1f7e24 100644 --- a/src-legacy/Domain/FlatBag.php +++ b/src-legacy/Domain/FlatBag.php @@ -14,21 +14,27 @@ * * The extents only grow as boxes are added, so a verdict reached for a candidate never flips * when more items follow, and any subset of an admitted set is admitted. + * + * A `gusseted_bag` (1.10) has side gussets of depth G folded into each long edge: the tube + * round the package's y-z section is 2(W + G) long instead of 2W, so the width sum becomes + * b + c <= W + G. The length sum is unchanged (no bottom gusset in 1.10), and G = 0 is the + * flat bag. Every method here takes the gusset depth in ticks, 0 for a flat bag. */ final class FlatBag { - public const KINDS=['flat_bag']; + public const GUSSETED_BAG='gusseted_bag'; + public const KINDS=['flat_bag',self::GUSSETED_BAG]; /** Whether a package of extents (a, b, c) passes both girth sums; the frame is the caller's. */ - public static function girthAdmits(Dimensions $inner,int $a,int $b,int $c):bool + public static function girthAdmits(Dimensions $inner,int $a,int $b,int $c,int $gusset=0):bool { - return $a+$c<=$inner->length->ticks&&$b+$c<=$inner->width->ticks; + return $a+$c<=$inner->length->ticks&&$b+$c<=$inner->width->ticks+$gusset; } - /** Whether one box of these dimensions, alone at the origin, fits a flat bag. */ - public static function fitsAlone(Dimensions $inner,Dimensions $box):bool + /** Whether one box of these dimensions, alone at the origin, fits a bag. */ + public static function fitsAlone(Dimensions $inner,Dimensions $box,int $gusset=0):bool { - return $box->fitsInside($inner)&&self::girthAdmits($inner,$box->length->ticks,$box->width->ticks,$box->height->ticks); + return $box->fitsInside($inner)&&self::girthAdmits($inner,$box->length->ticks,$box->width->ticks,$box->height->ticks,$gusset); } /** diff --git a/src-legacy/Domain/HullShape.php b/src-legacy/Domain/HullShape.php index 0ffa254..248248a 100644 --- a/src-legacy/Domain/HullShape.php +++ b/src-legacy/Domain/HullShape.php @@ -93,8 +93,8 @@ private function __construct(array $vertices, array $faceAxes, array $edgeDirect /** * How many rotated hulls stay resident, before the memo is dropped and refilled. * - * A request is bounded by its distinct hull items times the six orientations, so this - * holds far more than any request the solver is sized for. Bounded rather than growing + * A request is bounded by its distinct hull items times the orientations they allow (at + * most 24), so this holds far more than any request the solver is sized for. Bounded rather than growing * for the life of the process: the point of the memo is to spend less, not to spend it * somewhere else. */ @@ -198,51 +198,24 @@ public static function box(int $length, int $width, int $height): self } /** - * Reorient a hull the way `Dimensions::rotated` reorients its box, never mirroring it. + * Reorient a hull by one of the 24 proper rotations, never mirroring it (1.10). * - * Three of the six rotations are odd permutations of the coordinate axes. On a cuboid - * that is invisible; on a hull a bare permutation returns the item's mirror image, a - * shape the caller does not own. One axis therefore changes sign when the permutation is - * odd, which makes all six proper rotations. Vertices come back translated so the - * rotated hull's bounding box starts at the origin. + * `v'[i] = s[i] * v[src[i]]` with the code's source axes and signs from `Orientations`. A + * bare permutation would hand back the item's mirror image for an odd permutation -- a + * shape the caller does not own -- which is why the legacy odd codes negate x and every + * signed code has determinant +1. Vertices come back translated so the rotated hull's + * bounding box starts at the origin. * * @param list $vertices * @return list */ public static function rotate(array $vertices, string $rotation): array { - switch ($rotation) { - case Rotation::LWH: - $axes = [0, 1, 2]; - break; - case Rotation::LHW: - $axes = [0, 2, 1]; - break; - case Rotation::WLH: - $axes = [1, 0, 2]; - break; - case Rotation::WHL: - $axes = [1, 2, 0]; - break; - case Rotation::HLW: - $axes = [2, 0, 1]; - break; - case Rotation::HWL: - $axes = [2, 1, 0]; - break; - } - $inversions = 0; - for ($i = 0; $i < 3; $i++) { - for ($j = $i + 1; $j < 3; $j++) { - if ($axes[$i] > $axes[$j]) { - $inversions++; - } - } - } - $sign = $inversions % 2 === 1 ? -1 : 1; + $axes = Orientations::sourceAxes($rotation); + $signs = Orientations::signs($rotation); $turned = []; foreach ($vertices as $vertex) { - $turned[] = [$sign * $vertex[$axes[0]], $vertex[$axes[1]], $vertex[$axes[2]]]; + $turned[] = [$signs[0] * $vertex[$axes[0]], $signs[1] * $vertex[$axes[1]], $signs[2] * $vertex[$axes[2]]]; } $low = [PHP_INT_MAX, PHP_INT_MAX, PHP_INT_MAX]; foreach ($turned as $vertex) { diff --git a/src-legacy/Domain/Item.php b/src-legacy/Domain/Item.php index 472ef2e..85101dd 100644 --- a/src-legacy/Domain/Item.php +++ b/src-legacy/Domain/Item.php @@ -151,8 +151,9 @@ public function __construct(string $id,Dimensions $dimensions,?Weight $weight=nu if($nestingHeight!==null&&!($nestingHeight->ticks>=0&&$nestingHeight->ticks<$dimensions->height->ticks))throw new ObjectRefusal('invalid_value',"nesting_height must be at least zero and strictly less than the item's own height"); if($stopIndex!==null&&($stopIndex<0||$stopIndex>self::MAX_EXACT_STOP_INDEX))throw new ObjectRefusal($stopIndex<0?'below_minimum':'above_maximum','stop_index must be a non-negative safe integer'); if($value!==null&&$value<0)throw new ObjectRefusal('below_minimum','value must be non-negative'); + if($shapeType!==ShapeType::CONVEX_HULL)foreach($allowedRotations as $requested)if(Orientations::isSigned($requested))throw new ObjectRefusal('invalid_value',Orientations::SIGNED_CODE_NEEDS_A_HULL); if($keepUpright)$allowedRotations=array_values(array_filter($allowedRotations,static function (string $r) { - return in_array($r,Rotation::upright(),true); + return Orientations::isUpright($r); }));if($allowedRotations===[])throw new ObjectRefusal('invalid_value','At least one rotation must be allowed'); $this->id=$id;$this->dimensions=$dimensions;$this->weight=$weight??new Weight(0);$this->quantity=$quantity;$this->allowedRotations=$allowedRotations;$this->keepUpright=$keepUpright;$this->stackable=$stackable;$this->mustBeOnFloor=$mustBeOnFloor;$this->maxTopLoad=$maxTopLoad;$this->minimumSupportRatio=$minimumSupportRatio;$this->groundContactRule=$groundContactRule;$this->group=$group;$this->tags=array_values(array_unique($tags));$this->incompatibleTags=array_values(array_unique($incompatibleTags));$this->priority=$priority;$this->metadata=$metadata;$this->maxStackedItems=$maxStackedItems;$this->eligibleContainerTags=array_values(array_unique($eligibleContainerTags));$this->nestingHeight=$nestingHeight;$this->stopIndex=$stopIndex;$this->value=$value; $this->shapeType=$shapeType; diff --git a/src-legacy/Domain/Orientations.php b/src-legacy/Domain/Orientations.php new file mode 100644 index 0000000..8295f6b --- /dev/null +++ b/src-legacy/Domain/Orientations.php @@ -0,0 +1,93 @@ + [[0, 1, 2], [1, 1, 1]], 'LHW' => [[0, 2, 1], [-1, 1, 1]], + 'WLH' => [[1, 0, 2], [-1, 1, 1]], 'WHL' => [[1, 2, 0], [1, 1, 1]], + 'HLW' => [[2, 0, 1], [1, 1, 1]], 'HWL' => [[2, 1, 0], [-1, 1, 1]], + '+L-W-H' => [[0, 1, 2], [1, -1, -1]], '-L+W-H' => [[0, 1, 2], [-1, 1, -1]], + '-L-W+H' => [[0, 1, 2], [-1, -1, 1]], + '+L-H+W' => [[0, 2, 1], [1, -1, 1]], '+L+H-W' => [[0, 2, 1], [1, 1, -1]], + '-L-H-W' => [[0, 2, 1], [-1, -1, -1]], + '+W-L+H' => [[1, 0, 2], [1, -1, 1]], '+W+L-H' => [[1, 0, 2], [1, 1, -1]], + '-W-L-H' => [[1, 0, 2], [-1, -1, -1]], + '+W-H-L' => [[1, 2, 0], [1, -1, -1]], '-W+H-L' => [[1, 2, 0], [-1, 1, -1]], + '-W-H+L' => [[1, 2, 0], [-1, -1, 1]], + '+H-L-W' => [[2, 0, 1], [1, -1, -1]], '-H+L-W' => [[2, 0, 1], [-1, 1, -1]], + '-H-L+W' => [[2, 0, 1], [-1, -1, 1]], + '+H-W+L' => [[2, 1, 0], [1, -1, 1]], '+H+W-L' => [[2, 1, 0], [1, 1, -1]], + '-H-W-L' => [[2, 1, 0], [-1, -1, -1]], + ]; + + /** The codes that keep the item's own height vertical and pointing up: z takes `+H`. */ + public const UPRIGHT_CODES = ['LWH', 'WLH', '-L-W+H', '+W-L+H']; + + /** What a signed code on anything but a hull is refused with, at its own pointer. */ + public const SIGNED_CODE_NEEDS_A_HULL = 'a signed rotation code requires shape_type convex_hull'; + + /** The codes an item may name: all 24 for a hull, the six legacy codes otherwise. @return list */ + public static function vocabulary(bool $hull): array + { + return $hull ? \array_keys(self::TABLE) : self::LEGACY_CODES; + } + + /** + * Why `$value` cannot orient an item of this shape, or null when it can: `invalid_value` + * for a signed code beside a non-hull -- a rule broken, not an unknown word -- and + * `not_allowed` for anything outside the item's vocabulary. O(1). + * + * @param mixed $value + */ + public static function refusalReason($value, bool $hull): ?string + { + if (!\is_string($value) || !\array_key_exists($value, self::TABLE)) { + return 'not_allowed'; + } + if (!$hull && !\in_array($value, self::LEGACY_CODES, true)) { + return 'invalid_value'; + } + return null; + } + + /** @return array{0:int,1:int,2:int} */ + public static function sourceAxes(string $rotation): array + { + return self::TABLE[$rotation][0]; + } + + /** @return array{0:int,1:int,2:int} */ + public static function signs(string $rotation): array + { + return self::TABLE[$rotation][1]; + } + + public static function isSigned(string $rotation): bool + { + return !\in_array($rotation, self::LEGACY_CODES, true); + } + + public static function isUpright(string $rotation): bool + { + return \in_array($rotation, self::UPRIGHT_CODES, true); + } +} diff --git a/src-legacy/Domain/OverhangLimit.php b/src-legacy/Domain/OverhangLimit.php new file mode 100644 index 0000000..128bb5b --- /dev/null +++ b/src-legacy/Domain/OverhangLimit.php @@ -0,0 +1,27 @@ +length = $length; + $this->width = $width; + } +} diff --git a/src-legacy/Domain/PackedContainer.php b/src-legacy/Domain/PackedContainer.php index 2e06ef9..4273818 100644 --- a/src-legacy/Domain/PackedContainer.php +++ b/src-legacy/Domain/PackedContainer.php @@ -103,17 +103,22 @@ public function expandPlacements(): array /** * The largest envelope x2, y2 and z2 of its placements: a flat bag's conformed package *, or a made-to-measure box's extent before it is rounded onto the machine grid - *; null for any other container. O(p). + *; a pallet's deck grown by the overhang it used, at its load's height; + * null for any other container. O(p). */ public function achievedDimensions():?Dimensions { + $deck=$this->container->deck; + if($deck!==null)return PalletOverhang::achievedDimensions($deck,$this->placements); if(!$this->container->isFlatBag()&&$this->container->madeToMeasure===null)return null; return FlatBag::asDimensions(FlatBag::extentOf($this->placements)); } - /** What a carrier measures: a bag's achieved package, else the declared outer size. */ + /** What a carrier measures: a bag's achieved package, a pallet's footprint grown by its overhang, else the declared outer size. */ public function billedDimensions():Dimensions { + $deck=$this->container->deck; + if($deck!==null)return PalletOverhang::billedDimensions($this->container,$deck,$this->placements); $achieved=$this->container->isFlatBag()?$this->achievedDimensions():null; return $achieved??$this->container->outerDimensions??$this->container->innerDimensions; } diff --git a/src-legacy/Domain/PackingRequest.php b/src-legacy/Domain/PackingRequest.php index 5dc32d3..dd6c40c 100644 --- a/src-legacy/Domain/PackingRequest.php +++ b/src-legacy/Domain/PackingRequest.php @@ -19,9 +19,15 @@ final class PackingRequest * @var mixed[] */ public $fixedPlacements = []; - /** @param list $items @param list $containers @param list $fixedPlacements */ public function __construct(array $items,array $containers,array $fixedPlacements=[]){$this->items = $items; + /** + * @readonly + * @var string|null + */ + public $currency; + /** @param list $items @param list $containers @param list $fixedPlacements */ public function __construct(array $items,array $containers,array $fixedPlacements=[],?string $currency=null){$this->items = $items; $this->containers = $containers; $this->fixedPlacements = $fixedPlacements; + $this->currency = $currency; if($items===[])throw new ObjectRefusal('invalid_value','At least one item is required');if($containers===[])throw new ObjectRefusal('invalid_value','At least one container is required');self::unique(array_map(function (Item $i) { return $i->id; },$items),'item');self::unique(array_map(function (Container $c) { diff --git a/src-legacy/Domain/PalletOverhang.php b/src-legacy/Domain/PalletOverhang.php new file mode 100644 index 0000000..6b3ad3a --- /dev/null +++ b/src-legacy/Domain/PalletOverhang.php @@ -0,0 +1,125 @@ +palletOverhangLimit; + if($limit===null)return $container; + $inner=$container->innerDimensions; + $overhangX=$limit->length->ticks;$overhangY=$limit->width->ticks; + $frame=new Dimensions(new Length($inner->length->ticks+2*$overhangX),new Length($inner->width->ticks+2*$overhangY),$inner->height); + return $container->framed($frame,new Deck($overhangX,$overhangY,$inner->length->ticks,$inner->width->ticks)); + } + + /** A solving frame's container as declared, without the overhang zone: the rung a pallet trial packs first. O(1). */ + public static function deckAlone(Container $frame):Container + { + return $frame->framed($frame->declaredInner(),null); + } + + /** + * The shift that seats a frame trial's load with the least overhang. Per axis: flush with the + * deck's near edge when the load is no longer than the deck, else centred on the deck with an + * odd tick past the far edge. Either way the load stays inside the frame, since its span is at + * most the deck plus both allowances. O(p); `[0, 0]` for none. + * + * @param list $placements @return array{0:int,1:int} + */ + public static function centringOffset(Deck $deck,array $placements):array + { + if($placements===[])return [0,0]; + $lowX=$lowY=\PHP_INT_MAX;$highX=$highY=0; + foreach($placements as $placement){ + $box=$placement->envelopeBox(); + $lowX=min($lowX,$box->origin->x);$lowY=min($lowY,$box->origin->y); + $highX=max($highX,$box->x2());$highY=max($highY,$box->y2()); + } + return [self::seat($deck->x,$deck->length,$lowX,$highX),self::seat($deck->y,$deck->width,$lowY,$highY)]; + } + + private static function seat(int $start,int $length,int $low,int $high):int + { + $span=$high-$low; + $target=$span<=$length?$start:$start-intdiv($span-$length,2); + return $target-$low; + } + + /** The area of a floor placement's footprint that rests on the deck. O(1). + * @return int|string */ + public static function deckContactArea(Deck $deck,AxisAlignedBox $box) + { + return ExactGeometry::overlapAreaXY($deck->asBox(),$box); + } + + /** The support ratio a placement on the floor reports: whole without a deck. O(1). */ + public static function floorSupportRatio(?Deck $deck,AxisAlignedBox $box):float + { + if($deck===null)return 1.0; + return ExactInteger::ratio(self::deckContactArea($deck,$box),ExactGeometry::baseArea($box->dimensions)); + } + + /** + * The deck grown by the overhang the placements use past each of its edges: `[length, width]` + * of the footprint the load reaches. O(p). + * + * @param list $placements @return array{0:int,1:int} + */ + public static function footprint(Deck $deck,array $placements):array + { + $lowX=$deck->x;$lowY=$deck->y;$highX=$deck->x2();$highY=$deck->y2(); + foreach($placements as $placement){ + $box=$placement->envelopeBox(); + $lowX=min($lowX,$box->origin->x);$lowY=min($lowY,$box->origin->y); + $highX=max($highX,$box->x2());$highY=max($highY,$box->y2()); + } + return [$highX-$lowX,$highY-$lowY]; + } + + /** + * The footprint the loaded pallet reaches, at its load's height. A packed container holds at + * least one box. O(p). + * + * @param list $placements + */ + public static function achievedDimensions(Deck $deck,array $placements):Dimensions + { + [$length,$width]=self::footprint($deck,$placements); + return new Dimensions(new Length($length),new Length($width),new Length(FlatBag::extentOf($placements)[2])); + } + + /** + * Per horizontal axis the larger of the declared footprint, outer if stated, and the deck + * grown by the overhang used; the declared height. An outer margin is not positioned against + * the deck, so it is never added to the overhang. O(p). + * + * @param list $placements + */ + public static function billedDimensions(Container $frame,Deck $deck,array $placements):Dimensions + { + $base=$frame->outerDimensions??$frame->declaredInner(); + [$length,$width]=self::footprint($deck,$placements); + return new Dimensions(new Length(max($base->length->ticks,$length)),new Length(max($base->width->ticks,$width)),$base->height); + } +} diff --git a/src-legacy/Domain/Placement.php b/src-legacy/Domain/Placement.php index 54a4be4..7899bec 100644 --- a/src-legacy/Domain/Placement.php +++ b/src-legacy/Domain/Placement.php @@ -1,6 +1,7 @@ position,$this->dimensions);}public function envelopeBox():AxisAlignedBox{return new AxisAlignedBox($this->envelopeOrigin,$this->envelopeDimensions);} + /** This placement's cross-language id inside the container with id `$containerId` (1.10). */ + public function idIn(string $containerId):string{return self::identifier($containerId,$this->position,$this->instance->item->id,$this->rotation);} + + /** + * A placement's cross-language id (1.10): the RFC 8785 canonical JSON text of + * `[container id, x, y, z, item type, orientation]`, with the physical position in ticks as + * integers. Two valid placements never share that tuple -- the same solid in the same place + * would coincide -- and canonical JSON spells any id with no grammar of its own to escape. + * A position is below its container's side, itself at most 2^53 - 1 ticks, so every integer + * has a canonical spelling; a PHP string holds no lone UTF-16 surrogate, so the reference's + * surrogate escape never arises here. A pure function of the placement, so a validator + * recomputes it. O(length of the ids). + */ + public static function identifier(string $containerId,Point $position,string $itemType,string $orientation):string + { + return CanonicalJson::encode([$containerId,$position->x,$position->y,$position->z,$itemType,$orientation]); + } + /** * This placement's rotated hull, or null when its box is the honest answer. * diff --git a/src-legacy/Domain/RateTable.php b/src-legacy/Domain/RateTable.php index 003a836..a2ae7af 100644 --- a/src-legacy/Domain/RateTable.php +++ b/src-legacy/Domain/RateTable.php @@ -39,6 +39,11 @@ final class RateTable * @var int */ public $fuelSurchargePermille = 0; + /** + * @readonly + * @var string|null + */ + public $currency; /** * @param list $weightBracketsG * @param list $pricesMinor @@ -47,12 +52,16 @@ public function __construct( array $weightBracketsG, array $pricesMinor, int $minimumChargeMinor = 0, - int $fuelSurchargePermille = 0 + int $fuelSurchargePermille = 0, + ?string $currency = null ) { $this->weightBracketsG = $weightBracketsG; $this->pricesMinor = $pricesMinor; $this->minimumChargeMinor = $minimumChargeMinor; $this->fuelSurchargePermille = $fuelSurchargePermille; + // The ISO 4217 code the prices are in, or null for the request's own (1.10). Checked + // where the table sits in a request, against the request's currency, by `Packer::pack`. + $this->currency = $currency; if ($weightBracketsG === []) { throw new ObjectRefusal('invalid_value', 'rate_table requires at least one weight bracket'); } diff --git a/src-legacy/Domain/Rotation.php b/src-legacy/Domain/Rotation.php index d2b8f7c..66e31b8 100644 --- a/src-legacy/Domain/Rotation.php +++ b/src-legacy/Domain/Rotation.php @@ -5,8 +5,10 @@ final class Rotation { public const LWH='LWH', LHW='LHW', WLH='WLH', WHL='WHL', HLW='HLW', HWL='HWL'; - public static function cases():array{return [self::LWH,self::LHW,self::WLH,self::WHL,self::HLW,self::HWL];} - public static function all():array{return self::cases();} + public const PL_NW_NH='+L-W-H', NL_PW_NH='-L+W-H', NL_NW_PH='-L-W+H', PL_NH_PW='+L-H+W', PL_PH_NW='+L+H-W', NL_NH_NW='-L-H-W', PW_NL_PH='+W-L+H', PW_PL_NH='+W+L-H', NW_NL_NH='-W-L-H', PW_NH_NL='+W-H-L', NW_PH_NL='-W+H-L', NW_NH_PL='-W-H+L', PH_NL_NW='+H-L-W', NH_PL_NW='-H+L-W', NH_NL_PW='-H-L+W', PH_NW_PL='+H-W+L', PH_PW_NL='+H+W-L', NH_NW_NL='-H-W-L'; + public static function cases():array{return [self::LWH,self::LHW,self::WLH,self::WHL,self::HLW,self::HWL,self::PL_NW_NH,self::NL_PW_NH,self::NL_NW_PH,self::PL_NH_PW,self::PL_PH_NW,self::NL_NH_NW,self::PW_NL_PH,self::PW_PL_NH,self::NW_NL_NH,self::PW_NH_NL,self::NW_PH_NL,self::NW_NH_PL,self::PH_NL_NW,self::NH_PL_NW,self::NH_NL_PW,self::PH_NW_PL,self::PH_PW_NL,self::NH_NW_NL];} + public static function all():array{return [self::LWH,self::LHW,self::WLH,self::WHL,self::HLW,self::HWL];} public static function upright():array{return [self::LWH,self::WLH];} + public static function every():array{return self::cases();} public static function from(string $value):string{if(!in_array($value,self::cases(),true))throw new InvalidArgumentException('Unknown rotation '.$value);return $value;} } diff --git a/src-legacy/Execution/Plan.php b/src-legacy/Execution/Plan.php index 1751f89..38cd62e 100644 --- a/src-legacy/Execution/Plan.php +++ b/src-legacy/Execution/Plan.php @@ -79,6 +79,30 @@ public static function placementReference(int $containerIndex, $placement): arra ]; } + /** + * `placementReference` plus the result placement's `placement_id` (1.10), copied rather + * than derived, when the result carries one. A canonical projection (a golden) has no ids, + * so its plan keeps the bytes it always had. Locks read the id from here. + * + * @param array|\stdClass|mixed $placement + * @return array + */ + private static function stepReference(int $containerIndex, $placement): array + { + $reference = self::placementReference($containerIndex, $placement); + if (!JsonValue::has($placement, 'placement_id')) { + return $reference; + } + $identifier = JsonValue::get($placement, 'placement_id'); + if (!\is_string($identifier) || $identifier === '') { + throw new ExecutionPlanException( + 'placement_id ' . CanonicalJson::spelling($identifier) . ' is not a non-empty string' + ); + } + $reference['placement_id'] = $identifier; + return $reference; + } + /** * The operator sequence for one container, or an honest absence of one. * @@ -97,7 +121,7 @@ private static function steps(int $containerIndex, $container, ?array $loadingOr if ($loadingOrder === null) { $steps = []; foreach ($placements as $placement) { - $steps[] = ['placement' => self::placementReference($containerIndex, $placement)]; + $steps[] = ['placement' => self::stepReference($containerIndex, $placement)]; } return ['order' => 'unavailable', 'steps' => $steps]; } @@ -115,7 +139,7 @@ private static function steps(int $containerIndex, $container, ?array $loadingOr foreach ($loadingOrder as $step => $index) { $steps[] = [ 'sequence' => $step + 1, - 'placement' => self::placementReference($containerIndex, $placements[$index]), + 'placement' => self::stepReference($containerIndex, $placements[$index]), ]; } return ['order' => 'loading', 'steps' => $steps]; diff --git a/src-legacy/Nested/NestedPacker.php b/src-legacy/Nested/NestedPacker.php index f5e4da7..1323b5c 100644 --- a/src-legacy/Nested/NestedPacker.php +++ b/src-legacy/Nested/NestedPacker.php @@ -1,8 +1,212 @@ config??PackingConfig::balanced()))->pack($current,$level->containers);$results[]=$result;if(!$result->complete())break;$current=array_map(function ($c) { - return $c->asItem(); -},$result->containers);}return new NestedPackingResult($results);}} +use Packvium\Result\PackingResult; +use Packvium\Support\ExactInteger; +use Packvium\Support\StableSorter; + +/** + * Packs levels in order, each level's packed containers becoming the next level's items. + * + * `levelBeamWidth` K carries the K best chains from one level to the next. A chain + * is a sequence of level results; it extends by packing its handoff against the level's whole + * container list and, when K > 1 and the level offers more than one, against each container + * alone. Chains rank by their outermost result's score, then each earlier level's outward in, + * then generation order; two chains handing up the same items keep only the better. A level + * with no complete candidate ends every chain, and the best incomplete one is the answer. + * K = 1 is exactly the greedy chain. At most L * K * (T + 1) level packs for L levels offering + * at most T containers each. + */ +final class NestedPacker +{ + /** + * @readonly + * @var int + */ + public $levelBeamWidth = 1; + public function __construct(int $levelBeamWidth = 1) + { + $this->levelBeamWidth = $levelBeamWidth; + if ($levelBeamWidth < 1) { + throw new InvalidArgumentException('level_beam_width must be a positive integer'); + } + } + + /** @param list $items @param list $levels */ + public function pack(array $items, array $levels): NestedPackingResult + { + /** @var list> $beam */ + $beam = [[]]; + /** @var list> $handoffs */ + $handoffs = [$items]; + foreach ($levels as $level) { + $ranked = $this->rankedExtensions($level, $beam, $handoffs); + $complete = self::completeChains($ranked); + if ($complete === []) { + return new NestedPackingResult($ranked[0]); + } + $beam = $this->distinctHandoffs($complete); + $handoffs = \array_map(static function (array $chain): array { + return self::handoff(self::last($chain)); + }, $beam); + } + return new NestedPackingResult($beam[0]); + } + + /** + * Every extension of every chain, best first; the stable sort keeps generation order on ties. + * + * @param list> $beam @param list> $handoffs + * @return list> + */ + private function rankedExtensions(PackingLevel $level, array $beam, array $handoffs): array + { + $packer = new Packer($level->config ?? PackingConfig::balanced()); + $extensions = []; + foreach ($beam as $index => $chain) { + foreach ($this->candidates($packer, $handoffs[$index], $level->containers) as $result) { + $extension = $chain; + $extension[] = $result; + $extensions[] = $extension; + } + } + return StableSorter::sort( + $extensions, + static function (array $left, array $right): int { + return self::compareChains($left, $right); + }, + ); + } + + /** + * @param list $items @param list $containers + * @return list + */ + private function candidates(Packer $packer, array $items, array $containers): array + { + $offers = [$containers]; + if ($this->levelBeamWidth > 1 && \count($containers) > 1) { + foreach ($containers as $container) { + $offers[] = [$container]; + } + } + return \array_map(static function (array $offer) use ($packer, $items): PackingResult { + return $packer->pack($items, $offer); + }, $offers); + } + + /** + * The first K chains, best first, that hand distinct containers up to the next level. + * + * @param list> $ranked @return list> + */ + private function distinctHandoffs(array $ranked): array + { + $kept = []; + $seen = []; + foreach ($ranked as $chain) { + $handoff = self::handoffKey(self::last($chain)); + if (isset($seen[$handoff])) { + continue; + } + $seen[$handoff] = true; + $kept[] = $chain; + if (\count($kept) === $this->levelBeamWidth) { + break; + } + } + return $kept; + } + + /** @param list> $ranked @return list> */ + private static function completeChains(array $ranked): array + { + return \array_values(\array_filter($ranked, static function (array $chain): bool { + return self::last($chain)->complete(); + })); + } + + /** Each packed container as one upright item of the next level. @return list */ + private static function handoff(PackingResult $result): array + { + return \array_map(static function (PackedContainer $container): Item { + return $container->asItem(); + }, $result->containers); + } + + /** + * The handed-up containers as a multiset: instance numbers and emission order are not part + * of a packing's contract, so two engines must collapse the same chains. + */ + private static function handoffKey(PackingResult $result): string + { + $containers = []; + foreach ($result->containers as $container) { + $billed = $container->billedDimensions(); + $containers[] = \serialize([$container->container->id, $billed->length->ticks, $billed->width->ticks, + $billed->height->ticks, $container->grossWeight()->ticks]); + } + \sort($containers, \SORT_STRING); + return \implode("\0", $containers); + } + + /** + * Outermost level first, then each earlier level outward in; chains compared here always + * have the same length. + * + * @param list $left @param list $right + */ + private static function compareChains(array $left, array $right): int + { + for ($index = \count($left) - 1; $index >= 0; --$index) { + $order = self::compareScores($left[$index]->score, $right[$index]->score); + if ($order !== 0) { + return $order; + } + } + return 0; + } + + /** + * Lexicographic, lower is better. A component past PHP's integer range is a decimal + * string, so `<=>` on the raw arrays would compare it as text. + * + * @param list $left @param list $right + */ + private static function compareScores(array $left, array $right): int + { + $shared = \min(\count($left), \count($right)); + for ($index = 0; $index < $shared; ++$index) { + $order = self::compareComponents($left[$index], $right[$index]); + if ($order !== 0) { + return $order; + } + } + return \count($left) <=> \count($right); + } + + /** + * @param int|float|string $left + * @param int|float|string $right + */ + private static function compareComponents($left, $right): int + { + if (\is_float($left) || \is_float($right)) { + return (float)$left <=> (float)$right; + } + return ExactInteger::compare($left, $right); + } + + /** @param list $chain */ + private static function last(array $chain): PackingResult + { + return $chain[\count($chain) - 1]; + } +} diff --git a/src-legacy/Packer.php b/src-legacy/Packer.php index b302740..8809f68 100644 --- a/src-legacy/Packer.php +++ b/src-legacy/Packer.php @@ -6,7 +6,7 @@ use Packvium\Algorithm\{Deadline, FixedLoad, FixedPlacementAdmission, ObjectiveBoundScope, ObjectiveBounds, SolverOrchestrator}; use Packvium\Support\{RequestObjects, StableSorter, UnsupportedPlacements}; use Packvium\Config\PackingConfig; -use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, UnratedWeightException}; +use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, PalletOverhang, UnratedWeightException}; use Packvium\Extension\ExtensionRegistry; use Packvium\Objective\{LandedCostSolutionScorer, ObjectiveRegistry, SolutionScorer, UnknownObjectiveException}; use Packvium\Result\{ @@ -97,13 +97,16 @@ private static function statedOptimality(string $status, array $score, ?array $o return [$status, new ResultFact($code, $fields)]; } - /** @param list $items @param list $containers @param list $fixedPlacements */ - public function pack(array $items, array $containers, array $fixedPlacements = []): PackingResult + /** + * @param list $items @param list $containers @param list $fixedPlacements + * @param ?string $currency the ISO 4217 code the request's prices are in, echoed by the result (1.10) + */ + public function pack(array $items, array $containers, array $fixedPlacements = [], ?string $currency = null): PackingResult { // The JSON path's rules, with the JSON path's reason and field: a request // built from objects is refused exactly where the same request as JSON would be. - RequestObjects::check($items, $containers, $this->config, $fixedPlacements); - return $this->solve($items, $containers, $fixedPlacements); + RequestObjects::check($items, $containers, $this->config, $fixedPlacements, $currency); + return $this->solve($items, $containers, $fixedPlacements, $currency); } /** @@ -113,9 +116,15 @@ public function pack(array $items, array $containers, array $fixedPlacements = [ * * @param list $items @param list $containers @param list $fixedPlacements */ - private function solve(array $items, array $containers, array $fixedPlacements): PackingResult + private function solve(array $items, array $containers, array $fixedPlacements, ?string $currency = null): PackingResult { - $request = new PackingRequest($items, $containers, $fixedPlacements); + // A pallet with an overhang limit is packed as its widened frame from here on, so no + // solver, bound or validator needs to know the limit exists. + // A container without a limit is its own frame; asking only for one with a limit keeps + // `PalletOverhang` uncompiled on every other request, whose heap pays for its code. + $request = new PackingRequest($items, \array_map(static function (Container $container): Container { + return $container->palletOverhangLimit === null ? $container : PalletOverhang::solvingFrame($container); + }, $containers), $fixedPlacements, $currency); // Both cost objectives price the same billed weight, so both need the divisor. // There is no library-chosen default: a wrong guess would silently misprice // every shipment. `ShippingCostSolutionScorer::fromConfig` still refuses too, @@ -240,7 +249,7 @@ static function ($c) { $raw->stats->candidatesEvaluated, $raw->stats->placementsAttempted, $raw->stats->metrics(), - ), $score, $warnings, [], null, $termination, $optimality, $this->config->objective); + ), $score, $warnings, [], null, $termination, $optimality, $this->config->objective, $request->currency); } $ranked = StableSorter::sortBy($ranked, static function ($result): array { @@ -300,6 +309,7 @@ function (PackingResult $result) use ($landed): bool { $best->termination, $best->optimality, $best->objective, + $best->currency, ); } } diff --git a/src-legacy/Result/PackingResult.php b/src-legacy/Result/PackingResult.php index 70c5701..2afc560 100644 --- a/src-legacy/Result/PackingResult.php +++ b/src-legacy/Result/PackingResult.php @@ -49,6 +49,14 @@ final class PackingResult * @var string */ public $objective = 'default'; + /** + * @readonly + * @var string|null + */ + public $currency; + /** The serialization cache before any value is shared through it. */ + private const NOTHING_SHARED = ['length' => [], 'weight' => [], 'dimensions' => []]; + /** * @readonly * @var \Packvium\Result\ResultFact @@ -83,7 +91,8 @@ public function __construct( ?ResultFact $feasibility = null, ?ResultFact $termination = null, ?ResultFact $optimality = null, - string $objective = 'default' + string $objective = 'default', + ?string $currency = null ) { $this->status = $status; $this->containers = $containers; @@ -93,6 +102,9 @@ public function __construct( $this->warnings = $warnings; $this->alternatives = $alternatives; $this->objective = $objective; + // The request's ISO 4217 code, echoed only when the request declares one, by the + // answer and by every alternative alike (1.10). + $this->currency = $currency; [$derivedFeasibility, $derivedTermination, $derivedOptimality] = self::deriveFacts( $status, $unpacked === [], @@ -161,47 +173,48 @@ public function toArray( ): array { // Equal quantities share one array: placements repeat a type's dimensions, a lattice // coordinate and a zero top load, and a shared array serializes to the same bytes. - $shared = ['length' => [], 'weight' => [], 'dimensions' => []]; - return $this->serialized($lengthUnit, $weightUnit, $includeAlternatives, $shared); + $shared = self::NOTHING_SHARED; + return $this->serialized($lengthUnit, $weightUnit, $includeAlternatives, false, $shared); + } + + /** + * `toArray`, except that each container's `placements` (the answer's and every + * alternative's) is a one-pass `\Generator` of the same placement arrays, for + * `PrettyJsonStream` to write as it goes. + * + * The placements are most of a result's array, and holding all of them next to the result + * objects they come from is the peak of a `bin/packvium` run on `fast`; streamed, no more + * than one placement's array is alive at a time. Each generator holds its own container. + */ + public function toStreamedArray(string $lengthUnit = 'mm', string $weightUnit = 'g'): array + { + $shared = self::NOTHING_SHARED; + return $this->serialized($lengthUnit, $weightUnit, true, true, $shared); } /** @param array{length:array,weight:array,dimensions:array>>} $shared */ - private function serialized(string $lengthUnit, string $weightUnit, bool $includeAlternatives, array &$shared): array + private function serialized(string $lengthUnit, string $weightUnit, bool $includeAlternatives, bool $streamPlacements, array &$shared): array { $containers = []; foreach ($this->containers as $container) { - $placements = []; - foreach ($container->placements as $placement) { - $placements[] = [ - 'item_id' => $placement->instance->id(), - 'item_type' => $placement->instance->item->id, - 'position' => self::point($placement->position, $lengthUnit, $shared), - 'dimensions' => self::dimensions($placement->dimensions, $lengthUnit, $shared), - 'orientation' => $placement->rotation, - 'support_ratio' => sprintf('%.6f', $placement->supportRatio), - 'top_load' => $shared['weight'][$placement->topLoad->ticks] = $shared['weight'][$placement->topLoad->ticks] ?? $placement->topLoad->toArray($weightUnit), - ]; - // Absent unless true, so a request without fixed placements keeps its bytes. - if ($placement->fixed) { - $placements[array_key_last($placements)]['fixed'] = true; - } - } + $containerId = $container->id(); + $placements = self::placements($container, $containerId, $lengthUnit, $weightUnit, $streamPlacements, $shared); $serialized = [ - 'id' => $container->id(), + 'id' => $containerId, 'container_type' => $container->container->id, - 'inner_dimensions' => $container->container->innerDimensions->toArray($lengthUnit), + 'inner_dimensions' => $container->container->declaredInner()->toArray($lengthUnit), 'outer_dimensions' => ($container->container->outerDimensions - ?? $container->container->innerDimensions)->toArray($lengthUnit), + ?? $container->container->declaredInner())->toArray($lengthUnit), 'payload_weight' => $container->payloadWeight()->toArray($weightUnit), 'gross_weight' => $container->grossWeight()->toArray($weightUnit), 'used_volume_ticks3' => $container->usedVolumeString(), 'volume_utilization' => sprintf('%.6f', $container->utilization()), 'centre_of_mass_offset_ppm' => $container->centreOfMassOffsetPpm(), 'void_fill_reserve_ticks3' => VolumeReserve::reserved($container->container), - 'placements' => $placements, + 'placements' => $streamPlacements ? $placements : \iterator_to_array($placements, false), ]; - // Present exactly when the container conforms to its contents, so a - // rigid container's bytes are unchanged. + // Present exactly when the container conforms to its contents or is a + // pallet with an overhang limit, so a rigid container's bytes are unchanged. $achieved = $container->achievedDimensions(); if ($achieved !== null) { $serialized['achieved_dimensions'] = $achieved->toArray($lengthUnit); @@ -265,11 +278,11 @@ private function serialized(string $lengthUnit, string $weightUnit, bool $includ $alternatives = []; if ($includeAlternatives) { foreach ($this->alternatives as $alternative) { - $alternatives[] = $alternative->serialized($lengthUnit, $weightUnit, false, $shared); + $alternatives[] = $alternative->serialized($lengthUnit, $weightUnit, false, $streamPlacements, $shared); } } - return [ + $result = [ 'status' => $this->status, 'feasibility' => $this->feasibility->toArray(), 'termination' => $this->termination->toArray(), @@ -296,9 +309,47 @@ private function serialized(string $lengthUnit, string $weightUnit, bool $includ 'containers' => $containers, 'unpacked_items' => $unpacked, 'catalog_versions_used' => [], - 'warnings' => $this->warnings, - 'alternatives' => $alternatives, ]; + // Absent unless the request declared one, so every other request keeps its bytes. + if ($this->currency !== null) { + $result['currency'] = $this->currency; + } + $result['warnings'] = $this->warnings; + $result['alternatives'] = $alternatives; + return $result; + } + + /** + * One container's placements, serialized in order. + * + * Streamed, each array is written and dropped before the next is built, so a cached value + * would only be kept alive, never shared: the cache is let go after every placement. + * + * @param array{length:array,weight:array,dimensions:array>>} $shared + * @return \Generator> + */ + private static function placements(PackedContainer $container, string $containerId, string $lengthUnit, string $weightUnit, bool $streamed, array &$shared): \Generator + { + foreach ($container->placements as $placement) { + $serialized = [ + 'placement_id' => $placement->idIn($containerId), + 'item_id' => $placement->instance->id(), + 'item_type' => $placement->instance->item->id, + 'position' => self::point($placement->position, $lengthUnit, $shared), + 'dimensions' => self::dimensions($placement->dimensions, $lengthUnit, $shared), + 'orientation' => $placement->rotation, + 'support_ratio' => sprintf('%.6f', $placement->supportRatio), + 'top_load' => $shared['weight'][$placement->topLoad->ticks] = $shared['weight'][$placement->topLoad->ticks] ?? $placement->topLoad->toArray($weightUnit), + ]; + // Absent unless true, so a request without fixed placements keeps its bytes. + if ($placement->fixed) { + $serialized['fixed'] = true; + } + yield $serialized; + if ($streamed) { + $shared = self::NOTHING_SHARED; + } + } } /** `Point::toArray`, from shared length arrays. */ diff --git a/src-legacy/Revisions/PlanRevision.php b/src-legacy/Revisions/PlanRevision.php index 8708a46..8e29b1a 100644 --- a/src-legacy/Revisions/PlanRevision.php +++ b/src-legacy/Revisions/PlanRevision.php @@ -4,10 +4,16 @@ use JsonException; use Packvium\Artifacts\OperationalArtifact; +use Packvium\Domain\MadeToMeasure; +use Packvium\Support\BigInt; use Packvium\Support\CanonicalJson; use Packvium\Support\CanonicalJsonException; use Packvium\Support\FixedPlacementShape; use Packvium\Support\JsonValue; +use Packvium\Support\MeasureReading; +use Packvium\Support\RequestRules; +use Packvium\Unit\Length; +use Packvium\Unit\Weight; use stdClass; use Throwable; @@ -34,8 +40,9 @@ final class PlanRevision 'placement_locked' => ['placement'], 'placement_verified' => ['placement'], ]; - private const PLACEMENT_FIELDS = ['item_type', 'container_type', 'container_instance', 'position', 'orientation']; + private const PLACEMENT_FIELDS = ['item_type', 'container_type', 'container_instance', 'position', 'orientation', 'placement_id']; private const JSON_DEPTH = 512; + private const CUT_SIDES = ['length', 'width', 'height']; /** * Revision 0: the request as first approved, with nothing recorded against it. @@ -74,15 +81,17 @@ public static function derive($parent, $approvedArtifact, $events): stdClass throw new PlanRevisionException('invalid_event', 'a revision records at least one event'); } $first = self::lastSequence($parent) + 1; + $hulls = self::hullTypes($parent->request); $recorded = []; foreach ($events as $offset => $event) { - $recorded[] = self::event(self::tree($event), $first + $offset); + $recorded[] = self::event(self::tree($event), $first + $offset, $hulls); } - $request = self::applyEvents($parent->request, $recorded); + $number = self::number($parent) + 1; + $request = self::stockCutBoxes(self::applyEvents($parent->request, $recorded), $approvedArtifact, $number); $approved = new stdClass(); $approved->artifact = self::digest($approvedArtifact); $approved->replay = self::tree($approvedArtifact->provenance->replay); - $document = self::document(self::number($parent) + 1, self::digest($parent), $approved, $recorded, $request); + $document = self::document($number, self::digest($parent), $approved, $recorded, $request); self::canonicalJson($document); return $document; } @@ -104,10 +113,11 @@ public static function applyEvents($request, $events): stdClass throw new PlanRevisionException('invalid_event', 'events are a JSON array'); } $derived = self::tree($request); + $hulls = self::hullTypes($request); $placementSession = ['ready' => false, 'keys' => null, 'indexable' => true]; foreach ($events as $event) { $event = self::tree($event); - self::requireShape($event); + self::requireShape($event, $hulls); $sequence = JsonValue::get($event, 'sequence'); if (JsonValue::integer($sequence) === null) { throw new PlanRevisionException('invalid_event', 'event sequence ' . CanonicalJson::spelling($sequence) . ' is not an integer'); @@ -126,6 +136,29 @@ public static function applyEvents($request, $events): stdClass return $derived; } + /** + * `$request` with every made-to-measure box that holds a fixed placement made a stock + * container. The box was cut for the approved plan, so a replan cannot recut it: + * instance `n` of made-to-measure type `T` -- the `n`-th container of type `T` in the + * artifact, in result order -- becomes container `T@#`, a copy of `T` without + * `made_to_measure`, quantity 1, at the cut inner and outer size, price and tare, each in + * ticks; it follows `T` in the container list. Its fixed placements move to its instance 1 + * and `T`'s own `quantity`, if stated, loses the boxes taken (`T` is dropped at zero). New + * boxes are still cut to measure. Pure; O(C + F + A) for containers, fixed placements and + * the artifact's containers. + * + * @param stdClass|array $request + * @param stdClass|array|mixed $approvedArtifact + * @throws PlanRevisionException + */ + public static function stockCutBoxes($request, $approvedArtifact, int $revision): stdClass + { + if (!JsonValue::isObject($request)) { + throw new PlanRevisionException('invalid_revision', 'a request is a JSON object'); + } + return self::stockedRequest(self::tree($request), self::tree($approvedArtifact), $revision); + } + /** * Every way the chain fails to be what its root and events derive, without stopping at the * first. `$artifacts[$k]`, when given, is the artifact revision `$k` names as approved. @@ -169,10 +202,10 @@ public static function verifyChain($revisions, $artifacts = null): array $issues[] = new RevisionIssue('parent_mismatch', $position, 'parent ' . self::plain($recordedParent) . ', expected ' . self::plain($expectedParent)); } $lastSequence = self::checkSequences($revision, $position, $lastSequence, $issues); + $artifact = $artifacts[$position] ?? null; if ($parent !== null) { - self::checkRequest($revision, $parent, $position, $issues); + self::checkRequest($revision, $parent, $artifact === null ? null : self::tree($artifact), $position, $issues); } - $artifact = $artifacts[$position] ?? null; if ($artifact !== null && $parent !== null) { self::checkArtifact($revision, $parent, self::tree($artifact), $position, $issues); } @@ -293,10 +326,10 @@ private static function lastSequence(stdClass $revision): int return 0; } - /** @param mixed $raw */ - private static function event($raw, int $sequence): stdClass + /** @param mixed $raw @param list $hulls */ + private static function event($raw, int $sequence, array $hulls): stdClass { - self::requireShape($raw); + self::requireShape($raw, $hulls); $given = JsonValue::get($raw, 'sequence'); if (JsonValue::integer($given) !== $sequence) { throw new PlanRevisionException('invalid_event', 'event sequence ' . CanonicalJson::spelling($given) . " does not continue the chain at {$sequence}"); @@ -304,8 +337,19 @@ private static function event($raw, int $sequence): stdClass return $raw; } - /** @param mixed $raw */ - private static function requireShape($raw): void + /** + * The request's hull item types, which alone may be placed in a signed orientation (1.10). + * + * @param mixed $request + * @return list + */ + private static function hullTypes($request): array + { + return JsonValue::isObject($request) ? FixedPlacementShape::hullItemTypes(JsonValue::get($request, 'items')) : []; + } + + /** @param mixed $raw @param list $hulls */ + private static function requireShape($raw, array $hulls): void { if (!$raw instanceof stdClass) { throw new PlanRevisionException('invalid_event', 'an event is a JSON object'); @@ -329,7 +373,7 @@ private static function requireShape($raw): void } elseif ($kind === 'container_substituted') { self::validateContainerSubstituted($raw); } else { - self::validatePlacement($raw); + self::validatePlacement($raw, $hulls); } } @@ -351,7 +395,8 @@ private static function validateContainerSubstituted(stdClass $event): void self::requireName(JsonValue::get($event->replacement, 'id'), 'replacement.id'); } - private static function validatePlacement(stdClass $event): void + /** @param list $hulls */ + private static function validatePlacement(stdClass $event, array $hulls): void { $placement = $event->placement; if (!$placement instanceof stdClass) { @@ -363,8 +408,10 @@ private static function validatePlacement(stdClass $event): void } self::requireName(JsonValue::get($placement, 'item_type'), 'placement.item_type'); self::requireName(JsonValue::get($placement, 'container_type'), 'placement.container_type'); - if (!\in_array(JsonValue::get($placement, 'orientation'), FixedPlacementShape::ORIENTATIONS, true)) { - throw new PlanRevisionException('invalid_event', 'placement.orientation must be one of ' . CanonicalJson::spelling(FixedPlacementShape::ORIENTATIONS)); + $hull = \in_array(JsonValue::get($placement, 'item_type'), $hulls, true); + $refusal = RequestRules::orientationRefusal(JsonValue::get($placement, 'orientation'), $hull, 'placement.orientation'); + if ($refusal !== null) { + throw new PlanRevisionException('invalid_event', $refusal[1]); } $instance = JsonValue::has($placement, 'container_instance') ? JsonValue::integer($placement->container_instance) : 1; if ($instance === null || $instance < 1) { @@ -378,6 +425,12 @@ static function (string $message): Throwable { return new PlanRevisionException('invalid_event', $message); } ); + // Only its type is the event's to judge: whether it names this placement needs the + // request's unit, and is the engine's admission rule when the revision is solved (1.10). + $identifier = JsonValue::get($placement, 'placement_id'); + if ($identifier !== null && !\is_string($identifier)) { + throw new PlanRevisionException('invalid_event', 'placement.placement_id is a string'); + } } /** @param mixed $value */ @@ -450,7 +503,7 @@ private static function applyPlacement(stdClass $request, stdClass $event, array $session['keys'] = []; try { foreach ($request->fixed_placements as $entry) { - $session['keys'][self::canonicalJson(self::withDefaultInstance($entry))] = true; + $session['keys'][self::canonicalJson(self::identity($entry))] = true; } } catch (PlanRevisionException $error) { $session['indexable'] = false; @@ -458,7 +511,7 @@ private static function applyPlacement(stdClass $request, stdClass $event, array } // One box cannot be two fixed items: a lock that is later verified in place is recorded // twice in the chain and once in the request. - $placement = self::withDefaultInstance($event->placement); + $placement = self::identity($event->placement); if ($session['indexable']) { try { $key = self::canonicalJson($placement); @@ -476,16 +529,21 @@ private static function applyPlacement(stdClass $request, stdClass $event, array } // Keep the old first-match/error order for values outside canonical JSON. foreach ($request->fixed_placements as $entry) { - if (self::same(self::withDefaultInstance($entry), $placement)) { + if (self::same(self::identity($entry), $placement)) { return; } } $request->fixed_placements[] = self::tree($event->placement); } - private static function withDefaultInstance(stdClass $placement): stdClass + /** + * What makes two fixed entries one box: everything but `placement_id`, which only restates + * the container and position (1.10), with the default instance spelled out. + */ + private static function identity(stdClass $placement): stdClass { $copy = self::tree($placement); + unset($copy->placement_id); if (!JsonValue::has($copy, 'container_instance')) { $copy->container_instance = 1; } @@ -557,11 +615,22 @@ private static function checkSequences(stdClass $revision, int $position, int $l return $last; } - /** @param list $issues */ - private static function checkRequest(stdClass $revision, stdClass $parent, int $position, array &$issues): void + /** + * @param mixed $artifact the artifact this revision approved, when the caller gave one + * @param list $issues + */ + private static function checkRequest(stdClass $revision, stdClass $parent, $artifact, int $position, array &$issues): void { try { $derived = self::applyEvents($parent->request, $revision->events); + if (self::holdsCutBoxes($derived)) { + // The cut sizes live only in the approved artifact. + if ($artifact === null) { + $issues[] = new RevisionIssue('artifact_required', $position, 'fixed items in a made-to-measure box are checked against the approved artifact'); + return; + } + $derived = self::stockedRequest($derived, $artifact, self::number($revision)); + } } catch (PlanRevisionException $error) { $issues[] = new RevisionIssue('request_mismatch', $position, 'the events do not apply: ' . $error->getMessage()); return; @@ -591,6 +660,257 @@ private static function checkArtifact(stdClass $revision, stdClass $parent, $art } } + // ------------------------------------------------------------- cut-to-measure stock + + /** + * `stockCutBoxes` on a tree already deep-copied, so it mutates freely. + * + * @param mixed $artifact + * @throws PlanRevisionException + */ + private static function stockedRequest(stdClass $derived, $artifact, int $revision): stdClass + { + $fixed = JsonValue::get($derived, 'fixed_placements'); + $containers = JsonValue::get($derived, 'containers'); + if (!JsonValue::isList($fixed) || !JsonValue::isList($containers)) { + return $derived; + } + $machines = self::machines($containers); + $stocked = []; + $named = []; + $cuts = null; + foreach ($fixed as $entry) { + $machineId = $entry instanceof stdClass ? JsonValue::get($entry, 'container_type') : null; + if (!\is_string($machineId) || !isset($machines[$machineId])) { + continue; + } + $instance = JsonValue::integer(JsonValue::has($entry, 'container_instance') ? $entry->container_instance : 1); + $stockId = "{$machineId}@{$revision}#" . ($instance === null ? 'None' : $instance); + if (!isset($named[$stockId])) { + $cuts = $cuts ?? self::cutBoxes($artifact); + $named[$stockId] = self::stockBox($derived, $machines[$machineId], $stockId, self::cutInner($cuts, $machineId, $instance)); + $stocked[$machineId][] = $named[$stockId]; + } + $entry->container_type = $stockId; + $entry->container_instance = 1; + // A stated id named the cut box's instance of the machine, which this request no + // longer has; admission would refuse it as a mismatch. + unset($entry->placement_id); + } + if ($named === []) { + return $derived; + } + self::refuseClash(\array_keys($named), $containers); + $derived->containers = self::rebuilt($containers, $stocked); + return $derived; + } + + /** Whether a fixed placement names a made-to-measure container type. @param stdClass $request */ + private static function holdsCutBoxes(stdClass $request): bool + { + $containers = JsonValue::get($request, 'containers'); + $fixed = JsonValue::get($request, 'fixed_placements'); + if (!JsonValue::isList($containers) || !JsonValue::isList($fixed)) { + return false; + } + $machines = self::machines($containers); + foreach ($fixed as $entry) { + $type = $entry instanceof stdClass ? JsonValue::get($entry, 'container_type') : null; + if (\is_string($type) && isset($machines[$type])) { + return true; + } + } + return false; + } + + /** @param list $containers @return array */ + private static function machines(array $containers): array + { + $machines = []; + foreach ($containers as $entry) { + if ($entry instanceof stdClass && \is_string(JsonValue::get($entry, 'id')) && JsonValue::get($entry, 'made_to_measure') !== null) { + $machines[$entry->id] = $entry; + } + } + return $machines; + } + + /** @param list $names @param list $containers */ + private static function refuseClash(array $names, array $containers): void + { + $existing = []; + foreach ($containers as $container) { + $id = $container instanceof stdClass ? JsonValue::get($container, 'id') : null; + if (\is_string($id)) { + $existing[$id] = true; + } + } + $clash = null; + foreach ($names as $name) { + if (isset($existing[$name]) && ($clash === null || strcmp($name, $clash) < 0)) { + $clash = $name; + } + } + if ($clash !== null) { + throw new PlanRevisionException('event_conflict', 'a container is already named ' . CanonicalJson::spelling($clash)); + } + } + + /** + * @param list $containers @param array> $stocked + * @return list + */ + private static function rebuilt(array $containers, array $stocked): array + { + $rebuilt = []; + foreach ($containers as $container) { + $id = $container instanceof stdClass ? JsonValue::get($container, 'id') : null; + $boxes = \is_string($id) ? ($stocked[$id] ?? []) : []; + if ($boxes === []) { + $rebuilt[] = $container; + continue; + } + $quantity = JsonValue::get($container, 'quantity') === null ? null : JsonValue::integer($container->quantity); + if ($quantity === null || $quantity > \count($boxes)) { + if ($quantity !== null) { + $container->quantity = $quantity - \count($boxes); + } + $rebuilt[] = $container; + } + \array_push($rebuilt, ...$boxes); + } + return $rebuilt; + } + + /** + * Index raw shapes in artifact order; only selected dimensions are parsed. O(A). + * + * @param mixed $artifact @return array> + */ + private static function cutBoxes($artifact): array + { + $work = JsonValue::isObject($artifact) ? JsonValue::get($artifact, 'work_order') : null; + $geometry = JsonValue::isObject($artifact) ? JsonValue::get($artifact, 'geometry') : null; + $orders = JsonValue::isObject($work) ? JsonValue::get($work, 'containers') : null; + $shapes = JsonValue::isObject($geometry) ? JsonValue::get($geometry, 'containers') : null; + $cuts = []; + if (JsonValue::isList($orders) && JsonValue::isList($shapes)) { + $count = \min(\count($orders), \count($shapes)); + for ($index = 0; $index < $count; ++$index) { + $type = JsonValue::isObject($orders[$index]) ? JsonValue::get($orders[$index], 'container_type') : null; + if (\is_string($type)) { + $cuts[$type][] = $shapes[$index]; + } + } + } + return $cuts; + } + + /** @param array> $cuts @return array{0:int,1:int,2:int} */ + private static function cutInner(array $cuts, string $machineId, ?int $instance): array + { + $shapes = $cuts[$machineId] ?? []; + if ($instance !== null && $instance >= 1 && $instance <= \count($shapes)) { + $shape = $shapes[$instance - 1]; + return [self::artifactTicks($shape, 'length'), self::artifactTicks($shape, 'width'), self::artifactTicks($shape, 'height')]; + } + throw new PlanRevisionException('invalid_artifact', "the approved plan holds no {$machineId} instance " . CanonicalJson::spelling($instance)); + } + + /** @param mixed $shape */ + private static function artifactTicks($shape, string $axis): int + { + $sides = JsonValue::isObject($shape) ? JsonValue::get($shape, 'inner_dimensions') : null; + $value = JsonValue::isObject($sides) ? JsonValue::get($sides, $axis) : null; + if (!\is_string($value) || \preg_match('/^[0-9]+$/', $value) !== 1 + || BigInt::compare(\ltrim($value, '0') ?: '0', (string) JsonValue::MAX_EXACT_MAGNITUDE) > 0) { + throw new PlanRevisionException('invalid_artifact', "a cut box's {$axis} is not a tick count"); + } + return (int) $value; + } + + /** + * The stock container a cut box becomes, priced as `Container::fabricate` prices it. + * + * @param array{0:int,1:int,2:int} $inner + */ + private static function stockBox(stdClass $request, stdClass $machine, string $stockId, array $inner): stdClass + { + $units = self::stockObject(JsonValue::get($request, 'units'), 'units', true); + $unit = JsonValue::get($units, 'length') ?? 'mm'; + if (!\is_string($unit)) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's units.length is not a string"); + } + $spec = self::stockObject($machine->made_to_measure, 'made_to_measure'); + $allowance = self::stockObject(JsonValue::get($spec, 'outer_allowance'), 'outer_allowance', true); + $outer = []; + foreach (self::CUT_SIDES as $index => $axis) { + $side = JsonValue::get($allowance, $axis); + $outer[] = $inner[$index] + ($side === null ? 0 : self::stockMeasure($side, Length::class, $unit, 'outer_allowance')); + } + $area = MadeToMeasure::surfaceArea($inner); + $price = self::stockInteger(JsonValue::get($spec, 'cost_per_square_metre_minor'), 'cost_per_square_metre_minor'); + $rate = JsonValue::get($spec, 'tare_per_square_metre'); + $tareRate = $rate === null ? 0 : self::stockMeasure($rate, Weight::class, 'g', 'tare_per_square_metre'); + $tare = JsonValue::get($machine, 'tare_weight'); + $declaredTare = $tare === null ? 0 : self::stockMeasure($tare, Weight::class, 'g', 'tare_weight'); + $box = new stdClass(); + foreach (JsonValue::members($machine) as [$name, $value]) { + if ($name !== 'made_to_measure') { + $box->{$name} = self::tree($value); + } + } + $box->id = $stockId; + $box->quantity = 1; + $box->inner_dimensions = self::tickBox($inner); + $box->outer_dimensions = self::tickBox($outer); + $fee = self::stockInteger(JsonValue::get($machine, 'cost_minor'), 'cost_minor'); + $box->cost_minor = (int) BigInt::add((string) $fee, MadeToMeasure::perSquareMetre($price, $area)); + $box->tare_weight = (object) ['value' => BigInt::add((string) $declaredTare, MadeToMeasure::perSquareMetre($tareRate, $area)), 'unit' => 'ticks']; + return $box; + } + + /** @param mixed $value */ + private static function stockObject($value, string $name, bool $optional = false): stdClass + { + if ($value === null && $optional) { + return new stdClass(); + } + if (!$value instanceof stdClass) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's {$name} is not an object"); + } + return $value; + } + + /** @param mixed $value */ + private static function stockInteger($value, string $name): int + { + $integer = JsonValue::integer($value ?? 0); + if ($integer === null) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's {$name} is not an integer"); + } + return $integer; + } + + /** @param mixed $value @param class-string|class-string $kind */ + private static function stockMeasure($value, string $kind, string $unit, string $name): int + { + if (MeasureReading::verdict($value, $kind, $unit) !== MeasureReading::READABLE) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's {$name} is not a measure"); + } + return MeasureReading::ticks($value, $kind, $unit); + } + + /** @param list $sides */ + private static function tickBox(array $sides): stdClass + { + $box = new stdClass(); + foreach (self::CUT_SIDES as $index => $axis) { + $box->{$axis} = (object) ['value' => (string) $sides[$index], 'unit' => 'ticks']; + } + return $box; + } + // --------------------------------------------------------------------------- values /** diff --git a/src-legacy/Serialization/ArrayCodec.php b/src-legacy/Serialization/ArrayCodec.php index 54fc733..26790db 100644 --- a/src-legacy/Serialization/ArrayCodec.php +++ b/src-legacy/Serialization/ArrayCodec.php @@ -5,7 +5,7 @@ use InvalidArgumentException; use Packvium\Algorithm\EffortBudget; use Packvium\Config\{PackingConfig,SolverProfile}; -use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,Item,MadeToMeasure,Obstacle,Point,RateTable,Rotation,ShapeType}; +use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,Item,MadeToMeasure,Obstacle,OverhangLimit,Point,RateTable,Rotation,ShapeType}; use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; use Packvium\Policy\PolicyRuleSet; @@ -46,12 +46,10 @@ private static function axles(?array $r,string $unit):?array{if($r===null)return // list in, when PHP gained both the solver behaviour and the independent // validation the staged rollout requires. Rust and the JavaScript fallback still // carry them. - // `pallet_overhang_limit` was reserved in the schema by at the 1.1.0 - // contract freeze and is refused everywhere until an engine implements it from a - // request: a field a caller can set and the solver ignores is worse than a refusal. // `access_directions` left this list in, which wired the reserved field - // through to `StopAccessibilityConstraint` in all four engines at once. - 'item'=>[],'container'=>['pallet_overhang_limit']]; + // through to `StopAccessibilityConstraint` in all four engines at once, and + // `pallet_overhang_limit` in, which did the same for the pallet deck. + 'item'=>[],'container'=>[]]; /** * `item.shape_type` values this engine does not implement. @@ -105,6 +103,7 @@ public static function rejectUnsupported(array $data,?array $unsupported=null,?a } } foreach(self::madeToMeasureCombinations($data) as $name)$found[$name]=true; + foreach(self::palletOverhangCombinations($data) as $name)$found[$name]=true; foreach(self::entries($data,'items') as $entry){ if(!is_array($entry))continue; $shape=$entry['shape_type']??null; @@ -137,8 +136,6 @@ public static function madeToMeasureCombinations(array $data):array if(($entry['axles']??null)!==null)$found['container.made_to_measure+axles']=true; $obstacles=$entry['obstacles']??null; if(JsonValue::isList($obstacles)&&$obstacles!==[])$found['container.made_to_measure+obstacles']=true; - $reserve=$entry['void_fill_reserve_ratio']??null; - if((is_int($reserve)||is_float($reserve))&&$reserve>0)$found['container.made_to_measure+void_fill_reserve_ratio']=true; } $fixed=$data['fixed_placements']??null; if($measured!==[]&&is_array($fixed)){ @@ -150,6 +147,36 @@ public static function madeToMeasureCombinations(array $data):array return array_keys($found); } + /** + * The combinations a pallet with an overhang limit refuses. Obstacles and axles + * are positioned in the declared frame the widened frame moves; doors and route corridors + * would need a wall the overhang crosses; a reserve is a share of a volume the limit leaves + * undefined; a made-to-measure box has no deck. A flat bag is refused beside it as a request + * error instead. Checked on the raw request. O(items + containers). + * + * @param array $data + * @return list + */ + public static function palletOverhangCombinations(array $data):array + { + $found=[];$pallets=false; + foreach(self::entries($data,'containers') as $entry){ + if(!is_array($entry)||($entry['pallet_overhang_limit']??null)===null)continue; + $pallets=true; + $directions=$entry['access_directions']??null; + $obstacles=$entry['obstacles']??null; + $reserve=$entry['void_fill_reserve_ratio']??null; + $present=['access_directions'=>JsonValue::isList($directions)&&$directions!==[],'axles'=>($entry['axles']??null)!==null, + 'made_to_measure'=>($entry['made_to_measure']??null)!==null,'obstacles'=>JsonValue::isList($obstacles)&&$obstacles!==[], + 'void_fill_reserve_ratio'=>(is_int($reserve)||is_float($reserve))&&$reserve>0]; + foreach($present as $name=>$set)if($set)$found["container.pallet_overhang_limit+{$name}"]=true; + } + if($pallets) + foreach(self::entries($data,'items') as $item) + if(is_array($item)&&($item['stop_index']??null)!==null){$found['container.pallet_overhang_limit+item.stop_index']=true;break;} + return array_keys($found); + } + /** @return array a collection to scan, or nothing when it is not one */ /** * The output unit a request without `output.length_unit` is written in: the @@ -176,6 +203,24 @@ private static function entries(array $data,string $collection):array{$entries=$ * @param mixed $data */ public static function pack($data):array + { + return self::packed($data,false); + } + + /** + * `pack`, with each container's `placements` a one-pass generator of the same arrays + * (`PackingResult::toStreamedArray`): what `bin/packvium` hands `PrettyJsonStream`, so + * the answer's placements are never all held at once. + * + * @param mixed $data + */ + public static function packStreamed($data):array + { + return self::packed($data,true); + } + + /** @param mixed $data */ + private static function packed($data,bool $streamPlacements):array { if(!is_array($data)||($data!==[]&&JsonValue::isList($data)))throw new InvalidRequestException('wrong_type','','must be an object'); self::rejectUnsupported($data); @@ -184,7 +229,10 @@ public static function pack($data):array catch(InvalidArgumentException|TypeError|ValueError|ArithmeticError $error){throw self::asRequestError($error);} $unit=(string)($data['units']['length']??'mm'); $out=$data['output']??[]; - $result=self::solve(new Packer($config,$extensions),$items,$containers,$fixed)->toArray($out['length_unit']??self::outputLengthCode($unit),$out['weight_unit']??'g'); + $lengthUnit=$out['length_unit']??self::outputLengthCode($unit); + $weightUnit=$out['weight_unit']??'g'; + $packed=self::solve(new Packer($config,$extensions),$items,$containers,$fixed,$data['currency']??null); + $result=$streamPlacements?$packed->toStreamedArray($lengthUnit,$weightUnit):$packed->toArray($lengthUnit,$weightUnit); $result['catalog_versions_used']=$references; return $result; } @@ -197,10 +245,10 @@ public static function pack($data):array * * @param list $items @param list $containers @param list $fixed */ - private static function solve(Packer $packer,array $items,array $containers,array $fixed):PackingResult + private static function solve(Packer $packer,array $items,array $containers,array $fixed,?string $currency):PackingResult { - $solve=\Closure::bind(static function (Packer $packer) use ($items, $containers, $fixed): PackingResult { - return $packer->solve($items,$containers,$fixed); + $solve=\Closure::bind(static function (Packer $packer) use ($items, $containers, $fixed, $currency): PackingResult { + return $packer->solve($items,$containers,$fixed,$currency); },null,Packer::class); return $solve($packer); } @@ -231,7 +279,7 @@ private static function model(array $data):array $containers=array_map(function ($r) use ($unit) { return self::container($r,$unit); },$data['containers']); - $fixed=self::fixedPlacements($data['fixed_placements']??null,$unit); + $fixed=self::fixedPlacements($data['fixed_placements']??null,$unit,$data['items']); return [$config,$references,$extensions,$items,$containers,$fixed]; } @@ -322,14 +370,15 @@ private static function box(array $r,string $unit):AxisAlignedBox{return new Axi * compiles their shape checker. O(f) for f entries. * * @param mixed $raw + * @param mixed $items the request's raw `items`, read for their hull types only past the guard * @return list */ - private static function fixedPlacements($raw,string $unit):array + private static function fixedPlacements($raw,string $unit,$items):array { if($raw===null)return []; return array_map(function ($r) use ($unit) { return self::fixedPlacement($r,$unit); - },FixedPlacementShape::requireEntries($raw,$unit)); + },FixedPlacementShape::requireEntries($raw,$unit,FixedPlacementShape::hullItemTypes($items))); } /** @@ -338,14 +387,18 @@ private static function fixedPlacements($raw,string $unit):array * * @param array $r */ - private static function fixedPlacement(array $r,string $unit):FixedPlacement{return new FixedPlacement($r['item_type'],$r['container_type'],self::point($r['position']??[],$unit),Rotation::from($r['orientation']),array_key_exists('container_instance',$r)?(int)JsonValue::integer($r['container_instance']):1);} + private static function fixedPlacement(array $r,string $unit):FixedPlacement{return new FixedPlacement($r['item_type'],$r['container_type'],self::point($r['position']??[],$unit),Rotation::from($r['orientation']),array_key_exists('container_instance',$r)?(int)JsonValue::integer($r['container_instance']):1,$r['placement_id']??null);} private static function container(array $r,string $unit):Container{$obs=[];foreach($r['obstacles']??[] as $o){$additional=array_map(function ($b) use ($unit) { return self::box($b,$unit); },$o['additional_boxes']??[]);$obs[]=new Obstacle((string)$o['id'],self::box($o,$unit),$additional);}return new Container((string)$r['id'],Dimensions::fromArray($r['inner_dimensions'],$unit),isset($r['outer_dimensions'])?Dimensions::fromArray($r['outer_dimensions'],$unit):null,Weight::parse($r['tare_weight']??0),isset($r['max_payload'])?Weight::parse($r['max_payload']):null,(int)($r['cost_minor']??0),isset($r['quantity'])?(int)$r['quantity']:null,$obs,$r['tags']??[],isset($r['max_items'])?(int)$r['max_items']:null,$r['metadata']??[],(float)($r['void_fill_reserve_ratio']??0),array_map(static function ($v) { return (int)$v; },$r['tag_limits']??[]),isset($r['max_stack_density'])?Weight::parse($r['max_stack_density']):null,self::axles($r['axles']??null,$unit),self::rateTable($r['rate_table']??null),array_map(static function ($d) { return (string)$d; - },$r['access_directions']??[]),[],isset($r['deformable_boundary'])?(string)$r['deformable_boundary']['kind']:null,self::madeToMeasure($r['made_to_measure']??null,$unit));} + },$r['access_directions']??[]),[],isset($r['deformable_boundary'])?(string)$r['deformable_boundary']['kind']:null,self::madeToMeasure($r['made_to_measure']??null,$unit),self::palletOverhangLimit($r['pallet_overhang_limit']??null,$unit),null,self::sideGussetDepth($r['deformable_boundary']??null,$unit));} + /** @param array|null $r */ + private static function sideGussetDepth(?array $r,string $unit):?Length{return ($r['side_gusset_depth']??null)===null?null:new Length(MeasureReading::ticks($r['side_gusset_depth'],Length::class,$unit));} + /** @param array|null $r */ + private static function palletOverhangLimit(?array $r,string $unit):?OverhangLimit{return $r===null?null:new OverhangLimit(new Length(MeasureReading::ticks($r['length'],Length::class,$unit)),new Length(MeasureReading::ticks($r['width'],Length::class,$unit)));} /** @param array|null $r */ private static function madeToMeasure(?array $r,string $unit):?MadeToMeasure { @@ -359,5 +412,5 @@ private static function madeToMeasure(?array $r,string $unit):?MadeToMeasure $tare=$r['tare_per_square_metre']??null; return new MadeToMeasure($sides($r['minimum']??null),$sides($r['increment']??null),(int)($r['cost_per_square_metre_minor']??0),$tare===null?0:MeasureReading::ticks($tare,Weight::class,'g'),$sides($r['outer_allowance']??null)); } - private static function rateTable(?array $r):?RateTable{if($r===null)return null;return new RateTable(array_map('intval',$r['weight_brackets_g']),array_map('intval',$r['prices_minor']),(int)($r['minimum_charge_minor']??0),(int)($r['fuel_surcharge_permille']??0));} + private static function rateTable(?array $r):?RateTable{if($r===null)return null;return new RateTable(array_map('intval',$r['weight_brackets_g']),array_map('intval',$r['prices_minor']),(int)($r['minimum_charge_minor']??0),(int)($r['fuel_surcharge_permille']??0),$r['currency']??null);} } diff --git a/src-legacy/Support/FixedPlacementShape.php b/src-legacy/Support/FixedPlacementShape.php index 837cd4c..ea6e28a 100644 --- a/src-legacy/Support/FixedPlacementShape.php +++ b/src-legacy/Support/FixedPlacementShape.php @@ -2,6 +2,8 @@ declare(strict_types=1); namespace Packvium\Support; +use Packvium\Domain\Placement; +use Packvium\Domain\Point; use Packvium\Unit\Length; use Packvium\Validation\FixedPlacementException; use stdClass; @@ -18,28 +20,29 @@ */ final class FixedPlacementShape { - public const ORIENTATIONS = ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']; private const REQUIRED = ['item_type', 'container_type', 'orientation']; - private const FIELDS = ['item_type', 'container_type', 'orientation', 'container_instance', 'position']; + private const FIELDS = ['item_type', 'container_type', 'orientation', 'container_instance', 'position', 'placement_id']; private const AXES = ['x', 'y', 'z']; /** * The entries as JSON gave them. O(f) for f entries; an absent list never reaches here. * * Entries arrive from `json_decode(..., true)`, where `{}` is the empty array, so an empty - * array stands for an empty object wherever an object is required. + * array stands for an empty object wherever an object is required. `$hullTypes` names the + * item types that are hulls, the only ones a signed orientation may fix (1.10). * * @param mixed $raw + * @param list $hullTypes * @return list> * @throws FixedPlacementException */ - public static function requireEntries($raw, string $unit = 'mm'): array + public static function requireEntries($raw, string $unit = 'mm', array $hullTypes = []): array { if (!JsonValue::isList($raw)) { throw self::malformed('fixed_placements is a list', '/fixed_placements'); } foreach ($raw as $index => $entry) { - self::requireEntry($entry === [] ? new stdClass() : $entry, "fixed_placements[{$index}]", "/fixed_placements/{$index}", $unit); + self::requireEntry($entry === [] ? new stdClass() : $entry, "fixed_placements[{$index}]", "/fixed_placements/{$index}", $unit, $hullTypes); } return $raw; } @@ -69,8 +72,49 @@ public static function requirePoint($point, string $where, string $field, callab } } - /** @param mixed $entry */ - private static function requireEntry($entry, string $where, string $field, string $unit): void + /** + * The ids of the requested item types that are `convex_hull`, read from JSON items as + * written; anything that is not an item object names no hull. O(items). + * + * @param mixed $items + * @return list + */ + public static function hullItemTypes($items): array + { + if (!JsonValue::isList($items)) { + return []; + } + $hulls = []; + foreach ($items as $item) { + if (JsonValue::isObject($item) && JsonValue::get($item, 'shape_type') === 'convex_hull' && \is_string(JsonValue::get($item, 'id'))) { + $hulls[] = JsonValue::get($item, 'id'); + } + } + return $hulls; + } + + /** + * A fixed orientation from its item's vocabulary (1.10): an unknown code is `malformed` with + * the vocabulary listed -- six codes for a box, byte-identical to every release before -- and + * a signed code fixing a non-hull is `invalid_value`. Whether the item allows it is + * `FixedPlacementAdmission`'s rule. O(1). + * + * @param mixed $value + * @throws FixedPlacementException + */ + public static function requireOrientation($value, bool $hull, string $where, string $field): void + { + $refusal = RequestRules::orientationRefusal($value, $hull, "{$where}.orientation"); + if ($refusal !== null) { + throw new FixedPlacementException($refusal[1], $refusal[0] === 'not_allowed' ? 'malformed' : $refusal[0], $field); + } + } + + /** + * @param mixed $entry + * @param list $hullTypes + */ + private static function requireEntry($entry, string $where, string $field, string $unit, array $hullTypes): void { if (!JsonValue::isObject($entry)) { throw self::malformed("{$where} is an object", $field); @@ -91,9 +135,7 @@ private static function requireEntry($entry, string $where, string $field, strin throw self::malformed("{$where}.{$name} is a non-empty string", "{$field}/{$name}"); } } - if (!\in_array(JsonValue::get($entry, 'orientation'), self::ORIENTATIONS, true)) { - throw self::malformed("{$where}.orientation must be one of " . CanonicalJson::spelling(self::ORIENTATIONS), "{$field}/orientation"); - } + self::requireOrientation(JsonValue::get($entry, 'orientation'), \in_array(JsonValue::get($entry, 'item_type'), $hullTypes, true), $where, "{$field}/orientation"); $instance = JsonValue::has($entry, 'container_instance') ? JsonValue::integer(JsonValue::get($entry, 'container_instance')) : 1; if ($instance === null || $instance < 1) { throw self::malformed("{$where}.container_instance counts from 1", "{$field}/container_instance"); @@ -109,6 +151,41 @@ static function (string $message, string $at): Throwable { self::requireCoordinate(JsonValue::get($position, $axis), "{$where}.position.{$axis}", "{$field}/position/{$axis}", $unit); } } + $ticks = \array_map(static function (string $axis) use ($position, $unit): int { + return JsonValue::has($position, $axis) ? MeasureReading::ticks(JsonValue::get($position, $axis), Length::class, $unit) : 0; + }, self::AXES); + self::requirePlacementId(JsonValue::get($entry, 'placement_id'), JsonValue::get($entry, 'container_type') . "#{$instance}", new Point(...$ticks), + JsonValue::get($entry, 'item_type'), JsonValue::get($entry, 'orientation'), $where, $field); + } + + /** + * A fixed placement's optional `placement_id` (1.10) restates the id its result placement + * will carry, the canonical JSON of `[#, x, y, z, + * , ]` with the position in ticks; null is absent. A non-string is + * `malformed`, like every other shape error here; a string naming another placement is + * `invalid_value`, the reason a well-typed value outside its rule carries. O(1). + * + * @param mixed $value + * @throws FixedPlacementException + */ + public static function requirePlacementId($value, string $containerId, Point $position, string $itemType, string $orientation, string $where, string $field): void + { + if ($value === null) { + return; + } + $at = "{$field}/placement_id"; + if (!\is_string($value)) { + throw self::malformed("{$where}.placement_id is a string", $at); + } + // A coordinate past 2^53 - 1 has no canonical spelling, and no container holds it: the + // admission check refuses such an entry as `outside_container`, so the id is not judged. + if (\max($position->x, $position->y, $position->z) > JsonValue::MAX_EXACT_MAGNITUDE) { + return; + } + $expected = Placement::identifier($containerId, $position, $itemType, $orientation); + if ($value !== $expected) { + throw new FixedPlacementException("{$where}.placement_id must be " . CanonicalJson::spelling($expected), 'invalid_value', $at); + } } /** diff --git a/src-legacy/Support/Internal/RareRequestRules.php b/src-legacy/Support/Internal/RareRequestRules.php index 49a1627..a32be6d 100644 --- a/src-legacy/Support/Internal/RareRequestRules.php +++ b/src-legacy/Support/Internal/RareRequestRules.php @@ -19,6 +19,8 @@ */ final class RareRequestRules { + /** The two axes `pallet_overhang_limit` requires, in the order they are checked. */ + private const PALLET_OVERHANG_FIELDS = ['length', 'width']; /** Every key the request schema's `made_to_measure` declares; it sets `additionalProperties: false`. */ private const MADE_TO_MEASURE_FIELDS = ['cost_per_square_metre_minor', 'increment', 'minimum', 'outer_allowance', 'tare_per_square_metre']; @@ -75,20 +77,48 @@ public static function madeToMeasure(\Closure $call, $container, $raw, string $w } /** - * The bag's own shape, then every container field a flat bag refuses, in the - * order of `BAG_EXCLUSIONS`. + * Both axes, each a non-negative length, and a solving frame `(L + 2l, W + 2w, H)` + * inside the admission ceiling every box is held to. Run after every other container field. + * O(1). * * @param stdClass|array $container * @param mixed $raw */ - public static function deformableBoundary(\Closure $call, $container, $raw, string $where): void + public static function palletOverhangLimit(\Closure $call, $container, $raw, string $where, string $unit): void + { + $field = "{$where}/pallet_overhang_limit"; + $limit = $call('objectAt', $raw, $field); + $call('knownFields', $limit, $field, self::PALLET_OVERHANG_FIELDS); + foreach (self::PALLET_OVERHANG_FIELDS as $axis) { + $call('measure', $call('required', $limit, $axis, $field), "{$field}/{$axis}", Length::class, $unit); + } + [$length, $width, $height] = $call('sideTicks', JsonValue::get($container, 'inner_dimensions'), $unit); + $overhangX = MeasureReading::ticks(JsonValue::get($limit, 'length'), Length::class, $unit); + $overhangY = MeasureReading::ticks(JsonValue::get($limit, 'width'), Length::class, $unit); + RequestRules::box([$length + 2 * $overhangX, $width + 2 * $overhangY, $height], $field); + } + + /** + * The bag's own shape top to bottom -- kind, unknown keys, a gusseted bag's side + * gusset (1.10) -- then every container field a bag refuses, in the order of + * `BAG_EXCLUSIONS`. O(1). + * + * @param stdClass|array $container + * @param mixed $raw + */ + public static function deformableBoundary(\Closure $call, $container, $raw, string $where, string $unit): void { $field = "{$where}/deformable_boundary"; $boundary = $call('objectAt', $raw, $field); - if (!\in_array($call('required', $boundary, 'kind', $field), FlatBag::KINDS, true)) { + $kind = $call('required', $boundary, 'kind', $field); + if (!\in_array($kind, FlatBag::KINDS, true)) { throw $call('refuse', 'not_allowed', "{$field}/kind", 'must be one of ' . CanonicalJson::spelling(FlatBag::KINDS)); } - $call('knownFields', $boundary, $field, ['kind']); + $gusseted = $kind === FlatBag::GUSSETED_BAG; + $call('knownFields', $boundary, $field, $gusseted ? ['kind', 'side_gusset_depth'] : ['kind']); + if ($gusseted) { + self::sideGussetDepth($call, $container, $call('required', $boundary, 'side_gusset_depth', $field), "{$field}/side_gusset_depth", $unit); + } foreach (RequestRules::BAG_EXCLUSIONS as $name) { if ($call('setBesideABag', $name, JsonValue::get($container, $name))) { throw $call('refuse', 'not_allowed', "{$where}/{$name}", 'cannot be combined with deformable_boundary'); @@ -96,8 +126,30 @@ public static function deformableBoundary(\Closure $call, $container, $raw, stri } } - /** @param mixed $raw */ - public static function rateTable(\Closure $call, $raw, string $where): void + /** + * A length, positive once read in ticks, and no deeper than the bag's inner width. + * + * @param stdClass|array $container + * @param mixed $value + */ + private static function sideGussetDepth(\Closure $call, $container, $value, string $field, string $unit): void + { + $call('measure', $value, $field, Length::class, $unit); + $depth = MeasureReading::ticks($value, Length::class, $unit); + if ($depth === 0) { + throw $call('refuse', 'invalid_value', $field, 'must be positive'); + } + if ($depth > $call('sideTicks', JsonValue::get($container, 'inner_dimensions'), $unit)[1]) { + throw $call('refuse', 'invalid_value', $field, 'exceeds inner_dimensions width'); + } + } + + /** + * The table's integers, then its currency against the request's (1.10). + * + * @param mixed $raw + */ + public static function rateTable(\Closure $call, $raw, string $where, ?string $currency): void { $table = $call('objectAt', $raw, $where); foreach (['weight_brackets_g' => 1, 'prices_minor' => 0] as $name => $minimum) { @@ -111,6 +163,10 @@ public static function rateTable(\Closure $call, $raw, string $where): void } $call('optionalInteger', $table, 'minimum_charge_minor', $where, 0); $call('optionalInteger', $table, 'fuel_surcharge_permille', $where, 0); + $code = JsonValue::get($table, 'currency'); + if ($code !== null) { + RequestRules::rateTableCurrency($code, "{$where}/currency", $currency); + } } /** @param mixed $raw @param array{0:int,1:int,2:int} $inner */ diff --git a/src-legacy/Support/PrettyJsonStream.php b/src-legacy/Support/PrettyJsonStream.php index f2fc266..af9b34f 100644 --- a/src-legacy/Support/PrettyJsonStream.php +++ b/src-legacy/Support/PrettyJsonStream.php @@ -18,7 +18,10 @@ * pretty encoding with `4 * d` spaces after every newline, and an encoded string never * contains a raw newline. Arrays follow `json_encode`'s rule, the one in {@see JsonValue}: * a list is a JSON array, any other array a JSON object whose names are its keys as strings. - * An empty array, and anything that is not an array, is encoded whole. + * An empty array, and anything that is not an array, is encoded whole. A `\Traversable` is + * written as the JSON list of its values, one at a time, so a caller can hand over values it + * has not built yet (`ArrayCodec::packStreamed`'s placements); an array holding one is never + * encoded whole. * * One difference, on a path no answer takes: a value `json_encode` cannot encode throws * `JsonException` after the members before it were written, where the one-shot encoding @@ -63,7 +66,11 @@ public static function write($value, $stream): void /** @param mixed $value */ private function value($value, int $depth): void { - if (!\is_array($value) || \count($value, \COUNT_RECURSIVE) <= self::WHOLE_ELEMENTS) { + if ($value instanceof \Traversable) { + $this->traversed($value, $depth); + return; + } + if (!\is_array($value) || (\count($value, \COUNT_RECURSIVE) <= self::WHOLE_ELEMENTS && !self::holdsTraversable($value))) { $this->append(self::encoded($value, $depth)); return; } @@ -82,6 +89,41 @@ private function value($value, int $depth): void $this->append("\n" . \str_repeat(self::INDENT, $depth) . ($list ? ']' : '}')); } + /** + * A one-pass sequence, written as the JSON list of its values: `[]` when it yields none, + * as `json_encode` writes an empty list. + * + * @param \Traversable $values + */ + private function traversed(\Traversable $values, int $depth): void + { + $separator = "\n" . \str_repeat(self::INDENT, $depth + 1); + $first = true; + foreach ($values as $member) { + $this->append(($first ? '[' : ',') . $separator); + $first = false; + $this->value($member, $depth + 1); + } + $this->append($first ? '[]' : "\n" . \str_repeat(self::INDENT, $depth) . ']'); + } + + /** + * Whether a sequence sits anywhere inside a small array, which then cannot be encoded + * whole: `json_encode` writes an object it cannot see into as `{}`. Asked only of an + * array of at most {@see self::WHOLE_ELEMENTS} elements, so O(1). + * + * @param array $value + */ + private static function holdsTraversable(array $value): bool + { + foreach ($value as $member) { + if ($member instanceof \Traversable || (\is_array($member) && self::holdsTraversable($member))) { + return true; + } + } + return false; + } + /** @param mixed $value */ private static function encoded($value, int $depth): string { diff --git a/src-legacy/Support/RationalParser.php b/src-legacy/Support/RationalParser.php index 545dd49..43c8cf3 100644 --- a/src-legacy/Support/RationalParser.php +++ b/src-legacy/Support/RationalParser.php @@ -23,7 +23,9 @@ public static function parse($value): array $negative = strncmp($text, '-', strlen('-')) === 0; if (preg_match('/^([+-]?\d+)\s+(\d+)\s*\/\s*(\d+)$/', $text, $m)) { $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)) { + // `abs(PHP_INT_MIN)` is a float that compares equal to PHP_INT_MAX, so it would slip + // past the range check and fail later as a type error rather than an overflow. + if ($whole === PHP_INT_MIN || ($whole !== 0 && abs($whole) > intdiv(PHP_INT_MAX - $n, $d))) { throw new InvalidArgumentException('Scaled unit value exceeds integer range'); } $magnitude = abs($whole) * $d + $n; diff --git a/src-legacy/Support/RequestObjects.php b/src-legacy/Support/RequestObjects.php index e8ae4aa..fcd9f64 100644 --- a/src-legacy/Support/RequestObjects.php +++ b/src-legacy/Support/RequestObjects.php @@ -8,7 +8,9 @@ use Packvium\Domain\FixedPlacement; use Packvium\Domain\Item; use Packvium\Domain\MadeToMeasure; +use Packvium\Domain\OverhangLimit; use Packvium\Domain\RateTable; +use Packvium\Domain\ShapeType; use Packvium\Serialization\InvalidRequestException; use Packvium\Validation\FixedPlacementException; @@ -18,7 +20,7 @@ * Held to `packvium.request_objects.check_objects`. `RequestRules::check` walks a JSON * request; `Packer::pack` takes objects, whose own constructors already refuse most of the * same values but cannot know where in a request they will sit. This walks the objects in the - * JSON rules' order -- configuration, items, item ids, containers, container ids, fixed + * JSON rules' order -- currency, configuration, items, item ids, containers, container ids, fixed * placements -- with the same primitives, so a value the JSON path refuses is refused here with the same reason and * the same RFC 6901 field. Only rules `RequestRules::check` also applies are checked, so on * the JSON path, which runs that first, this never refuses anything. @@ -51,8 +53,11 @@ final class RequestObjects * @param list $fixedPlacements * @throws InvalidRequestException */ - public static function check(array $items, array $containers, PackingConfig $config, array $fixedPlacements = []): void + public static function check(array $items, array $containers, PackingConfig $config, array $fixedPlacements = [], ?string $currency = null): void { + if ($currency !== null) { + RequestRules::currencyCode($currency, '/currency'); + } self::configuration($config); foreach ($items as $index => $item) { self::item($item, "/items/{$index}"); @@ -61,11 +66,12 @@ public static function check(array $items, array $containers, PackingConfig $con return $item->id; }, $items), 'items'); foreach ($containers as $index => $container) { - self::container($container, "/containers/{$index}"); + self::container($container, "/containers/{$index}", $currency); } RequestRules::requireUniqueIds(\array_map(static function (Container $container): string { return $container->id; }, $containers), 'containers'); + self::routesBesidePallets($items, $containers); RequestRules::totalWeight( \array_map(static function (Item $item): array { return [$item->weight->ticks, $item->quantity]; @@ -74,8 +80,35 @@ public static function check(array $items, array $containers, PackingConfig $con return $container->tareWeight->ticks; }, $containers), ); + $hullTypes = \array_values(\array_map(static function (Item $item): string { + return $item->id; + }, + \array_filter($items, static function (Item $item): bool { + return $item->shapeType === ShapeType::CONVEX_HULL; + }))); foreach ($fixedPlacements as $index => $placement) { - self::fixedPlacement($placement, "fixed_placements[{$index}]", "/fixed_placements/{$index}"); + self::fixedPlacement($placement, "fixed_placements[{$index}]", "/fixed_placements/{$index}", $hullTypes); + } + } + + /** + * A routed item beside a pallet that allows overhang: the JSON path refuses it as + * `container.pallet_overhang_limit+item.stop_index`, this one at the first routed item. + * + * @param list $items @param list $containers + */ + private static function routesBesidePallets(array $items, array $containers): void + { + $pallets = \array_filter($containers, static function (Container $container): bool { + return $container->palletOverhangLimit !== null; + }); + if ($pallets === []) { + return; + } + foreach ($items as $index => $item) { + if ($item->stopIndex !== null) { + throw new InvalidRequestException('not_allowed', "/items/{$index}/stop_index", 'cannot be combined with pallet_overhang_limit'); + } } } @@ -83,18 +116,23 @@ public static function check(array $items, array $containers, PackingConfig $con * `FixedPlacementShape`'s rules that an object can break, in its order and with its refusal; * the types hold the orientation and the position, and `Point` refuses a negative * coordinate. Whether the set can hold is `FixedPlacementAdmission`'s to say. + * + * @param list $hullTypes the item types a signed orientation may fix (1.10) */ - private static function fixedPlacement(FixedPlacement $placement, string $where, string $field): void + private static function fixedPlacement(FixedPlacement $placement, string $where, string $field, array $hullTypes): void { foreach (['item_type' => $placement->itemId, 'container_type' => $placement->containerId] as $name => $value) { if ($value === '') { throw new FixedPlacementException("{$where}.{$name} is a non-empty string", 'malformed', "{$field}/{$name}"); } } + FixedPlacementShape::requireOrientation($placement->rotation, \in_array($placement->itemId, $hullTypes, true), $where, "{$field}/orientation"); $instance = JsonValue::integer($placement->containerInstance); if ($instance === null || $instance < 1) { throw new FixedPlacementException("{$where}.container_instance counts from 1", 'malformed', "{$field}/container_instance"); } + FixedPlacementShape::requirePlacementId($placement->placementId, $placement->packedContainerId(), $placement->position, + $placement->itemId, $placement->rotation, $where, $field); } /** @@ -140,7 +178,7 @@ private static function item(Item $item, string $where): void } } - private static function container(Container $container, string $where): void + private static function container(Container $container, string $where, ?string $currency): void { self::optionalInteger($container->quantity, "{$where}/quantity", 1); RequestRules::box(self::sides($container->innerDimensions), "{$where}/inner_dimensions"); @@ -152,7 +190,7 @@ private static function container(Container $container, string $where): void RequestRules::ratio($container->voidFillReserveRatio, "{$where}/void_fill_reserve_ratio", 1); self::tagLimits($container->tagLimits, "{$where}/tag_limits"); if ($container->rateTable !== null) { - self::rateTable($container->rateTable, "{$where}/rate_table"); + self::rateTable($container->rateTable, "{$where}/rate_table", $currency); } if ($container->deformableBoundary !== null) { self::flatBag($container, $where); @@ -160,6 +198,19 @@ private static function container(Container $container, string $where): void if ($container->madeToMeasure !== null) { self::madeToMeasure($container, $container->madeToMeasure, $where); } + if ($container->palletOverhangLimit !== null) { + self::palletOverhangLimit($container, $container->palletOverhangLimit, $where); + } + } + + /**: each axis, then the solving frame, against the admission ceiling. O(1). */ + private static function palletOverhangLimit(Container $container, OverhangLimit $limit, string $where): void + { + $field = "{$where}/pallet_overhang_limit"; + RequestRules::lengthTicks($limit->length->ticks, "{$field}/length"); + RequestRules::lengthTicks($limit->width->ticks, "{$field}/width"); + [$length, $width, $height] = self::sides($container->innerDimensions); + RequestRules::box([$length + 2 * $limit->length->ticks, $width + 2 * $limit->width->ticks, $height], $field); } /** @@ -177,7 +228,7 @@ private static function tagLimits(array $limits, string $where): void } } - private static function rateTable(RateTable $table, string $where): void + private static function rateTable(RateTable $table, string $where, ?string $currency): void { foreach (['weight_brackets_g' => [$table->weightBracketsG, 1], 'prices_minor' => [$table->pricesMinor, 0]] as $name => [$values, $minimum]) { foreach ($values as $index => $value) { @@ -186,6 +237,9 @@ private static function rateTable(RateTable $table, string $where): void } RequestRules::integer($table->minimumChargeMinor, "{$where}/minimum_charge_minor", 0); RequestRules::integer($table->fuelSurchargePermille, "{$where}/fuel_surcharge_permille", 0); + if ($table->currency !== null) { + RequestRules::rateTableCurrency($table->currency, "{$where}/currency", $currency); + } } /** @@ -200,7 +254,7 @@ private static function flatBag(Container $container, string $where): void 'obstacles' => $container->obstacles, 'axles' => $container->axles, 'access_directions' => $container->accessDirections, 'max_stack_density' => $container->maxStackDensity, 'outer_dimensions' => $container->outerDimensions, 'void_fill_reserve_ratio' => $container->voidFillReserveRatio, - 'made_to_measure' => $container->madeToMeasure, + 'made_to_measure' => $container->madeToMeasure, 'pallet_overhang_limit' => $container->palletOverhangLimit, ]; foreach (RequestRules::BAG_EXCLUSIONS as $name) { $value = $fields[$name] === [] ? null : $fields[$name]; diff --git a/src-legacy/Support/RequestRules.php b/src-legacy/Support/RequestRules.php index 16ae75d..32b906f 100644 --- a/src-legacy/Support/RequestRules.php +++ b/src-legacy/Support/RequestRules.php @@ -4,6 +4,7 @@ use Packvium\Domain\FlatBag; use Packvium\Domain\MadeToMeasure; +use Packvium\Domain\Orientations; use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\Length; use Packvium\Unit\Weight; @@ -14,7 +15,7 @@ * The request schema's rules, walked over the decoded JSON before any model is built. * * Held to `packvium.request_errors.check_request`: the first violation wins, in the order every - * engine follows -- units, output, configuration, items, containers -- and is refused with the same + * engine follows -- units, output, currency, configuration, items, containers -- and is refused with the same * reason, JSON Pointer and message the reference raises. * * The request arrives from `json_decode(..., true)`, where `{}` and `[]` are the same empty @@ -28,7 +29,6 @@ final class RequestRules public const ACCESS_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; /** The schema's closed vocabularies, each refused as `not_allowed` like the two above. */ public const SOLVERS = ['grid', 'extreme_points', 'homogeneous_blocks', 'layer', 'maximal_spaces', 'exact_small']; - public const ROTATIONS = ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']; public const LENGTH_UNITS = ['mm', 'cm', 'm', 'in', 'ft']; public const WEIGHT_UNITS = ['mg', 'g', 'kg', 'oz', 'lb']; public const GROUND_CONTACT_RULES = ['free', 'covered', 'single', 'multiple']; @@ -54,7 +54,7 @@ final class RequestRules private const ITEM_BOOLEANS = ['keep_upright', 'stackable', 'must_be_on_floor']; /** Container fields a flat bag refuses, in reporting order (docs/DEFORMABLE-CONTAINERS.md). */ public const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', - 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure']; + 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure', 'pallet_overhang_limit']; public const WEIGHT_UNIT = 'g'; /** * The admission ceiling every engine refuses past: a length is a tick count @@ -80,6 +80,7 @@ public static function check($data): void $request = self::objectAt($data, ''); $unit = self::units(JsonValue::get($request, 'units')); self::output(JsonValue::get($request, 'output')); + $currency = self::requestCurrency(JsonValue::get($request, 'currency')); self::configuration(JsonValue::get($request, 'configuration'), $unit); $items = self::requiredList($request, 'items', ''); foreach ($items as $index => $raw) { @@ -88,7 +89,7 @@ public static function check($data): void self::requireUniqueIds(self::identifiers($items), 'items'); $containers = self::requiredList($request, 'containers', ''); foreach ($containers as $index => $raw) { - self::container($raw, "/containers/{$index}", $unit); + self::container($raw, "/containers/{$index}", $unit, $currency); } self::requireUniqueIds(self::identifiers($containers), 'containers'); self::totalWeight(\array_map( @@ -140,7 +141,10 @@ private static function units($raw): string if ($raw === null) { return 'mm'; } - $length = JsonValue::get(self::objectAt($raw, '/units'), 'length'); + $units = self::objectAt($raw, '/units'); + // `{"length": "cm", "weight": "kg"}` used to read every bare weight as grams. + self::knownFields($units, '/units', ['length']); + $length = JsonValue::get($units, 'length'); if ($length === null) { return 'mm'; } @@ -236,12 +240,67 @@ private static function item($raw, string $where, string $unit): void self::stackingGroupName($name, "{$where}/accepts_stacking_groups/{$index}"); } } - self::optionalEachOneOf($item, 'allowed_rotations', $where, self::ROTATIONS); + self::optionalAllowedRotations($item, $where); self::optionalOneOf($item, 'ground_contact_rule', $where, self::GROUND_CONTACT_RULES); self::optionalOneOf($item, 'shape_type', $where, self::SHAPE_TYPES); foreach (self::ITEM_BOOLEANS as $name) { self::optionalBoolean($item, $name, $where); } + $listed = JsonValue::get($item, 'allowed_rotations'); + if ($listed !== null) { + $upright = JsonValue::get($item, 'keep_upright') === true; + foreach ($listed as $code) { + if (!$upright || \in_array($code, Orientations::UPRIGHT_CODES, true)) { + return; + } + } + throw self::refuse('invalid_value', "{$where}/allowed_rotations", 'must allow at least one rotation after keep_upright'); + } + } + + /** + * Each code from the item's vocabulary (1.10): all 24 for a hull, the six legacy codes for + * anything else, where a signed code is a rule broken rather than an unknown word. The shape + * is read as written, so a shape no engine knows is not a hull. O(len(list)). + * + * @param stdClass|array $item + */ + private static function optionalAllowedRotations($item, string $where): void + { + $value = JsonValue::get($item, 'allowed_rotations'); + if ($value === null) { + return; + } + $hull = JsonValue::get($item, 'shape_type') === 'convex_hull'; + foreach (self::listAt($value, "{$where}/allowed_rotations") as $index => $code) { + $refusal = self::orientationRefusal($code, $hull); + if ($refusal !== null) { + throw self::refuse($refusal[0], "{$where}/allowed_rotations/{$index}", $refusal[1]); + } + } + } + + /** + * Why `$value` cannot orient an item of this shape, as `[reason, detail]`, or null when it + * can (`Orientations::refusalReason`). `$where` names the value inside the detail, the way a + * fixed placement or a revision event words its own refusals. Shared by every field that + * names a requested item's orientation. O(1). + * + * @param mixed $value + * @return array{0:string,1:string}|null + */ + public static function orientationRefusal($value, bool $hull, string $where = ''): ?array + { + $reason = Orientations::refusalReason($value, $hull); + if ($reason === null) { + return null; + } + if ($reason === 'invalid_value') { + $signed = Orientations::SIGNED_CODE_NEEDS_A_HULL; + return [$reason, $where === '' ? $signed : "{$where}: {$signed}"]; + } + $rule = 'must be one of ' . CanonicalJson::spelling(Orientations::vocabulary($hull)); + return [$reason, $where === '' ? $rule : "{$where} {$rule}"]; } /** @param mixed $value */ @@ -255,8 +314,58 @@ public static function stackingGroupName($value, string $field): void } } + /** + * The request's `currency`, absent when null, or refused. O(1). + * + * @param mixed $raw + */ + private static function requestCurrency($raw): ?string + { + if ($raw === null) { + return null; + } + self::currencyCode($raw, '/currency'); + return (string) $raw; + } + + /** + * An ISO 4217 shape, `^[A-Z]{3}$`, with no code list: the engines never convert, so a code + * they do not know is still one they can echo (docs/SERIALIZATION.md). ASCII letters only, + * and `\z` rather than `$`, which would let a trailing newline through. Shared with + * `RequestObjects`. O(1). + * + * @param mixed $value + */ + public static function currencyCode($value, string $field): void + { + if (!\is_string($value)) { + throw self::refuse('wrong_type', $field, 'must be a string'); + } + if (\preg_match('/\A[A-Z]{3}\z/', $value) !== 1) { + throw self::refuse('invalid_value', $field, 'must be three capital letters (ISO 4217)'); + } + } + + /** + * A rate table prices in the request's currency or says nothing: a table in another one + * would be ranked as though its minor units were the request's. Shared with + * `RequestObjects`. O(1). + * + * @param mixed $value + */ + public static function rateTableCurrency($value, string $field, ?string $currency): void + { + self::currencyCode($value, $field); + if ($currency === null) { + throw self::refuse('missing_field', '/currency', 'is required when a rate_table declares a currency'); + } + if ($value !== $currency) { + throw self::refuse('not_allowed', $field, 'must equal the request currency ' . CanonicalJson::spelling($currency)); + } + } + /** @param mixed $raw */ - private static function container($raw, string $where, string $unit): void + private static function container($raw, string $where, string $unit, ?string $currency): void { $container = self::objectAt($raw, $where); self::requiredString($container, 'id', $where); @@ -282,7 +391,7 @@ private static function container($raw, string $where, string $unit): void } $rateTable = JsonValue::get($container, 'rate_table'); if ($rateTable !== null) { - RareRequestRules::rateTable(self::bridge(), $rateTable, "{$where}/rate_table"); + RareRequestRules::rateTable(self::bridge(), $rateTable, "{$where}/rate_table", $currency); } $obstacles = JsonValue::get($container, 'obstacles'); if ($obstacles !== null) { @@ -290,12 +399,16 @@ private static function container($raw, string $where, string $unit): void } $boundary = JsonValue::get($container, 'deformable_boundary'); if ($boundary !== null) { - RareRequestRules::deformableBoundary(self::bridge(), $container, $boundary, $where); + RareRequestRules::deformableBoundary(self::bridge(), $container, $boundary, $where, $unit); } $machine = JsonValue::get($container, 'made_to_measure'); if ($machine !== null) { RareRequestRules::madeToMeasure(self::bridge(), $container, $machine, $where, $unit); } + $limit = JsonValue::get($container, 'pallet_overhang_limit'); + if ($limit !== null) { + RareRequestRules::palletOverhangLimit(self::bridge(), $container, $limit, $where, $unit); + } } /** diff --git a/src-legacy/Support/ResultValidation/Accounting.php b/src-legacy/Support/ResultValidation/Accounting.php index a94048f..4459d5a 100644 --- a/src-legacy/Support/ResultValidation/Accounting.php +++ b/src-legacy/Support/ResultValidation/Accounting.php @@ -150,7 +150,7 @@ public static function fitsEmpty(ContainerSpec $container, array $size): bool } return !$container->flatBag || (Exact::compare(Exact::add($size[0], $size[2]), $container->inner[0]) <= 0 - && Exact::compare(Exact::add($size[1], $size[2]), $container->inner[1]) <= 0); + && Exact::compare(Exact::add($size[1], $size[2]), Exact::add($container->inner[1], $container->sideGusset)) <= 0); } /** @@ -218,7 +218,7 @@ private static function checkReasonProof($unpacked, ?ItemSpec $spec, Context $co /** @param mixed $unpacked @param mixed $reason @param list $issues */ private static function checkProvenReason($unpacked, $reason, ItemSpec $spec, Context $context, string $itemId, array &$issues): void { - $every = \array_keys(Geometry::ROTATIONS); + $every = Geometry::BOX_ROTATIONS; if (Json::isText($reason, 'no_compatible_container_dimensions')) { if (self::fitsSome($spec, $context, $spec->allowedRotations)) { $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: at least one allowed orientation fits a container"); diff --git a/src-legacy/Support/ResultValidation/Bound.php b/src-legacy/Support/ResultValidation/Bound.php index f5dc74f..0ad119d 100644 --- a/src-legacy/Support/ResultValidation/Bound.php +++ b/src-legacy/Support/ResultValidation/Bound.php @@ -16,8 +16,17 @@ */ final class Bound { - /** Where each covered objective reads `(L0, L1, L2, L3, L4)` in its own score order. */ - private const ORDERS = ['default' => [0, 1, 2, 3, 4], 'lowest_cost' => [0, 2, 1, 3, 4]]; + /** + * Where each covered objective reads `(L0, L1, L2, L3, L4)` in its own score order, a name + * standing for the one key only that objective ranks by. + */ + private const ORDERS = [ + 'default' => [0, 1, 2, 3, 4], + 'lowest_cost' => [0, 2, 1, 3, 4], + 'maximum_value' => [0, 'value_forgone', 1, 2, 3], + 'open_dimension_height' => [0, 'achieved_height', 1, 2, 3], + 'maximum_volume' => ['unpacked_volume_ppm', 0, 1, 2, 3], + ]; private const MAX_BOUND_SUM = '1000000000000000000000000000000'; private const MAX_BOUND_VALUE = 9007199254740991; private const SCORE_SCALE = 1000000; @@ -148,28 +157,82 @@ private static function stated($request, $status, Ordered $items, Ordered $conta if (Json::isText($status, 'invalid_result')) { return [null, "status is 'invalid_result'"]; } - [$volumes, $weights, $shrinks, $types] = self::inputs($items, $containers); - $bound = self::lowerBound($volumes, $weights, $shrinks, $types); + [$volumes, $weights, $values, $shrinks, $types] = self::inputs($items, $containers); + return self::objectiveBound($volumes, $weights, $values, $shrinks, $types, $name); + } + + /** + * The bound in a covered objective's score order, or null with the reason a ceiling withholds + * it -- the one predicate's, or the objective's own key's, which withholds that objective + * alone. Public so the shared scene can hold every objective's vector to the oracle. + * + * @param list $volumes value runs sorted ascending + * @param list $weights @param list $values + * @param list> $containers + * @return array{0:list|null,1:string} + */ + public static function objectiveBound(array $volumes, array $weights, array $values, bool $shrinks, array $containers, string $objective): array + { + $bound = self::lowerBound($volumes, $weights, $shrinks, $containers); if ($bound === null) { return [null, 'the request is past a declared ceiling']; } - return [\array_map(static function (int $position) use ($bound) { return $bound[$position]; }, self::ORDERS[$name]), '']; + $stated = \array_map(static function ($position) use ($bound, $volumes, $values, $shrinks, $containers) { + return \is_int($position) ? $bound[$position] : self::objectiveTerm($position, $volumes, $values, $shrinks, $containers, $bound[0]); + }, self::ORDERS[$objective]); + foreach ($stated as $value) { + if (Exact::compare($value, self::MAX_BOUND_VALUE) > 0) { + return [null, "the {$objective} key is past the portable ceiling"]; + } + } + return [$stated, '']; + } + + /** + * The key only one objective ranks by, each conditional on `L0` like the five: the + * least value forgone and the least summed top of a packing leaving `unpacked` behind, and + * the least unpacked share of requested volume any packing scores. O(t log t + c). + * + * @param list $volumes @param list $values + * @param list> $containers @param int|string $unpacked @return int|string + */ + private static function objectiveTerm(string $name, array $volumes, array $values, bool $shrinks, array $containers, $unpacked) + { + if ($name === 'value_forgone') { + return self::smallest($values, $unpacked); + } + if ($shrinks) { + return 0; + } + if ($name === 'achieved_height') { + $placed = Exact::sub(self::runCount($volumes), $unpacked); + $floors = self::positive(self::column($containers, 'base_area')); + return Exact::sign($placed) > 0 && $floors !== [] ? Exact::ceilDiv(self::smallest($volumes, $placed), self::largest($floors)) : 0; + } + $requested = self::sumRuns($volumes); + $capacity = self::capacityTotal(self::column($containers, 'usable'), self::column($containers, 'quantity')); + if (Exact::sign($requested) === 0 || $capacity === null) { + return 0; + } + return Exact::ceilDiv(Exact::mul(Exact::max(0, Exact::sub($requested, $capacity)), self::SCORE_SCALE), $requested); } /** * The request as the bound reads it: every instance, fixed ones included, and every type. * - * @param Ordered $items @param Ordered $containers @return array{0:list,1:list,2:bool,3:list>} + * @param Ordered $items @param Ordered $containers @return array{0:list,1:list,2:list,3:bool,4:list>} */ private static function inputs(Ordered $items, Ordered $containers): array { $volumes = []; $weights = []; + $values = []; $shrinks = false; foreach ($items->values() as $spec) { $quantity = Json::int($spec->quantity, 'quantity'); $volumes[] = [Exact::mul(Exact::mul($spec->dimensions[0], $spec->dimensions[1]), $spec->dimensions[2]), $quantity]; $weights[] = [$spec->weight, $quantity]; + $values[] = [Json::truthy($spec->value) ? Json::int($spec->value, 'value') : 0, $quantity]; $shrinks = $shrinks || ($quantity > 0 && ($spec->nestingHeight !== null || Json::isText($spec->shapeType, 'convex_hull') || Json::isText($spec->shapeType, 'compressible'))); } @@ -192,7 +255,7 @@ private static function inputs(Ordered $items, Ordered $containers): array 'quantity' => $spec->quantity, ]; } - return [self::runs($volumes), self::runs($weights), $shrinks, $types]; + return [self::runs($volumes), self::runs($weights), self::runs($values), $shrinks, $types]; } /** @param list> $containers @return list */ diff --git a/src-legacy/Support/ResultValidation/ContainerCheck.php b/src-legacy/Support/ResultValidation/ContainerCheck.php index 4f3658c..389162d 100644 --- a/src-legacy/Support/ResultValidation/ContainerCheck.php +++ b/src-legacy/Support/ResultValidation/ContainerCheck.php @@ -54,6 +54,45 @@ public static function achievedExtent($packed, $clearance): array return $extent ?? [0, 0, 0]; } + /** + * The deck grown by the overhang the placements use past each of its edges. + * + * @param mixed $packed @param array{0:int|string,1:int|string,2:int|string,3:int|string} $deck @param int|string $clearance + * @return array{0:int|string,1:int|string} + */ + public static function palletFootprint($packed, array $deck, $clearance): array + { + [$x, $y, $length, $width] = $deck; + [$lowX, $lowY, $highX, $highY] = [$x, $y, Exact::add($x, $length), Exact::add($y, $width)]; + foreach (Json::items(Json::at($packed, 'placements'), 'placements') as $placement) { + $box = self::envelope($placement, $clearance); + $lowX = Exact::compare($box->x, $lowX) < 0 ? $box->x : $lowX; + $lowY = Exact::compare($box->y, $lowY) < 0 ? $box->y : $lowY; + $highX = Exact::max($highX, $box->x2); + $highY = Exact::max($highY, $box->y2); + } + return [Exact::sub($highX, $lowX), Exact::sub($highY, $lowY)]; + } + + /** + * What a carrier measures: a bag's package; a pallet's declared footprint or its + * grown deck, the larger per axis; else the declared outer, else inner size. + * + * @param mixed $packed @param int|string $clearance @return array{0:int|string,1:int|string,2:int|string} + */ + public static function billedSize($packed, ContainerSpec $spec, $clearance): array + { + if ($spec->flatBag) { + return self::achievedExtent($packed, $clearance); + } + if ($spec->deck === null) { + return $spec->outer ?? $spec->inner; + } + [$length, $width] = self::palletFootprint($packed, $spec->deck, $clearance); + $base = $spec->outer ?? [$spec->deck[2], $spec->deck[3], $spec->inner[2]]; + return [Exact::max($base[0], $length), Exact::max($base[1], $width), $base[2]]; + } + /** * `achieved_dimensions` is present exactly when the container declares a soft size, and equals * the tight extent; a flat bag's extent must pass the girth rule. @@ -72,6 +111,9 @@ public static function checkAchievedExtent($packed, ContainerSpec $spec, $cleara return; } [$a, $b, $c] = self::achievedExtent($packed, $clearance); + if ($spec->deck !== null) { + [$a, $b] = self::palletFootprint($packed, $spec->deck, $clearance); + } $stated = null; if (Json::isDict($reported)) { $stated = []; @@ -82,8 +124,9 @@ public static function checkAchievedExtent($packed, ContainerSpec $spec, $cleara if (!self::matches($stated, [$a, $b, $c])) { $issues[] = new ResultIssue('achieved_dimensions_mismatch', "{$packedId}: reported " . self::optionalTuple($stated) . ', computed ' . PyFormat::intTuple([$a, $b, $c])); } - if ($spec->flatBag && (Exact::compare(Exact::add($a, $c), $spec->inner[0]) > 0 || Exact::compare(Exact::add($b, $c), $spec->inner[1]) > 0)) { - $issues[] = new ResultIssue('bag_girth_exceeded', "{$packedId}: a + c = " . Exact::add($a, $c) . ', b + c = ' . Exact::add($b, $c) . ", flat size {$spec->inner[0]} x {$spec->inner[1]}"); + if ($spec->flatBag && (Exact::compare(Exact::add($a, $c), $spec->inner[0]) > 0 || Exact::compare(Exact::add($b, $c), Exact::add($spec->inner[1], $spec->sideGusset)) > 0)) { + $gusset = Exact::sign($spec->sideGusset) === 0 ? '' : ", side gusset {$spec->sideGusset}"; + $issues[] = new ResultIssue('bag_girth_exceeded', "{$packedId}: a + c = " . Exact::add($a, $c) . ', b + c = ' . Exact::add($b, $c) . ", flat size {$spec->inner[0]} x {$spec->inner[1]}{$gusset}"); } $packedId->verify(); } @@ -128,6 +171,36 @@ private static function nestedTicks($block, string $key) return Json::truthy($value) ? Json::get($value, 'ticks') : null; } + /** + * Whether a reported box larger than the tight cut is a reserve cut: the tight box + * breaks the void-fill reserve, and the reported one is on the machine grid between the tight + * box and the maximum. That it keeps the reserve is the ordinary reserve check's. Reads the + * reported used volume, which `used_volume_mismatch` holds to the placements. O(1). + * + * @param mixed $packed @param array{0:int|string,1:int|string,2:int|string} $tight @param list|null $reported + */ + private static function reserveCut($packed, ContainerSpec $spec, MachineSpec $machine, array $tight, ?array $reported): bool + { + if ($spec->voidFillReserveRatio->compareInt(0) === 0 || $reported === null) { + return false; + } + foreach ($reported as $axis => $side) { + if (!\is_int($side) || Exact::compare($tight[$axis], $side) > 0 || Exact::compare($side, $spec->inner[$axis]) > 0 + || Exact::sign(Exact::mod(Exact::sub($side, $machine->minimum[$axis]), $machine->increment[$axis])) !== 0) { + return false; + } + } + $used = Json::get($packed, 'used_volume_ticks3'); + if (!\is_string($used) || \preg_match('/^[0-9]+$/', $used) !== 1) { + return false; + } + $volume = Exact::mul(Exact::mul($tight[0], $tight[1]), $tight[2]); + $scaled = self::ratioPpm($spec->voidFillReserveRatio); + $reserved = Exact::add(Exact::mul(Exact::floorDiv($volume, self::SCORE_SCALE), $scaled), + Exact::floorDiv(Exact::mul(Exact::mod($volume, self::SCORE_SCALE), $scaled), self::SCORE_SCALE)); + return Exact::compare(Exact::normalize(\ltrim($used, '0') ?: '0'), Exact::sub($volume, $reserved)) > 0; + } + /** * Recompute a made-to-measure container's box from its placements alone and return the spec * every later check uses: the recomputed box, never the reported one. @@ -167,6 +240,10 @@ public static function checkMadeToMeasure($packed, bool $compact, ContainerSpec } } $reportedInner = self::reportedTicks(Json::get($packed, 'inner_dimensions')); + if (!self::matches($reportedInner, $fabricated) && self::reserveCut($packed, $spec, $machine, $fabricated, $reportedInner)) { + /** @var array{0:int,1:int,2:int} $reportedInner reserveCut admits integer sides alone */ + $fabricated = $reportedInner; + } if (!self::matches($reportedInner, $fabricated)) { $issues[] = new ResultIssue('fabricated_dimensions_mismatch', "{$containerId}: reported " . self::optionalTuple($reportedInner) . ', computed ' . PyFormat::intTuple($fabricated)); } @@ -262,6 +339,9 @@ public static function check($packed, ContainerSpec $spec, Ordered $items, $clea self::checkPairs($entries, $packedId, $issues); [$supporters, $directAbove] = Stacking::supportGraph($entries); Stacking::checkSupportAndLoad($entries, $supporters, $directAbove, $globalSupport, $issues); + if ($spec->deck !== null) { + Stacking::checkDeckSupport($entries, $spec->deck, $globalSupport, $issues); + } $loads = Stacking::propagateLoad($entries, $supporters); Stacking::checkStackTopLoad($entries, $loads, $issues); if ($spec->maxStackDensity !== null) { diff --git a/src-legacy/Support/ResultValidation/ContainerSpec.php b/src-legacy/Support/ResultValidation/ContainerSpec.php index 9357724..949f8cb 100644 --- a/src-legacy/Support/ResultValidation/ContainerSpec.php +++ b/src-legacy/Support/ResultValidation/ContainerSpec.php @@ -39,10 +39,24 @@ final class ContainerSpec public $accessDirections; /** @var bool */ public $flatBag; + /** + * 1.10: a gusseted bag's side gusset depth G in ticks, which widens the width girth to + * b + c <= W + G; 0 for a flat bag and every rigid container. + * + * @var int|string + */ + public $sideGusset = 0; /** @var bool */ public $reportsAchievedExtent; /** @var MachineSpec|null */ public $madeToMeasure; + /** + * The weight-bearing deck `[x, y, length, width]` inside a pallet's solving frame, + * which `$inner` then is; null for every other container. + * + * @var array{0:int|string,1:int|string,2:int|string,3:int|string}|null + */ + public $deck; /** @return int|string */ public function volume() diff --git a/src-legacy/Support/ResultValidation/Geometry.php b/src-legacy/Support/ResultValidation/Geometry.php index ed76d9d..9d110f2 100644 --- a/src-legacy/Support/ResultValidation/Geometry.php +++ b/src-legacy/Support/ResultValidation/Geometry.php @@ -10,12 +10,40 @@ */ final class Geometry { - /** Axis permutation each orientation code applies to (length, width, height). */ + /** The six legacy orientation codes: every box a cuboid can make, and an item's default list. */ + public const BOX_ROTATIONS = ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']; + + /** + * Axis permutation each of the 24 proper rotations applies to (length, width, height), in + * canonical table order (1.10). Written out rather than read from the engine's + * `Orientations`, so this table is a second statement of the contract and not a copy. + */ public const ROTATIONS = [ 'LWH' => [0, 1, 2], 'LHW' => [0, 2, 1], 'WLH' => [1, 0, 2], 'WHL' => [1, 2, 0], 'HLW' => [2, 0, 1], 'HWL' => [2, 1, 0], + '+L-W-H' => [0, 1, 2], '-L+W-H' => [0, 1, 2], '-L-W+H' => [0, 1, 2], + '+L-H+W' => [0, 2, 1], '+L+H-W' => [0, 2, 1], '-L-H-W' => [0, 2, 1], + '+W-L+H' => [1, 0, 2], '+W+L-H' => [1, 0, 2], '-W-L-H' => [1, 0, 2], + '+W-H-L' => [1, 2, 0], '-W+H-L' => [1, 2, 0], '-W-H+L' => [1, 2, 0], + '+H-L-W' => [2, 0, 1], '-H+L-W' => [2, 0, 1], '-H-L+W' => [2, 0, 1], + '+H-W+L' => [2, 1, 0], '+H+W-L' => [2, 1, 0], '-H-W-L' => [2, 1, 0], + ]; + + /** The sign each container axis carries under each code; a box ignores it, a hull does not. The legacy codes negate x exactly when their permutation is odd. */ + public const ROTATION_SIGNS = [ + 'LWH' => [1, 1, 1], 'LHW' => [-1, 1, 1], 'WLH' => [-1, 1, 1], + 'WHL' => [1, 1, 1], 'HLW' => [1, 1, 1], 'HWL' => [-1, 1, 1], + '+L-W-H' => [1, -1, -1], '-L+W-H' => [-1, 1, -1], '-L-W+H' => [-1, -1, 1], + '+L-H+W' => [1, -1, 1], '+L+H-W' => [1, 1, -1], '-L-H-W' => [-1, -1, -1], + '+W-L+H' => [1, -1, 1], '+W+L-H' => [1, 1, -1], '-W-L-H' => [-1, -1, -1], + '+W-H-L' => [1, -1, -1], '-W+H-L' => [-1, 1, -1], '-W-H+L' => [-1, -1, 1], + '+H-L-W' => [1, -1, -1], '-H+L-W' => [-1, 1, -1], '-H-L+W' => [-1, -1, 1], + '+H-W+L' => [1, -1, 1], '+H+W-L' => [1, 1, -1], '-H-W-L' => [-1, -1, -1], ]; + /** Orientations that keep the item's own height vertical and pointing up: z takes `+H`. */ + public const UPRIGHT_ROTATIONS = ['LWH', 'WLH', '-L-W+H', '+W-L+H']; + /** `ROTATIONS[orientation]`. @return array{0:int,1:int,2:int} */ public static function axes(string $orientation): array { @@ -71,27 +99,26 @@ public static function primitiveAxis(array $axis): array } /** - * Reorient a hull the way `ROTATIONS` reorients its box, flipping one axis on an odd - * permutation so it stays a proper rotation, then translated so its bounds start at 0. + * Reorient a hull by one of the 24 proper rotations, without ever mirroring it: + * `v'[i] = s[i] * v[src[i]]` from `ROTATIONS` and `ROTATION_SIGNS`, where every code has + * determinant +1. The result is translated so its bounds start at 0, the frame a placement + * position is expressed in. * * @param list $vertices - * @param array{0:int,1:int,2:int} $axes * @return list */ - public static function rotateHull(array $vertices, array $axes): array + public static function rotateHull(array $vertices, string $orientation): array { - $inversions = 0; - for ($first = 0; $first < 3; ++$first) { - for ($second = $first + 1; $second < 3; ++$second) { - if ($axes[$first] > $axes[$second]) { - ++$inversions; - } - } - } + $axes = self::axes($orientation); + $signs = self::ROTATION_SIGNS[$orientation]; $turned = []; foreach ($vertices as $vertex) { - $x = $vertex[$axes[0]]; - $turned[] = [$inversions % 2 === 1 ? Exact::negate($x) : $x, $vertex[$axes[1]], $vertex[$axes[2]]]; + $point = []; + for ($axis = 0; $axis < 3; ++$axis) { + $value = $vertex[$axes[$axis]]; + $point[] = $signs[$axis] < 0 ? Exact::negate($value) : $value; + } + $turned[] = $point; } if ($turned === []) { throw MalformedResult::shape('a hull without vertices'); diff --git a/src-legacy/Support/ResultValidation/ObjectiveCheck.php b/src-legacy/Support/ResultValidation/ObjectiveCheck.php index c32cb75..ddd76bf 100644 --- a/src-legacy/Support/ResultValidation/ObjectiveCheck.php +++ b/src-legacy/Support/ResultValidation/ObjectiveCheck.php @@ -76,7 +76,7 @@ private static function objective($result, Context $context, Ordered $fabricated $achievedHeight = Exact::add($achievedHeight, $top); if ($billed && $billing['divisor'] !== null) { $gross = Json::pyInt(Json::get(Json::get($packed, 'gross_weight', []), 'ticks', 0), 'gross_weight'); - $size = $spec->flatBag ? ContainerCheck::achievedExtent($packed, $context->clearance) : ($spec->outer ?? $spec->inner); + $size = ContainerCheck::billedSize($packed, $spec, $context->clearance); $dimensional = self::dimensionalWeight( $size, Json::int($billing['divisor'], 'dimensional_weight_divisor'), diff --git a/src-legacy/Support/ResultValidation/PlacementIds.php b/src-legacy/Support/ResultValidation/PlacementIds.php new file mode 100644 index 0000000..0622c5f --- /dev/null +++ b/src-legacy/Support/ResultValidation/PlacementIds.php @@ -0,0 +1,81 @@ + $issues + */ + public static function check($result, array &$issues): void + { + $seen = []; + foreach (Json::items(Json::at($result, 'containers'), 'result.containers') as $container) { + $containerId = Json::get($container, 'id', ''); + foreach (Json::items(Json::at($container, 'placements'), 'placements') as $placement) { + $expected = self::expected($containerId, $placement); + $reported = Json::get($placement, 'placement_id'); + $where = PyFormat::str(Json::at($placement, 'item_id')) . ' in ' . PyFormat::str($containerId); + if (!\is_string($reported)) { + $issues[] = new ResultIssue('placement_id_mismatch', "{$where}: no placement_id, expected {$expected}"); + continue; + } + if ($reported !== $expected) { + $issues[] = new ResultIssue('placement_id_mismatch', "{$where}: reported {$reported}, expected {$expected}"); + } + if (isset($seen[$reported])) { + $issues[] = new ResultIssue('duplicate_placement_id', $reported); + } + $seen[$reported] = true; + } + } + } + + /** @param mixed $containerId @param mixed $placement */ + private static function expected($containerId, $placement): string + { + $position = Json::at($placement, 'position'); + $parts = [self::spelled(PyFormat::str($containerId))]; + foreach (['x', 'y', 'z'] as $axis) { + $parts[] = PyFormat::str(Json::at(Json::at($position, $axis), 'ticks')); + } + $parts[] = self::spelled(PyFormat::str(Json::at($placement, 'item_type'))); + $parts[] = self::spelled(PyFormat::str(Json::at($placement, 'orientation'))); + return '[' . \implode(',', $parts) . ']'; + } + + /** A string as RFC 8785 spells it: `"`, `\` and U+0000..U+001F escaped, the rest as UTF-8. */ + private static function spelled(string $text): string + { + return '"' . \strtr($text, self::escapes()) . '"'; + } + + /** @return array */ + private static function escapes(): array + { + static $escapes = null; + if ($escapes === null) { + $escapes = [ + '"' => '\\"', '\\' => '\\\\', "\x08" => '\\b', "\t" => '\\t', + "\n" => '\\n', "\x0C" => '\\f', "\r" => '\\r', + ]; + for ($code = 0; $code < 0x20; $code++) { + $escapes[\chr($code)] = $escapes[\chr($code)] ?? \sprintf('\\u%04x', $code); + } + } + return $escapes; + } +} diff --git a/src-legacy/Support/ResultValidation/Spec.php b/src-legacy/Support/ResultValidation/Spec.php index 45a6742..44891c0 100644 --- a/src-legacy/Support/ResultValidation/Spec.php +++ b/src-legacy/Support/ResultValidation/Spec.php @@ -10,7 +10,31 @@ final class Spec /** The six axis-aligned exit directions a placement could be slid out through. */ public const EXIT_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; - private const UPRIGHT_ROTATIONS = ['LWH', 'WLH']; + /** + * The codes an item may be placed in: its list, or the six legacy codes, narrowed to the + * upright ones under `keep_upright`. A signed code counts only on a hull -- the engines refuse + * it anywhere else -- so a box placed in one reads as a forbidden rotation (1.10). + * + * @param mixed $raw + * @return list + */ + private static function allowedRotations($raw, bool $keepUpright): array + { + $listed = Json::get($raw, 'allowed_rotations'); + $rotations = $listed === null ? Geometry::BOX_ROTATIONS : \array_values(Json::items($listed, 'allowed_rotations')); + if (!Json::isText(Json::get($raw, 'shape_type'), 'convex_hull')) { + $rotations = self::within($rotations, Geometry::BOX_ROTATIONS); + } + return $keepUpright ? self::within($rotations, Geometry::UPRIGHT_ROTATIONS) : $rotations; + } + + /** @param list $rotations @param list $codes @return list */ + private static function within(array $rotations, array $codes): array + { + return \array_values(\array_filter($rotations, static function ($code) use ($codes): bool { + return \is_string($code) && \in_array($code, $codes, true); + })); + } /** @param mixed $request @return Ordered */ public static function items($request, string $unit): Ordered @@ -21,11 +45,9 @@ public static function items($request, string $unit): Ordered $keepUpright = Json::flag($raw, 'keep_upright', false, $where); $stackable = Json::flag($raw, 'stackable', true, $where); $mustBeOnFloor = Json::flag($raw, 'must_be_on_floor', false, $where); - $rotations = Json::get($raw, 'allowed_rotations'); - if ($rotations === null) { - $rotations = $keepUpright ? self::UPRIGHT_ROTATIONS : \array_keys(Geometry::ROTATIONS); - } else { - $rotations = Json::items($rotations, 'allowed_rotations'); + $rotations = self::allowedRotations($raw, $keepUpright); + if ($rotations === []) { + throw MalformedResult::contract("{$where}.allowed_rotations must allow at least one rotation after keep_upright"); } $id = Json::at($raw, 'id'); $spec = new ItemSpec(); @@ -33,7 +55,7 @@ public static function items($request, string $unit): Ordered $spec->dimensions = Units::dimensions(Json::at($raw, 'dimensions'), $unit); $spec->weight = Units::toTicks(Json::get($raw, 'weight', 0), 'g', Units::WEIGHT); $spec->quantity = Json::get($raw, 'quantity', 1); - $spec->allowedRotations = \array_values($rotations); + $spec->allowedRotations = $rotations; $spec->stackable = $stackable; $spec->mustBeOnFloor = $mustBeOnFloor; $spec->maxTopLoad = self::measured($raw, 'max_top_load', 'g', Units::WEIGHT); @@ -68,7 +90,7 @@ public static function containers($request, string $unit): Ordered foreach (Json::items(Json::at($request, 'containers'), 'request.containers') as $raw) { $spec = new ContainerSpec(); $spec->id = Json::at($raw, 'id'); - $spec->inner = Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit); + [$spec->inner, $spec->deck] = self::frameAndDeck(Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit), Json::get($raw, 'pallet_overhang_limit'), $unit); $spec->accessDirections = self::accessDirections($raw); $outer = Json::get($raw, 'outer_dimensions'); $spec->outer = $outer === null ? null : Units::dimensions($outer, $unit); @@ -85,7 +107,8 @@ public static function containers($request, string $unit): Ordered $spec->maxStackDensity = self::measured($raw, 'max_stack_density', 'g', Units::WEIGHT); $spec->rateTable = Json::get($raw, 'rate_table'); $spec->flatBag = Json::get($raw, 'deformable_boundary') !== null; - $spec->reportsAchievedExtent = $spec->flatBag || Json::get($raw, 'made_to_measure') !== null; + $spec->sideGusset = self::sideGusset(Json::get($raw, 'deformable_boundary'), $unit); + $spec->reportsAchievedExtent = $spec->flatBag || Json::get($raw, 'made_to_measure') !== null || $spec->deck !== null; $machine = Json::get($raw, 'made_to_measure'); $spec->madeToMeasure = $machine === null ? null : self::machine($machine, $unit); $containers->set($spec->id, $spec); @@ -93,6 +116,34 @@ public static function containers($request, string $unit): Ordered return $containers; } + /** + * A gusseted bag's side gusset depth in ticks, else 0. + * + * @param mixed $boundary @return int|string + */ + private static function sideGusset($boundary, string $unit) + { + $depth = $boundary === null ? null : Json::get($boundary, 'side_gusset_depth'); + return $depth === null ? 0 : Units::toTicks($depth, $unit, Units::LENGTH); + } + + /** + * A pallet's solving frame and the deck inside it, else the declared size. + * + * @param array{0:int|string,1:int|string,2:int|string} $declared @param mixed $limit + * @return array{0:array{0:int|string,1:int|string,2:int|string},1:array{0:int|string,1:int|string,2:int|string,3:int|string}|null} + */ + private static function frameAndDeck(array $declared, $limit, string $unit): array + { + if ($limit === null) { + return [$declared, null]; + } + $overhangX = Units::toTicks(Json::at($limit, 'length'), $unit, Units::LENGTH); + $overhangY = Units::toTicks(Json::at($limit, 'width'), $unit, Units::LENGTH); + $frame = [Exact::add($declared[0], Exact::mul($overhangX, 2)), Exact::add($declared[1], Exact::mul($overhangY, 2)), $declared[2]]; + return [$frame, [$overhangX, $overhangY, $declared[0], $declared[1]]]; + } + /** `None if raw.get(key) is None else to_ticks(...)`. @param mixed $raw @param array $table @return int|string|null */ private static function measured($raw, string $key, string $unit, array $table) { diff --git a/src-legacy/Support/ResultValidation/Stacking.php b/src-legacy/Support/ResultValidation/Stacking.php index 3a41cb1..ff4f55e 100644 --- a/src-legacy/Support/ResultValidation/Stacking.php +++ b/src-legacy/Support/ResultValidation/Stacking.php @@ -93,6 +93,37 @@ public static function supportGraph(array $entries): array return [$supporters, $directAbove]; } + /** + * A floor placement on a pallet rests on its overlap with the deck alone, judged + * by the ratio and centre-of-gravity rule a supporting item would be. O(p). + * + * @param list $entries @param array{0:int|string,1:int|string,2:int|string,3:int|string} $deck + * @param list $issues + */ + public static function checkDeckSupport(array $entries, array $deck, Ratio $globalSupport, array &$issues): void + { + [$x, $y, $length, $width] = $deck; + $surface = new Cuboid($x, $y, -1, $length, $width, 1); + foreach ($entries as $entry) { + $spec = $entry->spec; + if ($spec === null || Exact::sign($entry->envelope->z) !== 0) { + continue; + } + $required = $globalSupport->compare($spec->minimumSupportRatio) < 0 ? $spec->minimumSupportRatio : $globalSupport; + if ($required->compareInt(0) <= 0) { + continue; + } + $area = $entry->envelope->overlapAreaXy($surface); + $itemId = PyFormat::str($entry->id); + if (Exact::compare($area, self::requiredSupportArea($entry->envelope->baseArea, ContainerCheck::ratioPpm($required))) < 0) { + $ratio = Ratio::of($area, $entry->envelope->baseArea); + $issues[] = new ResultIssue('insufficient_support', "{$itemId}: " . PyFormat::fixed6($ratio->toFloat()) . ' < ' . PyFormat::fixed6($required->toFloat()) . ' on the deck'); + } elseif (Exact::compare(Exact::mul($area, 2), $entry->envelope->baseArea) <= 0 && !self::centroidSupported($entry->envelope, [$surface])) { + $issues[] = new ResultIssue('centre_of_gravity_unsupported', "{$itemId}: centroid outside the deck"); + } + } + } + /** * @param list $entries @param list> $supporters * @param list> $directAbove @param list $issues @@ -521,7 +552,8 @@ public static function occupiedVolume(Cuboid $envelope, $placement, ?ItemSpec $s return Exact::mul($footprint, self::compressedHeight($height, $footprint, $spec, $load)); } if ($spec !== null && $spec->isConvexHull() && $spec->hullVertices !== null) { - return Geometry::hullVolume(Geometry::rotateHull($spec->hullVertices, Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')))); + // A proper rotation keeps the volume, so the authored vertices answer for every orientation. + return Geometry::hullVolume($spec->hullVertices); } $solid = self::placedHull($envelope, $placement, $spec); if ($solid === $envelope->vertices()) { @@ -539,10 +571,12 @@ public static function occupiedVolume(Cuboid $envelope, $placement, ?ItemSpec $s */ public static function placedHull(Cuboid $envelope, $placement, ?ItemSpec $spec): array { - if ($spec === null || $spec->hullVertices === null || !$spec->isConvexHull() || $spec->stopIndex !== null) { + if ($spec === null || $spec->hullVertices === null || !$spec->isConvexHull() || $spec->stopIndex !== null + || !Geometry::isRotation(Json::at($placement, 'orientation'))) { return $envelope->vertices(); } - $axes = Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')); + $orientation = Json::text(Json::at($placement, 'orientation'), 'orientation'); + $axes = Geometry::axes($orientation); $rotated = [$spec->dimensions[$axes[0]], $spec->dimensions[$axes[1]], $spec->dimensions[$axes[2]]]; if (Exact::compare($envelope->length, $rotated[0]) !== 0 || Exact::compare($envelope->width, $rotated[1]) !== 0 || Exact::compare($envelope->height, $rotated[2]) !== 0) { @@ -550,6 +584,6 @@ public static function placedHull(Cuboid $envelope, $placement, ?ItemSpec $spec) } return \array_map(static function (array $vertex) use ($envelope): array { return [Exact::add($envelope->x, $vertex[0]), Exact::add($envelope->y, $vertex[1]), Exact::add($envelope->z, $vertex[2])]; - }, Geometry::rotateHull($spec->hullVertices, $axes)); + }, Geometry::rotateHull($spec->hullVertices, $orientation)); } } diff --git a/src-legacy/Support/ResultValidation/Units.php b/src-legacy/Support/ResultValidation/Units.php index 051b39c..25f0f35 100644 --- a/src-legacy/Support/ResultValidation/Units.php +++ b/src-legacy/Support/ResultValidation/Units.php @@ -52,6 +52,19 @@ public static function lengthUnit($request): string if (!Json::isDict($units)) { throw MalformedResult::contract('units must be an object'); } + // A key other than `length`, the first in code-point order. PHP turns a + // numeric key into an int, so each is compared as the string it was; UTF-8 byte + // order is code-point order. + $unknown = \array_values(\array_filter( + \array_map('strval', \array_keys($units)), + static function (string $key): bool { + return $key !== 'length'; + } + )); + if ($unknown !== []) { + \usort($unknown, 'strcmp'); + throw MalformedResult::contract('units.' . $unknown[0] . ' is not a known field'); + } $length = Json::get($units, 'length'); if ($length === null) { return 'mm'; diff --git a/src-legacy/Support/ResultValidation/Validator.php b/src-legacy/Support/ResultValidation/Validator.php index 4c46c70..2688324 100644 --- a/src-legacy/Support/ResultValidation/Validator.php +++ b/src-legacy/Support/ResultValidation/Validator.php @@ -38,6 +38,7 @@ public static function validate($request, $result): array $issues = []; $validated = Lattice::materialize($coordinatesRequired, $result, $items, $containers, $clearance, $issues); Accounting::checkStructure($validated, $issues); + self::checkCurrency($request, $validated, $issues); Facts::checkAlgorithmMetrics($validated, $issues); Facts::checkEffortBudget($request, $validated, $issues); Facts::checkResultFacts($validated, $issues); @@ -49,6 +50,7 @@ public static function validate($request, $result): array self::checkContainerCounts($validated, $configuration, $containers, $issues); ObjectiveCheck::checkFixedPlacements($request, $validated, $unit, $issues); + PlacementIds::check($result, $issues); ObjectiveCheck::checkGroups($request, $validated, $issues); ObjectiveCheck::checkSolverSelection($request, $validated, $issues); $score = ObjectiveCheck::check($request, $validated, $context, $fabricated, $issues); @@ -56,6 +58,22 @@ public static function validate($request, $result): array return $issues; } + /** + * The result echoes the request's currency, and states none the request did not declare. + * A null is the field left out, on either side. O(1). + * + * @param mixed $request @param mixed $result @param list $issues + */ + private static function checkCurrency($request, $result, array &$issues): void + { + $requested = Json::get($request, 'currency'); + $reported = Json::get($result, 'currency'); + if (!Json::equals($reported, $requested)) { + $issues[] = new ResultIssue('currency_mismatch', 'reported ' . PyFormat::repr($reported) + . ', requested ' . PyFormat::repr($requested)); + } + } + /** @param mixed $result @param list $issues */ private static function checkInfeasibleProof($result, array &$issues): void { diff --git a/src-legacy/Validation/IndependentSolutionValidator.php b/src-legacy/Validation/IndependentSolutionValidator.php index ffd496b..5471a08 100644 --- a/src-legacy/Validation/IndependentSolutionValidator.php +++ b/src-legacy/Validation/IndependentSolutionValidator.php @@ -1,9 +1,10 @@ instance->item; if($item->tags!==[]||$item->incompatibleTags!==[])$compatibilitySensitive=true; if($item->minimumSupportRatio>0||($item->groundContactRule!==null&&$item->groundContactRule!=='free'))$supportSensitive=true; - // A stacking-group list refuses load on the same edges `stackable` does. - if(!$item->stackable||$item->acceptsStackingGroups!==[])$stackSensitive=true; + // A stacking-group list or bearing limit makes the scene stack-sensitive. + if($item->isStackSensitive())$stackSensitive=true; } $units=LoadCalculator::units($placements); $stackGraph=$stackSensitive?new LoadSupportGraph($units):null; + $compatibilityConstraints=$compatibilitySensitive?[new CompatibilityConstraint(),new TagCountConstraint()]:[]; + $supportConstraint=$supportSensitive?new SupportConstraint($minimumSupportRatio):null; foreach(self::collisionPairs($placements) as [$left,$right]) $issues[]=new ValidationIssue('collision',$placements[$left]->instance->id().' with '.$placements[$right]->instance->id()); foreach($packed->placements as $index=>$p){ @@ -57,17 +60,21 @@ public function validate(PackingRequest $request,array $containers,float $minimu if($eligibleTags!==[]&&array_intersect($eligibleTags,$packed->container->tags)===[]) $issues[]=new ValidationIssue('container_ineligible',$id); // The common lattice case has no pair-dependent rules. Avoid building - // an O(n) "all other placements" array for every item in that case. - $ctx=null; - if($compatibilitySensitive||$supportSensitive){ + // an O(n) "all other placements" array unless tag rules need it; + // support queries only inspect z2 == origin.z or origin.z < box.origin.z, + // which a positive-height box never satisfies against itself, so passing + // `$placements` reuses `LoadSupportGraph::$cachedByTop` in O(n). + if($compatibilitySensitive){ $others=array_merge(array_slice($placements,0,$index),array_slice($placements,$index+1)); - $ctx=new ConstraintContext($packed->container,$others,$p->instance,$p->envelopeOrigin,$p->rotation,$p->dimensions,$p->envelopeDimensions); + $compatCtx=new ConstraintContext($packed->container,$others,$p->instance,$p->envelopeOrigin,$p->rotation,$p->dimensions,$p->envelopeDimensions); + foreach($compatibilityConstraints as $constraint){ + $r=$constraint->evaluate($compatCtx); + if(!$r->allowed)$issues[]=new ValidationIssue($r->code,$id.': '.$r->detail); + } } - $constraints=[]; - if($compatibilitySensitive){$constraints[]=new CompatibilityConstraint();$constraints[]=new TagCountConstraint();} - if($supportSensitive)$constraints[]=new SupportConstraint($minimumSupportRatio); - foreach($constraints as $constraint){ - $r=$constraint->evaluate($ctx); + if($supportConstraint!==null){ + $supportCtx=new ConstraintContext($packed->container,$placements,$p->instance,$p->envelopeOrigin,$p->rotation,$p->dimensions,$p->envelopeDimensions); + $r=$supportConstraint->evaluate($supportCtx); if(!$r->allowed)$issues[]=new ValidationIssue($r->code,$id.': '.$r->detail); } if($stackSensitive){ @@ -78,9 +85,11 @@ public function validate(PackingRequest $request,array $containers,float $minimu // A second, whole-container bearing pass: the per-placement check above // reports the first offender it meets, this one is anchored on the container. $densityLimit=($nullsafeVariable2 = $packed->container->maxStackDensity) ? $nullsafeVariable2->ticks : null; - $analysis=new \Packvium\Constraint\Internal\LoadAnalysis($units,$stackGraph); - $failure=$analysis->overloaded()??$analysis->crushed()??$analysis->stackLimitExceeded()??$analysis->stackDensityExceeded($densityLimit); - if($failure!==null)$issues[]=new ValidationIssue($failure[0],$packed->id().': '.$failure[1]); + if($stackSensitive||$densityLimit!==null){ + $analysis=new \Packvium\Constraint\Internal\LoadAnalysis($units,$stackGraph); + $failure=$analysis->overloaded()??$analysis->crushed()??$analysis->stackLimitExceeded()??$analysis->stackDensityExceeded($densityLimit); + if($failure!==null)$issues[]=new ValidationIssue($failure[0],$packed->id().': '.$failure[1]); + } if($packed->container->axles!==null){ $axleFailure=AxleLoad::exceeded( $packed->container->axles, @@ -91,9 +100,10 @@ public function validate(PackingRequest $request,array $containers,float $minimu if($axleFailure!==null)$issues[]=new ValidationIssue($axleFailure[0],$packed->id().': '.$axleFailure[1]); } if($packed->container->isFlatBag()){ - // The girth rule over the envelopes alone; the frame is checked above. + // The girth rule over the envelopes alone, widened by a side gusset + // (1.10); the frame is checked above. [$a,$b,$c]=FlatBag::extentOf($packed->placements); - if(!FlatBag::girthAdmits($packed->container->innerDimensions,$a,$b,$c))$issues[]=new ValidationIssue('bag_girth_exceeded',$packed->id()); + if(!FlatBag::girthAdmits($packed->container->innerDimensions,$a,$b,$c,$packed->container->sideGussetTicks()))$issues[]=new ValidationIssue('bag_girth_exceeded',$packed->id()); } $onRoute=false;foreach($placements as $p)if($p->instance->item->stopIndex!==null){$onRoute=true;break;} if($onRoute){ @@ -146,6 +156,8 @@ private static function madeToMeasureIssues(PackingRequest $request,array $conta if($machine===null||$machine->madeToMeasure===null||$packed->container->madeToMeasure===null)continue; $expected=$machine->fabricate(FlatBag::extentOf($packed->placements)); $box=$packed->container; + if($box->innerDimensions!=$expected->innerDimensions&&self::reserveCut($packed,$expected,$machine->innerDimensions)) + $expected=$machine->fabricate(self::sides($box->innerDimensions)); if($box->innerDimensions!=$expected->innerDimensions)$issues[]=new ValidationIssue('fabricated_dimensions_mismatch',$packed->id()); if($box->outerDimensions!=$expected->outerDimensions)$issues[]=new ValidationIssue('outer_dimensions_mismatch',$packed->id()); if($box->costMinor!==$expected->costMinor)$issues[]=new ValidationIssue('made_to_measure_cost_mismatch',$packed->id()); @@ -154,6 +166,24 @@ private static function madeToMeasureIssues(PackingRequest $request,array $conta return $issues; } + /** + * A box larger than the tight cut is admitted when the tight box breaks the void-fill reserve + * and the larger one is on the machine grid within the maximum; whether it keeps the + * reserve is checked with every other container's reserve. O(1). + */ + private static function reserveCut(PackedContainer $packed,Container $tight,Dimensions $maximum):bool + { + $machine=$tight->madeToMeasure; + if($tight->voidFillReserveRatio===0.0||$machine===null)return false; + $cut=self::sides($packed->container->innerDimensions);$low=self::sides($tight->innerDimensions);$high=self::sides($maximum); + for($axis=0;$axis<3;$axis++) + if($cut[$axis]<$low[$axis]||$cut[$axis]>$high[$axis]||($cut[$axis]-$machine->minimum[$axis])%$machine->increment[$axis]!==0)return false; + return BigInt::compare($packed->usedVolumeString(),VolumeReserve::usable($tight))>0; + } + + /** @return array{0:int,1:int,2:int} */ + private static function sides(Dimensions $dimensions):array{return [$dimensions->length->ticks,$dimensions->width->ticks,$dimensions->height->ticks];} + /** * @param list $placements @return list * diff --git a/src/Algorithm/CandidateFinder.php b/src/Algorithm/CandidateFinder.php index 2228eb9..7b385cb 100644 --- a/src/Algorithm/CandidateFinder.php +++ b/src/Algorithm/CandidateFinder.php @@ -18,9 +18,59 @@ final class CandidateFinder */ public static function find(ContainerState $state,ItemInstance $item,PackingConfig $config,array $constraints,SearchStats $stats,Deadline $deadline,CandidateScorer $scorer,?int $max=null,?array $points=null):array { + $prepared=self::prepare($state,$item,$config,$constraints,$scorer); + if($prepared===null)return []; + $forms=$prepared[3]; + $limitX=$prepared[19]; $container=$state->container; - if($container->maxItems!==null&&count($state->placements)>=$container->maxItems)return []; - if($container->maxPayload!==null&&$state->payloadTicks+$item->weight()->ticks>$container->maxPayload->ticks)return []; + if($points===null){ + if($item->item->nestingHeight===null)$scan=array_slice($state->orderedPoints,0,$config->maxCandidatePoints); + else{ + $merged=[]; + foreach([...$state->orderedPoints,...self::nestingPoints($state,$item)] as $candidatePoint) + $merged["{$candidatePoint->x}:{$candidatePoint->y}:{$candidatePoint->z}"]=$candidatePoint; + $scan=array_values($merged); + usort($scan,static fn(Point $a,Point $b):int=>[$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]); + $scan=array_slice($scan,0,$config->maxCandidatePoints); + } + if($container->axles!==null)$scan=self::appendUnseen($scan,self::axleBalancedPoints($state,$item,$forms,$limitX)); + }else{ + $scan=$points; + if(count($scan)>1)usort($scan,static fn(Point $a,Point $b):int=>[$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]); + } + $fixedVerdicts=[]; + return self::scanPoints($prepared,$scan,$max,$stats,$deadline,$fixedVerdicts); + } + + /** + * Evaluate `$spaces` in order, preparing item-invariant forms and constraints once. + * + * @param list $spaces + * @param list $constraints + */ + public static function chooseInSpaces(ContainerState $state,array $spaces,ItemInstance $item,PackingConfig $config,array $constraints,SearchStats $stats,Deadline $deadline,CandidateScorer $scorer):?Candidate + { + if($spaces===[])return null; + $prepared=self::prepare($state,$item,$config,$constraints,$scorer); + if($prepared===null){ + foreach($spaces as $_)$deadline->check(); + return null; + } + $fixedVerdicts=[]; + foreach($spaces as $space){ + $deadline->check(); + foreach(self::scanPoints($prepared,[$space->origin],null,$stats,$deadline,$fixedVerdicts) as $candidate) + if($candidate->envelopeDimensions->fitsInside($space->dimensions))return $candidate; + } + return null; + } + + /** @param list $constraints */ + private static function prepare(ContainerState $state,ItemInstance $item,PackingConfig $config,array $constraints,CandidateScorer $scorer):?array + { + $container=$state->container; + if($container->maxItems!==null&&count($state->placements)>=$container->maxItems)return null; + if($container->maxPayload!==null&&$state->payloadTicks+$item->weight()->ticks>$container->maxPayload->ticks)return null; $compressionSensitive=$state->compressionSensitive ||$item->item->shapeType===ShapeType::COMPRESSIBLE; $reserveNeedsCandidate=$item->item->nestingHeight!==null @@ -28,14 +78,16 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf ||$compressionSensitive; if($container->voidFillReserveRatio>0&&!$reserveNeedsCandidate){ $projected=BigInt::add($state->usedVolume,$item->dimensions()->volumeString()); - if(BigInt::compare($projected,$state->usableVolume())>0)return []; + if(BigInt::compare($projected,$state->usableVolume())>0)return null; } $inner=$container->innerDimensions; $limitX=$inner->length->ticks;$limitY=$inner->width->ticks;$limitZ=$inner->height->ticks; - // A flat bag also needs a + c <= L and b + c <= W over the running extents grown by - // the candidate: O(1), and the extents only grow, so no verdict flips. + // A bag also needs a + c <= L and b + c <= W + G over the running extents grown by + // the candidate (G is a gusseted bag's side gusset, 0 for a flat one): O(1), + // and the extents only grow, so no verdict flips. W + G is summed once per call. $bag=$container->isFlatBag(); $bagX=$state->maxX;$bagY=$state->maxY;$bagZ=$state->maxZ; + $girthY=$limitY+$container->sideGussetTicks(); $clearance=$config->clearance->ticks; // Envelope and extents depend only on the rotation, so they are built once // instead of once per (point, rotation) pair. @@ -76,25 +128,27 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf } $inertSupportChecks=count($active); $defaultScorer=get_class($scorer)===\Packvium\Extension\DefaultCandidateScorer::class; - // A rule that reads no position answers the same at every (point, rotation) of this - // search, so it is asked once, by the first position that reaches it. - // Keyed by chain position; the stored value is the verdict's `allowed`. - $fixedVerdicts=[]; - if($points===null){ - if($item->item->nestingHeight===null)$scan=array_slice($state->orderedPoints,0,$config->maxCandidatePoints); - else{ - $merged=[]; - foreach([...$state->orderedPoints,...self::nestingPoints($state,$item)] as $candidatePoint) - $merged["{$candidatePoint->x}:{$candidatePoint->y}:{$candidatePoint->z}"]=$candidatePoint; - $scan=array_values($merged); - usort($scan,static fn(Point $a,Point $b):int=>[$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]); - $scan=array_slice($scan,0,$config->maxCandidatePoints); - } - if($container->axles!==null)$scan=self::appendUnseen($scan,self::axleBalancedPoints($state,$item,$forms,$limitX)); - }else{ - $scan=$points; - if(count($scan)>1)usort($scan,static fn(Point $a,Point $b):int=>[$a->z,$a->y,$a->x]<=>[$b->z,$b->y,$b->x]); - } + return [ + $state,$container,$item,$forms,$placed,$stackSensitive,$routeSensitive, + $bounds,$hullShapes,$index,$nesting,$reserveCheck,$usable,$compressionSensitive, + $active,$inertChain,$inertSupportChecks,$defaultScorer,$scorer, + $limitX,$limitY,$limitZ,$bag,$bagX,$bagY,$bagZ,$girthY,$clearance, + ]; + } + + /** + * @param list $scan + * @param array $fixedVerdicts + * @return list + */ + private static function scanPoints(array $prepared,array $scan,?int $max,SearchStats $stats,Deadline $deadline,array &$fixedVerdicts):array + { + [ + $state,$container,$item,$forms,$placed,$stackSensitive,$routeSensitive, + $bounds,$hullShapes,$index,$nesting,$reserveCheck,$usable,$compressionSensitive, + $active,$inertChain,$inertSupportChecks,$defaultScorer,$scorer, + $limitX,$limitY,$limitZ,$bag,$bagX,$bagY,$bagZ,$girthY,$clearance, + ]=$prepared; $out=[];$best=null; $retained=$max!==null&&$max>1?new \SplPriorityQueue():null; $placementOffset=count($bounds)-count($placed); @@ -114,7 +168,7 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf if($bag){ // Ternaries rather than max(): the call made this test dearer (44 ns against 74 ns). $thickness=$z2>$bagZ?$z2:$bagZ; - if(($x2>$bagX?$x2:$bagX)+$thickness>$limitX||($y2>$bagY?$y2:$bagY)+$thickness>$limitY)continue; + if(($x2>$bagX?$x2:$bagX)+$thickness>$limitX||($y2>$bagY?$y2:$bagY)+$thickness>$girthY)continue; } $tentative=null; if($nesting){ diff --git a/src/Algorithm/ContainerState.php b/src/Algorithm/ContainerState.php index a30ef62..68a0cf4 100644 --- a/src/Algorithm/ContainerState.php +++ b/src/Algorithm/ContainerState.php @@ -3,7 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Constraint\VolumeReserve; use Packvium\Config\PackingConfig; -use Packvium\Domain\{AxisAlignedBox,Container,FlatBag,ItemInstance,LatticeSummary,Nesting,Placement,Point,ShapeType}; +use Packvium\Domain\{AxisAlignedBox,Container,FlatBag,ItemInstance,LatticeSummary,Nesting,PalletOverhang,Placement,Point,ShapeType}; use Packvium\Support\BigInt; /** * Placed boxes plus the candidate points they expose. @@ -203,8 +203,10 @@ private function extendExtent(int $x2,int $y2,int $z2):void * The dimensional weight, in weight ticks, a carrier bills for this container as filled. * * A flat bag is billed on its running extents, the parcel a carrier measures; an empty bag - * has no parcel yet and bills nothing by volume. A rigid container is billed on its declared - * outer size, else its inner size. O(1). + * has no parcel yet and bills nothing by volume. A pallet is billed at the footprint its load + * reached. A rigid container is billed on its declared outer size, else its inner + * size. O(1) but for a pallet, O(p): the state tracks no lowest corner, and pallets are + * deck-first trials of few boxes each. */ public function billedDimensionalWeight(PackingConfig $config):int { @@ -212,6 +214,8 @@ public function billedDimensionalWeight(PackingConfig $config):int if($container->isFlatBag()){ if($this->placements===[])return 0; $dimensions=FlatBag::asDimensions([$this->maxX,$this->maxY,$this->maxZ]); + }elseif($container->deck!==null){ + $dimensions=PalletOverhang::billedDimensions($container,$container->deck,$this->placements); }else{ $dimensions=$container->outerDimensions??$container->innerDimensions; } diff --git a/src/Algorithm/FixedPlacementAdmission.php b/src/Algorithm/FixedPlacementAdmission.php index da6ea65..ee24e84 100644 --- a/src/Algorithm/FixedPlacementAdmission.php +++ b/src/Algorithm/FixedPlacementAdmission.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Packvium\Algorithm; use Packvium\Constraint\Internal\LoadSupportGraph; -use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,FixedPlacement,Item,ItemInstance,PackedContainer,PackingRequest,Placement,Point}; +use Packvium\Domain\{AxisAlignedBox,Container,Deck,Dimensions,FixedPlacement,Item,ItemInstance,PackedContainer,PackingRequest,PalletOverhang,Placement,Point}; use Packvium\Support\{CanonicalJson,ExactGeometry,ExactInteger}; use Packvium\Unit\{Length,Weight}; use Packvium\Validation\{FixedPlacementException,IndependentSolutionValidator}; @@ -39,7 +39,7 @@ public static function admit(PackingRequest $request,float $minimumSupportRatio, self::requireContiguousInstances($grouped,$containers,$maxContainers); $packed=[]; foreach($grouped as [$containerId,$sequence,$placements]) - $packed[]=new PackedContainer($containers[$containerId],$sequence,self::withSupportAndLoads($placements)); + $packed[]=new PackedContainer($containers[$containerId],$sequence,self::withSupportAndLoads($placements,$containers[$containerId]->deck)); self::requireValidAlone($request,$packed,$minimumSupportRatio,$clearance); $taken=[];foreach($packed as $container)foreach($container->placements as $placement)$taken[$placement->instance->id()]=true; $free=array_values(array_filter($request->instances(),static fn(ItemInstance $instance):bool=>!isset($taken[$instance->id()]))); @@ -144,22 +144,22 @@ private static function requireContiguousInstances(array $grouped,array $contain * * @param list $placements @return list */ - private static function withSupportAndLoads(array $placements):array + private static function withSupportAndLoads(array $placements,?Deck $deck):array { $supported=[]; foreach($placements as $index=>$placement){ $others=$placements;unset($others[$index]); $supported[]=new Placement($placement->instance,$placement->position,$placement->rotation,$placement->dimensions, - $placement->envelopeOrigin,$placement->envelopeDimensions,self::supportRatio(array_values($others),$placement),new Weight(0),true); + $placement->envelopeOrigin,$placement->envelopeDimensions,self::supportRatio(array_values($others),$placement,$deck),new Weight(0),true); } return TopLoadAssigner::assign($supported); } /** @param list $others */ - private static function supportRatio(array $others,Placement $placement):float + private static function supportRatio(array $others,Placement $placement,?Deck $deck):float { - if($placement->envelopeOrigin->z===0)return 1.0; $box=new AxisAlignedBox($placement->envelopeOrigin,$placement->envelopeDimensions); + if($placement->envelopeOrigin->z===0)return PalletOverhang::floorSupportRatio($deck,$box); $support=LoadSupportGraph::candidateView($others,$placement->instance,$box); return ExactInteger::ratio($support->supportingArea,ExactGeometry::baseArea($placement->envelopeDimensions)); } diff --git a/src/Algorithm/GridSolver.php b/src/Algorithm/GridSolver.php index eb454cc..0c8e282 100644 --- a/src/Algorithm/GridSolver.php +++ b/src/Algorithm/GridSolver.php @@ -50,6 +50,10 @@ private static function latticeProfile(\Packvium\Domain\Item $item):string // A lattice joins same-type items only, so two types may share one exactly when // they share the stacking rule as well. $item->stackingGroup,$acceptsStackingGroups, + // packOne refuses a prototype that is not a rigid box, so the shape must be in the + // key too: otherwise a compressible type of the same size and weight joins a rigid + // prototype's lattice and is stacked with no crush check at all. + $item->shapeType, ]); } @@ -85,6 +89,10 @@ public function packOne(Container $container,int $sequence,array $items,PackingC // The lattice counts cells against the rigid frame alone; a bag's girth rule // couples the axes, which the per-candidate check applies exactly. return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); + if($container->deck!==null) + // The lattice rests every floor cell on the whole floor; a pallet's frame bears + // weight only on its deck, which the per-candidate support check reads. + return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); if($container->maxStackDensity!==null) // The single-layer heuristic below only ever reasons about one item // resting on one other, never the cumulative load a tall column presses diff --git a/src/Algorithm/HomogeneousBlockSolver.php b/src/Algorithm/HomogeneousBlockSolver.php index 697614e..7b7492d 100644 --- a/src/Algorithm/HomogeneousBlockSolver.php +++ b/src/Algorithm/HomogeneousBlockSolver.php @@ -83,7 +83,7 @@ public function supports(Container $container,array $items,PackingConfig $config // 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||$container->isFlatBag())return false; + if($this->constraints!==[]||$container->obstacles!==[]||$container->preloaded!==[]||$container->axles!==null||$container->tagLimits!==[]||$container->maxStackDensity!==null||$container->voidFillReserveRatio>0||$container->isFlatBag()||$container->deck!==null)return false; foreach($items as $instance){ $item=$instance->item; 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; diff --git a/src/Algorithm/Internal/MadeToMeasureTrial.php b/src/Algorithm/Internal/MadeToMeasureTrial.php index d8844e2..0ade76c 100644 --- a/src/Algorithm/Internal/MadeToMeasureTrial.php +++ b/src/Algorithm/Internal/MadeToMeasureTrial.php @@ -5,7 +5,9 @@ use Packvium\Config\PackingConfig; use Packvium\Domain\{Container,ItemInstance,MadeToMeasure}; use Packvium\Extension\{ContainerSelector,DefaultContainerSelector}; -use Packvium\Algorithm\{Deadline,SearchStats,SingleContainerSolution,SingleContainerSolver,TimeLimitReached}; +use Packvium\Algorithm\{ContainerState,Deadline,SearchStats,SingleContainerSolution,SingleContainerSolver,TimeLimitReached}; +use Packvium\Constraint\VolumeReserve; +use Packvium\Support\BigInt; /** * Trials of made-to-measure boxes, loaded only for a made-to-measure container. A part of `SolverOrchestrator` kept in its own file so PHP compiles it only when a @@ -43,6 +45,7 @@ public static function madeToMeasureTrial(\Closure $call,?ContainerSelector $con $last=$one; if($one->state->placementCount()>0){ $trial=$call('fabricated',$container,$one); + if(!self::keepsReserve($trial->state))$trial=$call('fabricated',$container,$one,$rung); if($one->state->placementCount()===count($items))return [$trial,$trials]; $key=$call('roundScore',$trial,$items,$config,$selector); if($best===null||($key<=>$bestKey)<0){$best=$trial;$bestKey=$key;} @@ -52,4 +55,15 @@ public static function madeToMeasureTrial(\Closure $call,?ContainerSelector $con $chosen=$best??$last; return [new SingleContainerSolution($chosen->state,$chosen->unpacked,$chosen->exhaustive,$chosen->timeLimitReached||$stopped,$chosen->dominantLattice),$trials]; } + + /** + * Whether a fabricated box keeps its void-fill reserve. The reserve is a share of the + * box that ships, so a box cut tight to its load can break a reserve the rung kept: the trial + * then cuts the rung itself, on the grid by construction and solved under its reserve. + */ + private static function keepsReserve(ContainerState $state):bool + { + $container=$state->container; + return $container->voidFillReserveRatio===0.0||BigInt::compare($state->usedVolume,VolumeReserve::usable($container))<=0; + } } diff --git a/src/Algorithm/Internal/PalletTrial.php b/src/Algorithm/Internal/PalletTrial.php new file mode 100644 index 0000000..c5e81e8 --- /dev/null +++ b/src/Algorithm/Internal/PalletTrial.php @@ -0,0 +1,103 @@ + $items + * @return array{0:SingleContainerSolution,1:int} + */ + public static function palletTrial(\Closure $call,SingleContainerSolver $solver,Container $frame,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array + { + /** @var Deck $deck a solving frame always carries its deck */ + $deck=$frame->deck; + $rungConfig=$config->requirePlacementCoordinates?$config:$call('withCoordinates',$config); + $onDeck=$solver->packOne(PalletOverhang::deckAlone($frame),$sequence,$items,$rungConfig,$stats,$deadline); + if($onDeck->state->placementCount()===count($items)||$onDeck->timeLimitReached||$deadline->expired()) + return [self::moved($frame,$onDeck,$deck->x,$deck->y),1]; + try{ + $framed=$solver->packOne($frame,$sequence,$items,$rungConfig,$stats,$deadline); + }catch(TimeLimitReached){ + return [self::withOutcome(self::moved($frame,$onDeck,$deck->x,$deck->y),true),1]; + } + if($framed->state->placementCount()>$onDeck->state->placementCount()){ + $seated=self::seated($frame,$framed,$config); + return [new SingleContainerSolution($seated->state,$seated->unpacked,false,$seated->timeLimitReached,$seated->dominantLattice),2]; + } + return [self::withOutcome(self::moved($frame,$onDeck,$deck->x,$deck->y),$framed->timeLimitReached),2]; + } + + /** The trial, never exhaustive, with the time limit as the second rung left it. */ + private static function withOutcome(SingleContainerSolution $one,bool $timeLimitReached):SingleContainerSolution + { + return new SingleContainerSolution($one->state,$one->unpacked,false,$timeLimitReached,$one->dominantLattice); + } + + /** + * A trial's whole load moved by `($dx, $dy)` on the frame, rebuilt so the state's points and + * index describe the frame. Relative geometry is unchanged, so only a floor placement's + * support -- its overlap with the deck -- is measured again. O(p) adds. + */ + private static function moved(Container $frame,SingleContainerSolution $one,int $dx,int $dy):SingleContainerSolution + { + $state=new ContainerState($frame,$one->state->sequence); + foreach($one->state->placements as $placement){ + $origin=self::shifted($placement->envelopeOrigin,$dx,$dy); + $support=$origin->z===0 + ?PalletOverhang::floorSupportRatio($frame->deck,new AxisAlignedBox($origin,$placement->envelopeDimensions)) + :$placement->supportRatio; + $state->add(new Placement($placement->instance,self::shifted($placement->position,$dx,$dy),$placement->rotation,$placement->dimensions, + $origin,$placement->envelopeDimensions,$support,$placement->topLoad,$placement->fixed)); + } + return new SingleContainerSolution($state,$one->unpacked,$one->exhaustive,$one->timeLimitReached,false); + } + + /** + * A frame trial moved to the least overhang (`PalletOverhang::centringOffset`), kept where + * the solver left it if the move would leave a floor placement short of support. O(p). + */ + private static function seated(Container $frame,SingleContainerSolution $one,PackingConfig $config):SingleContainerSolution + { + /** @var Deck $deck a solving frame always carries its deck */ + $deck=$frame->deck; + [$dx,$dy]=PalletOverhang::centringOffset($deck,$one->state->placements); + if($dx===0&&$dy===0)return $one; + $seated=self::moved($frame,$one,$dx,$dy); + $support=new SupportConstraint($config->minimumSupportRatio); + foreach($seated->state->placements as $placement){ + if($placement->envelopeOrigin->z!==0)continue; + $context=new ConstraintContext($frame,[],$placement->instance,$placement->envelopeOrigin,$placement->rotation,$placement->dimensions,$placement->envelopeDimensions); + if(!$support->evaluate($context)->allowed)return $one; + } + return $seated; + } + + private static function shifted(Point $point,int $dx,int $dy):Point + { + return new Point($point->x+$dx,$point->y+$dy,$point->z); + } +} diff --git a/src/Algorithm/MaximalSpaceSolver.php b/src/Algorithm/MaximalSpaceSolver.php index 110680b..09bad5f 100644 --- a/src/Algorithm/MaximalSpaceSolver.php +++ b/src/Algorithm/MaximalSpaceSolver.php @@ -55,11 +55,6 @@ public function packOne(Container $container,int $sequence,array $items,PackingC /** @param list $spaces @param list $constraints */ private static function choose(ContainerState $state,array $spaces,ItemInstance $item,PackingConfig $config,array $constraints,SearchStats $stats,Deadline $deadline,CandidateScorer $scorer):?Candidate { - foreach($spaces as $space){ - $deadline->check(); - foreach(CandidateFinder::find($state,$item,$config,$constraints,$stats,$deadline,$scorer,null,[$space->origin]) as $candidate) - if($candidate->envelopeDimensions->fitsInside($space->dimensions))return $candidate; - } - return null; + return CandidateFinder::chooseInSpaces($state,$spaces,$item,$config,$constraints,$stats,$deadline,$scorer); } } diff --git a/src/Algorithm/ObjectiveBoundScope.php b/src/Algorithm/ObjectiveBoundScope.php index 4e5faa1..0f525fd 100644 --- a/src/Algorithm/ObjectiveBoundScope.php +++ b/src/Algorithm/ObjectiveBoundScope.php @@ -7,15 +7,19 @@ /** Request-only bound eligibility; keeps numeric bound code lazy. @internal */ final class ObjectiveBoundScope { + /** A name rather than a position is the one key only that objective ranks by. */ public const OBJECTIVE_ORDERS = [ 'default' => [0, 1, 2, 3, 4], 'lowest_cost' => [0, 2, 1, 3, 4], + 'maximum_value' => [0, 'value_forgone', 1, 2, 3], + 'open_dimension_height' => [0, 'achieved_height', 1, 2, 3], + 'maximum_volume' => ['unpacked_volume_ppm', 0, 1, 2, 3], ]; /** * O(containers) time, O(1) space; no instances or arithmetic are needed to refuse. * @param list $containers - * @return list|null + * @return list|null */ public static function order(array $containers, string $objective): ?array { diff --git a/src/Algorithm/ObjectiveBounds.php b/src/Algorithm/ObjectiveBounds.php index d9bdbca..a71a873 100644 --- a/src/Algorithm/ObjectiveBounds.php +++ b/src/Algorithm/ObjectiveBounds.php @@ -70,10 +70,11 @@ final class ObjectiveBounds public const MAX_BOUND_VALUE = '9007199254740991'; /** - * The objectives a bound is stated for, and where each reads the five bounds: the - * position in `compute`'s default-order vector of each of the objective's score keys. - * `lowest_cost` scores cost ahead of the container count, and the document shows the - * permuted vector is still a bound. Every other objective gets none. + * The objectives a bound is stated for, and where each reads its bounds: the position in + * `compute`'s default-order vector of each of the objective's score keys, or the name of + * the one key only that objective ranks by. `lowest_cost` scores cost ahead of + * the container count, and the document shows the permuted vector is still a bound. + * `shipping_cost` and `lowest_landed_cost` get none. */ public const OBJECTIVE_ORDERS = ObjectiveBoundScope::OBJECTIVE_ORDERS; @@ -84,7 +85,8 @@ final class ObjectiveBounds * (D13: the unused-volume key would read the machine maximum while the score * reads the fabricated box), and for a request past a declared ceiling. The last * withholds the bound and nothing else -- the pack is answered as it was before any - * bound existed, rather than failing with `BoundOverflowException` (finding F5). + * bound existed, rather than failing with `BoundOverflowException` (finding F5). An + * objective's own key past the portable ceiling withholds that objective's bound alone. * * @param list $instances every instance of the request, fixed ones included * @param list $containers @@ -97,11 +99,158 @@ public static function forRequest(array $instances, array $containers, string $o return null; } try { - $vector = self::compute($instances, $containers); + [$normalisedInstances, $normalisedContainers] = self::normalise($instances, $containers); + return self::objectiveVector($normalisedInstances, $normalisedContainers, $order); } catch (BoundOverflowException $refused) { return null; } - return array_map(static fn(int $position): int => $vector[$position], $order); + } + + /** + * The bound in one objective's score order, from the normalised numbers `fromNormalised` + * reads plus each instance's `value`, throwing `BoundOverflowException` where a ceiling + * withholds it -- the one predicate's, or the objective's own key's. + * + * @param list $instances + * @param list $containers + * @param list $order an `OBJECTIVE_ORDERS` entry + * @return list + */ + public static function objectiveVector(array $instances, array $containers, array $order): array + { + $evaluated = self::evaluate($instances, $containers); + $vector = $evaluated['vector']; + return array_map(static fn(int|string $position): int => is_int($position) + ? $vector[$position] + : self::objectiveTerm($position, $instances, $evaluated), $order); + } + + /** + * The bound on the one key an objective ranks by and the default does not. + * + * Each is conditional on the keys before it, as `fromNormalised`'s are: the value and + * height terms hold for every packing that leaves exactly `L0` instances behind, and the + * volume term leads its objective and holds for every packing. + * + * No term sorts: `evaluate` already paid for the only volume sort (finding F6 doubled that + * cost once) and hands its ascending volumes and capacity total over, and the value term + * selects the `L0` smallest values with a bounded heap in `O(n log L0)`. With `O(c)` over + * the container types the request bound stays `O(n log n + c log c)`. + * + * @param list $instances + * @param array{vector:array{int,int,int,int,int},volumes:list,shrinks:bool,areas:list,capacity:?string} $evaluated + */ + private static function objectiveTerm(string $name, array $instances, array $evaluated): int + { + $unpacked = $evaluated['vector'][0]; + if ($name === 'value_forgone') { + return self::valueForgoneBound(array_column($instances, 'value'), $unpacked); + } + if ($name === 'achieved_height') { + return self::achievedHeightBound($evaluated['volumes'], $evaluated['shrinks'], + count($instances) - $unpacked, $evaluated['areas']); + } + return self::unpackedVolumeBound($evaluated['volumes'], $evaluated['shrinks'], + $evaluated['capacity']); + } + + /** + * `maximum_value`'s second key: whichever `$unpacked` instances are left behind, their + * value is at least that of the `$unpacked` least valuable. Values are non-negative, so + * the sum passes the portable ceiling exactly when some running sum does. + * + * @param list $values + */ + private static function valueForgoneBound(array $values, int $unpacked): int + { + return self::guardOutput(self::sumBig(array_map(strval(...), self::smallestValues($values, $unpacked))), + 'value forgone'); + } + + /** + * The `$count` smallest of `$values`, in no particular order, without sorting them all: a + * max-heap holding the smallest seen so far evicts its largest whenever it overfills. + * `O(n log count)` time, `O(count)` space. + * + * @param list $values + * @return list + */ + private static function smallestValues(array $values, int $count): array + { + if ($count <= 0) { + return []; + } + if ($count >= count($values)) { + return $values; + } + $kept = new \SplMaxHeap(); + foreach ($values as $value) { + $kept->insert($value); + if ($kept->count() > $count) { + $kept->extract(); + } + } + return iterator_to_array($kept, false); + } + + /** + * `open_dimension_height`'s second key, the summed tops in ticks. + * + * A container holding volume `v` on floor `A` stands at least `v / A` tall, because its + * placements are disjoint boxes inside `A x top`. Summed over the opened containers that + * is at least the placed volume over the widest floor, and the score is an integer. The + * placed volume is at least the `$placed` smallest. An instance that occupies less than + * its box breaks the disjoint-boxes step, so the term is dropped. + * + * @param list $volumes ascending + * @param list $areas square ticks, exact past a native int + */ + private static function achievedHeightBound(array $volumes, bool $shrinks, int $placed, + array $areas): int + { + $widest = array_reduce($areas, ExactInteger::max(...), 0); + if ($shrinks || $placed <= 0 || ExactInteger::sign($widest) <= 0) { + return 0; + } + return self::guardOutput( + self::ceilDivide(self::sumBig(array_slice($volumes, 0, $placed)), (string)$widest), + 'achieved height', + ); + } + + /** + * `maximum_volume`'s first key: the volume no inventory can hold, as the score's own + * rounded-up share of the requested volume. + * + * The packed volume is at most the summed usable capacity, so at least the rest is left + * behind whatever the geometry does. Unlimited inventory (a null capacity) holds + * everything, and an instance that occupies less than its box stops nominal volumes + * summing, so both give 0. The share is at most `PPM`, so it needs no output guard. + * + * @param list $volumes + */ + private static function unpackedVolumeBound(array $volumes, bool $shrinks, ?string $capacity): int + { + if ($shrinks || $capacity === null) { + return 0; + } + $requested = self::sumBig($volumes); + if (BigInt::compare($requested, $capacity) <= 0) { + return 0; + } + return (int)self::ceilDivide( + BigInt::multiply(BigInt::subtract($requested, $capacity), (string)self::PPM), + $requested, + ); + } + + /** `ceil(numerator / denominator)` for a non-negative numerator and positive denominator. */ + private static function ceilDivide(string $numerator, string $denominator): string + { + if (BigInt::compare($numerator, '0') === 0) { + return '0'; + } + return BigInt::divide(BigInt::add(BigInt::subtract($numerator, '1'), $denominator), $denominator); } /** @@ -191,6 +340,18 @@ private static function guardOutput(string $value, string $quantity): int * @return array{int,int,int,int,int} */ public static function compute(array $instances, array $containers): array + { + return self::fromNormalised(...self::normalise($instances, $containers)); + } + + /** + * The numbers the formulas consume, read once from the engine objects. + * + * @param list $instances + * @param list $containers + * @return array{0:list,1:list} + */ + private static function normalise(array $instances, array $containers): array { $normalisedInstances = []; foreach ($instances as $instance) { @@ -198,6 +359,7 @@ public static function compute(array $instances, array $containers): array 'volume' => $instance->item->dimensions->volumeString(), 'weight' => $instance->item->weight->ticks, 'shrinks' => self::occupiesLessThanItsBox($instance->item), + 'value' => $instance->item->value ?? 0, ]; } $normalisedContainers = []; @@ -213,7 +375,7 @@ public static function compute(array $instances, array $containers): array 'cost_minor' => $container->costMinor, ]; } - return self::fromNormalised($normalisedInstances, $normalisedContainers); + return [$normalisedInstances, $normalisedContainers]; } /** @@ -225,11 +387,28 @@ public static function compute(array $instances, array $containers): array * flag correctly for a `convex_hull` is asserted separately, in this engine's own tests, * so a port cannot pass the arithmetic check by copying a flag it never computes. * - * @param list $instances + * Each instance's `value` is not read here: only `objectiveVector`'s `maximum_value` key + * consumes it. + * + * @param list $instances * @param list $containers * @return array{int,int,int,int,int} */ public static function fromNormalised(array $instances, array $containers): array + { + return self::evaluate($instances, $containers)['vector']; + } + + /** + * `fromNormalised`'s vector, with the intermediates the objective-only keys reuse rather + * than recompute: the ascending volumes, the shrink flag, the floors and the volume + * capacity total (null when unbounded). + * + * @param list $instances + * @param list $containers + * @return array{vector:array{int,int,int,int,int},volumes:list,shrinks:bool,areas:list,capacity:?string} + */ + private static function evaluate(array $instances, array $containers): array { $volumes = []; $weights = []; @@ -273,13 +452,15 @@ public static function fromNormalised(array $instances, array $containers): arra $cost = self::costBound($costs, $quantities, $opened); $unused = self::unusedVolumeBound($volumes, $shrinks, $placed, $inner, $opened); $height = self::stackHeightBound($volumes, $shrinks, $placed, $areas, $heights, $opened); - return [ + $vector = [ self::guardOutput((string)$unpacked, 'unpacked count'), self::guardOutput((string)$opened, 'container count'), self::guardOutput((string)$cost, 'opening cost'), self::guardOutput((string)$unused, 'unused volume'), self::guardOutput((string)$height, 'stack height'), ]; + return ['vector' => $vector, 'volumes' => $volumes, 'shrinks' => $shrinks, + 'areas' => $areas, 'capacity' => $capacities['volume']]; } /** diff --git a/src/Algorithm/SolverOrchestrator.php b/src/Algorithm/SolverOrchestrator.php index 5c4e851..56e6fc8 100644 --- a/src/Algorithm/SolverOrchestrator.php +++ b/src/Algorithm/SolverOrchestrator.php @@ -9,7 +9,7 @@ use Packvium\Result\StartRecord; use Packvium\Support\{BigInt,ExactGeometry,ExactInteger,StableSorter}; use Packvium\Objective\{LandedCostSolutionScorer,ObjectiveRegistry}; -use Packvium\Algorithm\Internal\{ConcurrentStarts,ContainerPlanBeam,MadeToMeasureTrial,QualityStages}; +use Packvium\Algorithm\Internal\{ConcurrentStarts,ContainerPlanBeam,MadeToMeasureTrial,PalletTrial,QualityStages}; final class SolverOrchestrator { /** @@ -224,7 +224,7 @@ private function finishPortfolio(array $items,array $containers,Deadline $deadli */ private static function fitsAlone(Container $container,Dimensions $dimensions):bool { - return $container->isFlatBag()?FlatBag::fitsAlone($container->innerDimensions,$dimensions):$dimensions->fitsInside($container->innerDimensions); + return $container->isFlatBag()?FlatBag::fitsAlone($container->innerDimensions,$dimensions,$container->sideGussetTicks()):$dimensions->fitsInside($container->innerDimensions); } /** @param list $containers */ @@ -620,21 +620,31 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem /** * One container's trial for a round, and how many single-container solves it spent. A * declared container is one solve; a made-to-measure one runs the rung chain and returns - * its trial already fabricated. + * its trial already fabricated; a pallet's frame without fixed items packs its + * deck first. * * @param list $items * @return array{0:SingleContainerSolution,1:int} */ private function trial(SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array { - if($container->madeToMeasure===null)return [$solver->packOne($container,$sequence,$items,$config,$stats,$deadline),1]; - return MadeToMeasureTrial::madeToMeasureTrial($this->bridge(),$this->containerSelector,$solver,$container,$sequence,$items,$config,$stats,$deadline); + if($container->madeToMeasure!==null) + return MadeToMeasureTrial::madeToMeasureTrial($this->bridge(),$this->containerSelector,$solver,$container,$sequence,$items,$config,$stats,$deadline); + if($container->deck!==null&&$container->preloaded===[]) + return PalletTrial::palletTrial($this->bridge(),$solver,$container,$sequence,$items,$config,$stats,$deadline); + return [$solver->packOne($container,$sequence,$items,$config,$stats,$deadline),1]; } - /** A rung trial as the box cut for it: the achieved extent of its placements, envelope far faces with clearance, rounded up onto the machine grid (D14). O(p). */ - private static function fabricated(Container $declared,SingleContainerSolution $one):SingleContainerSolution + /** + * A rung trial as the box cut for it: the achieved extent of its placements, envelope far faces + * with clearance, rounded up onto the machine grid (D14); or, given `$rung`, the rung itself, + * which is already on the grid. O(p). + * + * @param array{0:int,1:int,2:int}|null $rung + */ + private static function fabricated(Container $declared,SingleContainerSolution $one,?array $rung=null):SingleContainerSolution { - $box=$declared->fabricate(FlatBag::extentOf($one->state->placements)); + $box=$declared->fabricate($rung??FlatBag::extentOf($one->state->placements)); return new SingleContainerSolution($one->state->withContainer($box),$one->unpacked,false,$one->timeLimitReached,false); } diff --git a/src/Algorithm/SupportCalculator.php b/src/Algorithm/SupportCalculator.php index 7d710f4..d61d057 100644 --- a/src/Algorithm/SupportCalculator.php +++ b/src/Algorithm/SupportCalculator.php @@ -2,15 +2,16 @@ declare(strict_types=1); namespace Packvium\Algorithm; use Packvium\Constraint\Internal\LoadSupportGraph; -use Packvium\Domain\{AxisAlignedBox,ItemInstance}; +use Packvium\Domain\{AxisAlignedBox,ItemInstance,PalletOverhang}; use Packvium\Support\{ExactGeometry,ExactInteger}; final class SupportCalculator { - /** Reported support fraction, from resting contact with other placements only. */ + /** Reported support fraction, from resting contact with other placements, or on the floor with a pallet's deck. */ public static function ratio(ContainerState $state,ItemInstance $item,Candidate $c):float { - if($c->point->z===0)return 1.0; $box=new AxisAlignedBox($c->point,$c->envelopeDimensions); + // A floor without a deck is whole support; deciding it here keeps `PalletOverhang` unloaded. + if($c->point->z===0)return $state->container->deck===null?1.0:PalletOverhang::floorSupportRatio($state->container->deck,$box); $support=LoadSupportGraph::candidateView($state->placements,$item,$box); return ExactInteger::ratio($support->supportingArea,ExactGeometry::baseArea($c->envelopeDimensions)); } diff --git a/src/Artifacts/ArtifactExports.php b/src/Artifacts/ArtifactExports.php index 9acc487..08c793e 100644 --- a/src/Artifacts/ArtifactExports.php +++ b/src/Artifacts/ArtifactExports.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Artifacts; +use Packvium\Support\CanonicalJson; use Packvium\Support\JsonValue; /** @@ -312,10 +313,18 @@ private static function orDash($value): string */ private static function successor($index): string { + if (self::isIntegralFloat($index)) { + return self::text($index); + } if (!\is_int($index)) { throw new OperationalArtifactException('invalid_value', 'a container_index is not an integer'); } - return (string) ($index + 1); + // Checked before the addition, which past PHP_INT_MAX would turn into a float: the + // number shown is the index plus one, so 2^53 - 1 is already one past the ceiling. + if ($index >= CanonicalJson::MAX_EXACT_MAGNITUDE) { + throw new OperationalArtifactException('number_out_of_range', "container index {$index} is beyond what every engine holds exactly"); + } + return self::text($index + 1); } // ----------------------------------------------------------------------------- helpers @@ -335,6 +344,12 @@ private static function text($value): string if (\is_string($value)) { return $value; } + // Beyond 2^53 - 1 JavaScript has already rounded the integer, so its decimal would + // differ; past PHP_INT_MAX json_decode has made it a float, but it is still a whole number. + if (self::isIntegralFloat($value) + || (\is_int($value) && ($value > CanonicalJson::MAX_EXACT_MAGNITUDE || $value < -CanonicalJson::MAX_EXACT_MAGNITUDE))) { + throw new OperationalArtifactException('number_out_of_range', \json_encode($value) . ' is beyond what every engine holds exactly'); + } if (\is_int($value)) { return (string) $value; } @@ -342,6 +357,17 @@ private static function text($value): string throw new OperationalArtifactException('invalid_value', "a {$type} has no single rendering in a work order"); } + /** + * A whole number json_decode could only hold as a float, past PHP_INT_MAX. + * + * @param mixed $value + */ + private static function isIntegralFloat($value): bool + { + return \is_float($value) && \is_finite($value) && \floor($value) === $value + && \abs($value) > CanonicalJson::MAX_EXACT_MAGNITUDE; + } + /** * Python's truthiness for a JSON value: null, false, zero, an empty string, an empty array * and an empty object are false. PHP's own rule differs at `"0"`. diff --git a/src/Artifacts/OperationalArtifact.php b/src/Artifacts/OperationalArtifact.php index 5c8b0f1..7561c3c 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.9.0'; + public const SUITE_VERSION = '1.10.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']; @@ -168,12 +168,44 @@ public static function canonicalJson($artifact): string private static function plan($request, $result, array $loadingOrders): array { try { - return Plan::build($request, $result, $loadingOrders); + return Plan::build($request, self::withoutPlacementIds($result), $loadingOrders); } catch (ExecutionPlanException $error) { throw new OperationalArtifactException('invalid_plan_input', $error->getMessage(), $error); } } + /** + * The result as the v1 artifact reads it: every placement without its 1.10 `placement_id`. + * + * v1 is closed, and its embedded plan and placement references predate the id, so a plan + * built from a 1.10 result would otherwise gain a field inside a closed document. The id is + * recoverable from what v1 does carry: the canonical JSON of the result's + * `containers[container_index].id` and the reference's `position_ticks`, `item_type` and + * `orientation` (docs/OPERATIONAL-ARTIFACTS.md). Read after `requireObjects`, so every + * entry is an object; copies only what it changes, O(P). + * + * @param array|\stdClass $result + * @return array + */ + private static function withoutPlacementIds($result): array + { + $containers = []; + foreach (self::listOf(JsonValue::get($result, 'containers'), 'result.containers') as $index => $container) { + $placements = []; + foreach (self::placements($index, $container) as $placement) { + $placement = (array) $placement; + unset($placement['placement_id']); + $placements[] = $placement; + } + $container = (array) $container; + $container['placements'] = $placements; + $containers[] = $container; + } + $stripped = (array) $result; + $stripped['containers'] = $containers; + return $stripped; + } + // -------------------------------------------------------------------------- provenance /** diff --git a/src/Constraint/ContactGraph.php b/src/Constraint/ContactGraph.php index 1b5dd82..cc497f0 100644 --- a/src/Constraint/ContactGraph.php +++ b/src/Constraint/ContactGraph.php @@ -260,7 +260,18 @@ private function matches(array $buckets, array &$cache, int $plane, AxisAlignedB if (!isset($buckets[$plane])) { return []; } - $level = $cache[$plane] ??= new ContactLevelIndex($this->cell, $buckets[$plane]); + $entries = $buckets[$plane]; + if (count($entries) <= 32) { + $matches = []; + foreach ($entries as [$otherIndex, $other]) { + $area = ExactGeometry::overlapAreaXY($other, $box); + if ($area > 0) { + $matches[] = [$otherIndex, $area]; + } + } + return $matches; + } + $level = $cache[$plane] ??= new ContactLevelIndex($this->cell, $entries); $matches = []; foreach ($level->near($box) as [$otherIndex, $other]) { $area = ExactGeometry::overlapAreaXY($other, $box); diff --git a/src/Constraint/Internal/LoadSupportGraph.php b/src/Constraint/Internal/LoadSupportGraph.php index 2a209dd..57ff677 100644 --- a/src/Constraint/Internal/LoadSupportGraph.php +++ b/src/Constraint/Internal/LoadSupportGraph.php @@ -29,6 +29,10 @@ final class LoadSupportGraph private ?array $descending=null; /** @var list|null */ private ?array $priorDescending=null; + /** @var array>|null */ + private ?array $planeByTop=null; + /** @var array>|null */ + private ?array $planeByBottom=null; /** @var list|null */ private static ?array $cachedPlanePlacements=null; /** @var array> */ @@ -129,6 +133,8 @@ public function withUnit(LoadUnit $unit,int $cellHint=1):self $graph=clone $this; $graph->descending=null; $graph->priorDescending=$this->descendingIndices(); + $graph->planeByTop=null; + $graph->planeByBottom=null; $graph->face=$this->face->withBox($unit->box); $graph->units[]=$unit; // Without nesting this graph *is* the face graph, so read the edges straight off @@ -137,6 +143,55 @@ public function withUnit(LoadUnit $unit,int $cellHint=1):self return $graph; } + public function isNested():bool{return $this->nested;} + + /** @return list */ + public function contactsBelow(AxisAlignedBox $box):array + { + if($this->planeByTop===null)$this->buildPlaneExtents(); + $entries=$this->planeByTop[$box->origin->z]??[]; + if($entries===[])return []; + $bx1=$box->origin->x;$by1=$box->origin->y;$bx2=$box->x2();$by2=$box->y2(); + $out=[]; + foreach($entries as [$otherIndex,$ox1,$oy1,$ox2,$oy2]){ + $dx=($bx2<$ox2?$bx2:$ox2)-($bx1>$ox1?$bx1:$ox1); + if($dx<=0)continue; + $dy=($by2<$oy2?$by2:$oy2)-($by1>$oy1?$by1:$oy1); + if($dy>0)$out[]=new ContactEdge($otherIndex,ExactInteger::mul($dx,$dy)); + } + return $out; + } + + /** @return list */ + public function contactsAbove(AxisAlignedBox $box):array + { + if($this->planeByBottom===null)$this->buildPlaneExtents(); + $entries=$this->planeByBottom[$box->z2()]??[]; + if($entries===[])return []; + $bx1=$box->origin->x;$by1=$box->origin->y;$bx2=$box->x2();$by2=$box->y2(); + $out=[]; + foreach($entries as [$otherIndex,$ox1,$oy1,$ox2,$oy2]){ + $dx=($bx2<$ox2?$bx2:$ox2)-($bx1>$ox1?$bx1:$ox1); + if($dx<=0)continue; + $dy=($by2<$oy2?$by2:$oy2)-($by1>$oy1?$by1:$oy1); + if($dy>0)$out[]=new ContactEdge($otherIndex,ExactInteger::mul($dx,$dy)); + } + return $out; + } + + private function buildPlaneExtents():void + { + $byTop=[];$byBottom=[]; + foreach($this->units as $index=>$unit){ + $b=$unit->box; + $entry=[$index,$b->origin->x,$b->origin->y,$b->x2(),$b->y2()]; + $byTop[$b->z2()][]=$entry; + $byBottom[$b->origin->z][]=$entry; + } + $this->planeByTop=$byTop; + $this->planeByBottom=$byBottom; + } + /** @return list Canonical load order, shared across candidate siblings. */ public function descendingIndices():array { @@ -196,7 +251,7 @@ public function nonStackableFailure(array $placements,ItemInstance $item,int $ca } /** Why `$lower` refuses an item of `$upperGroup` resting directly on it, or null. O(1). */ - private static function stackingRefusal(Item $lower,?string $upperGroup):?string + public static function stackingRefusal(Item $lower,?string $upperGroup):?string { if(!$lower->stackable)return 'non_stackable'; if(!$lower->acceptsStackingGroup($upperGroup))return 'stacking_group_incompatible'; diff --git a/src/Constraint/Internal/PlacedSupportBase.php b/src/Constraint/Internal/PlacedSupportBase.php index c84d7a0..22b8e64 100644 --- a/src/Constraint/Internal/PlacedSupportBase.php +++ b/src/Constraint/Internal/PlacedSupportBase.php @@ -1,8 +1,9 @@ */ private array $baseUnits=[]; private int $hint=1; - - /** - * `$placements`' units and graph with `$unit` appended at the last index. - * - * @param list $placements - * @return array{0:list,1:LoadSupportGraph} - */ - public function withCandidate(array $placements,LoadUnit $unit):array - { - $box=$unit->box; - $base=$this->baseFor($placements,max($box->x2()-$box->origin->x,$box->y2()-$box->origin->y)); - $units=$this->baseUnits; - $units[]=$unit; - return [$units,$base->withUnit($unit,$this->hint)]; - } + /** @var list|null */ + private ?array $baseLoads=null; + /** @var list|null */ + private ?array $baseStackedCounts=null; + private bool $baseHasMaxTop=false; + private bool $baseHasCrush=false; + private bool $baseHasMaxStacked=false; + private ?bool $baseBearingHolds=null; + private ?int $baseDensityChecked=null; + private ?bool $baseDensityHolds=null; + /** @var list|null */ + private ?array $baseStops=null; + private bool $baseRouted=false; + /** @var list|null */ + private ?array $baseMaxStopAbove=null; + private ?bool $baseRouteHolds=null; /** * The support graph over `$placements` alone, rebuilt only when it cannot serve. @@ -56,8 +58,373 @@ private function baseFor(array $placements,int $footprint):LoadSupportGraph if($same&&$footprint<=$this->hint)return $this->base; $this->hint=max($same?$this->hint:1,$footprint); $this->placements=$placements; - $this->baseUnits=LoadCalculator::units($placements); + if(!$same)$this->baseUnits=LoadCalculator::units($placements); $this->base=new LoadSupportGraph($this->baseUnits,$this->hint); + if(!$same){ + $this->baseLoads=null; + $this->baseStackedCounts=null; + $this->baseBearingHolds=null; + $this->baseDensityChecked=null; + $this->baseDensityHolds=null; + $this->baseStops=null; + $this->baseRouted=false; + $this->baseMaxStopAbove=null; + $this->baseRouteHolds=null; + } return $this->base; } + + private function settleBearing(?int $densityLimit):bool + { + assert($this->base!==null); + $baseUnits=$this->baseUnits; + if($this->baseBearingHolds===null){ + $hasMaxTop=false;$hasCrush=false;$hasMaxStacked=false; + foreach($baseUnits as $u){ + if($u->maxTopLoadTicks!==null)$hasMaxTop=true; + if($u->maxCompressionPressureKpa!==null)$hasCrush=true; + if($u->maxStackedItems!==null)$hasMaxStacked=true; + } + $this->baseHasMaxTop=$hasMaxTop; + $this->baseHasCrush=$hasCrush; + $this->baseHasMaxStacked=$hasMaxStacked; + $analysis=new LoadAnalysis($baseUnits,$this->base); + $loads=$analysis->topLoads(); + $this->baseLoads=$loads; + $holds=$analysis->overloaded()===null&&$analysis->crushed()===null; + if($hasMaxStacked){ + $counts=$analysis->stackedCounts(); + $this->baseStackedCounts=$counts; + if($holds){ + foreach($baseUnits as $idx=>$u) + if($u->maxStackedItems!==null&&$counts[$idx]>$u->maxStackedItems){$holds=false;break;} + } + } + $this->baseBearingHolds=$holds; + } + if(!$this->baseBearingHolds)return false; + if($densityLimit===null)return true; + if($this->baseDensityChecked!==$densityLimit||$this->baseDensityHolds===null){ + assert($this->baseLoads!==null); + $this->baseDensityChecked=$densityLimit; + $holds=true; + foreach($baseUnits as $idx=>$u){ + $total=$u->weightTicks+$this->baseLoads[$idx]; + $bearing=BigInt::multiply($total,LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($u->box->dimensions)); + if(BigInt::compare($bearing,$allowed)>0){$holds=false;break;} + } + $this->baseDensityHolds=$holds; + } + return $this->baseDensityHolds; + } + + public function evaluateTopLoad(ConstraintContext $c):ConstraintResult + { + $candidate=$c->envelopeBox(); + $item=$c->item->item; + $footprint=max($candidate->x2()-$candidate->origin->x,$candidate->y2()-$candidate->origin->y); + $base=$this->baseFor($c->placements,$footprint); + $baseUnits=$this->baseUnits; + $densityLimit=$c->container->maxStackDensity?->ticks; + if(!$base->isNested()&&$item->nestingHeight===null&&$this->settleBearing($densityLimit)){ + $below=$base->contactsBelow($candidate); + $above=$base->contactsAbove($candidate); + $upperGroup=$item->stackingGroup; + $placements=$c->placements; + foreach($below as $edge){ + $lower=$placements[$edge->index]->instance->item; + $code=LoadSupportGraph::stackingRefusal($lower,$upperGroup); + if($code!==null)return ConstraintResult::reject($code,$lower->id); + } + if(!$item->stackable||$item->acceptsStackingGroups!==[]){ + foreach($above as $edge){ + $code=LoadSupportGraph::stackingRefusal($item,$placements[$edge->index]->instance->item->stackingGroup); + if($code!==null)return ConstraintResult::reject($code,$item->id); + } + } + $hasMaxTop=$this->baseHasMaxTop||$item->maxTopLoad!==null; + $hasCrush=$this->baseHasCrush||$item->maxCompressionPressureKpa!==null; + $hasMaxStacked=$this->baseHasMaxStacked||$item->maxStackedItems!==null; + if(!$hasMaxTop&&!$hasCrush&&!$hasMaxStacked&&$densityLimit===null)return ConstraintResult::allow(); + if($below===[]&&$above===[]){ + if($densityLimit!==null){ + $bearing=BigInt::multiply($c->item->weight()->ticks,LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($candidate->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$c->item->id()); + } + return ConstraintResult::allow(); + } + if($above===[]){ + $baseLoads=$this->baseLoads; + assert($baseLoads!==null); + $allFloor=true; + foreach($below as $edge)if($base->supporters($edge->index)!==[]){$allFloor=false;break;} + if($allFloor){ + $downward=$c->item->weight()->ticks; + $totalArea=0; + foreach($below as $edge)$totalArea=ExactInteger::add($totalArea,$edge->area); + $assigned=0;$lastPos=count($below)-1; + $shares=[]; + foreach($below as $pos=>$edge){ + if($totalArea!==0&&$downward>0){ + $share=$pos===$lastPos?$downward-$assigned:ExactInteger::mulDiv($downward,$edge->area,$totalArea); + $assigned+=$share; + }else $share=0; + $shares[]=$share; + } + if($this->baseHasMaxTop){ + foreach($below as $pos=>$edge){ + $u=$edge->index; + $limitTicks=$baseUnits[$u]->maxTopLoadTicks; + if($limitTicks!==null&&$baseLoads[$u]+$shares[$pos]>$limitTicks) + return ConstraintResult::reject('top_load_exceeded',$baseUnits[$u]->label); + } + } + if($this->baseHasCrush){ + foreach($below as $pos=>$edge){ + $unitU=$baseUnits[$edge->index]; + $limitKpa=$unitU->maxCompressionPressureKpa; + if($limitKpa===null)continue; + $boxU=$unitU->box; + $fp=$unitU->footprintTicks2??ExactInteger::mul($boxU->x2()-$boxU->origin->x,$boxU->y2()-$boxU->origin->y); + if(Compression::exceeds(Compression::pressure($baseLoads[$edge->index]+$shares[$pos],$fp),$limitKpa)) + return ConstraintResult::reject('crush_violation',$unitU->label); + } + } + if($this->baseHasMaxStacked){ + assert($this->baseStackedCounts!==null); + foreach($below as $edge){ + $u=$edge->index; + $maxStacked=$baseUnits[$u]->maxStackedItems; + if($maxStacked!==null&&$this->baseStackedCounts[$u]+1>$maxStacked) + return ConstraintResult::reject('stacked_item_limit_exceeded',$baseUnits[$u]->label); + } + } + if($densityLimit!==null){ + foreach($below as $pos=>$edge){ + $u=$edge->index; + $unitU=$baseUnits[$u]; + $bearing=BigInt::multiply($unitU->weightTicks+$baseLoads[$u]+$shares[$pos],LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($unitU->box->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$unitU->label); + } + $bearing=BigInt::multiply($downward,LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($candidate->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$c->item->id()); + } + return ConstraintResult::allow(); + } + + $pending=[];$seenAffected=[]; + foreach($below as $edge){$pending[]=$edge->index;$seenAffected[$edge->index]=true;} + $idx=0; + while($idxsupporters($u) as $edge){ + if(!isset($seenAffected[$edge->index])){ + $seenAffected[$edge->index]=true; + $pending[]=$edge->index; + } + } + } + $deltaLoads=[]; + if($hasMaxTop||$hasCrush||$densityLimit!==null){ + $downward=$c->item->weight()->ticks; + $totalArea=0; + foreach($below as $edge)$totalArea=ExactInteger::add($totalArea,$edge->area); + if($totalArea!==0&&$downward>0){ + $assigned=0;$lastPos=count($below)-1; + foreach($below as $pos=>$edge){ + $share=$pos===$lastPos?$downward-$assigned:ExactInteger::mulDiv($downward,$edge->area,$totalArea); + $assigned+=$share; + $deltaLoads[$edge->index]=($deltaLoads[$edge->index]??0)+$share; + } + } + $order=array_keys($seenAffected); + usort($order,static fn(int $a,int $b):int=>[-$baseUnits[$a]->box->z2(),-$baseUnits[$a]->box->origin->z,$a]<=>[-$baseUnits[$b]->box->z2(),-$baseUnits[$b]->box->origin->z,$b]); + foreach($order as $u){ + $dLoad=$deltaLoads[$u]??0; + if($dLoad===0)continue; + $supports=$base->supporters($u); + if($supports===[])continue; + $totalArea=0; + foreach($supports as $edge)$totalArea=ExactInteger::add($totalArea,$edge->area); + if($totalArea===0)continue; + $oldDownward=$baseUnits[$u]->weightTicks+$baseLoads[$u]; + $newDownward=$oldDownward+$dLoad; + $oldAssigned=0;$newAssigned=0;$lastPos=count($supports)-1; + foreach($supports as $pos=>$edge){ + if($pos===$lastPos){ + $oldShare=$oldDownward-$oldAssigned; + $newShare=$newDownward-$newAssigned; + }else{ + $oldShare=ExactInteger::mulDiv($oldDownward,$edge->area,$totalArea); + $newShare=ExactInteger::mulDiv($newDownward,$edge->area,$totalArea); + $oldAssigned+=$oldShare; + $newAssigned+=$newShare; + } + $diff=$newShare-$oldShare; + if($diff!==0)$deltaLoads[$edge->index]=($deltaLoads[$edge->index]??0)+$diff; + } + } + } + $ascending=array_keys($seenAffected); + sort($ascending); + if($this->baseHasMaxTop){ + foreach($ascending as $u){ + $limitTicks=$baseUnits[$u]->maxTopLoadTicks; + if($limitTicks!==null&&$baseLoads[$u]+($deltaLoads[$u]??0)>$limitTicks) + return ConstraintResult::reject('top_load_exceeded',$baseUnits[$u]->label); + } + } + if($this->baseHasCrush){ + foreach($ascending as $u){ + $unitU=$baseUnits[$u]; + $limitKpa=$unitU->maxCompressionPressureKpa; + if($limitKpa===null)continue; + $boxU=$unitU->box; + $fp=$unitU->footprintTicks2??ExactInteger::mul($boxU->x2()-$boxU->origin->x,$boxU->y2()-$boxU->origin->y); + if(Compression::exceeds(Compression::pressure($baseLoads[$u]+($deltaLoads[$u]??0),$fp),$limitKpa)) + return ConstraintResult::reject('crush_violation',$unitU->label); + } + } + if($this->baseHasMaxStacked){ + assert($this->baseStackedCounts!==null); + foreach($ascending as $u){ + $maxStacked=$baseUnits[$u]->maxStackedItems; + if($maxStacked!==null&&$this->baseStackedCounts[$u]+1>$maxStacked) + return ConstraintResult::reject('stacked_item_limit_exceeded',$baseUnits[$u]->label); + } + } + if($densityLimit!==null){ + foreach($ascending as $u){ + $unitU=$baseUnits[$u]; + $bearing=BigInt::multiply($unitU->weightTicks+$baseLoads[$u]+($deltaLoads[$u]??0),LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($unitU->box->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$unitU->label); + } + $bearing=BigInt::multiply($c->item->weight()->ticks,LoadCalculator::SQUARE_METRE_TICKS); + $allowed=BigInt::multiply($densityLimit,ExactGeometry::baseArea($candidate->dimensions)); + if(BigInt::compare($bearing,$allowed)>0)return ConstraintResult::reject('stack_density_exceeded',$c->item->id()); + } + return ConstraintResult::allow(); + } + } + + $unit=new LoadUnit( + $candidate,$c->item->weight()->ticks,$item->maxTopLoad?->ticks,$item->maxStackedItems,$c->item->id(), + $item->nestingHeight===null?null:$item->id,$item->nestingHeight?->ticks, + $item->compressionRatioPpm,$item->maxCompressionPressureKpa, + ExactInteger::mul($c->dimensions->length->ticks,$c->dimensions->width->ticks), + ); + $units=$baseUnits; + $units[]=$unit; + $graph=$base->withUnit($unit,$this->hint); + $nonStackable=$graph->nonStackableFailure($c->placements,$c->item,count($units)-1); + if($nonStackable!==null)return ConstraintResult::reject($nonStackable[0],$nonStackable[1]); + $analysis=new LoadAnalysis($units,$graph); + $failure=$analysis->overloaded() + ??$analysis->crushed() + ??$analysis->stackLimitExceeded() + ??$analysis->stackDensityExceeded($densityLimit); + return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); + } + + /** @param list $placements */ + private function settleRoute(array $placements):void + { + assert($this->base!==null); + if($this->baseStops!==null)return; + $stops=[];$routed=false; + foreach($placements as $p){ + $stop=$p->instance->item->stopIndex===null?INF:(float)$p->instance->item->stopIndex; + if($stop!==INF)$routed=true; + $stops[]=$stop; + } + $this->baseStops=$stops; + $this->baseRouted=$routed; + $count=count($stops); + $maxStopAbove=$count===0?[]:array_fill(0,$count,-INF); + if($routed&&$count>0){ + foreach($this->base->descendingIndices() as $index){ + $best=-INF; + foreach($this->base->children($index) as $child){ + $childStop=$stops[$child]; + if($childStop>$best)$best=$childStop; + $childAbove=$maxStopAbove[$child]; + if($childAbove>$best)$best=$childAbove; + } + $maxStopAbove[$index]=$best; + } + $holds=true; + foreach($stops as $index=>$stop) + if($maxStopAbove[$index]>$stop){$holds=false;break;} + $this->baseRouteHolds=$holds; + }else{ + $this->baseRouteHolds=true; + } + $this->baseMaxStopAbove=$maxStopAbove; + } + + public function evaluateRouteOrder(ConstraintContext $c):ConstraintResult + { + $box=$c->envelopeBox(); + $footprint=max($box->x2()-$box->origin->x,$box->y2()-$box->origin->y); + $base=$this->baseFor($c->placements,$footprint); + $baseUnits=$this->baseUnits; + $this->settleRoute($c->placements); + assert($this->baseStops!==null&&$this->baseMaxStopAbove!==null); + $candidateStop=$c->item->item->stopIndex===null?INF:(float)$c->item->item->stopIndex; + if(!$this->baseRouted&&$candidateStop===INF)return ConstraintResult::allow(); + if(!$base->isNested()&&$c->item->item->nestingHeight===null&&$this->baseRouteHolds){ + $below=$base->contactsBelow($box); + $above=$base->contactsAbove($box); + if($below===[]&&$above===[])return ConstraintResult::allow(); + $baseStops=$this->baseStops; + $baseMaxAbove=$this->baseMaxStopAbove; + $violated=false; + foreach($below as $edge){ + if($candidateStop>$baseStops[$edge->index]){$violated=true;break;} + } + if(!$violated){ + foreach($above as $edge){ + $ch=$edge->index; + if($baseStops[$ch]>$candidateStop||$baseMaxAbove[$ch]>$candidateStop){$violated=true;break;} + } + } + if(!$violated)return ConstraintResult::allow(); + if($above===[]){ + $pending=[];$seen=[]; + foreach($below as $edge){$pending[]=$edge->index;$seen[$edge->index]=true;} + $idx=0;$offender=null; + while($idxsupporters($u) as $edge){ + if(!isset($seen[$edge->index])){ + $seen[$edge->index]=true; + $pending[]=$edge->index; + } + } + } + assert($offender!==null); + return ConstraintResult::reject( + 'unloading_order_violation', + $baseUnits[$offender]->label.' blocked by '.$c->item->id(), + ); + } + } + $candidate=new LoadUnit( + $box,$c->item->weight()->ticks,null,null,$c->item->id(), + $c->item->item->nestingHeight===null?null:$c->item->item->id,$c->item->item->nestingHeight?->ticks, + ); + $stops=$this->baseStops; + $stops[]=$candidateStop; + $units=$baseUnits; + $units[]=$candidate; + $graph=$base->withUnit($candidate,$this->hint); + $failure=(new LoadAnalysis($units,$graph))->routeOrderViolated($stops); + return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); + } } diff --git a/src/Constraint/RouteOrderConstraint.php b/src/Constraint/RouteOrderConstraint.php index 08af4e0..09da42e 100644 --- a/src/Constraint/RouteOrderConstraint.php +++ b/src/Constraint/RouteOrderConstraint.php @@ -19,16 +19,6 @@ final class RouteOrderConstraint implements PlacementConstraint public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->routeSensitive)return ConstraintResult::allow(); - $candidate=new LoadUnit( - $c->envelopeBox(),$c->item->weight()->ticks,null,null,$c->item->id(), - $c->item->item->nestingHeight===null?null:$c->item->item->id,$c->item->item->nestingHeight?->ticks, - ); - $stops=[]; - foreach($c->placements as $p)$stops[]=$p->instance->item->stopIndex===null?INF:(float)$p->instance->item->stopIndex; - $stops[]=$c->item->item->stopIndex===null?INF:(float)$c->item->item->stopIndex; - if(!LoadAnalysis::routed($stops))return ConstraintResult::allow(); - [$units,$graph]=($this->support??=new PlacedSupportBase())->withCandidate($c->placements,$candidate); - $failure=(new LoadAnalysis($units,$graph))->routeOrderViolated($stops); - return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); + return ($this->support??=new PlacedSupportBase())->evaluateRouteOrder($c); } } diff --git a/src/Constraint/SupportConstraint.php b/src/Constraint/SupportConstraint.php index 0910cd2..11d2872 100644 --- a/src/Constraint/SupportConstraint.php +++ b/src/Constraint/SupportConstraint.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Constraint\Internal\LoadSupportGraph; +use Packvium\Domain\{AxisAlignedBox,PalletOverhang}; use Packvium\Support\{ExactGeometry,ExactInteger}; /** * Support ratios arrive as floats from the public API but must never decide feasibility @@ -34,7 +35,7 @@ public function canReject(\Packvium\Domain\ItemInstance $item):bool public function evaluate(ConstraintContext $c):ConstraintResult { - if($c->point->z===0)return ConstraintResult::allow(); + if($c->point->z===0)return $this->onFloor($c); if(!$this->canReject($c->item))return ConstraintResult::allow(); $box=$c->envelopeBox(); $support=LoadSupportGraph::candidateView($c->placements,$c->item,$box); @@ -49,9 +50,27 @@ public function evaluate(ConstraintContext $c):ConstraintResult if($rule==='multiple'&&$count<2) return ConstraintResult::reject('ground_contact_violation',"multiple: rests on {$count} item(s)"); } + return $this->ratioAndCentroid($c,$box,$supporters,$support->supportingArea); + } + + /** + * A floor is whole support unless it is a pallet deck: then the deck is the one + * supporter, judged by the same ratio and centre-of-gravity rule. The ground contact rules + * name supporting items, and the floor is none, so they do not apply. + */ + private function onFloor(ConstraintContext $c):ConstraintResult + { + $deck=$c->container->deck; + if($deck===null)return ConstraintResult::allow(); + $box=$c->envelopeBox(); + return $this->ratioAndCentroid($c,$box,[$deck->asBox()],PalletOverhang::deckContactArea($deck,$box)); + } + + /** @param list $supporters */ + private function ratioAndCentroid(ConstraintContext $c,AxisAlignedBox $box,array $supporters,int|string $area):ConstraintResult + { $required=max($this->globalMinimum,$c->item->item->minimumSupportRatio); if($required<=0)return ConstraintResult::allow(); - $area=$support->supportingArea; $baseArea=ExactGeometry::baseArea($c->envelopeDimensions); if(ExactInteger::compare($area,self::exactRequiredArea($baseArea,self::scaled($required)))<0) return ConstraintResult::reject('insufficient_support',sprintf('%s/%s < %.6f',$area,$baseArea,$required)); diff --git a/src/Constraint/TopLoadConstraint.php b/src/Constraint/TopLoadConstraint.php index 35d65d3..32aa895 100644 --- a/src/Constraint/TopLoadConstraint.php +++ b/src/Constraint/TopLoadConstraint.php @@ -19,22 +19,6 @@ final class TopLoadConstraint implements PlacementConstraint public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->stackSensitive)return ConstraintResult::allow(); - $item=$c->item->item; - $unit=new LoadUnit( - $c->envelopeBox(),$c->item->weight()->ticks,$item->maxTopLoad?->ticks,$item->maxStackedItems,$c->item->id(), - $item->nestingHeight===null?null:$item->id,$item->nestingHeight?->ticks, - $item->compressionRatioPpm,$item->maxCompressionPressureKpa, - ExactInteger::mul($c->dimensions->length->ticks,$c->dimensions->width->ticks), - ); - [$units,$graph]=($this->support??=new PlacedSupportBase())->withCandidate($c->placements,$unit); - $nonStackable=$graph->nonStackableFailure($c->placements,$c->item,count($units)-1); - if($nonStackable!==null)return ConstraintResult::reject($nonStackable[0],$nonStackable[1]); - $densityLimit=$c->container->maxStackDensity?->ticks; - $analysis=new LoadAnalysis($units,$graph); - $failure=$analysis->overloaded() - ??$analysis->crushed() - ??$analysis->stackLimitExceeded() - ??$analysis->stackDensityExceeded($densityLimit); - return $failure===null?ConstraintResult::allow():ConstraintResult::reject($failure[0],$failure[1]); + return ($this->support??=new PlacedSupportBase())->evaluateTopLoad($c); } } diff --git a/src/Domain/Container.php b/src/Domain/Container.php index 9dd8df7..544a861 100644 --- a/src/Domain/Container.php +++ b/src/Domain/Container.php @@ -32,20 +32,40 @@ * carries the container with this emptied again (docs/PLAN-REVISIONS.md). * * `$deformableBoundary`: `'flat_bag'` makes this a flexible bag whose package conforms to its - * contents (`FlatBag`); null is a rigid container. + * contents (`FlatBag`); `'gusseted_bag'` is one whose width girth is widened by + * `$sideGussetDepth`, which that kind requires and every other container refuses (1.10). + * null is a rigid container. + * + * `$palletOverhangLimit`: how far a load may pass this pallet deck's edges (, + * `PalletOverhang`). `$deck`: the deck inside a solving frame, set only by + * `PalletOverhang::solvingFrame`, which widens `$innerDimensions` to the frame and drops the + * limit. * * @param list $obstacles @param list $tags @param array $tagLimits @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections @param list $preloaded */ - public function __construct(public string $id,public Dimensions $innerDimensions,public ?Dimensions $outerDimensions=null,public Weight $tareWeight=new Weight(0),public ?Weight $maxPayload=null,public int $costMinor=0,public ?int $quantity=null,public array $obstacles=[],public array $tags=[],public ?int $maxItems=null,public array $metadata=[],public float $voidFillReserveRatio=0.0,public array $tagLimits=[],public ?Weight $maxStackDensity=null,public ?array $axles=null,public ?RateTable $rateTable=null,array $accessDirections=[],public array $preloaded=[],public ?string $deformableBoundary=null,public ?MadeToMeasure $madeToMeasure=null) - {if($id==='')throw new ObjectRefusal('invalid_value','Container id is required');$madeToMeasure?->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]);if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio);if($quantity!==null&&$quantity<=0)throw new ObjectRefusal('below_minimum','Container quantity must be positive');if($costMinor<0)throw new ObjectRefusal('below_minimum','Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new ObjectRefusal('below_minimum','Container max_items must be at least 1');if(!($voidFillReserveRatio>=0&&$voidFillReserveRatio<=1))throw ObjectRefusal::ratio($voidFillReserveRatio,'void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new ObjectRefusal('below_minimum','tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new ObjectRefusal('invalid_value','Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new ObjectRefusal('invalid_value',"Obstacle {$o->id} lies outside container"); + public function __construct(public string $id,public Dimensions $innerDimensions,public ?Dimensions $outerDimensions=null,public Weight $tareWeight=new Weight(0),public ?Weight $maxPayload=null,public int $costMinor=0,public ?int $quantity=null,public array $obstacles=[],public array $tags=[],public ?int $maxItems=null,public array $metadata=[],public float $voidFillReserveRatio=0.0,public array $tagLimits=[],public ?Weight $maxStackDensity=null,public ?array $axles=null,public ?RateTable $rateTable=null,array $accessDirections=[],public array $preloaded=[],public ?string $deformableBoundary=null,public ?MadeToMeasure $madeToMeasure=null,public ?OverhangLimit $palletOverhangLimit=null,public ?Deck $deck=null,public ?Length $sideGussetDepth=null) + {if($id==='')throw new ObjectRefusal('invalid_value','Container id is required');$madeToMeasure?->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]);if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$innerDimensions,$sideGussetDepth,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio,$palletOverhangLimit);elseif($sideGussetDepth!==null)throw new ObjectRefusal('not_allowed','side_gusset_depth requires deformable_boundary gusseted_bag');if($palletOverhangLimit!==null)self::requirePalletFields($obstacles,$axles,$accessDirections,$voidFillReserveRatio,$madeToMeasure);if($quantity!==null&&$quantity<=0)throw new ObjectRefusal('below_minimum','Container quantity must be positive');if($costMinor<0)throw new ObjectRefusal('below_minimum','Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new ObjectRefusal('below_minimum','Container max_items must be at least 1');if(!($voidFillReserveRatio>=0&&$voidFillReserveRatio<=1))throw ObjectRefusal::ratio($voidFillReserveRatio,'void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new ObjectRefusal('below_minimum','tag_limits must be at least 1');if($outerDimensions!==null&&!self::declaredInnerOf($innerDimensions,$deck)->fitsInside($outerDimensions))throw new ObjectRefusal('invalid_value','Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new ObjectRefusal('invalid_value',"Obstacle {$o->id} lies outside container"); if($axles!==null){[$front,$rear]=$axles;if($front->position->ticks>=$rear->position->ticks)throw new ObjectRefusal('invalid_value','The front axle must be strictly nearer the origin than the rear axle');if($front->position->ticks<0||$rear->position->ticks>$innerDimensions->length->ticks)throw new ObjectRefusal('invalid_value',"Axle positions must lie within the container's length");} foreach($accessDirections as $direction)if(!in_array($direction,SweptRegion::ALL_DIRECTIONS,true))throw new InvalidArgumentException("unknown movement direction {$direction}"); // Deduplicated into the canonical order rather than kept as given: two callers // naming the same doors in a different order must search identically. $this->accessDirections=$accessDirections===[]?[]:array_values(array_filter(SweptRegion::ALL_DIRECTIONS,static fn(string $d):bool=>in_array($d,$accessDirections,true)));} /** The same container holding `$placements` before search. @param list $placements */ - public function withPreloaded(array $placements):self{return new self($this->id,$this->innerDimensions,$this->outerDimensions,$this->tareWeight,$this->maxPayload,$this->costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$placements,$this->deformableBoundary,$this->madeToMeasure);} + public function withPreloaded(array $placements):self{return new self($this->id,$this->innerDimensions,$this->outerDimensions,$this->tareWeight,$this->maxPayload,$this->costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$placements,$this->deformableBoundary,$this->madeToMeasure,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth);} public function isFlatBag():bool{return $this->deformableBoundary!==null;} + /** The side gusset depth G in ticks; 0 for a flat bag and every rigid container. */ + public function sideGussetTicks():int{return $this->sideGussetDepth===null?0:$this->sideGussetDepth->ticks;} + /** + * The same container packed in `$inner` with `$deck` as its only weight-bearing floor, and + * no overhang limit: how `PalletOverhang` builds a pallet's solving frame and its deck rung + *. A frame states no limit, so it is never widened twice. O(1). + * + * @internal + */ + public function framed(Dimensions $inner,?Deck $deck):self{return new self($this->id,$inner,$this->outerDimensions,$this->tareWeight,$this->maxPayload,$this->costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure,null,$deck,$this->sideGussetDepth);} + /** The inner size the caller declared: a solving frame's deck at its height, else `innerDimensions`. */ + public function declaredInner():Dimensions{return self::declaredInnerOf($this->innerDimensions,$this->deck);} + private static function declaredInnerOf(Dimensions $inner,?Deck $deck):Dimensions{return $deck===null?$inner:new Dimensions(new Length($deck->length),new Length($deck->width),$inner->height);} /** The declared container solved inside `$rung`: same id, everything else unchanged. @param array{0:int,1:int,2:int} $rung */ public function withEnvelope(array $rung):self{return $this->resized(self::dimensionsOf($rung),null,$this->costMinor,$this->tareWeight);} /** @@ -68,7 +88,7 @@ public function fabricate(array $achieved):self } return $this->resized(self::dimensionsOf($sides),self::dimensionsOf($outer),$machine->boxCostMinor($this->costMinor,$sides),new Weight($machine->boxTareTicks($this->tareWeight->ticks,$sides))); } - private function resized(Dimensions $inner,?Dimensions $outer,int $costMinor,Weight $tareWeight):self{return new self($this->id,$inner,$outer,$tareWeight,$this->maxPayload,$costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure);} + private function resized(Dimensions $inner,?Dimensions $outer,int $costMinor,Weight $tareWeight):self{return new self($this->id,$inner,$outer,$tareWeight,$this->maxPayload,$costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth);} /** @param array{0:int,1:int,2:int} $sides */ private static function dimensionsOf(array $sides):Dimensions{return new Dimensions(new Length($sides[0]),new Length($sides[1]),new Length($sides[2]));} /** @@ -78,11 +98,38 @@ private static function dimensionsOf(array $sides):Dimensions{return new Dimensi * * @param list $obstacles @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections */ - private static function requireBagFields(string $kind,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio):void + private static function requireBagFields(string $kind,Dimensions $inner,?Length $sideGussetDepth,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio,?OverhangLimit $palletOverhangLimit):void { if(!in_array($kind,FlatBag::KINDS,true))throw new ObjectRefusal('not_allowed',"unknown deformable_boundary kind {$kind}"); - $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'max_stack_density'=>$maxStackDensity!==null,'outer_dimensions'=>$outerDimensions!==null,'void_fill_reserve_ratio'=>$voidFillReserveRatio>0]; + self::requireGussetRule($kind===FlatBag::GUSSETED_BAG,$inner,$sideGussetDepth); + $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'max_stack_density'=>$maxStackDensity!==null,'outer_dimensions'=>$outerDimensions!==null,'void_fill_reserve_ratio'=>$voidFillReserveRatio>0,'pallet_overhang_limit'=>$palletOverhangLimit!==null]; foreach($present as $name=>$set)if($set)throw new ObjectRefusal('not_allowed',"{$name} cannot be combined with deformable_boundary"); } - public static function create(string $id,Dimensions $innerDimensions,Weight|int|string|array $tareWeight=0,Weight|int|string|array|null $maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],Weight|int|string|array|null $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],?string $deformableBoundary=null):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections,[],$deformableBoundary);} + /** + * A gusseted bag's side gusset is required, positive and no deeper than the bag is wide: a + * deeper fold would have no flat sheet left to fold from. A flat bag takes none. O(1). + */ + private static function requireGussetRule(bool $gusseted,Dimensions $inner,?Length $sideGussetDepth):void + { + if($sideGussetDepth===null){ + if($gusseted)throw new ObjectRefusal('missing_field','a gusseted_bag requires side_gusset_depth'); + return; + } + if(!$gusseted)throw new ObjectRefusal('not_allowed','side_gusset_depth requires deformable_boundary gusseted_bag'); + if($sideGussetDepth->ticks<=0)throw new ObjectRefusal('invalid_value','side_gusset_depth must be positive'); + if($sideGussetDepth->ticks>$inner->width->ticks)throw new ObjectRefusal('invalid_value','side_gusset_depth exceeds inner_dimensions width'); + } + /** + * The fields a pallet with an overhang limit refuses: each reads the declared frame or a wall + * the widened frame moves. The JSON path refuses the same combinations as + * `unsupported_feature` first. + * + * @param list $obstacles @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections + */ + private static function requirePalletFields(array $obstacles,?array $axles,array $accessDirections,float $voidFillReserveRatio,?MadeToMeasure $madeToMeasure):void + { + $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'void_fill_reserve_ratio'=>$voidFillReserveRatio>0,'made_to_measure'=>$madeToMeasure!==null]; + foreach($present as $name=>$set)if($set)throw new ObjectRefusal('not_allowed',"{$name} cannot be combined with pallet_overhang_limit"); + } + public static function create(string $id,Dimensions $innerDimensions,Weight|int|string|array $tareWeight=0,Weight|int|string|array|null $maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],Weight|int|string|array|null $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],?string $deformableBoundary=null,?Length $sideGussetDepth=null):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections,[],$deformableBoundary,null,null,null,$sideGussetDepth);} } diff --git a/src/Domain/Deck.php b/src/Domain/Deck.php new file mode 100644 index 0000000..cced598 --- /dev/null +++ b/src/Domain/Deck.php @@ -0,0 +1,18 @@ +x+$this->length;} + public function y2():int{return $this->y+$this->width;} + + /** The deck as a one-tick slab on the floor: only its footprint is ever read. */ + public function asBox():AxisAlignedBox{return new AxisAlignedBox(new Point($this->x,$this->y,0),new Dimensions(new Length($this->length),new Length($this->width),new Length(1)));} +} diff --git a/src/Domain/Dimensions.php b/src/Domain/Dimensions.php index 0728f74..9ad7081 100644 --- a/src/Domain/Dimensions.php +++ b/src/Domain/Dimensions.php @@ -16,7 +16,8 @@ public static function inches(int|string $l,int|string $w,int|string $h,Rounding /** @param array{length:mixed,width:mixed,height:mixed} $data */ public static function fromArray(array $data,string $unit='mm',Rounding $rounding=Rounding::Nearest):self{return self::read(Length::parse($data['length'],$unit,$rounding),Length::parse($data['width'],$unit,$rounding),Length::parse($data['height'],$unit,$rounding));} /** Sides read from the caller's input, where a zero side is a request refusal; the constructor still guards the arithmetic. */ private static function read(Length $length,Length $width,Length $height):self{if(min($length->ticks,$width->ticks,$height->ticks)<=0)throw new ObjectRefusal('invalid_value','All dimensions must be positive');return new self($length,$width,$height);} - public function rotated(Rotation $r):self{return match($r){Rotation::LWH=>new self($this->length,$this->width,$this->height),Rotation::LHW=>new self($this->length,$this->height,$this->width),Rotation::WLH=>new self($this->width,$this->length,$this->height),Rotation::WHL=>new self($this->width,$this->height,$this->length),Rotation::HLW=>new self($this->height,$this->length,$this->width),Rotation::HWL=>new self($this->height,$this->width,$this->length)};} + public function rotated(Rotation $r):self{return match($r){Rotation::LWH=>new self($this->length,$this->width,$this->height),Rotation::LHW=>new self($this->length,$this->height,$this->width),Rotation::WLH=>new self($this->width,$this->length,$this->height),Rotation::WHL=>new self($this->width,$this->height,$this->length),Rotation::HLW=>new self($this->height,$this->length,$this->width),Rotation::HWL=>new self($this->height,$this->width,$this->length),default=>$this->signedRotated($r)};} + /** A signed code's box: its permutation, the signs being invisible on a cuboid (1.10). */ private function signedRotated(Rotation $r):self{$sides=[$this->length,$this->width,$this->height];[$x,$y,$z]=Orientations::sourceAxes($r);return new self($sides[$x],$sides[$y],$sides[$z]);} /** @param list $allowed @return list */ public function uniqueRotations(array $allowed):array{$seen=[];$out=[];foreach($allowed as $r){$d=$this->rotated($r);$k=$d->length->ticks.':'.$d->width->ticks.':'.$d->height->ticks;if(!isset($seen[$k])){$seen[$k]=true;$out[]=[$r,$d];}}return $out;} public function fitsInside(self $o):bool{return $this->length->ticks<=$o->length->ticks&&$this->width->ticks<=$o->width->ticks&&$this->height->ticks<=$o->height->ticks;} public function expand(Length $c):self{$x=$c->ticks*2;return new self(new Length($this->length->ticks+$x),new Length($this->width->ticks+$x),new Length($this->height->ticks+$x));} diff --git a/src/Domain/FixedPlacement.php b/src/Domain/FixedPlacement.php index ce3efa2..e05c9a4 100644 --- a/src/Domain/FixedPlacement.php +++ b/src/Domain/FixedPlacement.php @@ -14,7 +14,8 @@ * Every rule on these fields is checked where the placement sits in a request, by * `Packer::pack` (`RequestObjects::check`), with the JSON path's refusal and pointer. */ - public function __construct(public string $itemId,public string $containerId,public Point $position,public Rotation $rotation,public int $containerInstance=1) + /** `$placementId`: the result placement's id restated (1.10), refused unless it is this placement's. */ + public function __construct(public string $itemId,public string $containerId,public Point $position,public Rotation $rotation,public int $containerInstance=1,public ?string $placementId=null) { } diff --git a/src/Domain/FlatBag.php b/src/Domain/FlatBag.php index e5ea524..d1f7e24 100644 --- a/src/Domain/FlatBag.php +++ b/src/Domain/FlatBag.php @@ -14,21 +14,27 @@ * * The extents only grow as boxes are added, so a verdict reached for a candidate never flips * when more items follow, and any subset of an admitted set is admitted. + * + * A `gusseted_bag` (1.10) has side gussets of depth G folded into each long edge: the tube + * round the package's y-z section is 2(W + G) long instead of 2W, so the width sum becomes + * b + c <= W + G. The length sum is unchanged (no bottom gusset in 1.10), and G = 0 is the + * flat bag. Every method here takes the gusset depth in ticks, 0 for a flat bag. */ final class FlatBag { - public const KINDS=['flat_bag']; + public const GUSSETED_BAG='gusseted_bag'; + public const KINDS=['flat_bag',self::GUSSETED_BAG]; /** Whether a package of extents (a, b, c) passes both girth sums; the frame is the caller's. */ - public static function girthAdmits(Dimensions $inner,int $a,int $b,int $c):bool + public static function girthAdmits(Dimensions $inner,int $a,int $b,int $c,int $gusset=0):bool { - return $a+$c<=$inner->length->ticks&&$b+$c<=$inner->width->ticks; + return $a+$c<=$inner->length->ticks&&$b+$c<=$inner->width->ticks+$gusset; } - /** Whether one box of these dimensions, alone at the origin, fits a flat bag. */ - public static function fitsAlone(Dimensions $inner,Dimensions $box):bool + /** Whether one box of these dimensions, alone at the origin, fits a bag. */ + public static function fitsAlone(Dimensions $inner,Dimensions $box,int $gusset=0):bool { - return $box->fitsInside($inner)&&self::girthAdmits($inner,$box->length->ticks,$box->width->ticks,$box->height->ticks); + return $box->fitsInside($inner)&&self::girthAdmits($inner,$box->length->ticks,$box->width->ticks,$box->height->ticks,$gusset); } /** diff --git a/src/Domain/HullShape.php b/src/Domain/HullShape.php index d58e081..1b666c9 100644 --- a/src/Domain/HullShape.php +++ b/src/Domain/HullShape.php @@ -63,8 +63,8 @@ private function __construct( /** * How many rotated hulls stay resident, before the memo is dropped and refilled. * - * A request is bounded by its distinct hull items times the six orientations, so this - * holds far more than any request the solver is sized for. Bounded rather than growing + * A request is bounded by its distinct hull items times the orientations they allow (at + * most 24), so this holds far more than any request the solver is sized for. Bounded rather than growing * for the life of the process: the point of the memo is to spend less, not to spend it * somewhere else. */ @@ -166,36 +166,24 @@ public static function box(int $length, int $width, int $height): self } /** - * Reorient a hull the way `Dimensions::rotated` reorients its box, never mirroring it. + * Reorient a hull by one of the 24 proper rotations, never mirroring it (1.10). * - * Three of the six rotations are odd permutations of the coordinate axes. On a cuboid - * that is invisible; on a hull a bare permutation returns the item's mirror image, a - * shape the caller does not own. One axis therefore changes sign when the permutation is - * odd, which makes all six proper rotations. Vertices come back translated so the - * rotated hull's bounding box starts at the origin. + * `v'[i] = s[i] * v[src[i]]` with the code's source axes and signs from `Orientations`. A + * bare permutation would hand back the item's mirror image for an odd permutation -- a + * shape the caller does not own -- which is why the legacy odd codes negate x and every + * signed code has determinant +1. Vertices come back translated so the rotated hull's + * bounding box starts at the origin. * * @param list $vertices * @return list */ public static function rotate(array $vertices, Rotation $rotation): array { - $axes = match ($rotation) { - Rotation::LWH => [0, 1, 2], Rotation::LHW => [0, 2, 1], - Rotation::WLH => [1, 0, 2], Rotation::WHL => [1, 2, 0], - Rotation::HLW => [2, 0, 1], Rotation::HWL => [2, 1, 0], - }; - $inversions = 0; - for ($i = 0; $i < 3; $i++) { - for ($j = $i + 1; $j < 3; $j++) { - if ($axes[$i] > $axes[$j]) { - $inversions++; - } - } - } - $sign = $inversions % 2 === 1 ? -1 : 1; + $axes = Orientations::sourceAxes($rotation); + $signs = Orientations::signs($rotation); $turned = []; foreach ($vertices as $vertex) { - $turned[] = [$sign * $vertex[$axes[0]], $vertex[$axes[1]], $vertex[$axes[2]]]; + $turned[] = [$signs[0] * $vertex[$axes[0]], $signs[1] * $vertex[$axes[1]], $signs[2] * $vertex[$axes[2]]]; } $low = [PHP_INT_MAX, PHP_INT_MAX, PHP_INT_MAX]; foreach ($turned as $vertex) { diff --git a/src/Domain/Item.php b/src/Domain/Item.php index 70f8aa9..de593c9 100644 --- a/src/Domain/Item.php +++ b/src/Domain/Item.php @@ -54,7 +54,8 @@ public function __construct(string $id,Dimensions $dimensions,?Weight $weight=nu if($nestingHeight!==null&&!($nestingHeight->ticks>=0&&$nestingHeight->ticks<$dimensions->height->ticks))throw new ObjectRefusal('invalid_value',"nesting_height must be at least zero and strictly less than the item's own height"); if($stopIndex!==null&&($stopIndex<0||$stopIndex>self::MAX_EXACT_STOP_INDEX))throw new ObjectRefusal($stopIndex<0?'below_minimum':'above_maximum','stop_index must be a non-negative safe integer'); if($value!==null&&$value<0)throw new ObjectRefusal('below_minimum','value must be non-negative'); - if($keepUpright)$allowedRotations=array_values(array_filter($allowedRotations,static fn(Rotation $r)=>in_array($r,Rotation::upright(),true)));if($allowedRotations===[])throw new ObjectRefusal('invalid_value','At least one rotation must be allowed'); + if($shapeType!==ShapeType::CONVEX_HULL)foreach($allowedRotations as $requested)if(Orientations::isSigned($requested))throw new ObjectRefusal('invalid_value',Orientations::SIGNED_CODE_NEEDS_A_HULL); + if($keepUpright)$allowedRotations=array_values(array_filter($allowedRotations,static fn(Rotation $r)=>Orientations::isUpright($r)));if($allowedRotations===[])throw new ObjectRefusal('invalid_value','At least one rotation must be allowed'); $this->id=$id;$this->dimensions=$dimensions;$this->weight=$weight??new Weight(0);$this->quantity=$quantity;$this->allowedRotations=$allowedRotations;$this->keepUpright=$keepUpright;$this->stackable=$stackable;$this->mustBeOnFloor=$mustBeOnFloor;$this->maxTopLoad=$maxTopLoad;$this->minimumSupportRatio=$minimumSupportRatio;$this->groundContactRule=$groundContactRule;$this->group=$group;$this->tags=array_values(array_unique($tags));$this->incompatibleTags=array_values(array_unique($incompatibleTags));$this->priority=$priority;$this->metadata=$metadata;$this->maxStackedItems=$maxStackedItems;$this->eligibleContainerTags=array_values(array_unique($eligibleContainerTags));$this->nestingHeight=$nestingHeight;$this->stopIndex=$stopIndex;$this->value=$value; $this->shapeType=$shapeType; $this->hullVertices=self::admitShape($shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa,$dimensions,$nestingHeight); diff --git a/src/Domain/Orientations.php b/src/Domain/Orientations.php new file mode 100644 index 0000000..b743487 --- /dev/null +++ b/src/Domain/Orientations.php @@ -0,0 +1,93 @@ + [[0, 1, 2], [1, 1, 1]], 'LHW' => [[0, 2, 1], [-1, 1, 1]], + 'WLH' => [[1, 0, 2], [-1, 1, 1]], 'WHL' => [[1, 2, 0], [1, 1, 1]], + 'HLW' => [[2, 0, 1], [1, 1, 1]], 'HWL' => [[2, 1, 0], [-1, 1, 1]], + '+L-W-H' => [[0, 1, 2], [1, -1, -1]], '-L+W-H' => [[0, 1, 2], [-1, 1, -1]], + '-L-W+H' => [[0, 1, 2], [-1, -1, 1]], + '+L-H+W' => [[0, 2, 1], [1, -1, 1]], '+L+H-W' => [[0, 2, 1], [1, 1, -1]], + '-L-H-W' => [[0, 2, 1], [-1, -1, -1]], + '+W-L+H' => [[1, 0, 2], [1, -1, 1]], '+W+L-H' => [[1, 0, 2], [1, 1, -1]], + '-W-L-H' => [[1, 0, 2], [-1, -1, -1]], + '+W-H-L' => [[1, 2, 0], [1, -1, -1]], '-W+H-L' => [[1, 2, 0], [-1, 1, -1]], + '-W-H+L' => [[1, 2, 0], [-1, -1, 1]], + '+H-L-W' => [[2, 0, 1], [1, -1, -1]], '-H+L-W' => [[2, 0, 1], [-1, 1, -1]], + '-H-L+W' => [[2, 0, 1], [-1, -1, 1]], + '+H-W+L' => [[2, 1, 0], [1, -1, 1]], '+H+W-L' => [[2, 1, 0], [1, 1, -1]], + '-H-W-L' => [[2, 1, 0], [-1, -1, -1]], + ]; + + /** The codes that keep the item's own height vertical and pointing up: z takes `+H`. */ + public const UPRIGHT_CODES = ['LWH', 'WLH', '-L-W+H', '+W-L+H']; + + /** What a signed code on anything but a hull is refused with, at its own pointer. */ + public const SIGNED_CODE_NEEDS_A_HULL = 'a signed rotation code requires shape_type convex_hull'; + + /** The codes an item may name: all 24 for a hull, the six legacy codes otherwise. @return list */ + public static function vocabulary(bool $hull): array + { + return $hull ? \array_keys(self::TABLE) : self::LEGACY_CODES; + } + + /** + * Why `$value` cannot orient an item of this shape, or null when it can: `invalid_value` + * for a signed code beside a non-hull -- a rule broken, not an unknown word -- and + * `not_allowed` for anything outside the item's vocabulary. O(1). + * + * @param mixed $value + */ + public static function refusalReason($value, bool $hull): ?string + { + if (!\is_string($value) || !\array_key_exists($value, self::TABLE)) { + return 'not_allowed'; + } + if (!$hull && !\in_array($value, self::LEGACY_CODES, true)) { + return 'invalid_value'; + } + return null; + } + + /** @return array{0:int,1:int,2:int} */ + public static function sourceAxes(Rotation $rotation): array + { + return self::TABLE[$rotation->value][0]; + } + + /** @return array{0:int,1:int,2:int} */ + public static function signs(Rotation $rotation): array + { + return self::TABLE[$rotation->value][1]; + } + + public static function isSigned(Rotation $rotation): bool + { + return !\in_array($rotation->value, self::LEGACY_CODES, true); + } + + public static function isUpright(Rotation $rotation): bool + { + return \in_array($rotation->value, self::UPRIGHT_CODES, true); + } +} diff --git a/src/Domain/OverhangLimit.php b/src/Domain/OverhangLimit.php new file mode 100644 index 0000000..7dd9fa5 --- /dev/null +++ b/src/Domain/OverhangLimit.php @@ -0,0 +1,13 @@ +container->deck; + if($deck!==null)return PalletOverhang::achievedDimensions($deck,$this->placements); if(!$this->container->isFlatBag()&&$this->container->madeToMeasure===null)return null; return FlatBag::asDimensions(FlatBag::extentOf($this->placements)); } - /** What a carrier measures: a bag's achieved package, else the declared outer size. */ + /** What a carrier measures: a bag's achieved package, a pallet's footprint grown by its overhang, else the declared outer size. */ public function billedDimensions():Dimensions { + $deck=$this->container->deck; + if($deck!==null)return PalletOverhang::billedDimensions($this->container,$deck,$this->placements); $achieved=$this->container->isFlatBag()?$this->achievedDimensions():null; return $achieved??$this->container->outerDimensions??$this->container->innerDimensions; } diff --git a/src/Domain/PackingRequest.php b/src/Domain/PackingRequest.php index 846a844..bc47f32 100644 --- a/src/Domain/PackingRequest.php +++ b/src/Domain/PackingRequest.php @@ -4,7 +4,7 @@ use Packvium\Support\ObjectRefusal; final readonly class PackingRequest { - /** @param list $items @param list $containers @param list $fixedPlacements */ public function __construct(public array $items,public array $containers,public array $fixedPlacements=[]){if($items===[])throw new ObjectRefusal('invalid_value','At least one item is required');if($containers===[])throw new ObjectRefusal('invalid_value','At least one container is required');self::unique(array_map(fn(Item $i)=>$i->id,$items),'item');self::unique(array_map(fn(Container $c)=>$c->id,$containers),'container');} + /** @param list $items @param list $containers @param list $fixedPlacements */ public function __construct(public array $items,public array $containers,public array $fixedPlacements=[],public ?string $currency=null){if($items===[])throw new ObjectRefusal('invalid_value','At least one item is required');if($containers===[])throw new ObjectRefusal('invalid_value','At least one container is required');self::unique(array_map(fn(Item $i)=>$i->id,$items),'item');self::unique(array_map(fn(Container $c)=>$c->id,$containers),'container');} /** @return list */ public function instances():array{$out=[];foreach($this->items as $i)array_push($out,...$i->instances());return $out;} private static function unique(array $ids,string $kind):void{if(count($ids)!==count(array_unique($ids)))throw new ObjectRefusal('duplicate_id',ucfirst($kind).' ids must be unique');} } diff --git a/src/Domain/PalletOverhang.php b/src/Domain/PalletOverhang.php new file mode 100644 index 0000000..0ca82b6 --- /dev/null +++ b/src/Domain/PalletOverhang.php @@ -0,0 +1,124 @@ +palletOverhangLimit; + if($limit===null)return $container; + $inner=$container->innerDimensions; + $overhangX=$limit->length->ticks;$overhangY=$limit->width->ticks; + $frame=new Dimensions(new Length($inner->length->ticks+2*$overhangX),new Length($inner->width->ticks+2*$overhangY),$inner->height); + return $container->framed($frame,new Deck($overhangX,$overhangY,$inner->length->ticks,$inner->width->ticks)); + } + + /** A solving frame's container as declared, without the overhang zone: the rung a pallet trial packs first. O(1). */ + public static function deckAlone(Container $frame):Container + { + return $frame->framed($frame->declaredInner(),null); + } + + /** + * The shift that seats a frame trial's load with the least overhang. Per axis: flush with the + * deck's near edge when the load is no longer than the deck, else centred on the deck with an + * odd tick past the far edge. Either way the load stays inside the frame, since its span is at + * most the deck plus both allowances. O(p); `[0, 0]` for none. + * + * @param list $placements @return array{0:int,1:int} + */ + public static function centringOffset(Deck $deck,array $placements):array + { + if($placements===[])return [0,0]; + $lowX=$lowY=\PHP_INT_MAX;$highX=$highY=0; + foreach($placements as $placement){ + $box=$placement->envelopeBox(); + $lowX=min($lowX,$box->origin->x);$lowY=min($lowY,$box->origin->y); + $highX=max($highX,$box->x2());$highY=max($highY,$box->y2()); + } + return [self::seat($deck->x,$deck->length,$lowX,$highX),self::seat($deck->y,$deck->width,$lowY,$highY)]; + } + + private static function seat(int $start,int $length,int $low,int $high):int + { + $span=$high-$low; + $target=$span<=$length?$start:$start-intdiv($span-$length,2); + return $target-$low; + } + + /** The area of a floor placement's footprint that rests on the deck. O(1). */ + public static function deckContactArea(Deck $deck,AxisAlignedBox $box):int|string + { + return ExactGeometry::overlapAreaXY($deck->asBox(),$box); + } + + /** The support ratio a placement on the floor reports: whole without a deck. O(1). */ + public static function floorSupportRatio(?Deck $deck,AxisAlignedBox $box):float + { + if($deck===null)return 1.0; + return ExactInteger::ratio(self::deckContactArea($deck,$box),ExactGeometry::baseArea($box->dimensions)); + } + + /** + * The deck grown by the overhang the placements use past each of its edges: `[length, width]` + * of the footprint the load reaches. O(p). + * + * @param list $placements @return array{0:int,1:int} + */ + public static function footprint(Deck $deck,array $placements):array + { + $lowX=$deck->x;$lowY=$deck->y;$highX=$deck->x2();$highY=$deck->y2(); + foreach($placements as $placement){ + $box=$placement->envelopeBox(); + $lowX=min($lowX,$box->origin->x);$lowY=min($lowY,$box->origin->y); + $highX=max($highX,$box->x2());$highY=max($highY,$box->y2()); + } + return [$highX-$lowX,$highY-$lowY]; + } + + /** + * The footprint the loaded pallet reaches, at its load's height. A packed container holds at + * least one box. O(p). + * + * @param list $placements + */ + public static function achievedDimensions(Deck $deck,array $placements):Dimensions + { + [$length,$width]=self::footprint($deck,$placements); + return new Dimensions(new Length($length),new Length($width),new Length(FlatBag::extentOf($placements)[2])); + } + + /** + * Per horizontal axis the larger of the declared footprint, outer if stated, and the deck + * grown by the overhang used; the declared height. An outer margin is not positioned against + * the deck, so it is never added to the overhang. O(p). + * + * @param list $placements + */ + public static function billedDimensions(Container $frame,Deck $deck,array $placements):Dimensions + { + $base=$frame->outerDimensions??$frame->declaredInner(); + [$length,$width]=self::footprint($deck,$placements); + return new Dimensions(new Length(max($base->length->ticks,$length)),new Length(max($base->width->ticks,$width)),$base->height); + } +} diff --git a/src/Domain/Placement.php b/src/Domain/Placement.php index 9fac7a6..994f2a9 100644 --- a/src/Domain/Placement.php +++ b/src/Domain/Placement.php @@ -1,6 +1,7 @@ position,$this->dimensions);}public function envelopeBox():AxisAlignedBox{return new AxisAlignedBox($this->envelopeOrigin,$this->envelopeDimensions);} + /** This placement's cross-language id inside the container with id `$containerId` (1.10). */ + public function idIn(string $containerId):string{return self::identifier($containerId,$this->position,$this->instance->item->id,$this->rotation->value);} + + /** + * A placement's cross-language id (1.10): the RFC 8785 canonical JSON text of + * `[container id, x, y, z, item type, orientation]`, with the physical position in ticks as + * integers. Two valid placements never share that tuple -- the same solid in the same place + * would coincide -- and canonical JSON spells any id with no grammar of its own to escape. + * A position is below its container's side, itself at most 2^53 - 1 ticks, so every integer + * has a canonical spelling; a PHP string holds no lone UTF-16 surrogate, so the reference's + * surrogate escape never arises here. A pure function of the placement, so a validator + * recomputes it. O(length of the ids). + */ + public static function identifier(string $containerId,Point $position,string $itemType,string $orientation):string + { + return CanonicalJson::encode([$containerId,$position->x,$position->y,$position->z,$itemType,$orientation]); + } + /** * This placement's rotated hull, or null when its box is the honest answer. * diff --git a/src/Domain/RateTable.php b/src/Domain/RateTable.php index afe9e7d..8c2aecc 100644 --- a/src/Domain/RateTable.php +++ b/src/Domain/RateTable.php @@ -28,6 +28,9 @@ public function __construct( public readonly array $pricesMinor, public readonly int $minimumChargeMinor = 0, public readonly int $fuelSurchargePermille = 0, + // The ISO 4217 code the prices are in, or null for the request's own (1.10). Checked + // where the table sits in a request, against the request's currency, by `Packer::pack`. + public readonly ?string $currency = null, ) { if ($weightBracketsG === []) { throw new ObjectRefusal('invalid_value', 'rate_table requires at least one weight bracket'); diff --git a/src/Domain/Rotation.php b/src/Domain/Rotation.php index 02fbf81..a507d8b 100644 --- a/src/Domain/Rotation.php +++ b/src/Domain/Rotation.php @@ -1,9 +1,21 @@ */ public static function all():array{return self::cases();} - /** @return list */ public static function upright():array{return [self::LWH,self::WLH];} + case PL_NW_NH='+L-W-H';case NL_PW_NH='-L+W-H';case NL_NW_PH='-L-W+H'; + case PL_NH_PW='+L-H+W';case PL_PH_NW='+L+H-W';case NL_NH_NW='-L-H-W'; + case PW_NL_PH='+W-L+H';case PW_PL_NH='+W+L-H';case NW_NL_NH='-W-L-H'; + case PW_NH_NL='+W-H-L';case NW_PH_NL='-W+H-L';case NW_NH_PL='-W-H+L'; + case PH_NL_NW='+H-L-W';case NH_PL_NW='-H+L-W';case NH_NL_PW='-H-L+W'; + case PH_NW_PL='+H-W+L';case PH_PW_NL='+H+W-L';case NH_NW_NL='-H-W-L'; + /** The six legacy codes: an item's default list, and every box a cuboid can make. @return list */ public static function all():array{return [self::LWH,self::LHW,self::WLH,self::WHL,self::HLW,self::HWL];} + /** The legacy codes `keep_upright` leaves of the default list. @return list */ public static function upright():array{return [self::LWH,self::WLH];} + /** All 24 proper rotations in table order; the 18 past `all()` need a hull. @return list */ public static function every():array{return self::cases();} } diff --git a/src/Execution/Plan.php b/src/Execution/Plan.php index aae6ef9..f9c14f1 100644 --- a/src/Execution/Plan.php +++ b/src/Execution/Plan.php @@ -79,6 +79,30 @@ public static function placementReference(int $containerIndex, $placement): arra ]; } + /** + * `placementReference` plus the result placement's `placement_id` (1.10), copied rather + * than derived, when the result carries one. A canonical projection (a golden) has no ids, + * so its plan keeps the bytes it always had. Locks read the id from here. + * + * @param array|\stdClass|mixed $placement + * @return array + */ + private static function stepReference(int $containerIndex, $placement): array + { + $reference = self::placementReference($containerIndex, $placement); + if (!JsonValue::has($placement, 'placement_id')) { + return $reference; + } + $identifier = JsonValue::get($placement, 'placement_id'); + if (!\is_string($identifier) || $identifier === '') { + throw new ExecutionPlanException( + 'placement_id ' . CanonicalJson::spelling($identifier) . ' is not a non-empty string' + ); + } + $reference['placement_id'] = $identifier; + return $reference; + } + /** * The operator sequence for one container, or an honest absence of one. * @@ -97,7 +121,7 @@ private static function steps(int $containerIndex, $container, ?array $loadingOr if ($loadingOrder === null) { $steps = []; foreach ($placements as $placement) { - $steps[] = ['placement' => self::placementReference($containerIndex, $placement)]; + $steps[] = ['placement' => self::stepReference($containerIndex, $placement)]; } return ['order' => 'unavailable', 'steps' => $steps]; } @@ -115,7 +139,7 @@ private static function steps(int $containerIndex, $container, ?array $loadingOr foreach ($loadingOrder as $step => $index) { $steps[] = [ 'sequence' => $step + 1, - 'placement' => self::placementReference($containerIndex, $placements[$index]), + 'placement' => self::stepReference($containerIndex, $placements[$index]), ]; } return ['order' => 'loading', 'steps' => $steps]; diff --git a/src/Nested/NestedPacker.php b/src/Nested/NestedPacker.php index 21d50c7..7b7e06e 100644 --- a/src/Nested/NestedPacker.php +++ b/src/Nested/NestedPacker.php @@ -1,6 +1,192 @@ config??PackingConfig::balanced()))->pack($current,$level->containers);$results[]=$result;if(!$result->complete())break;$current=array_map(fn($c)=>$c->asItem(),$result->containers);}return new NestedPackingResult($results);}} +use Packvium\Result\PackingResult; +use Packvium\Support\ExactInteger; +use Packvium\Support\StableSorter; + +/** + * Packs levels in order, each level's packed containers becoming the next level's items. + * + * `levelBeamWidth` K carries the K best chains from one level to the next. A chain + * is a sequence of level results; it extends by packing its handoff against the level's whole + * container list and, when K > 1 and the level offers more than one, against each container + * alone. Chains rank by their outermost result's score, then each earlier level's outward in, + * then generation order; two chains handing up the same items keep only the better. A level + * with no complete candidate ends every chain, and the best incomplete one is the answer. + * K = 1 is exactly the greedy chain. At most L * K * (T + 1) level packs for L levels offering + * at most T containers each. + */ +final class NestedPacker +{ + public function __construct(public readonly int $levelBeamWidth = 1) + { + if ($levelBeamWidth < 1) { + throw new InvalidArgumentException('level_beam_width must be a positive integer'); + } + } + + /** @param list $items @param list $levels */ + public function pack(array $items, array $levels): NestedPackingResult + { + /** @var list> $beam */ + $beam = [[]]; + /** @var list> $handoffs */ + $handoffs = [$items]; + foreach ($levels as $level) { + $ranked = $this->rankedExtensions($level, $beam, $handoffs); + $complete = self::completeChains($ranked); + if ($complete === []) { + return new NestedPackingResult($ranked[0]); + } + $beam = $this->distinctHandoffs($complete); + $handoffs = \array_map(static fn(array $chain): array => self::handoff(self::last($chain)), $beam); + } + return new NestedPackingResult($beam[0]); + } + + /** + * Every extension of every chain, best first; the stable sort keeps generation order on ties. + * + * @param list> $beam @param list> $handoffs + * @return list> + */ + private function rankedExtensions(PackingLevel $level, array $beam, array $handoffs): array + { + $packer = new Packer($level->config ?? PackingConfig::balanced()); + $extensions = []; + foreach ($beam as $index => $chain) { + foreach ($this->candidates($packer, $handoffs[$index], $level->containers) as $result) { + $extension = $chain; + $extension[] = $result; + $extensions[] = $extension; + } + } + return StableSorter::sort( + $extensions, + static fn(array $left, array $right): int => self::compareChains($left, $right), + ); + } + + /** + * @param list $items @param list $containers + * @return list + */ + private function candidates(Packer $packer, array $items, array $containers): array + { + $offers = [$containers]; + if ($this->levelBeamWidth > 1 && \count($containers) > 1) { + foreach ($containers as $container) { + $offers[] = [$container]; + } + } + return \array_map(static fn(array $offer): PackingResult => $packer->pack($items, $offer), $offers); + } + + /** + * The first K chains, best first, that hand distinct containers up to the next level. + * + * @param list> $ranked @return list> + */ + private function distinctHandoffs(array $ranked): array + { + $kept = []; + $seen = []; + foreach ($ranked as $chain) { + $handoff = self::handoffKey(self::last($chain)); + if (isset($seen[$handoff])) { + continue; + } + $seen[$handoff] = true; + $kept[] = $chain; + if (\count($kept) === $this->levelBeamWidth) { + break; + } + } + return $kept; + } + + /** @param list> $ranked @return list> */ + private static function completeChains(array $ranked): array + { + return \array_values(\array_filter($ranked, static fn(array $chain): bool => self::last($chain)->complete())); + } + + /** Each packed container as one upright item of the next level. @return list */ + private static function handoff(PackingResult $result): array + { + return \array_map(static fn(PackedContainer $container): Item => $container->asItem(), $result->containers); + } + + /** + * The handed-up containers as a multiset: instance numbers and emission order are not part + * of a packing's contract, so two engines must collapse the same chains. + */ + private static function handoffKey(PackingResult $result): string + { + $containers = []; + foreach ($result->containers as $container) { + $billed = $container->billedDimensions(); + $containers[] = \serialize([$container->container->id, $billed->length->ticks, $billed->width->ticks, + $billed->height->ticks, $container->grossWeight()->ticks]); + } + \sort($containers, \SORT_STRING); + return \implode("\0", $containers); + } + + /** + * Outermost level first, then each earlier level outward in; chains compared here always + * have the same length. + * + * @param list $left @param list $right + */ + private static function compareChains(array $left, array $right): int + { + for ($index = \count($left) - 1; $index >= 0; --$index) { + $order = self::compareScores($left[$index]->score, $right[$index]->score); + if ($order !== 0) { + return $order; + } + } + return 0; + } + + /** + * Lexicographic, lower is better. A component past PHP's integer range is a decimal + * string, so `<=>` on the raw arrays would compare it as text. + * + * @param list $left @param list $right + */ + private static function compareScores(array $left, array $right): int + { + $shared = \min(\count($left), \count($right)); + for ($index = 0; $index < $shared; ++$index) { + $order = self::compareComponents($left[$index], $right[$index]); + if ($order !== 0) { + return $order; + } + } + return \count($left) <=> \count($right); + } + + private static function compareComponents(int|float|string $left, int|float|string $right): int + { + if (\is_float($left) || \is_float($right)) { + return (float)$left <=> (float)$right; + } + return ExactInteger::compare($left, $right); + } + + /** @param list $chain */ + private static function last(array $chain): PackingResult + { + return $chain[\count($chain) - 1]; + } +} diff --git a/src/Packer.php b/src/Packer.php index 8161cf3..cb0239a 100644 --- a/src/Packer.php +++ b/src/Packer.php @@ -6,7 +6,7 @@ use Packvium\Algorithm\{Deadline, FixedLoad, FixedPlacementAdmission, ObjectiveBoundScope, ObjectiveBounds, SolverOrchestrator}; use Packvium\Support\{RequestObjects, StableSorter, UnsupportedPlacements}; use Packvium\Config\PackingConfig; -use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, UnratedWeightException}; +use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, PalletOverhang, UnratedWeightException}; use Packvium\Extension\ExtensionRegistry; use Packvium\Objective\{LandedCostSolutionScorer, ObjectiveRegistry, SolutionScorer, UnknownObjectiveException}; use Packvium\Result\{ @@ -74,13 +74,16 @@ private static function statedOptimality(PackingStatus $status, array $score, ?a return [$status, new ResultFact($code, $fields)]; } - /** @param list $items @param list $containers @param list $fixedPlacements */ - public function pack(array $items, array $containers, array $fixedPlacements = []): PackingResult + /** + * @param list $items @param list $containers @param list $fixedPlacements + * @param ?string $currency the ISO 4217 code the request's prices are in, echoed by the result (1.10) + */ + public function pack(array $items, array $containers, array $fixedPlacements = [], ?string $currency = null): PackingResult { // The JSON path's rules, with the JSON path's reason and field: a request // built from objects is refused exactly where the same request as JSON would be. - RequestObjects::check($items, $containers, $this->config, $fixedPlacements); - return $this->solve($items, $containers, $fixedPlacements); + RequestObjects::check($items, $containers, $this->config, $fixedPlacements, $currency); + return $this->solve($items, $containers, $fixedPlacements, $currency); } /** @@ -90,9 +93,13 @@ public function pack(array $items, array $containers, array $fixedPlacements = [ * * @param list $items @param list $containers @param list $fixedPlacements */ - private function solve(array $items, array $containers, array $fixedPlacements): PackingResult + private function solve(array $items, array $containers, array $fixedPlacements, ?string $currency = null): PackingResult { - $request = new PackingRequest($items, $containers, $fixedPlacements); + // A pallet with an overhang limit is packed as its widened frame from here on, so no + // solver, bound or validator needs to know the limit exists. + // A container without a limit is its own frame; asking only for one with a limit keeps + // `PalletOverhang` uncompiled on every other request, whose heap pays for its code. + $request = new PackingRequest($items, \array_map(static fn(Container $container): Container => $container->palletOverhangLimit === null ? $container : PalletOverhang::solvingFrame($container), $containers), $fixedPlacements, $currency); // Both cost objectives price the same billed weight, so both need the divisor. // There is no library-chosen default: a wrong guess would silently misprice // every shipment. `ShippingCostSolutionScorer::fromConfig` still refuses too, @@ -225,6 +232,7 @@ private function solve(array $items, array $containers, array $fixedPlacements): termination: $termination, optimality: $optimality, objective: $this->config->objective, + currency: $request->currency, ); } @@ -279,6 +287,7 @@ private function solve(array $items, array $containers, array $fixedPlacements): $best->termination, $best->optimality, $best->objective, + $best->currency, ); } } diff --git a/src/Result/PackingResult.php b/src/Result/PackingResult.php index d18d2cf..e7181d1 100644 --- a/src/Result/PackingResult.php +++ b/src/Result/PackingResult.php @@ -9,6 +9,9 @@ final readonly class PackingResult { + /** The serialization cache before any value is shared through it. */ + private const NOTHING_SHARED = ['length' => [], 'weight' => [], 'dimensions' => []]; + public ResultFact $feasibility; public ResultFact $termination; public ResultFact $optimality; @@ -32,6 +35,9 @@ public function __construct( ?ResultFact $termination = null, ?ResultFact $optimality = null, public string $objective = 'default', + // The request's ISO 4217 code, echoed only when the request declares one, by the + // answer and by every alternative alike (1.10). + public ?string $currency = null, ) { [$derivedFeasibility, $derivedTermination, $derivedOptimality] = self::deriveFacts( $status, @@ -91,47 +97,48 @@ public function toArray( ): array { // Equal quantities share one array: placements repeat a type's dimensions, a lattice // coordinate and a zero top load, and a shared array serializes to the same bytes. - $shared = ['length' => [], 'weight' => [], 'dimensions' => []]; - return $this->serialized($lengthUnit, $weightUnit, $includeAlternatives, $shared); + $shared = self::NOTHING_SHARED; + return $this->serialized($lengthUnit, $weightUnit, $includeAlternatives, false, $shared); + } + + /** + * `toArray`, except that each container's `placements` (the answer's and every + * alternative's) is a one-pass `\Generator` of the same placement arrays, for + * `PrettyJsonStream` to write as it goes. + * + * The placements are most of a result's array, and holding all of them next to the result + * objects they come from is the peak of a `bin/packvium` run on `fast`; streamed, no more + * than one placement's array is alive at a time. Each generator holds its own container. + */ + public function toStreamedArray(string $lengthUnit = 'mm', string $weightUnit = 'g'): array + { + $shared = self::NOTHING_SHARED; + return $this->serialized($lengthUnit, $weightUnit, true, true, $shared); } /** @param array{length:array,weight:array,dimensions:array>>} $shared */ - private function serialized(string $lengthUnit, string $weightUnit, bool $includeAlternatives, array &$shared): array + private function serialized(string $lengthUnit, string $weightUnit, bool $includeAlternatives, bool $streamPlacements, array &$shared): array { $containers = []; foreach ($this->containers as $container) { - $placements = []; - foreach ($container->placements as $placement) { - $placements[] = [ - 'item_id' => $placement->instance->id(), - 'item_type' => $placement->instance->item->id, - 'position' => self::point($placement->position, $lengthUnit, $shared), - 'dimensions' => self::dimensions($placement->dimensions, $lengthUnit, $shared), - 'orientation' => $placement->rotation->value, - 'support_ratio' => sprintf('%.6f', $placement->supportRatio), - 'top_load' => $shared['weight'][$placement->topLoad->ticks] ??= $placement->topLoad->toArray($weightUnit), - ]; - // Absent unless true, so a request without fixed placements keeps its bytes. - if ($placement->fixed) { - $placements[array_key_last($placements)]['fixed'] = true; - } - } + $containerId = $container->id(); + $placements = self::placements($container, $containerId, $lengthUnit, $weightUnit, $streamPlacements, $shared); $serialized = [ - 'id' => $container->id(), + 'id' => $containerId, 'container_type' => $container->container->id, - 'inner_dimensions' => $container->container->innerDimensions->toArray($lengthUnit), + 'inner_dimensions' => $container->container->declaredInner()->toArray($lengthUnit), 'outer_dimensions' => ($container->container->outerDimensions - ?? $container->container->innerDimensions)->toArray($lengthUnit), + ?? $container->container->declaredInner())->toArray($lengthUnit), 'payload_weight' => $container->payloadWeight()->toArray($weightUnit), 'gross_weight' => $container->grossWeight()->toArray($weightUnit), 'used_volume_ticks3' => $container->usedVolumeString(), 'volume_utilization' => sprintf('%.6f', $container->utilization()), 'centre_of_mass_offset_ppm' => $container->centreOfMassOffsetPpm(), 'void_fill_reserve_ticks3' => VolumeReserve::reserved($container->container), - 'placements' => $placements, + 'placements' => $streamPlacements ? $placements : \iterator_to_array($placements, false), ]; - // Present exactly when the container conforms to its contents, so a - // rigid container's bytes are unchanged. + // Present exactly when the container conforms to its contents or is a + // pallet with an overhang limit, so a rigid container's bytes are unchanged. $achieved = $container->achievedDimensions(); if ($achieved !== null) { $serialized['achieved_dimensions'] = $achieved->toArray($lengthUnit); @@ -195,11 +202,11 @@ private function serialized(string $lengthUnit, string $weightUnit, bool $includ $alternatives = []; if ($includeAlternatives) { foreach ($this->alternatives as $alternative) { - $alternatives[] = $alternative->serialized($lengthUnit, $weightUnit, false, $shared); + $alternatives[] = $alternative->serialized($lengthUnit, $weightUnit, false, $streamPlacements, $shared); } } - return [ + $result = [ 'status' => $this->status->value, 'feasibility' => $this->feasibility->toArray(), 'termination' => $this->termination->toArray(), @@ -226,9 +233,47 @@ private function serialized(string $lengthUnit, string $weightUnit, bool $includ 'containers' => $containers, 'unpacked_items' => $unpacked, 'catalog_versions_used' => [], - 'warnings' => $this->warnings, - 'alternatives' => $alternatives, ]; + // Absent unless the request declared one, so every other request keeps its bytes. + if ($this->currency !== null) { + $result['currency'] = $this->currency; + } + $result['warnings'] = $this->warnings; + $result['alternatives'] = $alternatives; + return $result; + } + + /** + * One container's placements, serialized in order. + * + * Streamed, each array is written and dropped before the next is built, so a cached value + * would only be kept alive, never shared: the cache is let go after every placement. + * + * @param array{length:array,weight:array,dimensions:array>>} $shared + * @return \Generator> + */ + private static function placements(PackedContainer $container, string $containerId, string $lengthUnit, string $weightUnit, bool $streamed, array &$shared): \Generator + { + foreach ($container->placements as $placement) { + $serialized = [ + 'placement_id' => $placement->idIn($containerId), + 'item_id' => $placement->instance->id(), + 'item_type' => $placement->instance->item->id, + 'position' => self::point($placement->position, $lengthUnit, $shared), + 'dimensions' => self::dimensions($placement->dimensions, $lengthUnit, $shared), + 'orientation' => $placement->rotation->value, + 'support_ratio' => sprintf('%.6f', $placement->supportRatio), + 'top_load' => $shared['weight'][$placement->topLoad->ticks] ??= $placement->topLoad->toArray($weightUnit), + ]; + // Absent unless true, so a request without fixed placements keeps its bytes. + if ($placement->fixed) { + $serialized['fixed'] = true; + } + yield $serialized; + if ($streamed) { + $shared = self::NOTHING_SHARED; + } + } } /** `Point::toArray`, from shared length arrays. */ diff --git a/src/Revisions/PlanRevision.php b/src/Revisions/PlanRevision.php index d99e25b..c66cac9 100644 --- a/src/Revisions/PlanRevision.php +++ b/src/Revisions/PlanRevision.php @@ -4,10 +4,16 @@ use JsonException; use Packvium\Artifacts\OperationalArtifact; +use Packvium\Domain\MadeToMeasure; +use Packvium\Support\BigInt; use Packvium\Support\CanonicalJson; use Packvium\Support\CanonicalJsonException; use Packvium\Support\FixedPlacementShape; use Packvium\Support\JsonValue; +use Packvium\Support\MeasureReading; +use Packvium\Support\RequestRules; +use Packvium\Unit\Length; +use Packvium\Unit\Weight; use stdClass; use Throwable; @@ -34,8 +40,9 @@ final class PlanRevision 'placement_locked' => ['placement'], 'placement_verified' => ['placement'], ]; - private const PLACEMENT_FIELDS = ['item_type', 'container_type', 'container_instance', 'position', 'orientation']; + private const PLACEMENT_FIELDS = ['item_type', 'container_type', 'container_instance', 'position', 'orientation', 'placement_id']; private const JSON_DEPTH = 512; + private const CUT_SIDES = ['length', 'width', 'height']; /** * Revision 0: the request as first approved, with nothing recorded against it. @@ -74,15 +81,17 @@ public static function derive($parent, $approvedArtifact, $events): stdClass throw new PlanRevisionException('invalid_event', 'a revision records at least one event'); } $first = self::lastSequence($parent) + 1; + $hulls = self::hullTypes($parent->request); $recorded = []; foreach ($events as $offset => $event) { - $recorded[] = self::event(self::tree($event), $first + $offset); + $recorded[] = self::event(self::tree($event), $first + $offset, $hulls); } - $request = self::applyEvents($parent->request, $recorded); + $number = self::number($parent) + 1; + $request = self::stockCutBoxes(self::applyEvents($parent->request, $recorded), $approvedArtifact, $number); $approved = new stdClass(); $approved->artifact = self::digest($approvedArtifact); $approved->replay = self::tree($approvedArtifact->provenance->replay); - $document = self::document(self::number($parent) + 1, self::digest($parent), $approved, $recorded, $request); + $document = self::document($number, self::digest($parent), $approved, $recorded, $request); self::canonicalJson($document); return $document; } @@ -104,10 +113,11 @@ public static function applyEvents($request, $events): stdClass throw new PlanRevisionException('invalid_event', 'events are a JSON array'); } $derived = self::tree($request); + $hulls = self::hullTypes($request); $placementSession = ['ready' => false, 'keys' => null, 'indexable' => true]; foreach ($events as $event) { $event = self::tree($event); - self::requireShape($event); + self::requireShape($event, $hulls); $sequence = JsonValue::get($event, 'sequence'); if (JsonValue::integer($sequence) === null) { throw new PlanRevisionException('invalid_event', 'event sequence ' . CanonicalJson::spelling($sequence) . ' is not an integer'); @@ -126,6 +136,29 @@ public static function applyEvents($request, $events): stdClass return $derived; } + /** + * `$request` with every made-to-measure box that holds a fixed placement made a stock + * container. The box was cut for the approved plan, so a replan cannot recut it: + * instance `n` of made-to-measure type `T` -- the `n`-th container of type `T` in the + * artifact, in result order -- becomes container `T@#`, a copy of `T` without + * `made_to_measure`, quantity 1, at the cut inner and outer size, price and tare, each in + * ticks; it follows `T` in the container list. Its fixed placements move to its instance 1 + * and `T`'s own `quantity`, if stated, loses the boxes taken (`T` is dropped at zero). New + * boxes are still cut to measure. Pure; O(C + F + A) for containers, fixed placements and + * the artifact's containers. + * + * @param stdClass|array $request + * @param stdClass|array|mixed $approvedArtifact + * @throws PlanRevisionException + */ + public static function stockCutBoxes($request, $approvedArtifact, int $revision): stdClass + { + if (!JsonValue::isObject($request)) { + throw new PlanRevisionException('invalid_revision', 'a request is a JSON object'); + } + return self::stockedRequest(self::tree($request), self::tree($approvedArtifact), $revision); + } + /** * Every way the chain fails to be what its root and events derive, without stopping at the * first. `$artifacts[$k]`, when given, is the artifact revision `$k` names as approved. @@ -169,10 +202,10 @@ public static function verifyChain($revisions, $artifacts = null): array $issues[] = new RevisionIssue('parent_mismatch', $position, 'parent ' . self::plain($recordedParent) . ', expected ' . self::plain($expectedParent)); } $lastSequence = self::checkSequences($revision, $position, $lastSequence, $issues); + $artifact = $artifacts[$position] ?? null; if ($parent !== null) { - self::checkRequest($revision, $parent, $position, $issues); + self::checkRequest($revision, $parent, $artifact === null ? null : self::tree($artifact), $position, $issues); } - $artifact = $artifacts[$position] ?? null; if ($artifact !== null && $parent !== null) { self::checkArtifact($revision, $parent, self::tree($artifact), $position, $issues); } @@ -293,10 +326,10 @@ private static function lastSequence(stdClass $revision): int return 0; } - /** @param mixed $raw */ - private static function event($raw, int $sequence): stdClass + /** @param mixed $raw @param list $hulls */ + private static function event($raw, int $sequence, array $hulls): stdClass { - self::requireShape($raw); + self::requireShape($raw, $hulls); $given = JsonValue::get($raw, 'sequence'); if (JsonValue::integer($given) !== $sequence) { throw new PlanRevisionException('invalid_event', 'event sequence ' . CanonicalJson::spelling($given) . " does not continue the chain at {$sequence}"); @@ -304,8 +337,19 @@ private static function event($raw, int $sequence): stdClass return $raw; } - /** @param mixed $raw */ - private static function requireShape($raw): void + /** + * The request's hull item types, which alone may be placed in a signed orientation (1.10). + * + * @param mixed $request + * @return list + */ + private static function hullTypes($request): array + { + return JsonValue::isObject($request) ? FixedPlacementShape::hullItemTypes(JsonValue::get($request, 'items')) : []; + } + + /** @param mixed $raw @param list $hulls */ + private static function requireShape($raw, array $hulls): void { if (!$raw instanceof stdClass) { throw new PlanRevisionException('invalid_event', 'an event is a JSON object'); @@ -329,7 +373,7 @@ private static function requireShape($raw): void } elseif ($kind === 'container_substituted') { self::validateContainerSubstituted($raw); } else { - self::validatePlacement($raw); + self::validatePlacement($raw, $hulls); } } @@ -351,7 +395,8 @@ private static function validateContainerSubstituted(stdClass $event): void self::requireName(JsonValue::get($event->replacement, 'id'), 'replacement.id'); } - private static function validatePlacement(stdClass $event): void + /** @param list $hulls */ + private static function validatePlacement(stdClass $event, array $hulls): void { $placement = $event->placement; if (!$placement instanceof stdClass) { @@ -363,8 +408,10 @@ private static function validatePlacement(stdClass $event): void } self::requireName(JsonValue::get($placement, 'item_type'), 'placement.item_type'); self::requireName(JsonValue::get($placement, 'container_type'), 'placement.container_type'); - if (!\in_array(JsonValue::get($placement, 'orientation'), FixedPlacementShape::ORIENTATIONS, true)) { - throw new PlanRevisionException('invalid_event', 'placement.orientation must be one of ' . CanonicalJson::spelling(FixedPlacementShape::ORIENTATIONS)); + $hull = \in_array(JsonValue::get($placement, 'item_type'), $hulls, true); + $refusal = RequestRules::orientationRefusal(JsonValue::get($placement, 'orientation'), $hull, 'placement.orientation'); + if ($refusal !== null) { + throw new PlanRevisionException('invalid_event', $refusal[1]); } $instance = JsonValue::has($placement, 'container_instance') ? JsonValue::integer($placement->container_instance) : 1; if ($instance === null || $instance < 1) { @@ -376,6 +423,12 @@ private static function validatePlacement(stdClass $event): void '/placement/position', static fn(string $message): Throwable => new PlanRevisionException('invalid_event', $message) ); + // Only its type is the event's to judge: whether it names this placement needs the + // request's unit, and is the engine's admission rule when the revision is solved (1.10). + $identifier = JsonValue::get($placement, 'placement_id'); + if ($identifier !== null && !\is_string($identifier)) { + throw new PlanRevisionException('invalid_event', 'placement.placement_id is a string'); + } } /** @param mixed $value */ @@ -448,7 +501,7 @@ private static function applyPlacement(stdClass $request, stdClass $event, array $session['keys'] = []; try { foreach ($request->fixed_placements as $entry) { - $session['keys'][self::canonicalJson(self::withDefaultInstance($entry))] = true; + $session['keys'][self::canonicalJson(self::identity($entry))] = true; } } catch (PlanRevisionException $error) { $session['indexable'] = false; @@ -456,7 +509,7 @@ private static function applyPlacement(stdClass $request, stdClass $event, array } // One box cannot be two fixed items: a lock that is later verified in place is recorded // twice in the chain and once in the request. - $placement = self::withDefaultInstance($event->placement); + $placement = self::identity($event->placement); if ($session['indexable']) { try { $key = self::canonicalJson($placement); @@ -474,16 +527,21 @@ private static function applyPlacement(stdClass $request, stdClass $event, array } // Keep the old first-match/error order for values outside canonical JSON. foreach ($request->fixed_placements as $entry) { - if (self::same(self::withDefaultInstance($entry), $placement)) { + if (self::same(self::identity($entry), $placement)) { return; } } $request->fixed_placements[] = self::tree($event->placement); } - private static function withDefaultInstance(stdClass $placement): stdClass + /** + * What makes two fixed entries one box: everything but `placement_id`, which only restates + * the container and position (1.10), with the default instance spelled out. + */ + private static function identity(stdClass $placement): stdClass { $copy = self::tree($placement); + unset($copy->placement_id); if (!JsonValue::has($copy, 'container_instance')) { $copy->container_instance = 1; } @@ -555,11 +613,22 @@ private static function checkSequences(stdClass $revision, int $position, int $l return $last; } - /** @param list $issues */ - private static function checkRequest(stdClass $revision, stdClass $parent, int $position, array &$issues): void + /** + * @param mixed $artifact the artifact this revision approved, when the caller gave one + * @param list $issues + */ + private static function checkRequest(stdClass $revision, stdClass $parent, $artifact, int $position, array &$issues): void { try { $derived = self::applyEvents($parent->request, $revision->events); + if (self::holdsCutBoxes($derived)) { + // The cut sizes live only in the approved artifact. + if ($artifact === null) { + $issues[] = new RevisionIssue('artifact_required', $position, 'fixed items in a made-to-measure box are checked against the approved artifact'); + return; + } + $derived = self::stockedRequest($derived, $artifact, self::number($revision)); + } } catch (PlanRevisionException $error) { $issues[] = new RevisionIssue('request_mismatch', $position, 'the events do not apply: ' . $error->getMessage()); return; @@ -589,6 +658,257 @@ private static function checkArtifact(stdClass $revision, stdClass $parent, $art } } + // ------------------------------------------------------------- cut-to-measure stock + + /** + * `stockCutBoxes` on a tree already deep-copied, so it mutates freely. + * + * @param mixed $artifact + * @throws PlanRevisionException + */ + private static function stockedRequest(stdClass $derived, $artifact, int $revision): stdClass + { + $fixed = JsonValue::get($derived, 'fixed_placements'); + $containers = JsonValue::get($derived, 'containers'); + if (!JsonValue::isList($fixed) || !JsonValue::isList($containers)) { + return $derived; + } + $machines = self::machines($containers); + $stocked = []; + $named = []; + $cuts = null; + foreach ($fixed as $entry) { + $machineId = $entry instanceof stdClass ? JsonValue::get($entry, 'container_type') : null; + if (!\is_string($machineId) || !isset($machines[$machineId])) { + continue; + } + $instance = JsonValue::integer(JsonValue::has($entry, 'container_instance') ? $entry->container_instance : 1); + $stockId = "{$machineId}@{$revision}#" . ($instance === null ? 'None' : $instance); + if (!isset($named[$stockId])) { + $cuts ??= self::cutBoxes($artifact); + $named[$stockId] = self::stockBox($derived, $machines[$machineId], $stockId, self::cutInner($cuts, $machineId, $instance)); + $stocked[$machineId][] = $named[$stockId]; + } + $entry->container_type = $stockId; + $entry->container_instance = 1; + // A stated id named the cut box's instance of the machine, which this request no + // longer has; admission would refuse it as a mismatch. + unset($entry->placement_id); + } + if ($named === []) { + return $derived; + } + self::refuseClash(\array_keys($named), $containers); + $derived->containers = self::rebuilt($containers, $stocked); + return $derived; + } + + /** Whether a fixed placement names a made-to-measure container type. @param stdClass $request */ + private static function holdsCutBoxes(stdClass $request): bool + { + $containers = JsonValue::get($request, 'containers'); + $fixed = JsonValue::get($request, 'fixed_placements'); + if (!JsonValue::isList($containers) || !JsonValue::isList($fixed)) { + return false; + } + $machines = self::machines($containers); + foreach ($fixed as $entry) { + $type = $entry instanceof stdClass ? JsonValue::get($entry, 'container_type') : null; + if (\is_string($type) && isset($machines[$type])) { + return true; + } + } + return false; + } + + /** @param list $containers @return array */ + private static function machines(array $containers): array + { + $machines = []; + foreach ($containers as $entry) { + if ($entry instanceof stdClass && \is_string(JsonValue::get($entry, 'id')) && JsonValue::get($entry, 'made_to_measure') !== null) { + $machines[$entry->id] = $entry; + } + } + return $machines; + } + + /** @param list $names @param list $containers */ + private static function refuseClash(array $names, array $containers): void + { + $existing = []; + foreach ($containers as $container) { + $id = $container instanceof stdClass ? JsonValue::get($container, 'id') : null; + if (\is_string($id)) { + $existing[$id] = true; + } + } + $clash = null; + foreach ($names as $name) { + if (isset($existing[$name]) && ($clash === null || strcmp($name, $clash) < 0)) { + $clash = $name; + } + } + if ($clash !== null) { + throw new PlanRevisionException('event_conflict', 'a container is already named ' . CanonicalJson::spelling($clash)); + } + } + + /** + * @param list $containers @param array> $stocked + * @return list + */ + private static function rebuilt(array $containers, array $stocked): array + { + $rebuilt = []; + foreach ($containers as $container) { + $id = $container instanceof stdClass ? JsonValue::get($container, 'id') : null; + $boxes = \is_string($id) ? ($stocked[$id] ?? []) : []; + if ($boxes === []) { + $rebuilt[] = $container; + continue; + } + $quantity = JsonValue::get($container, 'quantity') === null ? null : JsonValue::integer($container->quantity); + if ($quantity === null || $quantity > \count($boxes)) { + if ($quantity !== null) { + $container->quantity = $quantity - \count($boxes); + } + $rebuilt[] = $container; + } + \array_push($rebuilt, ...$boxes); + } + return $rebuilt; + } + + /** + * Index raw shapes in artifact order; only selected dimensions are parsed. O(A). + * + * @param mixed $artifact @return array> + */ + private static function cutBoxes($artifact): array + { + $work = JsonValue::isObject($artifact) ? JsonValue::get($artifact, 'work_order') : null; + $geometry = JsonValue::isObject($artifact) ? JsonValue::get($artifact, 'geometry') : null; + $orders = JsonValue::isObject($work) ? JsonValue::get($work, 'containers') : null; + $shapes = JsonValue::isObject($geometry) ? JsonValue::get($geometry, 'containers') : null; + $cuts = []; + if (JsonValue::isList($orders) && JsonValue::isList($shapes)) { + $count = \min(\count($orders), \count($shapes)); + for ($index = 0; $index < $count; ++$index) { + $type = JsonValue::isObject($orders[$index]) ? JsonValue::get($orders[$index], 'container_type') : null; + if (\is_string($type)) { + $cuts[$type][] = $shapes[$index]; + } + } + } + return $cuts; + } + + /** @param array> $cuts @return array{0:int,1:int,2:int} */ + private static function cutInner(array $cuts, string $machineId, ?int $instance): array + { + $shapes = $cuts[$machineId] ?? []; + if ($instance !== null && $instance >= 1 && $instance <= \count($shapes)) { + $shape = $shapes[$instance - 1]; + return [self::artifactTicks($shape, 'length'), self::artifactTicks($shape, 'width'), self::artifactTicks($shape, 'height')]; + } + throw new PlanRevisionException('invalid_artifact', "the approved plan holds no {$machineId} instance " . CanonicalJson::spelling($instance)); + } + + /** @param mixed $shape */ + private static function artifactTicks($shape, string $axis): int + { + $sides = JsonValue::isObject($shape) ? JsonValue::get($shape, 'inner_dimensions') : null; + $value = JsonValue::isObject($sides) ? JsonValue::get($sides, $axis) : null; + if (!\is_string($value) || \preg_match('/^[0-9]+$/', $value) !== 1 + || BigInt::compare(\ltrim($value, '0') ?: '0', (string) JsonValue::MAX_EXACT_MAGNITUDE) > 0) { + throw new PlanRevisionException('invalid_artifact', "a cut box's {$axis} is not a tick count"); + } + return (int) $value; + } + + /** + * The stock container a cut box becomes, priced as `Container::fabricate` prices it. + * + * @param array{0:int,1:int,2:int} $inner + */ + private static function stockBox(stdClass $request, stdClass $machine, string $stockId, array $inner): stdClass + { + $units = self::stockObject(JsonValue::get($request, 'units'), 'units', true); + $unit = JsonValue::get($units, 'length') ?? 'mm'; + if (!\is_string($unit)) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's units.length is not a string"); + } + $spec = self::stockObject($machine->made_to_measure, 'made_to_measure'); + $allowance = self::stockObject(JsonValue::get($spec, 'outer_allowance'), 'outer_allowance', true); + $outer = []; + foreach (self::CUT_SIDES as $index => $axis) { + $side = JsonValue::get($allowance, $axis); + $outer[] = $inner[$index] + ($side === null ? 0 : self::stockMeasure($side, Length::class, $unit, 'outer_allowance')); + } + $area = MadeToMeasure::surfaceArea($inner); + $price = self::stockInteger(JsonValue::get($spec, 'cost_per_square_metre_minor'), 'cost_per_square_metre_minor'); + $rate = JsonValue::get($spec, 'tare_per_square_metre'); + $tareRate = $rate === null ? 0 : self::stockMeasure($rate, Weight::class, 'g', 'tare_per_square_metre'); + $tare = JsonValue::get($machine, 'tare_weight'); + $declaredTare = $tare === null ? 0 : self::stockMeasure($tare, Weight::class, 'g', 'tare_weight'); + $box = new stdClass(); + foreach (JsonValue::members($machine) as [$name, $value]) { + if ($name !== 'made_to_measure') { + $box->{$name} = self::tree($value); + } + } + $box->id = $stockId; + $box->quantity = 1; + $box->inner_dimensions = self::tickBox($inner); + $box->outer_dimensions = self::tickBox($outer); + $fee = self::stockInteger(JsonValue::get($machine, 'cost_minor'), 'cost_minor'); + $box->cost_minor = (int) BigInt::add((string) $fee, MadeToMeasure::perSquareMetre($price, $area)); + $box->tare_weight = (object) ['value' => BigInt::add((string) $declaredTare, MadeToMeasure::perSquareMetre($tareRate, $area)), 'unit' => 'ticks']; + return $box; + } + + /** @param mixed $value */ + private static function stockObject($value, string $name, bool $optional = false): stdClass + { + if ($value === null && $optional) { + return new stdClass(); + } + if (!$value instanceof stdClass) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's {$name} is not an object"); + } + return $value; + } + + /** @param mixed $value */ + private static function stockInteger($value, string $name): int + { + $integer = JsonValue::integer($value ?? 0); + if ($integer === null) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's {$name} is not an integer"); + } + return $integer; + } + + /** @param mixed $value @param class-string|class-string $kind */ + private static function stockMeasure($value, string $kind, string $unit, string $name): int + { + if (MeasureReading::verdict($value, $kind, $unit) !== MeasureReading::READABLE) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's {$name} is not a measure"); + } + return MeasureReading::ticks($value, $kind, $unit); + } + + /** @param list $sides */ + private static function tickBox(array $sides): stdClass + { + $box = new stdClass(); + foreach (self::CUT_SIDES as $index => $axis) { + $box->{$axis} = (object) ['value' => (string) $sides[$index], 'unit' => 'ticks']; + } + return $box; + } + // --------------------------------------------------------------------------- values /** diff --git a/src/Serialization/ArrayCodec.php b/src/Serialization/ArrayCodec.php index f5520fc..2126b84 100644 --- a/src/Serialization/ArrayCodec.php +++ b/src/Serialization/ArrayCodec.php @@ -5,7 +5,7 @@ use InvalidArgumentException; use Packvium\Algorithm\EffortBudget; use Packvium\Config\{PackingConfig,SolverProfile}; -use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,Item,MadeToMeasure,Obstacle,Point,RateTable,Rotation,ShapeType}; +use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,Item,MadeToMeasure,Obstacle,OverhangLimit,Point,RateTable,Rotation,ShapeType}; use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; use Packvium\Policy\PolicyRuleSet; @@ -46,12 +46,10 @@ private static function axles(?array $r,string $unit):?array{if($r===null)return // list in, when PHP gained both the solver behaviour and the independent // validation the staged rollout requires. Rust and the JavaScript fallback still // carry them. - // `pallet_overhang_limit` was reserved in the schema by at the 1.1.0 - // contract freeze and is refused everywhere until an engine implements it from a - // request: a field a caller can set and the solver ignores is worse than a refusal. // `access_directions` left this list in, which wired the reserved field - // through to `StopAccessibilityConstraint` in all four engines at once. - 'item'=>[],'container'=>['pallet_overhang_limit']]; + // through to `StopAccessibilityConstraint` in all four engines at once, and + // `pallet_overhang_limit` in, which did the same for the pallet deck. + 'item'=>[],'container'=>[]]; /** * `item.shape_type` values this engine does not implement. @@ -105,6 +103,7 @@ public static function rejectUnsupported(array $data,?array $unsupported=null,?a } } foreach(self::madeToMeasureCombinations($data) as $name)$found[$name]=true; + foreach(self::palletOverhangCombinations($data) as $name)$found[$name]=true; foreach(self::entries($data,'items') as $entry){ if(!is_array($entry))continue; $shape=$entry['shape_type']??null; @@ -137,8 +136,6 @@ public static function madeToMeasureCombinations(array $data):array if(($entry['axles']??null)!==null)$found['container.made_to_measure+axles']=true; $obstacles=$entry['obstacles']??null; if(JsonValue::isList($obstacles)&&$obstacles!==[])$found['container.made_to_measure+obstacles']=true; - $reserve=$entry['void_fill_reserve_ratio']??null; - if((is_int($reserve)||is_float($reserve))&&$reserve>0)$found['container.made_to_measure+void_fill_reserve_ratio']=true; } $fixed=$data['fixed_placements']??null; if($measured!==[]&&is_array($fixed)){ @@ -150,6 +147,36 @@ public static function madeToMeasureCombinations(array $data):array return array_keys($found); } + /** + * The combinations a pallet with an overhang limit refuses. Obstacles and axles + * are positioned in the declared frame the widened frame moves; doors and route corridors + * would need a wall the overhang crosses; a reserve is a share of a volume the limit leaves + * undefined; a made-to-measure box has no deck. A flat bag is refused beside it as a request + * error instead. Checked on the raw request. O(items + containers). + * + * @param array $data + * @return list + */ + public static function palletOverhangCombinations(array $data):array + { + $found=[];$pallets=false; + foreach(self::entries($data,'containers') as $entry){ + if(!is_array($entry)||($entry['pallet_overhang_limit']??null)===null)continue; + $pallets=true; + $directions=$entry['access_directions']??null; + $obstacles=$entry['obstacles']??null; + $reserve=$entry['void_fill_reserve_ratio']??null; + $present=['access_directions'=>JsonValue::isList($directions)&&$directions!==[],'axles'=>($entry['axles']??null)!==null, + 'made_to_measure'=>($entry['made_to_measure']??null)!==null,'obstacles'=>JsonValue::isList($obstacles)&&$obstacles!==[], + 'void_fill_reserve_ratio'=>(is_int($reserve)||is_float($reserve))&&$reserve>0]; + foreach($present as $name=>$set)if($set)$found["container.pallet_overhang_limit+{$name}"]=true; + } + if($pallets) + foreach(self::entries($data,'items') as $item) + if(is_array($item)&&($item['stop_index']??null)!==null){$found['container.pallet_overhang_limit+item.stop_index']=true;break;} + return array_keys($found); + } + /** @return array a collection to scan, or nothing when it is not one */ /** * The output unit a request without `output.length_unit` is written in: the @@ -176,6 +203,24 @@ private static function entries(array $data,string $collection):array{$entries=$ * @param mixed $data */ public static function pack($data):array + { + return self::packed($data,false); + } + + /** + * `pack`, with each container's `placements` a one-pass generator of the same arrays + * (`PackingResult::toStreamedArray`): what `bin/packvium` hands `PrettyJsonStream`, so + * the answer's placements are never all held at once. + * + * @param mixed $data + */ + public static function packStreamed($data):array + { + return self::packed($data,true); + } + + /** @param mixed $data */ + private static function packed($data,bool $streamPlacements):array { if(!is_array($data)||($data!==[]&&JsonValue::isList($data)))throw new InvalidRequestException('wrong_type','','must be an object'); self::rejectUnsupported($data); @@ -184,7 +229,10 @@ public static function pack($data):array catch(InvalidArgumentException|TypeError|ValueError|ArithmeticError $error){throw self::asRequestError($error);} $unit=(string)($data['units']['length']??'mm'); $out=$data['output']??[]; - $result=self::solve(new Packer($config,$extensions),$items,$containers,$fixed)->toArray($out['length_unit']??self::outputLengthCode($unit),$out['weight_unit']??'g'); + $lengthUnit=$out['length_unit']??self::outputLengthCode($unit); + $weightUnit=$out['weight_unit']??'g'; + $packed=self::solve(new Packer($config,$extensions),$items,$containers,$fixed,$data['currency']??null); + $result=$streamPlacements?$packed->toStreamedArray($lengthUnit,$weightUnit):$packed->toArray($lengthUnit,$weightUnit); $result['catalog_versions_used']=$references; return $result; } @@ -197,9 +245,9 @@ public static function pack($data):array * * @param list $items @param list $containers @param list $fixed */ - private static function solve(Packer $packer,array $items,array $containers,array $fixed):PackingResult + private static function solve(Packer $packer,array $items,array $containers,array $fixed,?string $currency):PackingResult { - $solve=\Closure::bind(static fn(Packer $packer):PackingResult=>$packer->solve($items,$containers,$fixed),null,Packer::class); + $solve=\Closure::bind(static fn(Packer $packer):PackingResult=>$packer->solve($items,$containers,$fixed,$currency),null,Packer::class); return $solve($packer); } @@ -225,7 +273,7 @@ private static function model(array $data):array $extensions=new ExtensionRegistry(($data['policy']??null)===null?[]:PolicyRuleSet::fromArray($data['policy'])->constraints()); $items=array_map(fn($r)=>self::item($r,$unit),$data['items']); $containers=array_map(fn($r)=>self::container($r,$unit),$data['containers']); - $fixed=self::fixedPlacements($data['fixed_placements']??null,$unit); + $fixed=self::fixedPlacements($data['fixed_placements']??null,$unit,$data['items']); return [$config,$references,$extensions,$items,$containers,$fixed]; } @@ -311,12 +359,13 @@ private static function box(array $r,string $unit):AxisAlignedBox{return new Axi * compiles their shape checker. O(f) for f entries. * * @param mixed $raw + * @param mixed $items the request's raw `items`, read for their hull types only past the guard * @return list */ - private static function fixedPlacements($raw,string $unit):array + private static function fixedPlacements($raw,string $unit,$items):array { if($raw===null)return []; - return array_map(fn($r)=>self::fixedPlacement($r,$unit),FixedPlacementShape::requireEntries($raw,$unit)); + return array_map(fn($r)=>self::fixedPlacement($r,$unit),FixedPlacementShape::requireEntries($raw,$unit,FixedPlacementShape::hullItemTypes($items))); } /** @@ -325,8 +374,12 @@ private static function fixedPlacements($raw,string $unit):array * * @param array $r */ - private static function fixedPlacement(array $r,string $unit):FixedPlacement{return new FixedPlacement($r['item_type'],$r['container_type'],self::point($r['position']??[],$unit),Rotation::from($r['orientation']),array_key_exists('container_instance',$r)?(int)JsonValue::integer($r['container_instance']):1);} - private static function container(array $r,string $unit):Container{$obs=[];foreach($r['obstacles']??[] as $o){$additional=array_map(fn($b)=>self::box($b,$unit),$o['additional_boxes']??[]);$obs[]=new Obstacle((string)$o['id'],self::box($o,$unit),$additional);}return new Container((string)$r['id'],Dimensions::fromArray($r['inner_dimensions'],$unit),isset($r['outer_dimensions'])?Dimensions::fromArray($r['outer_dimensions'],$unit):null,Weight::parse($r['tare_weight']??0),isset($r['max_payload'])?Weight::parse($r['max_payload']):null,(int)($r['cost_minor']??0),isset($r['quantity'])?(int)$r['quantity']:null,$obs,$r['tags']??[],isset($r['max_items'])?(int)$r['max_items']:null,$r['metadata']??[],(float)($r['void_fill_reserve_ratio']??0),array_map(static fn($v)=>(int)$v,$r['tag_limits']??[]),isset($r['max_stack_density'])?Weight::parse($r['max_stack_density']):null,self::axles($r['axles']??null,$unit),self::rateTable($r['rate_table']??null),array_map(static fn($d)=>(string)$d,$r['access_directions']??[]),[],isset($r['deformable_boundary'])?(string)$r['deformable_boundary']['kind']:null,self::madeToMeasure($r['made_to_measure']??null,$unit));} + private static function fixedPlacement(array $r,string $unit):FixedPlacement{return new FixedPlacement($r['item_type'],$r['container_type'],self::point($r['position']??[],$unit),Rotation::from($r['orientation']),array_key_exists('container_instance',$r)?(int)JsonValue::integer($r['container_instance']):1,$r['placement_id']??null);} + private static function container(array $r,string $unit):Container{$obs=[];foreach($r['obstacles']??[] as $o){$additional=array_map(fn($b)=>self::box($b,$unit),$o['additional_boxes']??[]);$obs[]=new Obstacle((string)$o['id'],self::box($o,$unit),$additional);}return new Container((string)$r['id'],Dimensions::fromArray($r['inner_dimensions'],$unit),isset($r['outer_dimensions'])?Dimensions::fromArray($r['outer_dimensions'],$unit):null,Weight::parse($r['tare_weight']??0),isset($r['max_payload'])?Weight::parse($r['max_payload']):null,(int)($r['cost_minor']??0),isset($r['quantity'])?(int)$r['quantity']:null,$obs,$r['tags']??[],isset($r['max_items'])?(int)$r['max_items']:null,$r['metadata']??[],(float)($r['void_fill_reserve_ratio']??0),array_map(static fn($v)=>(int)$v,$r['tag_limits']??[]),isset($r['max_stack_density'])?Weight::parse($r['max_stack_density']):null,self::axles($r['axles']??null,$unit),self::rateTable($r['rate_table']??null),array_map(static fn($d)=>(string)$d,$r['access_directions']??[]),[],isset($r['deformable_boundary'])?(string)$r['deformable_boundary']['kind']:null,self::madeToMeasure($r['made_to_measure']??null,$unit),self::palletOverhangLimit($r['pallet_overhang_limit']??null,$unit),null,self::sideGussetDepth($r['deformable_boundary']??null,$unit));} + /** @param array|null $r */ + private static function sideGussetDepth(?array $r,string $unit):?Length{return ($r['side_gusset_depth']??null)===null?null:new Length(MeasureReading::ticks($r['side_gusset_depth'],Length::class,$unit));} + /** @param array|null $r */ + private static function palletOverhangLimit(?array $r,string $unit):?OverhangLimit{return $r===null?null:new OverhangLimit(new Length(MeasureReading::ticks($r['length'],Length::class,$unit)),new Length(MeasureReading::ticks($r['width'],Length::class,$unit)));} /** @param array|null $r */ private static function madeToMeasure(?array $r,string $unit):?MadeToMeasure { @@ -338,5 +391,5 @@ private static function madeToMeasure(?array $r,string $unit):?MadeToMeasure $tare=$r['tare_per_square_metre']??null; return new MadeToMeasure($sides($r['minimum']??null),$sides($r['increment']??null),(int)($r['cost_per_square_metre_minor']??0),$tare===null?0:MeasureReading::ticks($tare,Weight::class,'g'),$sides($r['outer_allowance']??null)); } - private static function rateTable(?array $r):?RateTable{if($r===null)return null;return new RateTable(array_map('intval',$r['weight_brackets_g']),array_map('intval',$r['prices_minor']),(int)($r['minimum_charge_minor']??0),(int)($r['fuel_surcharge_permille']??0));} + private static function rateTable(?array $r):?RateTable{if($r===null)return null;return new RateTable(array_map('intval',$r['weight_brackets_g']),array_map('intval',$r['prices_minor']),(int)($r['minimum_charge_minor']??0),(int)($r['fuel_surcharge_permille']??0),$r['currency']??null);} } diff --git a/src/Support/FixedPlacementShape.php b/src/Support/FixedPlacementShape.php index 1ab837f..07f610f 100644 --- a/src/Support/FixedPlacementShape.php +++ b/src/Support/FixedPlacementShape.php @@ -2,6 +2,8 @@ declare(strict_types=1); namespace Packvium\Support; +use Packvium\Domain\Placement; +use Packvium\Domain\Point; use Packvium\Unit\Length; use Packvium\Validation\FixedPlacementException; use stdClass; @@ -18,28 +20,29 @@ */ final class FixedPlacementShape { - public const ORIENTATIONS = ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']; private const REQUIRED = ['item_type', 'container_type', 'orientation']; - private const FIELDS = ['item_type', 'container_type', 'orientation', 'container_instance', 'position']; + private const FIELDS = ['item_type', 'container_type', 'orientation', 'container_instance', 'position', 'placement_id']; private const AXES = ['x', 'y', 'z']; /** * The entries as JSON gave them. O(f) for f entries; an absent list never reaches here. * * Entries arrive from `json_decode(..., true)`, where `{}` is the empty array, so an empty - * array stands for an empty object wherever an object is required. + * array stands for an empty object wherever an object is required. `$hullTypes` names the + * item types that are hulls, the only ones a signed orientation may fix (1.10). * * @param mixed $raw + * @param list $hullTypes * @return list> * @throws FixedPlacementException */ - public static function requireEntries($raw, string $unit = 'mm'): array + public static function requireEntries($raw, string $unit = 'mm', array $hullTypes = []): array { if (!JsonValue::isList($raw)) { throw self::malformed('fixed_placements is a list', '/fixed_placements'); } foreach ($raw as $index => $entry) { - self::requireEntry($entry === [] ? new stdClass() : $entry, "fixed_placements[{$index}]", "/fixed_placements/{$index}", $unit); + self::requireEntry($entry === [] ? new stdClass() : $entry, "fixed_placements[{$index}]", "/fixed_placements/{$index}", $unit, $hullTypes); } return $raw; } @@ -69,8 +72,49 @@ public static function requirePoint($point, string $where, string $field, callab } } - /** @param mixed $entry */ - private static function requireEntry($entry, string $where, string $field, string $unit): void + /** + * The ids of the requested item types that are `convex_hull`, read from JSON items as + * written; anything that is not an item object names no hull. O(items). + * + * @param mixed $items + * @return list + */ + public static function hullItemTypes($items): array + { + if (!JsonValue::isList($items)) { + return []; + } + $hulls = []; + foreach ($items as $item) { + if (JsonValue::isObject($item) && JsonValue::get($item, 'shape_type') === 'convex_hull' && \is_string(JsonValue::get($item, 'id'))) { + $hulls[] = JsonValue::get($item, 'id'); + } + } + return $hulls; + } + + /** + * A fixed orientation from its item's vocabulary (1.10): an unknown code is `malformed` with + * the vocabulary listed -- six codes for a box, byte-identical to every release before -- and + * a signed code fixing a non-hull is `invalid_value`. Whether the item allows it is + * `FixedPlacementAdmission`'s rule. O(1). + * + * @param mixed $value + * @throws FixedPlacementException + */ + public static function requireOrientation($value, bool $hull, string $where, string $field): void + { + $refusal = RequestRules::orientationRefusal($value, $hull, "{$where}.orientation"); + if ($refusal !== null) { + throw new FixedPlacementException($refusal[1], $refusal[0] === 'not_allowed' ? 'malformed' : $refusal[0], $field); + } + } + + /** + * @param mixed $entry + * @param list $hullTypes + */ + private static function requireEntry($entry, string $where, string $field, string $unit, array $hullTypes): void { if (!JsonValue::isObject($entry)) { throw self::malformed("{$where} is an object", $field); @@ -89,9 +133,7 @@ private static function requireEntry($entry, string $where, string $field, strin throw self::malformed("{$where}.{$name} is a non-empty string", "{$field}/{$name}"); } } - if (!\in_array(JsonValue::get($entry, 'orientation'), self::ORIENTATIONS, true)) { - throw self::malformed("{$where}.orientation must be one of " . CanonicalJson::spelling(self::ORIENTATIONS), "{$field}/orientation"); - } + self::requireOrientation(JsonValue::get($entry, 'orientation'), \in_array(JsonValue::get($entry, 'item_type'), $hullTypes, true), $where, "{$field}/orientation"); $instance = JsonValue::has($entry, 'container_instance') ? JsonValue::integer(JsonValue::get($entry, 'container_instance')) : 1; if ($instance === null || $instance < 1) { throw self::malformed("{$where}.container_instance counts from 1", "{$field}/container_instance"); @@ -105,6 +147,39 @@ private static function requireEntry($entry, string $where, string $field, strin self::requireCoordinate(JsonValue::get($position, $axis), "{$where}.position.{$axis}", "{$field}/position/{$axis}", $unit); } } + $ticks = \array_map(static fn(string $axis): int => JsonValue::has($position, $axis) ? MeasureReading::ticks(JsonValue::get($position, $axis), Length::class, $unit) : 0, self::AXES); + self::requirePlacementId(JsonValue::get($entry, 'placement_id'), JsonValue::get($entry, 'container_type') . "#{$instance}", new Point(...$ticks), + JsonValue::get($entry, 'item_type'), JsonValue::get($entry, 'orientation'), $where, $field); + } + + /** + * A fixed placement's optional `placement_id` (1.10) restates the id its result placement + * will carry, the canonical JSON of `[#, x, y, z, + * , ]` with the position in ticks; null is absent. A non-string is + * `malformed`, like every other shape error here; a string naming another placement is + * `invalid_value`, the reason a well-typed value outside its rule carries. O(1). + * + * @param mixed $value + * @throws FixedPlacementException + */ + public static function requirePlacementId($value, string $containerId, Point $position, string $itemType, string $orientation, string $where, string $field): void + { + if ($value === null) { + return; + } + $at = "{$field}/placement_id"; + if (!\is_string($value)) { + throw self::malformed("{$where}.placement_id is a string", $at); + } + // A coordinate past 2^53 - 1 has no canonical spelling, and no container holds it: the + // admission check refuses such an entry as `outside_container`, so the id is not judged. + if (\max($position->x, $position->y, $position->z) > JsonValue::MAX_EXACT_MAGNITUDE) { + return; + } + $expected = Placement::identifier($containerId, $position, $itemType, $orientation); + if ($value !== $expected) { + throw new FixedPlacementException("{$where}.placement_id must be " . CanonicalJson::spelling($expected), 'invalid_value', $at); + } } /** diff --git a/src/Support/Internal/RareRequestRules.php b/src/Support/Internal/RareRequestRules.php index 49a1627..a32be6d 100644 --- a/src/Support/Internal/RareRequestRules.php +++ b/src/Support/Internal/RareRequestRules.php @@ -19,6 +19,8 @@ */ final class RareRequestRules { + /** The two axes `pallet_overhang_limit` requires, in the order they are checked. */ + private const PALLET_OVERHANG_FIELDS = ['length', 'width']; /** Every key the request schema's `made_to_measure` declares; it sets `additionalProperties: false`. */ private const MADE_TO_MEASURE_FIELDS = ['cost_per_square_metre_minor', 'increment', 'minimum', 'outer_allowance', 'tare_per_square_metre']; @@ -75,20 +77,48 @@ public static function madeToMeasure(\Closure $call, $container, $raw, string $w } /** - * The bag's own shape, then every container field a flat bag refuses, in the - * order of `BAG_EXCLUSIONS`. + * Both axes, each a non-negative length, and a solving frame `(L + 2l, W + 2w, H)` + * inside the admission ceiling every box is held to. Run after every other container field. + * O(1). * * @param stdClass|array $container * @param mixed $raw */ - public static function deformableBoundary(\Closure $call, $container, $raw, string $where): void + public static function palletOverhangLimit(\Closure $call, $container, $raw, string $where, string $unit): void + { + $field = "{$where}/pallet_overhang_limit"; + $limit = $call('objectAt', $raw, $field); + $call('knownFields', $limit, $field, self::PALLET_OVERHANG_FIELDS); + foreach (self::PALLET_OVERHANG_FIELDS as $axis) { + $call('measure', $call('required', $limit, $axis, $field), "{$field}/{$axis}", Length::class, $unit); + } + [$length, $width, $height] = $call('sideTicks', JsonValue::get($container, 'inner_dimensions'), $unit); + $overhangX = MeasureReading::ticks(JsonValue::get($limit, 'length'), Length::class, $unit); + $overhangY = MeasureReading::ticks(JsonValue::get($limit, 'width'), Length::class, $unit); + RequestRules::box([$length + 2 * $overhangX, $width + 2 * $overhangY, $height], $field); + } + + /** + * The bag's own shape top to bottom -- kind, unknown keys, a gusseted bag's side + * gusset (1.10) -- then every container field a bag refuses, in the order of + * `BAG_EXCLUSIONS`. O(1). + * + * @param stdClass|array $container + * @param mixed $raw + */ + public static function deformableBoundary(\Closure $call, $container, $raw, string $where, string $unit): void { $field = "{$where}/deformable_boundary"; $boundary = $call('objectAt', $raw, $field); - if (!\in_array($call('required', $boundary, 'kind', $field), FlatBag::KINDS, true)) { + $kind = $call('required', $boundary, 'kind', $field); + if (!\in_array($kind, FlatBag::KINDS, true)) { throw $call('refuse', 'not_allowed', "{$field}/kind", 'must be one of ' . CanonicalJson::spelling(FlatBag::KINDS)); } - $call('knownFields', $boundary, $field, ['kind']); + $gusseted = $kind === FlatBag::GUSSETED_BAG; + $call('knownFields', $boundary, $field, $gusseted ? ['kind', 'side_gusset_depth'] : ['kind']); + if ($gusseted) { + self::sideGussetDepth($call, $container, $call('required', $boundary, 'side_gusset_depth', $field), "{$field}/side_gusset_depth", $unit); + } foreach (RequestRules::BAG_EXCLUSIONS as $name) { if ($call('setBesideABag', $name, JsonValue::get($container, $name))) { throw $call('refuse', 'not_allowed', "{$where}/{$name}", 'cannot be combined with deformable_boundary'); @@ -96,8 +126,30 @@ public static function deformableBoundary(\Closure $call, $container, $raw, stri } } - /** @param mixed $raw */ - public static function rateTable(\Closure $call, $raw, string $where): void + /** + * A length, positive once read in ticks, and no deeper than the bag's inner width. + * + * @param stdClass|array $container + * @param mixed $value + */ + private static function sideGussetDepth(\Closure $call, $container, $value, string $field, string $unit): void + { + $call('measure', $value, $field, Length::class, $unit); + $depth = MeasureReading::ticks($value, Length::class, $unit); + if ($depth === 0) { + throw $call('refuse', 'invalid_value', $field, 'must be positive'); + } + if ($depth > $call('sideTicks', JsonValue::get($container, 'inner_dimensions'), $unit)[1]) { + throw $call('refuse', 'invalid_value', $field, 'exceeds inner_dimensions width'); + } + } + + /** + * The table's integers, then its currency against the request's (1.10). + * + * @param mixed $raw + */ + public static function rateTable(\Closure $call, $raw, string $where, ?string $currency): void { $table = $call('objectAt', $raw, $where); foreach (['weight_brackets_g' => 1, 'prices_minor' => 0] as $name => $minimum) { @@ -111,6 +163,10 @@ public static function rateTable(\Closure $call, $raw, string $where): void } $call('optionalInteger', $table, 'minimum_charge_minor', $where, 0); $call('optionalInteger', $table, 'fuel_surcharge_permille', $where, 0); + $code = JsonValue::get($table, 'currency'); + if ($code !== null) { + RequestRules::rateTableCurrency($code, "{$where}/currency", $currency); + } } /** @param mixed $raw @param array{0:int,1:int,2:int} $inner */ diff --git a/src/Support/PrettyJsonStream.php b/src/Support/PrettyJsonStream.php index f2fc266..af9b34f 100644 --- a/src/Support/PrettyJsonStream.php +++ b/src/Support/PrettyJsonStream.php @@ -18,7 +18,10 @@ * pretty encoding with `4 * d` spaces after every newline, and an encoded string never * contains a raw newline. Arrays follow `json_encode`'s rule, the one in {@see JsonValue}: * a list is a JSON array, any other array a JSON object whose names are its keys as strings. - * An empty array, and anything that is not an array, is encoded whole. + * An empty array, and anything that is not an array, is encoded whole. A `\Traversable` is + * written as the JSON list of its values, one at a time, so a caller can hand over values it + * has not built yet (`ArrayCodec::packStreamed`'s placements); an array holding one is never + * encoded whole. * * One difference, on a path no answer takes: a value `json_encode` cannot encode throws * `JsonException` after the members before it were written, where the one-shot encoding @@ -63,7 +66,11 @@ public static function write($value, $stream): void /** @param mixed $value */ private function value($value, int $depth): void { - if (!\is_array($value) || \count($value, \COUNT_RECURSIVE) <= self::WHOLE_ELEMENTS) { + if ($value instanceof \Traversable) { + $this->traversed($value, $depth); + return; + } + if (!\is_array($value) || (\count($value, \COUNT_RECURSIVE) <= self::WHOLE_ELEMENTS && !self::holdsTraversable($value))) { $this->append(self::encoded($value, $depth)); return; } @@ -82,6 +89,41 @@ private function value($value, int $depth): void $this->append("\n" . \str_repeat(self::INDENT, $depth) . ($list ? ']' : '}')); } + /** + * A one-pass sequence, written as the JSON list of its values: `[]` when it yields none, + * as `json_encode` writes an empty list. + * + * @param \Traversable $values + */ + private function traversed(\Traversable $values, int $depth): void + { + $separator = "\n" . \str_repeat(self::INDENT, $depth + 1); + $first = true; + foreach ($values as $member) { + $this->append(($first ? '[' : ',') . $separator); + $first = false; + $this->value($member, $depth + 1); + } + $this->append($first ? '[]' : "\n" . \str_repeat(self::INDENT, $depth) . ']'); + } + + /** + * Whether a sequence sits anywhere inside a small array, which then cannot be encoded + * whole: `json_encode` writes an object it cannot see into as `{}`. Asked only of an + * array of at most {@see self::WHOLE_ELEMENTS} elements, so O(1). + * + * @param array $value + */ + private static function holdsTraversable(array $value): bool + { + foreach ($value as $member) { + if ($member instanceof \Traversable || (\is_array($member) && self::holdsTraversable($member))) { + return true; + } + } + return false; + } + /** @param mixed $value */ private static function encoded($value, int $depth): string { diff --git a/src/Support/RationalParser.php b/src/Support/RationalParser.php index c224122..43e2b16 100644 --- a/src/Support/RationalParser.php +++ b/src/Support/RationalParser.php @@ -22,7 +22,9 @@ public static function parse(int|string $value): array $negative = str_starts_with($text, '-'); if (preg_match('/^([+-]?\d+)\s+(\d+)\s*\/\s*(\d+)$/', $text, $m)) { $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)) { + // `abs(PHP_INT_MIN)` is a float that compares equal to PHP_INT_MAX, so it would slip + // past the range check and fail later as a type error rather than an overflow. + if ($whole === PHP_INT_MIN || ($whole !== 0 && abs($whole) > intdiv(PHP_INT_MAX - $n, $d))) { throw new InvalidArgumentException('Scaled unit value exceeds integer range'); } $magnitude = abs($whole) * $d + $n; diff --git a/src/Support/RequestObjects.php b/src/Support/RequestObjects.php index 4c61ec1..0d6a721 100644 --- a/src/Support/RequestObjects.php +++ b/src/Support/RequestObjects.php @@ -8,7 +8,9 @@ use Packvium\Domain\FixedPlacement; use Packvium\Domain\Item; use Packvium\Domain\MadeToMeasure; +use Packvium\Domain\OverhangLimit; use Packvium\Domain\RateTable; +use Packvium\Domain\ShapeType; use Packvium\Serialization\InvalidRequestException; use Packvium\Validation\FixedPlacementException; @@ -18,7 +20,7 @@ * Held to `packvium.request_objects.check_objects`. `RequestRules::check` walks a JSON * request; `Packer::pack` takes objects, whose own constructors already refuse most of the * same values but cannot know where in a request they will sit. This walks the objects in the - * JSON rules' order -- configuration, items, item ids, containers, container ids, fixed + * JSON rules' order -- currency, configuration, items, item ids, containers, container ids, fixed * placements -- with the same primitives, so a value the JSON path refuses is refused here with the same reason and * the same RFC 6901 field. Only rules `RequestRules::check` also applies are checked, so on * the JSON path, which runs that first, this never refuses anything. @@ -51,23 +53,48 @@ final class RequestObjects * @param list $fixedPlacements * @throws InvalidRequestException */ - public static function check(array $items, array $containers, PackingConfig $config, array $fixedPlacements = []): void + public static function check(array $items, array $containers, PackingConfig $config, array $fixedPlacements = [], ?string $currency = null): void { + if ($currency !== null) { + RequestRules::currencyCode($currency, '/currency'); + } self::configuration($config); foreach ($items as $index => $item) { self::item($item, "/items/{$index}"); } RequestRules::requireUniqueIds(\array_map(static fn(Item $item): string => $item->id, $items), 'items'); foreach ($containers as $index => $container) { - self::container($container, "/containers/{$index}"); + self::container($container, "/containers/{$index}", $currency); } RequestRules::requireUniqueIds(\array_map(static fn(Container $container): string => $container->id, $containers), 'containers'); + self::routesBesidePallets($items, $containers); RequestRules::totalWeight( \array_map(static fn(Item $item): array => [$item->weight->ticks, $item->quantity], $items), \array_map(static fn(Container $container): int => $container->tareWeight->ticks, $containers), ); + $hullTypes = \array_values(\array_map(static fn(Item $item): string => $item->id, + \array_filter($items, static fn(Item $item): bool => $item->shapeType === ShapeType::CONVEX_HULL))); foreach ($fixedPlacements as $index => $placement) { - self::fixedPlacement($placement, "fixed_placements[{$index}]", "/fixed_placements/{$index}"); + self::fixedPlacement($placement, "fixed_placements[{$index}]", "/fixed_placements/{$index}", $hullTypes); + } + } + + /** + * A routed item beside a pallet that allows overhang: the JSON path refuses it as + * `container.pallet_overhang_limit+item.stop_index`, this one at the first routed item. + * + * @param list $items @param list $containers + */ + private static function routesBesidePallets(array $items, array $containers): void + { + $pallets = \array_filter($containers, static fn(Container $container): bool => $container->palletOverhangLimit !== null); + if ($pallets === []) { + return; + } + foreach ($items as $index => $item) { + if ($item->stopIndex !== null) { + throw new InvalidRequestException('not_allowed', "/items/{$index}/stop_index", 'cannot be combined with pallet_overhang_limit'); + } } } @@ -75,18 +102,23 @@ public static function check(array $items, array $containers, PackingConfig $con * `FixedPlacementShape`'s rules that an object can break, in its order and with its refusal; * the types hold the orientation and the position, and `Point` refuses a negative * coordinate. Whether the set can hold is `FixedPlacementAdmission`'s to say. + * + * @param list $hullTypes the item types a signed orientation may fix (1.10) */ - private static function fixedPlacement(FixedPlacement $placement, string $where, string $field): void + private static function fixedPlacement(FixedPlacement $placement, string $where, string $field, array $hullTypes): void { foreach (['item_type' => $placement->itemId, 'container_type' => $placement->containerId] as $name => $value) { if ($value === '') { throw new FixedPlacementException("{$where}.{$name} is a non-empty string", 'malformed', "{$field}/{$name}"); } } + FixedPlacementShape::requireOrientation($placement->rotation->value, \in_array($placement->itemId, $hullTypes, true), $where, "{$field}/orientation"); $instance = JsonValue::integer($placement->containerInstance); if ($instance === null || $instance < 1) { throw new FixedPlacementException("{$where}.container_instance counts from 1", 'malformed', "{$field}/container_instance"); } + FixedPlacementShape::requirePlacementId($placement->placementId, $placement->packedContainerId(), $placement->position, + $placement->itemId, $placement->rotation->value, $where, $field); } /** @@ -132,7 +164,7 @@ private static function item(Item $item, string $where): void } } - private static function container(Container $container, string $where): void + private static function container(Container $container, string $where, ?string $currency): void { self::optionalInteger($container->quantity, "{$where}/quantity", 1); RequestRules::box(self::sides($container->innerDimensions), "{$where}/inner_dimensions"); @@ -144,7 +176,7 @@ private static function container(Container $container, string $where): void RequestRules::ratio($container->voidFillReserveRatio, "{$where}/void_fill_reserve_ratio", 1); self::tagLimits($container->tagLimits, "{$where}/tag_limits"); if ($container->rateTable !== null) { - self::rateTable($container->rateTable, "{$where}/rate_table"); + self::rateTable($container->rateTable, "{$where}/rate_table", $currency); } if ($container->deformableBoundary !== null) { self::flatBag($container, $where); @@ -152,6 +184,19 @@ private static function container(Container $container, string $where): void if ($container->madeToMeasure !== null) { self::madeToMeasure($container, $container->madeToMeasure, $where); } + if ($container->palletOverhangLimit !== null) { + self::palletOverhangLimit($container, $container->palletOverhangLimit, $where); + } + } + + /**: each axis, then the solving frame, against the admission ceiling. O(1). */ + private static function palletOverhangLimit(Container $container, OverhangLimit $limit, string $where): void + { + $field = "{$where}/pallet_overhang_limit"; + RequestRules::lengthTicks($limit->length->ticks, "{$field}/length"); + RequestRules::lengthTicks($limit->width->ticks, "{$field}/width"); + [$length, $width, $height] = self::sides($container->innerDimensions); + RequestRules::box([$length + 2 * $limit->length->ticks, $width + 2 * $limit->width->ticks, $height], $field); } /** @@ -169,7 +214,7 @@ private static function tagLimits(array $limits, string $where): void } } - private static function rateTable(RateTable $table, string $where): void + private static function rateTable(RateTable $table, string $where, ?string $currency): void { foreach (['weight_brackets_g' => [$table->weightBracketsG, 1], 'prices_minor' => [$table->pricesMinor, 0]] as $name => [$values, $minimum]) { foreach ($values as $index => $value) { @@ -178,6 +223,9 @@ private static function rateTable(RateTable $table, string $where): void } RequestRules::integer($table->minimumChargeMinor, "{$where}/minimum_charge_minor", 0); RequestRules::integer($table->fuelSurchargePermille, "{$where}/fuel_surcharge_permille", 0); + if ($table->currency !== null) { + RequestRules::rateTableCurrency($table->currency, "{$where}/currency", $currency); + } } /** @@ -192,7 +240,7 @@ private static function flatBag(Container $container, string $where): void 'obstacles' => $container->obstacles, 'axles' => $container->axles, 'access_directions' => $container->accessDirections, 'max_stack_density' => $container->maxStackDensity, 'outer_dimensions' => $container->outerDimensions, 'void_fill_reserve_ratio' => $container->voidFillReserveRatio, - 'made_to_measure' => $container->madeToMeasure, + 'made_to_measure' => $container->madeToMeasure, 'pallet_overhang_limit' => $container->palletOverhangLimit, ]; foreach (RequestRules::BAG_EXCLUSIONS as $name) { $value = $fields[$name] === [] ? null : $fields[$name]; diff --git a/src/Support/RequestRules.php b/src/Support/RequestRules.php index 418bc61..a6019fb 100644 --- a/src/Support/RequestRules.php +++ b/src/Support/RequestRules.php @@ -4,6 +4,7 @@ use Packvium\Domain\FlatBag; use Packvium\Domain\MadeToMeasure; +use Packvium\Domain\Orientations; use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\Length; use Packvium\Unit\Weight; @@ -14,7 +15,7 @@ * The request schema's rules, walked over the decoded JSON before any model is built. * * Held to `packvium.request_errors.check_request`: the first violation wins, in the order every - * engine follows -- units, output, configuration, items, containers -- and is refused with the same + * engine follows -- units, output, currency, configuration, items, containers -- and is refused with the same * reason, JSON Pointer and message the reference raises. * * The request arrives from `json_decode(..., true)`, where `{}` and `[]` are the same empty @@ -28,7 +29,6 @@ final class RequestRules public const ACCESS_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; /** The schema's closed vocabularies, each refused as `not_allowed` like the two above. */ public const SOLVERS = ['grid', 'extreme_points', 'homogeneous_blocks', 'layer', 'maximal_spaces', 'exact_small']; - public const ROTATIONS = ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']; public const LENGTH_UNITS = ['mm', 'cm', 'm', 'in', 'ft']; public const WEIGHT_UNITS = ['mg', 'g', 'kg', 'oz', 'lb']; public const GROUND_CONTACT_RULES = ['free', 'covered', 'single', 'multiple']; @@ -54,7 +54,7 @@ final class RequestRules private const ITEM_BOOLEANS = ['keep_upright', 'stackable', 'must_be_on_floor']; /** Container fields a flat bag refuses, in reporting order (docs/DEFORMABLE-CONTAINERS.md). */ public const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', - 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure']; + 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure', 'pallet_overhang_limit']; public const WEIGHT_UNIT = 'g'; /** * The admission ceiling every engine refuses past: a length is a tick count @@ -80,6 +80,7 @@ public static function check($data): void $request = self::objectAt($data, ''); $unit = self::units(JsonValue::get($request, 'units')); self::output(JsonValue::get($request, 'output')); + $currency = self::requestCurrency(JsonValue::get($request, 'currency')); self::configuration(JsonValue::get($request, 'configuration'), $unit); $items = self::requiredList($request, 'items', ''); foreach ($items as $index => $raw) { @@ -88,7 +89,7 @@ public static function check($data): void self::requireUniqueIds(self::identifiers($items), 'items'); $containers = self::requiredList($request, 'containers', ''); foreach ($containers as $index => $raw) { - self::container($raw, "/containers/{$index}", $unit); + self::container($raw, "/containers/{$index}", $unit, $currency); } self::requireUniqueIds(self::identifiers($containers), 'containers'); self::totalWeight(\array_map( @@ -136,7 +137,10 @@ private static function units($raw): string if ($raw === null) { return 'mm'; } - $length = JsonValue::get(self::objectAt($raw, '/units'), 'length'); + $units = self::objectAt($raw, '/units'); + // `{"length": "cm", "weight": "kg"}` used to read every bare weight as grams. + self::knownFields($units, '/units', ['length']); + $length = JsonValue::get($units, 'length'); if ($length === null) { return 'mm'; } @@ -232,12 +236,67 @@ private static function item($raw, string $where, string $unit): void self::stackingGroupName($name, "{$where}/accepts_stacking_groups/{$index}"); } } - self::optionalEachOneOf($item, 'allowed_rotations', $where, self::ROTATIONS); + self::optionalAllowedRotations($item, $where); self::optionalOneOf($item, 'ground_contact_rule', $where, self::GROUND_CONTACT_RULES); self::optionalOneOf($item, 'shape_type', $where, self::SHAPE_TYPES); foreach (self::ITEM_BOOLEANS as $name) { self::optionalBoolean($item, $name, $where); } + $listed = JsonValue::get($item, 'allowed_rotations'); + if ($listed !== null) { + $upright = JsonValue::get($item, 'keep_upright') === true; + foreach ($listed as $code) { + if (!$upright || \in_array($code, Orientations::UPRIGHT_CODES, true)) { + return; + } + } + throw self::refuse('invalid_value', "{$where}/allowed_rotations", 'must allow at least one rotation after keep_upright'); + } + } + + /** + * Each code from the item's vocabulary (1.10): all 24 for a hull, the six legacy codes for + * anything else, where a signed code is a rule broken rather than an unknown word. The shape + * is read as written, so a shape no engine knows is not a hull. O(len(list)). + * + * @param stdClass|array $item + */ + private static function optionalAllowedRotations($item, string $where): void + { + $value = JsonValue::get($item, 'allowed_rotations'); + if ($value === null) { + return; + } + $hull = JsonValue::get($item, 'shape_type') === 'convex_hull'; + foreach (self::listAt($value, "{$where}/allowed_rotations") as $index => $code) { + $refusal = self::orientationRefusal($code, $hull); + if ($refusal !== null) { + throw self::refuse($refusal[0], "{$where}/allowed_rotations/{$index}", $refusal[1]); + } + } + } + + /** + * Why `$value` cannot orient an item of this shape, as `[reason, detail]`, or null when it + * can (`Orientations::refusalReason`). `$where` names the value inside the detail, the way a + * fixed placement or a revision event words its own refusals. Shared by every field that + * names a requested item's orientation. O(1). + * + * @param mixed $value + * @return array{0:string,1:string}|null + */ + public static function orientationRefusal($value, bool $hull, string $where = ''): ?array + { + $reason = Orientations::refusalReason($value, $hull); + if ($reason === null) { + return null; + } + if ($reason === 'invalid_value') { + $signed = Orientations::SIGNED_CODE_NEEDS_A_HULL; + return [$reason, $where === '' ? $signed : "{$where}: {$signed}"]; + } + $rule = 'must be one of ' . CanonicalJson::spelling(Orientations::vocabulary($hull)); + return [$reason, $where === '' ? $rule : "{$where} {$rule}"]; } /** @param mixed $value */ @@ -251,8 +310,58 @@ public static function stackingGroupName($value, string $field): void } } + /** + * The request's `currency`, absent when null, or refused. O(1). + * + * @param mixed $raw + */ + private static function requestCurrency($raw): ?string + { + if ($raw === null) { + return null; + } + self::currencyCode($raw, '/currency'); + return (string) $raw; + } + + /** + * An ISO 4217 shape, `^[A-Z]{3}$`, with no code list: the engines never convert, so a code + * they do not know is still one they can echo (docs/SERIALIZATION.md). ASCII letters only, + * and `\z` rather than `$`, which would let a trailing newline through. Shared with + * `RequestObjects`. O(1). + * + * @param mixed $value + */ + public static function currencyCode($value, string $field): void + { + if (!\is_string($value)) { + throw self::refuse('wrong_type', $field, 'must be a string'); + } + if (\preg_match('/\A[A-Z]{3}\z/', $value) !== 1) { + throw self::refuse('invalid_value', $field, 'must be three capital letters (ISO 4217)'); + } + } + + /** + * A rate table prices in the request's currency or says nothing: a table in another one + * would be ranked as though its minor units were the request's. Shared with + * `RequestObjects`. O(1). + * + * @param mixed $value + */ + public static function rateTableCurrency($value, string $field, ?string $currency): void + { + self::currencyCode($value, $field); + if ($currency === null) { + throw self::refuse('missing_field', '/currency', 'is required when a rate_table declares a currency'); + } + if ($value !== $currency) { + throw self::refuse('not_allowed', $field, 'must equal the request currency ' . CanonicalJson::spelling($currency)); + } + } + /** @param mixed $raw */ - private static function container($raw, string $where, string $unit): void + private static function container($raw, string $where, string $unit, ?string $currency): void { $container = self::objectAt($raw, $where); self::requiredString($container, 'id', $where); @@ -278,7 +387,7 @@ private static function container($raw, string $where, string $unit): void } $rateTable = JsonValue::get($container, 'rate_table'); if ($rateTable !== null) { - RareRequestRules::rateTable(self::bridge(), $rateTable, "{$where}/rate_table"); + RareRequestRules::rateTable(self::bridge(), $rateTable, "{$where}/rate_table", $currency); } $obstacles = JsonValue::get($container, 'obstacles'); if ($obstacles !== null) { @@ -286,12 +395,16 @@ private static function container($raw, string $where, string $unit): void } $boundary = JsonValue::get($container, 'deformable_boundary'); if ($boundary !== null) { - RareRequestRules::deformableBoundary(self::bridge(), $container, $boundary, $where); + RareRequestRules::deformableBoundary(self::bridge(), $container, $boundary, $where, $unit); } $machine = JsonValue::get($container, 'made_to_measure'); if ($machine !== null) { RareRequestRules::madeToMeasure(self::bridge(), $container, $machine, $where, $unit); } + $limit = JsonValue::get($container, 'pallet_overhang_limit'); + if ($limit !== null) { + RareRequestRules::palletOverhangLimit(self::bridge(), $container, $limit, $where, $unit); + } } /** diff --git a/src/Support/ResultValidation/Accounting.php b/src/Support/ResultValidation/Accounting.php index a94048f..4459d5a 100644 --- a/src/Support/ResultValidation/Accounting.php +++ b/src/Support/ResultValidation/Accounting.php @@ -150,7 +150,7 @@ public static function fitsEmpty(ContainerSpec $container, array $size): bool } return !$container->flatBag || (Exact::compare(Exact::add($size[0], $size[2]), $container->inner[0]) <= 0 - && Exact::compare(Exact::add($size[1], $size[2]), $container->inner[1]) <= 0); + && Exact::compare(Exact::add($size[1], $size[2]), Exact::add($container->inner[1], $container->sideGusset)) <= 0); } /** @@ -218,7 +218,7 @@ private static function checkReasonProof($unpacked, ?ItemSpec $spec, Context $co /** @param mixed $unpacked @param mixed $reason @param list $issues */ private static function checkProvenReason($unpacked, $reason, ItemSpec $spec, Context $context, string $itemId, array &$issues): void { - $every = \array_keys(Geometry::ROTATIONS); + $every = Geometry::BOX_ROTATIONS; if (Json::isText($reason, 'no_compatible_container_dimensions')) { if (self::fitsSome($spec, $context, $spec->allowedRotations)) { $issues[] = new ResultIssue('invalid_proven_reason', "{$itemId}: at least one allowed orientation fits a container"); diff --git a/src/Support/ResultValidation/Bound.php b/src/Support/ResultValidation/Bound.php index f5dc74f..0ad119d 100644 --- a/src/Support/ResultValidation/Bound.php +++ b/src/Support/ResultValidation/Bound.php @@ -16,8 +16,17 @@ */ final class Bound { - /** Where each covered objective reads `(L0, L1, L2, L3, L4)` in its own score order. */ - private const ORDERS = ['default' => [0, 1, 2, 3, 4], 'lowest_cost' => [0, 2, 1, 3, 4]]; + /** + * Where each covered objective reads `(L0, L1, L2, L3, L4)` in its own score order, a name + * standing for the one key only that objective ranks by. + */ + private const ORDERS = [ + 'default' => [0, 1, 2, 3, 4], + 'lowest_cost' => [0, 2, 1, 3, 4], + 'maximum_value' => [0, 'value_forgone', 1, 2, 3], + 'open_dimension_height' => [0, 'achieved_height', 1, 2, 3], + 'maximum_volume' => ['unpacked_volume_ppm', 0, 1, 2, 3], + ]; private const MAX_BOUND_SUM = '1000000000000000000000000000000'; private const MAX_BOUND_VALUE = 9007199254740991; private const SCORE_SCALE = 1000000; @@ -148,28 +157,82 @@ private static function stated($request, $status, Ordered $items, Ordered $conta if (Json::isText($status, 'invalid_result')) { return [null, "status is 'invalid_result'"]; } - [$volumes, $weights, $shrinks, $types] = self::inputs($items, $containers); - $bound = self::lowerBound($volumes, $weights, $shrinks, $types); + [$volumes, $weights, $values, $shrinks, $types] = self::inputs($items, $containers); + return self::objectiveBound($volumes, $weights, $values, $shrinks, $types, $name); + } + + /** + * The bound in a covered objective's score order, or null with the reason a ceiling withholds + * it -- the one predicate's, or the objective's own key's, which withholds that objective + * alone. Public so the shared scene can hold every objective's vector to the oracle. + * + * @param list $volumes value runs sorted ascending + * @param list $weights @param list $values + * @param list> $containers + * @return array{0:list|null,1:string} + */ + public static function objectiveBound(array $volumes, array $weights, array $values, bool $shrinks, array $containers, string $objective): array + { + $bound = self::lowerBound($volumes, $weights, $shrinks, $containers); if ($bound === null) { return [null, 'the request is past a declared ceiling']; } - return [\array_map(static function (int $position) use ($bound) { return $bound[$position]; }, self::ORDERS[$name]), '']; + $stated = \array_map(static function ($position) use ($bound, $volumes, $values, $shrinks, $containers) { + return \is_int($position) ? $bound[$position] : self::objectiveTerm($position, $volumes, $values, $shrinks, $containers, $bound[0]); + }, self::ORDERS[$objective]); + foreach ($stated as $value) { + if (Exact::compare($value, self::MAX_BOUND_VALUE) > 0) { + return [null, "the {$objective} key is past the portable ceiling"]; + } + } + return [$stated, '']; + } + + /** + * The key only one objective ranks by, each conditional on `L0` like the five: the + * least value forgone and the least summed top of a packing leaving `unpacked` behind, and + * the least unpacked share of requested volume any packing scores. O(t log t + c). + * + * @param list $volumes @param list $values + * @param list> $containers @param int|string $unpacked @return int|string + */ + private static function objectiveTerm(string $name, array $volumes, array $values, bool $shrinks, array $containers, $unpacked) + { + if ($name === 'value_forgone') { + return self::smallest($values, $unpacked); + } + if ($shrinks) { + return 0; + } + if ($name === 'achieved_height') { + $placed = Exact::sub(self::runCount($volumes), $unpacked); + $floors = self::positive(self::column($containers, 'base_area')); + return Exact::sign($placed) > 0 && $floors !== [] ? Exact::ceilDiv(self::smallest($volumes, $placed), self::largest($floors)) : 0; + } + $requested = self::sumRuns($volumes); + $capacity = self::capacityTotal(self::column($containers, 'usable'), self::column($containers, 'quantity')); + if (Exact::sign($requested) === 0 || $capacity === null) { + return 0; + } + return Exact::ceilDiv(Exact::mul(Exact::max(0, Exact::sub($requested, $capacity)), self::SCORE_SCALE), $requested); } /** * The request as the bound reads it: every instance, fixed ones included, and every type. * - * @param Ordered $items @param Ordered $containers @return array{0:list,1:list,2:bool,3:list>} + * @param Ordered $items @param Ordered $containers @return array{0:list,1:list,2:list,3:bool,4:list>} */ private static function inputs(Ordered $items, Ordered $containers): array { $volumes = []; $weights = []; + $values = []; $shrinks = false; foreach ($items->values() as $spec) { $quantity = Json::int($spec->quantity, 'quantity'); $volumes[] = [Exact::mul(Exact::mul($spec->dimensions[0], $spec->dimensions[1]), $spec->dimensions[2]), $quantity]; $weights[] = [$spec->weight, $quantity]; + $values[] = [Json::truthy($spec->value) ? Json::int($spec->value, 'value') : 0, $quantity]; $shrinks = $shrinks || ($quantity > 0 && ($spec->nestingHeight !== null || Json::isText($spec->shapeType, 'convex_hull') || Json::isText($spec->shapeType, 'compressible'))); } @@ -192,7 +255,7 @@ private static function inputs(Ordered $items, Ordered $containers): array 'quantity' => $spec->quantity, ]; } - return [self::runs($volumes), self::runs($weights), $shrinks, $types]; + return [self::runs($volumes), self::runs($weights), self::runs($values), $shrinks, $types]; } /** @param list> $containers @return list */ diff --git a/src/Support/ResultValidation/ContainerCheck.php b/src/Support/ResultValidation/ContainerCheck.php index 4f3658c..389162d 100644 --- a/src/Support/ResultValidation/ContainerCheck.php +++ b/src/Support/ResultValidation/ContainerCheck.php @@ -54,6 +54,45 @@ public static function achievedExtent($packed, $clearance): array return $extent ?? [0, 0, 0]; } + /** + * The deck grown by the overhang the placements use past each of its edges. + * + * @param mixed $packed @param array{0:int|string,1:int|string,2:int|string,3:int|string} $deck @param int|string $clearance + * @return array{0:int|string,1:int|string} + */ + public static function palletFootprint($packed, array $deck, $clearance): array + { + [$x, $y, $length, $width] = $deck; + [$lowX, $lowY, $highX, $highY] = [$x, $y, Exact::add($x, $length), Exact::add($y, $width)]; + foreach (Json::items(Json::at($packed, 'placements'), 'placements') as $placement) { + $box = self::envelope($placement, $clearance); + $lowX = Exact::compare($box->x, $lowX) < 0 ? $box->x : $lowX; + $lowY = Exact::compare($box->y, $lowY) < 0 ? $box->y : $lowY; + $highX = Exact::max($highX, $box->x2); + $highY = Exact::max($highY, $box->y2); + } + return [Exact::sub($highX, $lowX), Exact::sub($highY, $lowY)]; + } + + /** + * What a carrier measures: a bag's package; a pallet's declared footprint or its + * grown deck, the larger per axis; else the declared outer, else inner size. + * + * @param mixed $packed @param int|string $clearance @return array{0:int|string,1:int|string,2:int|string} + */ + public static function billedSize($packed, ContainerSpec $spec, $clearance): array + { + if ($spec->flatBag) { + return self::achievedExtent($packed, $clearance); + } + if ($spec->deck === null) { + return $spec->outer ?? $spec->inner; + } + [$length, $width] = self::palletFootprint($packed, $spec->deck, $clearance); + $base = $spec->outer ?? [$spec->deck[2], $spec->deck[3], $spec->inner[2]]; + return [Exact::max($base[0], $length), Exact::max($base[1], $width), $base[2]]; + } + /** * `achieved_dimensions` is present exactly when the container declares a soft size, and equals * the tight extent; a flat bag's extent must pass the girth rule. @@ -72,6 +111,9 @@ public static function checkAchievedExtent($packed, ContainerSpec $spec, $cleara return; } [$a, $b, $c] = self::achievedExtent($packed, $clearance); + if ($spec->deck !== null) { + [$a, $b] = self::palletFootprint($packed, $spec->deck, $clearance); + } $stated = null; if (Json::isDict($reported)) { $stated = []; @@ -82,8 +124,9 @@ public static function checkAchievedExtent($packed, ContainerSpec $spec, $cleara if (!self::matches($stated, [$a, $b, $c])) { $issues[] = new ResultIssue('achieved_dimensions_mismatch', "{$packedId}: reported " . self::optionalTuple($stated) . ', computed ' . PyFormat::intTuple([$a, $b, $c])); } - if ($spec->flatBag && (Exact::compare(Exact::add($a, $c), $spec->inner[0]) > 0 || Exact::compare(Exact::add($b, $c), $spec->inner[1]) > 0)) { - $issues[] = new ResultIssue('bag_girth_exceeded', "{$packedId}: a + c = " . Exact::add($a, $c) . ', b + c = ' . Exact::add($b, $c) . ", flat size {$spec->inner[0]} x {$spec->inner[1]}"); + if ($spec->flatBag && (Exact::compare(Exact::add($a, $c), $spec->inner[0]) > 0 || Exact::compare(Exact::add($b, $c), Exact::add($spec->inner[1], $spec->sideGusset)) > 0)) { + $gusset = Exact::sign($spec->sideGusset) === 0 ? '' : ", side gusset {$spec->sideGusset}"; + $issues[] = new ResultIssue('bag_girth_exceeded', "{$packedId}: a + c = " . Exact::add($a, $c) . ', b + c = ' . Exact::add($b, $c) . ", flat size {$spec->inner[0]} x {$spec->inner[1]}{$gusset}"); } $packedId->verify(); } @@ -128,6 +171,36 @@ private static function nestedTicks($block, string $key) return Json::truthy($value) ? Json::get($value, 'ticks') : null; } + /** + * Whether a reported box larger than the tight cut is a reserve cut: the tight box + * breaks the void-fill reserve, and the reported one is on the machine grid between the tight + * box and the maximum. That it keeps the reserve is the ordinary reserve check's. Reads the + * reported used volume, which `used_volume_mismatch` holds to the placements. O(1). + * + * @param mixed $packed @param array{0:int|string,1:int|string,2:int|string} $tight @param list|null $reported + */ + private static function reserveCut($packed, ContainerSpec $spec, MachineSpec $machine, array $tight, ?array $reported): bool + { + if ($spec->voidFillReserveRatio->compareInt(0) === 0 || $reported === null) { + return false; + } + foreach ($reported as $axis => $side) { + if (!\is_int($side) || Exact::compare($tight[$axis], $side) > 0 || Exact::compare($side, $spec->inner[$axis]) > 0 + || Exact::sign(Exact::mod(Exact::sub($side, $machine->minimum[$axis]), $machine->increment[$axis])) !== 0) { + return false; + } + } + $used = Json::get($packed, 'used_volume_ticks3'); + if (!\is_string($used) || \preg_match('/^[0-9]+$/', $used) !== 1) { + return false; + } + $volume = Exact::mul(Exact::mul($tight[0], $tight[1]), $tight[2]); + $scaled = self::ratioPpm($spec->voidFillReserveRatio); + $reserved = Exact::add(Exact::mul(Exact::floorDiv($volume, self::SCORE_SCALE), $scaled), + Exact::floorDiv(Exact::mul(Exact::mod($volume, self::SCORE_SCALE), $scaled), self::SCORE_SCALE)); + return Exact::compare(Exact::normalize(\ltrim($used, '0') ?: '0'), Exact::sub($volume, $reserved)) > 0; + } + /** * Recompute a made-to-measure container's box from its placements alone and return the spec * every later check uses: the recomputed box, never the reported one. @@ -167,6 +240,10 @@ public static function checkMadeToMeasure($packed, bool $compact, ContainerSpec } } $reportedInner = self::reportedTicks(Json::get($packed, 'inner_dimensions')); + if (!self::matches($reportedInner, $fabricated) && self::reserveCut($packed, $spec, $machine, $fabricated, $reportedInner)) { + /** @var array{0:int,1:int,2:int} $reportedInner reserveCut admits integer sides alone */ + $fabricated = $reportedInner; + } if (!self::matches($reportedInner, $fabricated)) { $issues[] = new ResultIssue('fabricated_dimensions_mismatch', "{$containerId}: reported " . self::optionalTuple($reportedInner) . ', computed ' . PyFormat::intTuple($fabricated)); } @@ -262,6 +339,9 @@ public static function check($packed, ContainerSpec $spec, Ordered $items, $clea self::checkPairs($entries, $packedId, $issues); [$supporters, $directAbove] = Stacking::supportGraph($entries); Stacking::checkSupportAndLoad($entries, $supporters, $directAbove, $globalSupport, $issues); + if ($spec->deck !== null) { + Stacking::checkDeckSupport($entries, $spec->deck, $globalSupport, $issues); + } $loads = Stacking::propagateLoad($entries, $supporters); Stacking::checkStackTopLoad($entries, $loads, $issues); if ($spec->maxStackDensity !== null) { diff --git a/src/Support/ResultValidation/ContainerSpec.php b/src/Support/ResultValidation/ContainerSpec.php index 9357724..949f8cb 100644 --- a/src/Support/ResultValidation/ContainerSpec.php +++ b/src/Support/ResultValidation/ContainerSpec.php @@ -39,10 +39,24 @@ final class ContainerSpec public $accessDirections; /** @var bool */ public $flatBag; + /** + * 1.10: a gusseted bag's side gusset depth G in ticks, which widens the width girth to + * b + c <= W + G; 0 for a flat bag and every rigid container. + * + * @var int|string + */ + public $sideGusset = 0; /** @var bool */ public $reportsAchievedExtent; /** @var MachineSpec|null */ public $madeToMeasure; + /** + * The weight-bearing deck `[x, y, length, width]` inside a pallet's solving frame, + * which `$inner` then is; null for every other container. + * + * @var array{0:int|string,1:int|string,2:int|string,3:int|string}|null + */ + public $deck; /** @return int|string */ public function volume() diff --git a/src/Support/ResultValidation/Geometry.php b/src/Support/ResultValidation/Geometry.php index ed76d9d..9d110f2 100644 --- a/src/Support/ResultValidation/Geometry.php +++ b/src/Support/ResultValidation/Geometry.php @@ -10,12 +10,40 @@ */ final class Geometry { - /** Axis permutation each orientation code applies to (length, width, height). */ + /** The six legacy orientation codes: every box a cuboid can make, and an item's default list. */ + public const BOX_ROTATIONS = ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']; + + /** + * Axis permutation each of the 24 proper rotations applies to (length, width, height), in + * canonical table order (1.10). Written out rather than read from the engine's + * `Orientations`, so this table is a second statement of the contract and not a copy. + */ public const ROTATIONS = [ 'LWH' => [0, 1, 2], 'LHW' => [0, 2, 1], 'WLH' => [1, 0, 2], 'WHL' => [1, 2, 0], 'HLW' => [2, 0, 1], 'HWL' => [2, 1, 0], + '+L-W-H' => [0, 1, 2], '-L+W-H' => [0, 1, 2], '-L-W+H' => [0, 1, 2], + '+L-H+W' => [0, 2, 1], '+L+H-W' => [0, 2, 1], '-L-H-W' => [0, 2, 1], + '+W-L+H' => [1, 0, 2], '+W+L-H' => [1, 0, 2], '-W-L-H' => [1, 0, 2], + '+W-H-L' => [1, 2, 0], '-W+H-L' => [1, 2, 0], '-W-H+L' => [1, 2, 0], + '+H-L-W' => [2, 0, 1], '-H+L-W' => [2, 0, 1], '-H-L+W' => [2, 0, 1], + '+H-W+L' => [2, 1, 0], '+H+W-L' => [2, 1, 0], '-H-W-L' => [2, 1, 0], + ]; + + /** The sign each container axis carries under each code; a box ignores it, a hull does not. The legacy codes negate x exactly when their permutation is odd. */ + public const ROTATION_SIGNS = [ + 'LWH' => [1, 1, 1], 'LHW' => [-1, 1, 1], 'WLH' => [-1, 1, 1], + 'WHL' => [1, 1, 1], 'HLW' => [1, 1, 1], 'HWL' => [-1, 1, 1], + '+L-W-H' => [1, -1, -1], '-L+W-H' => [-1, 1, -1], '-L-W+H' => [-1, -1, 1], + '+L-H+W' => [1, -1, 1], '+L+H-W' => [1, 1, -1], '-L-H-W' => [-1, -1, -1], + '+W-L+H' => [1, -1, 1], '+W+L-H' => [1, 1, -1], '-W-L-H' => [-1, -1, -1], + '+W-H-L' => [1, -1, -1], '-W+H-L' => [-1, 1, -1], '-W-H+L' => [-1, -1, 1], + '+H-L-W' => [1, -1, -1], '-H+L-W' => [-1, 1, -1], '-H-L+W' => [-1, -1, 1], + '+H-W+L' => [1, -1, 1], '+H+W-L' => [1, 1, -1], '-H-W-L' => [-1, -1, -1], ]; + /** Orientations that keep the item's own height vertical and pointing up: z takes `+H`. */ + public const UPRIGHT_ROTATIONS = ['LWH', 'WLH', '-L-W+H', '+W-L+H']; + /** `ROTATIONS[orientation]`. @return array{0:int,1:int,2:int} */ public static function axes(string $orientation): array { @@ -71,27 +99,26 @@ public static function primitiveAxis(array $axis): array } /** - * Reorient a hull the way `ROTATIONS` reorients its box, flipping one axis on an odd - * permutation so it stays a proper rotation, then translated so its bounds start at 0. + * Reorient a hull by one of the 24 proper rotations, without ever mirroring it: + * `v'[i] = s[i] * v[src[i]]` from `ROTATIONS` and `ROTATION_SIGNS`, where every code has + * determinant +1. The result is translated so its bounds start at 0, the frame a placement + * position is expressed in. * * @param list $vertices - * @param array{0:int,1:int,2:int} $axes * @return list */ - public static function rotateHull(array $vertices, array $axes): array + public static function rotateHull(array $vertices, string $orientation): array { - $inversions = 0; - for ($first = 0; $first < 3; ++$first) { - for ($second = $first + 1; $second < 3; ++$second) { - if ($axes[$first] > $axes[$second]) { - ++$inversions; - } - } - } + $axes = self::axes($orientation); + $signs = self::ROTATION_SIGNS[$orientation]; $turned = []; foreach ($vertices as $vertex) { - $x = $vertex[$axes[0]]; - $turned[] = [$inversions % 2 === 1 ? Exact::negate($x) : $x, $vertex[$axes[1]], $vertex[$axes[2]]]; + $point = []; + for ($axis = 0; $axis < 3; ++$axis) { + $value = $vertex[$axes[$axis]]; + $point[] = $signs[$axis] < 0 ? Exact::negate($value) : $value; + } + $turned[] = $point; } if ($turned === []) { throw MalformedResult::shape('a hull without vertices'); diff --git a/src/Support/ResultValidation/ObjectiveCheck.php b/src/Support/ResultValidation/ObjectiveCheck.php index 07b8228..de7885a 100644 --- a/src/Support/ResultValidation/ObjectiveCheck.php +++ b/src/Support/ResultValidation/ObjectiveCheck.php @@ -76,7 +76,7 @@ private static function objective($result, Context $context, Ordered $fabricated $achievedHeight = Exact::add($achievedHeight, $top); if ($billed && $billing['divisor'] !== null) { $gross = Json::pyInt(Json::get(Json::get($packed, 'gross_weight', []), 'ticks', 0), 'gross_weight'); - $size = $spec->flatBag ? ContainerCheck::achievedExtent($packed, $context->clearance) : ($spec->outer ?? $spec->inner); + $size = ContainerCheck::billedSize($packed, $spec, $context->clearance); $dimensional = self::dimensionalWeight( $size, Json::int($billing['divisor'], 'dimensional_weight_divisor'), diff --git a/src/Support/ResultValidation/PlacementIds.php b/src/Support/ResultValidation/PlacementIds.php new file mode 100644 index 0000000..0622c5f --- /dev/null +++ b/src/Support/ResultValidation/PlacementIds.php @@ -0,0 +1,81 @@ + $issues + */ + public static function check($result, array &$issues): void + { + $seen = []; + foreach (Json::items(Json::at($result, 'containers'), 'result.containers') as $container) { + $containerId = Json::get($container, 'id', ''); + foreach (Json::items(Json::at($container, 'placements'), 'placements') as $placement) { + $expected = self::expected($containerId, $placement); + $reported = Json::get($placement, 'placement_id'); + $where = PyFormat::str(Json::at($placement, 'item_id')) . ' in ' . PyFormat::str($containerId); + if (!\is_string($reported)) { + $issues[] = new ResultIssue('placement_id_mismatch', "{$where}: no placement_id, expected {$expected}"); + continue; + } + if ($reported !== $expected) { + $issues[] = new ResultIssue('placement_id_mismatch', "{$where}: reported {$reported}, expected {$expected}"); + } + if (isset($seen[$reported])) { + $issues[] = new ResultIssue('duplicate_placement_id', $reported); + } + $seen[$reported] = true; + } + } + } + + /** @param mixed $containerId @param mixed $placement */ + private static function expected($containerId, $placement): string + { + $position = Json::at($placement, 'position'); + $parts = [self::spelled(PyFormat::str($containerId))]; + foreach (['x', 'y', 'z'] as $axis) { + $parts[] = PyFormat::str(Json::at(Json::at($position, $axis), 'ticks')); + } + $parts[] = self::spelled(PyFormat::str(Json::at($placement, 'item_type'))); + $parts[] = self::spelled(PyFormat::str(Json::at($placement, 'orientation'))); + return '[' . \implode(',', $parts) . ']'; + } + + /** A string as RFC 8785 spells it: `"`, `\` and U+0000..U+001F escaped, the rest as UTF-8. */ + private static function spelled(string $text): string + { + return '"' . \strtr($text, self::escapes()) . '"'; + } + + /** @return array */ + private static function escapes(): array + { + static $escapes = null; + if ($escapes === null) { + $escapes = [ + '"' => '\\"', '\\' => '\\\\', "\x08" => '\\b', "\t" => '\\t', + "\n" => '\\n', "\x0C" => '\\f', "\r" => '\\r', + ]; + for ($code = 0; $code < 0x20; $code++) { + $escapes[\chr($code)] = $escapes[\chr($code)] ?? \sprintf('\\u%04x', $code); + } + } + return $escapes; + } +} diff --git a/src/Support/ResultValidation/Spec.php b/src/Support/ResultValidation/Spec.php index 45a6742..44891c0 100644 --- a/src/Support/ResultValidation/Spec.php +++ b/src/Support/ResultValidation/Spec.php @@ -10,7 +10,31 @@ final class Spec /** The six axis-aligned exit directions a placement could be slid out through. */ public const EXIT_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; - private const UPRIGHT_ROTATIONS = ['LWH', 'WLH']; + /** + * The codes an item may be placed in: its list, or the six legacy codes, narrowed to the + * upright ones under `keep_upright`. A signed code counts only on a hull -- the engines refuse + * it anywhere else -- so a box placed in one reads as a forbidden rotation (1.10). + * + * @param mixed $raw + * @return list + */ + private static function allowedRotations($raw, bool $keepUpright): array + { + $listed = Json::get($raw, 'allowed_rotations'); + $rotations = $listed === null ? Geometry::BOX_ROTATIONS : \array_values(Json::items($listed, 'allowed_rotations')); + if (!Json::isText(Json::get($raw, 'shape_type'), 'convex_hull')) { + $rotations = self::within($rotations, Geometry::BOX_ROTATIONS); + } + return $keepUpright ? self::within($rotations, Geometry::UPRIGHT_ROTATIONS) : $rotations; + } + + /** @param list $rotations @param list $codes @return list */ + private static function within(array $rotations, array $codes): array + { + return \array_values(\array_filter($rotations, static function ($code) use ($codes): bool { + return \is_string($code) && \in_array($code, $codes, true); + })); + } /** @param mixed $request @return Ordered */ public static function items($request, string $unit): Ordered @@ -21,11 +45,9 @@ public static function items($request, string $unit): Ordered $keepUpright = Json::flag($raw, 'keep_upright', false, $where); $stackable = Json::flag($raw, 'stackable', true, $where); $mustBeOnFloor = Json::flag($raw, 'must_be_on_floor', false, $where); - $rotations = Json::get($raw, 'allowed_rotations'); - if ($rotations === null) { - $rotations = $keepUpright ? self::UPRIGHT_ROTATIONS : \array_keys(Geometry::ROTATIONS); - } else { - $rotations = Json::items($rotations, 'allowed_rotations'); + $rotations = self::allowedRotations($raw, $keepUpright); + if ($rotations === []) { + throw MalformedResult::contract("{$where}.allowed_rotations must allow at least one rotation after keep_upright"); } $id = Json::at($raw, 'id'); $spec = new ItemSpec(); @@ -33,7 +55,7 @@ public static function items($request, string $unit): Ordered $spec->dimensions = Units::dimensions(Json::at($raw, 'dimensions'), $unit); $spec->weight = Units::toTicks(Json::get($raw, 'weight', 0), 'g', Units::WEIGHT); $spec->quantity = Json::get($raw, 'quantity', 1); - $spec->allowedRotations = \array_values($rotations); + $spec->allowedRotations = $rotations; $spec->stackable = $stackable; $spec->mustBeOnFloor = $mustBeOnFloor; $spec->maxTopLoad = self::measured($raw, 'max_top_load', 'g', Units::WEIGHT); @@ -68,7 +90,7 @@ public static function containers($request, string $unit): Ordered foreach (Json::items(Json::at($request, 'containers'), 'request.containers') as $raw) { $spec = new ContainerSpec(); $spec->id = Json::at($raw, 'id'); - $spec->inner = Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit); + [$spec->inner, $spec->deck] = self::frameAndDeck(Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit), Json::get($raw, 'pallet_overhang_limit'), $unit); $spec->accessDirections = self::accessDirections($raw); $outer = Json::get($raw, 'outer_dimensions'); $spec->outer = $outer === null ? null : Units::dimensions($outer, $unit); @@ -85,7 +107,8 @@ public static function containers($request, string $unit): Ordered $spec->maxStackDensity = self::measured($raw, 'max_stack_density', 'g', Units::WEIGHT); $spec->rateTable = Json::get($raw, 'rate_table'); $spec->flatBag = Json::get($raw, 'deformable_boundary') !== null; - $spec->reportsAchievedExtent = $spec->flatBag || Json::get($raw, 'made_to_measure') !== null; + $spec->sideGusset = self::sideGusset(Json::get($raw, 'deformable_boundary'), $unit); + $spec->reportsAchievedExtent = $spec->flatBag || Json::get($raw, 'made_to_measure') !== null || $spec->deck !== null; $machine = Json::get($raw, 'made_to_measure'); $spec->madeToMeasure = $machine === null ? null : self::machine($machine, $unit); $containers->set($spec->id, $spec); @@ -93,6 +116,34 @@ public static function containers($request, string $unit): Ordered return $containers; } + /** + * A gusseted bag's side gusset depth in ticks, else 0. + * + * @param mixed $boundary @return int|string + */ + private static function sideGusset($boundary, string $unit) + { + $depth = $boundary === null ? null : Json::get($boundary, 'side_gusset_depth'); + return $depth === null ? 0 : Units::toTicks($depth, $unit, Units::LENGTH); + } + + /** + * A pallet's solving frame and the deck inside it, else the declared size. + * + * @param array{0:int|string,1:int|string,2:int|string} $declared @param mixed $limit + * @return array{0:array{0:int|string,1:int|string,2:int|string},1:array{0:int|string,1:int|string,2:int|string,3:int|string}|null} + */ + private static function frameAndDeck(array $declared, $limit, string $unit): array + { + if ($limit === null) { + return [$declared, null]; + } + $overhangX = Units::toTicks(Json::at($limit, 'length'), $unit, Units::LENGTH); + $overhangY = Units::toTicks(Json::at($limit, 'width'), $unit, Units::LENGTH); + $frame = [Exact::add($declared[0], Exact::mul($overhangX, 2)), Exact::add($declared[1], Exact::mul($overhangY, 2)), $declared[2]]; + return [$frame, [$overhangX, $overhangY, $declared[0], $declared[1]]]; + } + /** `None if raw.get(key) is None else to_ticks(...)`. @param mixed $raw @param array $table @return int|string|null */ private static function measured($raw, string $key, string $unit, array $table) { diff --git a/src/Support/ResultValidation/Stacking.php b/src/Support/ResultValidation/Stacking.php index 3a41cb1..ff4f55e 100644 --- a/src/Support/ResultValidation/Stacking.php +++ b/src/Support/ResultValidation/Stacking.php @@ -93,6 +93,37 @@ public static function supportGraph(array $entries): array return [$supporters, $directAbove]; } + /** + * A floor placement on a pallet rests on its overlap with the deck alone, judged + * by the ratio and centre-of-gravity rule a supporting item would be. O(p). + * + * @param list $entries @param array{0:int|string,1:int|string,2:int|string,3:int|string} $deck + * @param list $issues + */ + public static function checkDeckSupport(array $entries, array $deck, Ratio $globalSupport, array &$issues): void + { + [$x, $y, $length, $width] = $deck; + $surface = new Cuboid($x, $y, -1, $length, $width, 1); + foreach ($entries as $entry) { + $spec = $entry->spec; + if ($spec === null || Exact::sign($entry->envelope->z) !== 0) { + continue; + } + $required = $globalSupport->compare($spec->minimumSupportRatio) < 0 ? $spec->minimumSupportRatio : $globalSupport; + if ($required->compareInt(0) <= 0) { + continue; + } + $area = $entry->envelope->overlapAreaXy($surface); + $itemId = PyFormat::str($entry->id); + if (Exact::compare($area, self::requiredSupportArea($entry->envelope->baseArea, ContainerCheck::ratioPpm($required))) < 0) { + $ratio = Ratio::of($area, $entry->envelope->baseArea); + $issues[] = new ResultIssue('insufficient_support', "{$itemId}: " . PyFormat::fixed6($ratio->toFloat()) . ' < ' . PyFormat::fixed6($required->toFloat()) . ' on the deck'); + } elseif (Exact::compare(Exact::mul($area, 2), $entry->envelope->baseArea) <= 0 && !self::centroidSupported($entry->envelope, [$surface])) { + $issues[] = new ResultIssue('centre_of_gravity_unsupported', "{$itemId}: centroid outside the deck"); + } + } + } + /** * @param list $entries @param list> $supporters * @param list> $directAbove @param list $issues @@ -521,7 +552,8 @@ public static function occupiedVolume(Cuboid $envelope, $placement, ?ItemSpec $s return Exact::mul($footprint, self::compressedHeight($height, $footprint, $spec, $load)); } if ($spec !== null && $spec->isConvexHull() && $spec->hullVertices !== null) { - return Geometry::hullVolume(Geometry::rotateHull($spec->hullVertices, Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')))); + // A proper rotation keeps the volume, so the authored vertices answer for every orientation. + return Geometry::hullVolume($spec->hullVertices); } $solid = self::placedHull($envelope, $placement, $spec); if ($solid === $envelope->vertices()) { @@ -539,10 +571,12 @@ public static function occupiedVolume(Cuboid $envelope, $placement, ?ItemSpec $s */ public static function placedHull(Cuboid $envelope, $placement, ?ItemSpec $spec): array { - if ($spec === null || $spec->hullVertices === null || !$spec->isConvexHull() || $spec->stopIndex !== null) { + if ($spec === null || $spec->hullVertices === null || !$spec->isConvexHull() || $spec->stopIndex !== null + || !Geometry::isRotation(Json::at($placement, 'orientation'))) { return $envelope->vertices(); } - $axes = Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')); + $orientation = Json::text(Json::at($placement, 'orientation'), 'orientation'); + $axes = Geometry::axes($orientation); $rotated = [$spec->dimensions[$axes[0]], $spec->dimensions[$axes[1]], $spec->dimensions[$axes[2]]]; if (Exact::compare($envelope->length, $rotated[0]) !== 0 || Exact::compare($envelope->width, $rotated[1]) !== 0 || Exact::compare($envelope->height, $rotated[2]) !== 0) { @@ -550,6 +584,6 @@ public static function placedHull(Cuboid $envelope, $placement, ?ItemSpec $spec) } return \array_map(static function (array $vertex) use ($envelope): array { return [Exact::add($envelope->x, $vertex[0]), Exact::add($envelope->y, $vertex[1]), Exact::add($envelope->z, $vertex[2])]; - }, Geometry::rotateHull($spec->hullVertices, $axes)); + }, Geometry::rotateHull($spec->hullVertices, $orientation)); } } diff --git a/src/Support/ResultValidation/Units.php b/src/Support/ResultValidation/Units.php index 1ed2bd2..2684e52 100644 --- a/src/Support/ResultValidation/Units.php +++ b/src/Support/ResultValidation/Units.php @@ -52,6 +52,19 @@ public static function lengthUnit($request): string if (!Json::isDict($units)) { throw MalformedResult::contract('units must be an object'); } + // A key other than `length`, the first in code-point order. PHP turns a + // numeric key into an int, so each is compared as the string it was; UTF-8 byte + // order is code-point order. + $unknown = \array_values(\array_filter( + \array_map('strval', \array_keys($units)), + static function (string $key): bool { + return $key !== 'length'; + } + )); + if ($unknown !== []) { + \usort($unknown, 'strcmp'); + throw MalformedResult::contract('units.' . $unknown[0] . ' is not a known field'); + } $length = Json::get($units, 'length'); if ($length === null) { return 'mm'; diff --git a/src/Support/ResultValidation/Validator.php b/src/Support/ResultValidation/Validator.php index 4c46c70..2688324 100644 --- a/src/Support/ResultValidation/Validator.php +++ b/src/Support/ResultValidation/Validator.php @@ -38,6 +38,7 @@ public static function validate($request, $result): array $issues = []; $validated = Lattice::materialize($coordinatesRequired, $result, $items, $containers, $clearance, $issues); Accounting::checkStructure($validated, $issues); + self::checkCurrency($request, $validated, $issues); Facts::checkAlgorithmMetrics($validated, $issues); Facts::checkEffortBudget($request, $validated, $issues); Facts::checkResultFacts($validated, $issues); @@ -49,6 +50,7 @@ public static function validate($request, $result): array self::checkContainerCounts($validated, $configuration, $containers, $issues); ObjectiveCheck::checkFixedPlacements($request, $validated, $unit, $issues); + PlacementIds::check($result, $issues); ObjectiveCheck::checkGroups($request, $validated, $issues); ObjectiveCheck::checkSolverSelection($request, $validated, $issues); $score = ObjectiveCheck::check($request, $validated, $context, $fabricated, $issues); @@ -56,6 +58,22 @@ public static function validate($request, $result): array return $issues; } + /** + * The result echoes the request's currency, and states none the request did not declare. + * A null is the field left out, on either side. O(1). + * + * @param mixed $request @param mixed $result @param list $issues + */ + private static function checkCurrency($request, $result, array &$issues): void + { + $requested = Json::get($request, 'currency'); + $reported = Json::get($result, 'currency'); + if (!Json::equals($reported, $requested)) { + $issues[] = new ResultIssue('currency_mismatch', 'reported ' . PyFormat::repr($reported) + . ', requested ' . PyFormat::repr($requested)); + } + } + /** @param mixed $result @param list $issues */ private static function checkInfeasibleProof($result, array &$issues): void { diff --git a/src/Validation/IndependentSolutionValidator.php b/src/Validation/IndependentSolutionValidator.php index ceee35e..8b103e9 100644 --- a/src/Validation/IndependentSolutionValidator.php +++ b/src/Validation/IndependentSolutionValidator.php @@ -1,9 +1,10 @@ instance->item; if($item->tags!==[]||$item->incompatibleTags!==[])$compatibilitySensitive=true; if($item->minimumSupportRatio>0||($item->groundContactRule!==null&&$item->groundContactRule!=='free'))$supportSensitive=true; - // A stacking-group list refuses load on the same edges `stackable` does. - if(!$item->stackable||$item->acceptsStackingGroups!==[])$stackSensitive=true; + // A stacking-group list or bearing limit makes the scene stack-sensitive. + if($item->isStackSensitive())$stackSensitive=true; } $units=LoadCalculator::units($placements); $stackGraph=$stackSensitive?new LoadSupportGraph($units):null; + $compatibilityConstraints=$compatibilitySensitive?[new CompatibilityConstraint(),new TagCountConstraint()]:[]; + $supportConstraint=$supportSensitive?new SupportConstraint($minimumSupportRatio):null; foreach(self::collisionPairs($placements) as [$left,$right]) $issues[]=new ValidationIssue('collision',$placements[$left]->instance->id().' with '.$placements[$right]->instance->id()); foreach($packed->placements as $index=>$p){ @@ -57,17 +60,21 @@ public function validate(PackingRequest $request,array $containers,float $minimu if($eligibleTags!==[]&&array_intersect($eligibleTags,$packed->container->tags)===[]) $issues[]=new ValidationIssue('container_ineligible',$id); // The common lattice case has no pair-dependent rules. Avoid building - // an O(n) "all other placements" array for every item in that case. - $ctx=null; - if($compatibilitySensitive||$supportSensitive){ + // an O(n) "all other placements" array unless tag rules need it; + // support queries only inspect z2 == origin.z or origin.z < box.origin.z, + // which a positive-height box never satisfies against itself, so passing + // `$placements` reuses `LoadSupportGraph::$cachedByTop` in O(n). + if($compatibilitySensitive){ $others=array_merge(array_slice($placements,0,$index),array_slice($placements,$index+1)); - $ctx=new ConstraintContext($packed->container,$others,$p->instance,$p->envelopeOrigin,$p->rotation,$p->dimensions,$p->envelopeDimensions); + $compatCtx=new ConstraintContext($packed->container,$others,$p->instance,$p->envelopeOrigin,$p->rotation,$p->dimensions,$p->envelopeDimensions); + foreach($compatibilityConstraints as $constraint){ + $r=$constraint->evaluate($compatCtx); + if(!$r->allowed)$issues[]=new ValidationIssue($r->code,$id.': '.$r->detail); + } } - $constraints=[]; - if($compatibilitySensitive){$constraints[]=new CompatibilityConstraint();$constraints[]=new TagCountConstraint();} - if($supportSensitive)$constraints[]=new SupportConstraint($minimumSupportRatio); - foreach($constraints as $constraint){ - $r=$constraint->evaluate($ctx); + if($supportConstraint!==null){ + $supportCtx=new ConstraintContext($packed->container,$placements,$p->instance,$p->envelopeOrigin,$p->rotation,$p->dimensions,$p->envelopeDimensions); + $r=$supportConstraint->evaluate($supportCtx); if(!$r->allowed)$issues[]=new ValidationIssue($r->code,$id.': '.$r->detail); } if($stackSensitive){ @@ -78,9 +85,11 @@ public function validate(PackingRequest $request,array $containers,float $minimu // A second, whole-container bearing pass: the per-placement check above // reports the first offender it meets, this one is anchored on the container. $densityLimit=$packed->container->maxStackDensity?->ticks; - $analysis=new \Packvium\Constraint\Internal\LoadAnalysis($units,$stackGraph); - $failure=$analysis->overloaded()??$analysis->crushed()??$analysis->stackLimitExceeded()??$analysis->stackDensityExceeded($densityLimit); - if($failure!==null)$issues[]=new ValidationIssue($failure[0],$packed->id().': '.$failure[1]); + if($stackSensitive||$densityLimit!==null){ + $analysis=new \Packvium\Constraint\Internal\LoadAnalysis($units,$stackGraph); + $failure=$analysis->overloaded()??$analysis->crushed()??$analysis->stackLimitExceeded()??$analysis->stackDensityExceeded($densityLimit); + if($failure!==null)$issues[]=new ValidationIssue($failure[0],$packed->id().': '.$failure[1]); + } if($packed->container->axles!==null){ $axleFailure=AxleLoad::exceeded( $packed->container->axles, @@ -91,9 +100,10 @@ public function validate(PackingRequest $request,array $containers,float $minimu if($axleFailure!==null)$issues[]=new ValidationIssue($axleFailure[0],$packed->id().': '.$axleFailure[1]); } if($packed->container->isFlatBag()){ - // The girth rule over the envelopes alone; the frame is checked above. + // The girth rule over the envelopes alone, widened by a side gusset + // (1.10); the frame is checked above. [$a,$b,$c]=FlatBag::extentOf($packed->placements); - if(!FlatBag::girthAdmits($packed->container->innerDimensions,$a,$b,$c))$issues[]=new ValidationIssue('bag_girth_exceeded',$packed->id()); + if(!FlatBag::girthAdmits($packed->container->innerDimensions,$a,$b,$c,$packed->container->sideGussetTicks()))$issues[]=new ValidationIssue('bag_girth_exceeded',$packed->id()); } $onRoute=false;foreach($placements as $p)if($p->instance->item->stopIndex!==null){$onRoute=true;break;} if($onRoute){ @@ -146,6 +156,8 @@ private static function madeToMeasureIssues(PackingRequest $request,array $conta if($machine===null||$machine->madeToMeasure===null||$packed->container->madeToMeasure===null)continue; $expected=$machine->fabricate(FlatBag::extentOf($packed->placements)); $box=$packed->container; + if($box->innerDimensions!=$expected->innerDimensions&&self::reserveCut($packed,$expected,$machine->innerDimensions)) + $expected=$machine->fabricate(self::sides($box->innerDimensions)); if($box->innerDimensions!=$expected->innerDimensions)$issues[]=new ValidationIssue('fabricated_dimensions_mismatch',$packed->id()); if($box->outerDimensions!=$expected->outerDimensions)$issues[]=new ValidationIssue('outer_dimensions_mismatch',$packed->id()); if($box->costMinor!==$expected->costMinor)$issues[]=new ValidationIssue('made_to_measure_cost_mismatch',$packed->id()); @@ -154,6 +166,24 @@ private static function madeToMeasureIssues(PackingRequest $request,array $conta return $issues; } + /** + * A box larger than the tight cut is admitted when the tight box breaks the void-fill reserve + * and the larger one is on the machine grid within the maximum; whether it keeps the + * reserve is checked with every other container's reserve. O(1). + */ + private static function reserveCut(PackedContainer $packed,Container $tight,Dimensions $maximum):bool + { + $machine=$tight->madeToMeasure; + if($tight->voidFillReserveRatio===0.0||$machine===null)return false; + $cut=self::sides($packed->container->innerDimensions);$low=self::sides($tight->innerDimensions);$high=self::sides($maximum); + for($axis=0;$axis<3;$axis++) + if($cut[$axis]<$low[$axis]||$cut[$axis]>$high[$axis]||($cut[$axis]-$machine->minimum[$axis])%$machine->increment[$axis]!==0)return false; + return BigInt::compare($packed->usedVolumeString(),VolumeReserve::usable($tight))>0; + } + + /** @return array{0:int,1:int,2:int} */ + private static function sides(Dimensions $dimensions):array{return [$dimensions->length->ticks,$dimensions->width->ticks,$dimensions->height->ticks];} + /** * @param list $placements @return list * diff --git a/tests/BoundLoadingTest.php b/tests/BoundLoadingTest.php index 29abba3..3cfdfdb 100644 --- a/tests/BoundLoadingTest.php +++ b/tests/BoundLoadingTest.php @@ -17,7 +17,9 @@ private static function probe(string $case): array $container = new Packvium\Domain\Container('m', Packvium\Domain\Dimensions::mm(100, 100, 100), madeToMeasure: new Packvium\Domain\MadeToMeasure([800000, 800000, 800000], [400000, 400000, 400000])); } -$config = new Packvium\Config\PackingConfig(objective: $case === 'unsupported' ? 'maximum_volume' : 'default'); +$config = $case === 'unsupported' + ? new Packvium\Config\PackingConfig(objective: 'shipping_cost', dimensionalWeightDivisor: 5000) + : new Packvium\Config\PackingConfig(objective: 'default'); $scorer = $case === 'custom' ? new Packvium\Objective\DefaultSolutionScorer() : null; $result = (new Packvium\Packer($config, solutionScorer: $scorer))->pack([$item], [$container])->toArray(); $loaded = false; diff --git a/tests/ConstraintTest.php b/tests/ConstraintTest.php index ff39f64..c0fe695 100644 --- a/tests/ConstraintTest.php +++ b/tests/ConstraintTest.php @@ -1735,4 +1735,185 @@ public static function testTheFirstBlockerNamedIsTheLowestIndexNotTheFirstReache self::assertSame(['unloading_order_violation', 'base blocked by right'], LoadCalculator::routeOrderViolated($scene, [0.0, 0.0, 1.0, 2.0])); } + + public static function testDiamondDagSingleTickRemainderShiftMatchesFullRebuildOracle(): void + { + $b0 = new Placement( + Item::create('b0', new Dimensions(new Length(6), new Length(10), new Length(10)), weight: new Weight(100))->instances()[0], + new Point(0, 0, 0), Rotation::LWH, new Dimensions(new Length(6), new Length(10), new Length(10)), + new Point(0, 0, 0), new Dimensions(new Length(6), new Length(10), new Length(10)), + ); + $b1 = new Placement( + Item::create('b1', new Dimensions(new Length(14), new Length(10), new Length(10)), weight: new Weight(100))->instances()[0], + new Point(6, 0, 0), Rotation::LWH, new Dimensions(new Length(14), new Length(10), new Length(10)), + new Point(6, 0, 0), new Dimensions(new Length(14), new Length(10), new Length(10)), + ); + $m0 = new Placement( + Item::create('m0', new Dimensions(new Length(10), new Length(5), new Length(10)), weight: new Weight(17))->instances()[0], + new Point(3, 0, 10), Rotation::LWH, new Dimensions(new Length(10), new Length(5), new Length(10)), + new Point(3, 0, 10), new Dimensions(new Length(10), new Length(5), new Length(10)), + ); + $m1 = new Placement( + Item::create('m1', new Dimensions(new Length(11), new Length(5), new Length(10)), weight: new Weight(23))->instances()[0], + new Point(3, 5, 10), Rotation::LWH, new Dimensions(new Length(11), new Length(5), new Length(10)), + new Point(3, 5, 10), new Dimensions(new Length(11), new Length(5), new Length(10)), + ); + $container = Container::create('box', Dimensions::mm(100, 100, 100)); + $apexDims = new Dimensions(new Length(8), new Length(10), new Length(10)); + $apexOrigin = new Point(4, 0, 20); + + foreach ([0, 1, 2, 3, 7, 13, 97] as $apexWeight) { + [$apex] = Item::create('apex', $apexDims, weight: new Weight($apexWeight))->instances(); + $apexUnit = new LoadUnit(new AxisAlignedBox($apexOrigin, $apexDims), $apexWeight, null, null, $apex->id()); + $exactLoads = LoadCalculator::topLoads([...LoadCalculator::units([$b0, $b1, $m0, $m1]), $apexUnit]); + for ($targetIdx = 0; $targetIdx < 4; $targetIdx++) { + $exact = $exactLoads[$targetIdx]; + foreach ([-1, 0, 1] as $delta) { + $limit = $exact + $delta; + if ($limit < 0) { + continue; + } + $rebuilt = []; + foreach ([$b0, $b1, $m0, $m1] as $idx => $p) { + $lim = $idx === $targetIdx ? new Weight($limit) : null; + [$inst] = Item::create($p->instance->item->id, $p->dimensions, weight: $p->instance->weight(), maxTopLoad: $lim)->instances(); + $rebuilt[] = new Placement($inst, $p->position, $p->rotation, $p->dimensions, $p->envelopeOrigin, $p->envelopeDimensions); + } + $ctx = new ConstraintContext($container, $rebuilt, $apex, $apexOrigin, Rotation::LWH, $apexDims, $apexDims); + $got = (new TopLoadConstraint())->evaluate($ctx); + $units = [...LoadCalculator::units($rebuilt), $apexUnit]; + $oracleFailure = (new \Packvium\Constraint\Internal\LoadAnalysis($units))->overloaded(); + $expected = $oracleFailure === null + ? \Packvium\Constraint\ConstraintResult::allow() + : \Packvium\Constraint\ConstraintResult::reject($oracleFailure[0], $oracleFailure[1]); + self::assertSame($expected->allowed, $got->allowed); + self::assertSame($expected->code, $got->code); + self::assertSame($expected->detail, $got->detail); + } + } + } + } + + public static function testDiamondDagStackedItemCountDeduplicatesSharedCandidate(): void + { + foreach ([[3, true], [2, false]] as [$maxStacked, $shouldAllow]) { + $base = self::placed(self::instance('base', 200, 100, 100, ['maxStackedItems' => $maxStacked]), x: 0, y: 0, z: 0); + $left = self::placed(self::instance('left', 100, 100, 100), x: 0, y: 0, z: 1_600_000); + $right = self::placed(self::instance('right', 100, 100, 100), x: 1_600_000, y: 0, z: 1_600_000); + $apex = self::instance('apex', 200, 100, 100); + $ctx = self::context($apex, 3_200_000, [$base, $left, $right]); + $got = (new TopLoadConstraint())->evaluate($ctx); + self::assertSame($shouldAllow, $got->allowed); + if (!$shouldAllow) { + self::assertSame('stacked_item_limit_exceeded', $got->code); + } + } + } + + public static function testCandidateSlidUnderneathExistingUpperBoxChecksBearingStackingAndRoute(): void + { + $upperHeavy = self::placed( + self::instance('upper', 100, 100, 100, ['weight' => '10 kg', 'stackingGroup' => 'B', 'stopIndex' => 2]), + z: 1_600_000, + ); + // 1. Candidate is non-stackable -> rejected + $cNs = self::instance('c-ns', 100, 100, 100, ['stackable' => false]); + $rNs = (new TopLoadConstraint())->evaluate(self::context($cNs, 0, [$upperHeavy])); + self::assertFalse($rNs->allowed); + self::assertSame('non_stackable', $rNs->code); + + // 2. Candidate only accepts group A, upper is group B -> rejected + $cGrp = self::instance('c-grp', 100, 100, 100, ['acceptsStackingGroups' => ['A']]); + $rGrp = (new TopLoadConstraint())->evaluate(self::context($cGrp, 0, [$upperHeavy])); + self::assertFalse($rGrp->allowed); + self::assertSame('stacking_group_incompatible', $rGrp->code); + + // 3. Candidate has maxTopLoad="5 kg" under 10 kg upper -> rejected + $cWeak = self::instance('c-weak', 100, 100, 100, ['maxTopLoad' => '5 kg']); + $rWeak = (new TopLoadConstraint())->evaluate(self::context($cWeak, 0, [$upperHeavy])); + self::assertFalse($rWeak->allowed); + self::assertSame('top_load_exceeded', $rWeak->code); + + // 4. Candidate has stopIndex=1 under stopIndex=2 upper -> rejected by RouteOrderConstraint + $cEarly = self::instance('c-early', 100, 100, 100, ['stopIndex' => 1]); + $rRoute = (new RouteOrderConstraint())->evaluate(self::context($cEarly, 0, [$upperHeavy])); + self::assertFalse($rRoute->allowed); + self::assertSame('unloading_order_violation', $rRoute->code); + } + + public static function testContactGraphPlaneBucketThreshold32Vs33AndKnifeEdgeContacts(): void + { + foreach ([0, 1, 31, 32, 33, 34, 65] as $count) { + $boxes = []; + $units = []; + for ($i = 0; $i < $count; $i++) { + $box = new AxisAlignedBox(new Point($i * 10, 0, 0), new Dimensions(new Length(10), new Length(10), new Length(10))); + $boxes[] = $box; + $units[] = new LoadUnit($box, 10, null, null, "b{$i}"); + } + $hint = max(10, $count * 10); + $query = new AxisAlignedBox(new Point(0, 9, 10), new Dimensions(new Length($hint), new Length(2), new Length(10))); + $supportGraph = new \Packvium\Constraint\Internal\LoadSupportGraph($units, $hint); + $below = $supportGraph->contactsBelow($query); + self::assertCount($count, $below); + foreach ($below as $idx => $edge) { + self::assertSame($idx, $edge->index); + self::assertSame(10, $edge->area); + } + $graph = new ContactGraph($boxes, $hint); + $appended = $graph->withBox($query, $hint); + $rebuilt = new ContactGraph([...$boxes, $query], $hint); + for ($i = 0; $i <= $count; $i++) { + self::assertEquals($rebuilt->supporters($i), $appended->supporters($i)); + self::assertSame($rebuilt->children($i), $appended->children($i)); + } + } + } + + /** + * The rejections and the allowance the randomized scenes cannot reach on their own: a floor + * supporter that already carries a box, a candidate whose own footprint breaks the density on + * a tier, and a nesting candidate that every route shortcut hands to the full rebuild. + */ + public static function testEachShortcutRejectionAndTheNestingRouteAllowanceAreExact(): void + { + $mm = Length::mm(1)->ticks; + $dense = static fn(string $limit): Container => Container::create('c', Dimensions::mm(100, 100, 100), + maxStackDensity: Weight::of($limit, 'kg')); + $wideFloor = static fn(array $options): array => [ + self::placed(self::instance('floor', 40, 20, 10, ['weight' => Weight::of(10, 'kg'), ...$options])), + self::placed(self::instance('upper', 20, 20, 10, ['weight' => Weight::of(10, 'kg')]), z: 10 * $mm), + ]; + + $stacked = (new TopLoadConstraint())->evaluate(self::context( + self::instance('cand', 20, 20, 10, ['weight' => Weight::of(1, 'kg')]), 10 * $mm, + $wideFloor(['maxStackedItems' => 1]), x: 20 * $mm, + )); + self::assertSame(['stacked_item_limit_exceeded', 'floor#1'], [$stacked->code, $stacked->detail]); + + $tier = [ + self::placed(self::instance('floor', 40, 20, 10, ['weight' => Weight::of(1, 'kg')])), + self::placed(self::instance('middle', 40, 20, 10, ['weight' => Weight::of(1, 'kg')]), z: 10 * $mm), + ]; + $onTier = (new TopLoadConstraint())->evaluate(self::context( + self::instance('cand', 10, 10, 10, ['weight' => Weight::of(5, 'kg')]), 20 * $mm, $tier, + container: $dense('20000'), + )); + self::assertSame(['stack_density_exceeded', 'cand#1'], [$onTier->code, $onTier->detail]); + + $heavyTier = [ + self::placed(self::instance('floor', 20, 20, 10, ['weight' => Weight::of(1, 'kg')])), + self::placed(self::instance('middle', 20, 20, 10, ['weight' => Weight::of(1, 'kg')]), z: 10 * $mm), + ]; + $atSupporter = (new TopLoadConstraint())->evaluate(self::context( + self::instance('cand', 20, 20, 10, ['weight' => Weight::of(5, 'kg')]), 20 * $mm, $heavyTier, + container: $dense('15000'), + )); + self::assertSame(['stack_density_exceeded', 'floor#1'], [$atSupporter->code, $atSupporter->detail]); + + $cup = self::instance('cup', 20, 20, 10, ['weight' => Weight::of(1, 'kg'), 'stopIndex' => 0, + 'nestingHeight' => Length::mm(4)]); + $base = [self::placed(self::instance('first', 20, 20, 10, ['weight' => Weight::of(1, 'kg'), 'stopIndex' => 1]))]; + self::assertTrue((new RouteOrderConstraint())->evaluate(self::context($cup, 10 * $mm, $base))->allowed); + } } diff --git a/tests/CurrencyTest.php b/tests/CurrencyTest.php new file mode 100644 index 0000000..020783b --- /dev/null +++ b/tests/CurrencyTest.php @@ -0,0 +1,146 @@ + null] + self::jsonRequest()))); + } + + public static function testTheCurrencyChangesNothingButTheEcho(): void + { + $plain = ArrayCodec::pack(self::jsonRequest()); + $declared = ArrayCodec::pack(self::jsonRequest('JPY')); + $plain['algorithm']['duration_ms'] = 0; + $declared['algorithm']['duration_ms'] = 0; + unset($declared['currency']); + + self::assertSame($plain, $declared); + } + + public static function testBothPathsRefuseABadCurrencyAlike(): void + { + $cases = [ + [978, null, 'wrong_type', '/currency', 'must be a string'], + ['usd', null, 'invalid_value', '/currency', self::THREE_LETTERS], + ["USD\n", null, 'invalid_value', '/currency', self::THREE_LETTERS], + ['ÜSD', null, 'invalid_value', '/currency', self::THREE_LETTERS], + ['USD', 840, 'wrong_type', '/containers/0/rate_table/currency', 'must be a string'], + ['USD', 'EURO', 'invalid_value', '/containers/0/rate_table/currency', self::THREE_LETTERS], + [null, 'USD', 'missing_field', '/currency', 'is required when a rate_table declares a currency'], + ['USD', 'EUR', 'not_allowed', '/containers/0/rate_table/currency', 'must equal the request currency "USD"'], + ]; + foreach ($cases as [$currency, $table, $reason, $field, $detail]) { + $expected = [$reason, $field, $detail]; + self::assertSame($expected, self::refusal(static fn() => ArrayCodec::pack(self::jsonRequest($currency, $table)))); + // A `?string` cannot hold a number: the object path has no such request to refuse. + if (\is_int($currency) || \is_int($table)) { + continue; + } + self::assertSame($expected, self::refusal(static fn() => self::packObjects($currency, $table))); + } + } + + public static function testARateTableMayLeaveItsCurrencyToTheRequest(): void + { + self::assertSame('USD', self::packObjects('USD')->currency); + self::assertSame('USD', self::packObjects('USD', 'USD')->currency); + self::assertNull(self::packObjects()->currency); + } + + public static function testTheObjectApiCarriesTheCurrencyLastAndOptional(): void + { + self::assertNull((new RateTable([1000], [500]))->currency); + $request = new PackingRequest([Item::create('cube', Dimensions::mm(1, 1, 1))], [Container::create('box', Dimensions::mm(2, 2, 2))]); + self::assertNull($request->currency); + self::assertSame('EUR', (new PackingRequest($request->items, $request->containers, [], 'EUR'))->currency); + } + + /** + * @param mixed $currency + * @param mixed $table + * @return array + */ + private static function jsonRequest($currency = null, $table = null): array + { + $request = [ + 'items' => [['id' => 'cube', 'quantity' => 2, 'weight' => '1000', + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '200', 'width' => '100', 'height' => '200'], + 'rate_table' => ['weight_brackets_g' => [5000], 'prices_minor' => [900]]]], + 'configuration' => ['solver_profile' => 'fast'], + ]; + if ($currency !== null) { + $request['currency'] = $currency; + } + if ($table !== null) { + $request['containers'][0]['rate_table']['currency'] = $table; + } + return $request; + } + + private static function packObjects(?string $currency = null, ?string $table = null): PackingResult + { + $rates = new RateTable([5000], [900], currency: $table); + $items = [Item::create('cube', Dimensions::mm(100, 100, 100), weight: 1000, quantity: 2)]; + $containers = [Container::create('box', Dimensions::mm(200, 100, 200), rateTable: $rates)]; + return (new Packer(PackingConfig::fast()))->pack($items, $containers, [], $currency); + } + + /** @return array{0:string,1:string,2:string} */ + private static function refusal(callable $pack): array + { + try { + $pack(); + } catch (InvalidRequestException $error) { + return [$error->reason(), $error->field(), $error->detail()]; + } + self::assertTrue(false, 'the request was answered'); + return ['', '', '']; + } +} diff --git a/tests/EffectiveRotationValidationTest.php b/tests/EffectiveRotationValidationTest.php new file mode 100644 index 0000000..b606613 --- /dev/null +++ b/tests/EffectiveRotationValidationTest.php @@ -0,0 +1,33 @@ + [['id' => 'cube', 'dimensions' => ['length' => '10', 'width' => '10', 'height' => '10']]], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '10', 'width' => '10', 'height' => '10']]], + ]; + $result = ArrayCodec::pack($request); + foreach ([[['+L-W-H'], true], [['LHW'], true], [[], true], [[], false]] as [$codes, $upright]) { + $invalid = $request; + $invalid['items'][0]['shape_type'] = 'convex_hull'; + $invalid['items'][0]['allowed_rotations'] = $codes; + $invalid['items'][0]['keep_upright'] = $upright; + try { + validate($invalid, $result); + self::assertTrue(false, 'the independent validator must refuse the invalid request'); + } catch (MalformedResult $error) { + self::assertSame(MalformedResult::CONTRACT, $error->kind); + self::assertSame('items[0].allowed_rotations must allow at least one rotation after keep_upright', $error->getMessage()); + } + } + } +} diff --git a/tests/EffortBoundaryTest.php b/tests/EffortBoundaryTest.php index 3ff4c7c..2e83b13 100644 --- a/tests/EffortBoundaryTest.php +++ b/tests/EffortBoundaryTest.php @@ -11,6 +11,7 @@ use Packvium\Algorithm\ExtremePointSolver; use Packvium\Algorithm\MaximalSpaceSolver; use Packvium\Algorithm\SearchStats; +use Packvium\Algorithm\Space; use Packvium\Algorithm\SolverOrchestrator; use Packvium\Algorithm\TimeLimitReached; use Packvium\Config\PackingConfig; @@ -18,8 +19,10 @@ use Packvium\Domain\Container; use Packvium\Domain\Dimensions; use Packvium\Domain\Item; +use Packvium\Domain\Point; use Packvium\Extension\DefaultCandidateScorer; use Packvium\Serialization\ArrayCodec; +use Packvium\Unit\Weight; /** * An effort budget names a stop, never a counter that merely reached its limit. @@ -211,6 +214,23 @@ private static function cubes(int $quantity): array return Item::create('cube', Dimensions::mm(30, 20, 10), quantity: $quantity)->instances(); } + public static function testAnItemNoSpaceCanTakeStillChecksTheClockOncePerSpace(): void + { + // An item past the container's payload is refused before any space is scanned, yet the + // scan it skips must stay as interruptible as the one it replaces: one clock check per space. + $state = new ContainerState(Container::create('c', Dimensions::mm(100, 100, 100), maxPayload: new Weight(1)), 1); + [$heavy] = Item::create('heavy', Dimensions::mm(10, 10, 10), new Weight(2))->instances(); + $space = new Space(new Point(0, 0, 0), Dimensions::mm(100, 100, 100)); + $config = PackingConfig::balanced(); + $choose = static fn(Deadline $deadline): mixed => CandidateFinder::chooseInSpaces( + $state, [$space, $space], $heavy, $config, ConstraintSet::defaults(0.0), new SearchStats(), $deadline, + new DefaultCandidateScorer(), + ); + + self::assertNull($choose(Deadline::ofMilliseconds(60_000))); + self::assertThrows(TimeLimitReached::class, static fn() => $choose(new Deadline(0, static fn(): int => 1))); + } + public static function testAFeasibleCandidatePastItsLimitStopsTheScanInsideAPoint(): void { $config = PackingConfig::balanced(); diff --git a/tests/FlatBagTest.php b/tests/FlatBagTest.php index 957c268..1b4991a 100644 --- a/tests/FlatBagTest.php +++ b/tests/FlatBagTest.php @@ -64,7 +64,7 @@ public static function testAMalformedBagIsRefusedWithItsPointer(): void $cases = [ [['deformable_boundary' => 'flat_bag'], '/deformable_boundary', 'wrong_type', 'must be an object'], [['deformable_boundary' => []], '/deformable_boundary/kind', 'missing_field', 'is required'], - [['deformable_boundary' => ['kind' => 'pouch']], '/deformable_boundary/kind', 'not_allowed', 'must be one of ["flat_bag"]'], + [['deformable_boundary' => ['kind' => 'pouch']], '/deformable_boundary/kind', 'not_allowed', 'must be one of ["flat_bag","gusseted_bag"]'], [['deformable_boundary' => ['kind' => 'flat_bag', 'seam' => 1]], '/deformable_boundary/seam', 'not_allowed', 'is not a known field'], [self::BAG + ['made_to_measure' => []], '/made_to_measure', 'not_allowed', 'cannot be combined with deformable_boundary'], [self::BAG + ['obstacles' => [['id' => 'o', 'dimensions' => ['length' => '1', 'width' => '1', 'height' => '1']]]], '/obstacles', 'not_allowed', 'cannot be combined with deformable_boundary'], diff --git a/tests/GussetedBagTest.php b/tests/GussetedBagTest.php new file mode 100644 index 0000000..a5efe2b --- /dev/null +++ b/tests/GussetedBagTest.php @@ -0,0 +1,200 @@ +sideGussetTicks()); + self::assertTrue(self::pouch()->isFlatBag()); + self::assertSame(0, Container::create('box', Dimensions::mm(1, 1, 1))->sideGussetTicks()); + self::assertSame(self::ticks(150), self::pouch(150)->sideGussetTicks()); + } + + public static function testAMalformedGussetIsRefused(): void + { + $cases = [ + ['gusseted_bag', null, 'missing_field', 'a gusseted_bag requires side_gusset_depth'], + ['flat_bag', new Length(1), 'not_allowed', 'side_gusset_depth requires deformable_boundary gusseted_bag'], + [null, new Length(1), 'not_allowed', 'side_gusset_depth requires deformable_boundary gusseted_bag'], + ['gusseted_bag', new Length(0), 'invalid_value', 'side_gusset_depth must be positive'], + ['gusseted_bag', new Length(self::ticks(150) + 1), 'invalid_value', 'side_gusset_depth exceeds inner_dimensions width'], + ]; + foreach ($cases as [$kind, $depth, $reason, $detail]) { + $error = self::caught(static fn() => Container::create('pouch', Dimensions::mm(300, 150, 100), 0, null, null, 0, null, [], [], null, [], 0.0, [], null, null, null, [], $kind, $depth)); + self::assertSame([$reason, $detail], [$error->reason(), $error->detail()]); + } + $outer = self::caught(static fn() => new Container('pouch', Dimensions::mm(300, 150, 100), Dimensions::mm(310, 160, 110), deformableBoundary: 'gusseted_bag', sideGussetDepth: Length::mm(10))); + self::assertSame('outer_dimensions cannot be combined with deformable_boundary', $outer->detail()); + } + + public static function testTheJsonPathReadsTheDepthInTheRequestUnit(): void + { + $result = ArrayCodec::pack(self::request(3, self::gusseted(['value' => '1', 'unit' => 'cm'])) + ['units' => ['length' => 'mm']]); + self::assertSame([], $result['unpacked_items']); + } + + public static function testAFlatBagRefusesAGussetAsAnUnknownField(): void + { + $error = self::caught(static fn() => ArrayCodec::pack(self::request(1, ['kind' => 'flat_bag', 'side_gusset_depth' => '10']))); + self::assertSame(['/containers/0/deformable_boundary/side_gusset_depth', 'not_allowed'], [$error->field(), $error->reason()]); + } + + public static function testTheGussetAdmitsTheLayerTheFlatBagRefuses(): void + { + $flat = ArrayCodec::pack(self::request(4, ['kind' => 'flat_bag'])); + $wide = ArrayCodec::pack(self::request(4, self::gusseted('25'))); + self::assertSame([2], array_map(static fn(array $c): int => count($c['placements']), $flat['containers'])); + self::assertSame([3], array_map(static fn(array $c): int => count($c['placements']), $wide['containers'])); + self::assertSame('60', $wide['containers'][0]['achieved_dimensions']['height']['value']); + } + + public static function testTheLatticeAndBlockSolversDeferToTheCandidateCheck(): void + { + $items = self::book(4)->instances(); + $config = new PackingConfig(); + $solution = (new GridSolver())->packOne(self::pouch(), 1, $items, $config, new SearchStats(), Deadline::ofMilliseconds(60_000)); + self::assertFalse($solution->dominantLattice); + self::assertCount(3, $solution->state->placements); + self::assertFalse((new HomogeneousBlockSolver())->supports(self::pouch(), $items, $config)); + } + + public static function testACandidateOneTickPastTheWidenedGirthIsNeverProposed(): void + { + $book = self::book(4); + $state = new ContainerState(self::pouch(), 1); + foreach ([0, 1, 2] as $level) { + $state->add(self::placed($book, $level + 1, 20 * $level)); + } + $config = new PackingConfig(); + $candidates = CandidateFinder::find($state, new ItemInstance($book, 4), $config, ConstraintSet::defaults($config->minimumSupportRatio), + new SearchStats(), Deadline::ofMilliseconds(60_000), new DefaultCandidateScorer()); + self::assertSame([], $candidates); + } + + public static function testAnItemOnlyTheGussetAdmitsIsNotProvenUnfit(): void + { + $base = self::request(1, ['kind' => 'flat_bag']); + $base['items'] = [['id' => 'brick', 'allowed_rotations' => ['LWH'], 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '60']]]; + $base['containers'][0]['inner_dimensions']['length'] = '200'; + self::assertSame('no_compatible_container_dimensions', ArrayCodec::pack($base)['unpacked_items'][0]['reason']); + $base['containers'][0]['deformable_boundary'] = self::gusseted('10'); + self::assertSame([], ArrayCodec::pack($base)['unpacked_items']); + } + + public static function testAGussetedBagIsBilledOnItsAchievedPackage(): void + { + $packed = new PackedContainer(self::pouch(), 1, [self::placed(self::book(1), 1, 0)]); + self::assertEquals(Dimensions::mm(200, 100, 20), $packed->billedDimensions()); + $config = new PackingConfig(dimensionalWeightDivisor: 5000, dimensionalWeightLengthUnit: 'cm', dimensionalWeightWeightUnit: 'kg'); + $state = new ContainerState(self::pouch(), 1); + $state->add(self::placed(self::book(1), 1, 0)); + self::assertSame(Weight::parse('80 g')->ticks, $state->billedDimensionalWeight($config)); + } + + public static function testTheValidatorReadsTheGusset(): void + { + $book = self::book(3); + $three = [self::placed($book, 1, 0), self::placed($book, 2, 20), self::placed($book, 3, 40)]; + $validator = new IndependentSolutionValidator(); + self::assertSame([], $validator->validate(new PackingRequest([$book], [self::pouch()]), [new PackedContainer(self::pouch(), 1, $three)])->issues); + $narrow = self::pouch(9); + $issues = $validator->validate(new PackingRequest([$book], [$narrow]), [new PackedContainer($narrow, 1, $three)])->issues; + self::assertSame([['bag_girth_exceeded', 'pouch#1']], array_map(static fn($issue): array => [$issue->code, $issue->detail], $issues)); + } + + public static function testAFixedSetOneTickPastTheWidenedGirthCannotHold(): void + { + $fixed = []; + foreach ([0, 20, 40] as $z) { + $fixed[] = ['item_type' => 'book', 'container_type' => 'pouch', 'orientation' => 'LWH', 'position' => ['x' => '0', 'y' => '0', 'z' => (string) $z]]; + } + $past = self::request(3, self::gusseted(['value' => (string) (self::ticks(10) - 1), 'unit' => 'ticks'])) + ['fixed_placements' => $fixed]; + try { + ArrayCodec::pack($past); + throw new \RuntimeException('the fixed set was admitted'); + } catch (FixedPlacementException $error) { + self::assertSame('invalid_fixed_placement: bag_girth_exceeded: pouch#1', $error->getMessage()); + } + self::assertSame([], ArrayCodec::pack(self::request(3, self::gusseted('10')) + ['fixed_placements' => $fixed])['unpacked_items']); + } + + private static function ticks(int $millimetres): int + { + return Length::mm($millimetres)->ticks; + } + + private static function pouch(int $gusset = 10): Container + { + return Container::create('pouch', Dimensions::mm(300, 150, 100), 0, null, null, 0, null, [], [], null, [], 0.0, [], null, null, null, [], 'gusseted_bag', Length::mm($gusset)); + } + + private static function book(int $quantity): Item + { + return Item::create('book', Dimensions::mm(200, 100, 20), '300 g', $quantity, [Rotation::LWH]); + } + + private static function placed(Item $item, int $sequence, int $z): Placement + { + $origin = new Point(0, 0, self::ticks($z)); + return new Placement(new ItemInstance($item, $sequence), $origin, Rotation::LWH, $item->dimensions, $origin, $item->dimensions); + } + + /** @param mixed $depth @return array */ + private static function gusseted($depth): array + { + return ['kind' => 'gusseted_bag', 'side_gusset_depth' => $depth]; + } + + /** @param array $boundary @return array */ + private static function request(int $quantity, array $boundary): array + { + return ['items' => [['id' => 'book', 'quantity' => $quantity, 'weight' => '300 g', 'allowed_rotations' => ['LWH'], + 'dimensions' => ['length' => '200', 'width' => '100', 'height' => '20']]], + 'containers' => [['id' => 'pouch', 'quantity' => 1, 'deformable_boundary' => $boundary, + 'inner_dimensions' => ['length' => '300', 'width' => '150', 'height' => '100']]], + 'configuration' => ['solver_profile' => 'fast', 'time_limit_ms' => 60000, 'effort_budget' => ['max_search_nodes' => 100000]]]; + } + + private static function caught(callable $build): InvalidRequestException + { + try { + $build(); + } catch (InvalidRequestException $error) { + return $error; + } + throw new \RuntimeException('was not refused'); + } +} diff --git a/tests/InvariantTest.php b/tests/InvariantTest.php index 67c8b07..2f69b09 100644 --- a/tests/InvariantTest.php +++ b/tests/InvariantTest.php @@ -3,13 +3,18 @@ namespace Packvium\Tests; +use Packvium\Algorithm\Deadline; use Packvium\Algorithm\EffortBudget; +use Packvium\Algorithm\Internal\ConcurrentStarts; +use Packvium\Algorithm\SolverOrchestrator; use Packvium\Config\PackingConfig; use Packvium\Config\SolverProfile; use Packvium\Domain\Container; +use Packvium\Domain\Dimensions; use Packvium\Domain\Item; use Packvium\Result\PackingStatus; use Packvium\Unit\Length; +use ReflectionMethod; /** * Randomised orders checked against the properties that must hold for all of them. @@ -399,6 +404,48 @@ public static function testConcurrentStartsReportAnEffortStopAsEffortNotTime(): self::chosenAnswer(Support::pack($items, $containers, $config)->toArray())); } + public static function testAStartTheForkCouldNotTakeRunsInProcessToTheForkedAnswer(): void + { + // `pcntl_fork()` returning -1 sends that one start to `runOneStartInProcess`; the + // fork itself cannot be made to fail here, so the fallback is driven directly with + // the orchestrator's own starts and must reproduce every forked child's answer. + if (!function_exists('pcntl_fork')) { + self::skip('pcntl extension not available'); + } + $items = []; + foreach ([[30, 20, 15], [25, 25, 10], [40, 10, 10]] as $index => [$length, $width, $height]) { + array_push($items, ...Item::create("i{$index}", Dimensions::mm($length, $width, $height), 0, 3)->instances()); + } + $containers = [Container::create('c', Dimensions::mm(60, 60, 40))]; + $config = new PackingConfig( + SolverProfile::Balanced, timeLimitMs: 60_000, seed: 1234, multiStartOrders: 4, + solvers: ['extreme_points', 'layer'], parallelStarts: 4, + ); + $orchestrator = new SolverOrchestrator(); + $bridge = (new ReflectionMethod(SolverOrchestrator::class, 'bridge'))->invoke($orchestrator); + $starts = (new ReflectionMethod(SolverOrchestrator::class, 'starts'))->invoke($orchestrator, $items, $config, $containers); + $forked = []; + foreach ($orchestrator->solvePortfolio($items, $containers, $config, Deadline::ofMilliseconds(60_000))->solutions as $solution) { + $forked[$solution->solverName] = $solution; + } + + $compared = 0; + foreach (array_slice($starts, 1) as [$solver, $orderName, $order]) { + [$solution, $record] = ConcurrentStarts::runOneStartInProcess( + $bridge, $solver, $orderName, $order, $containers, $config, null, hrtime(true) + 60_000_000_000, [], + ); + self::assertSame($solver->name() . ':' . $orderName, $solution->solverName); + self::assertTrue($record->completed && !$record->truncated, "{$solution->solverName} ran to completion"); + if (!isset($forked[$solution->solverName])) { + continue; + } + self::assertSame(serialize($forked[$solution->solverName]->containers), serialize($solution->containers), $solution->solverName); + self::assertSame(serialize($forked[$solution->solverName]->unpacked), serialize($solution->unpacked), $solution->solverName); + $compared++; + } + self::assertGreaterThan(0, $compared, 'no forked start was compared'); + } + 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 3c050b2..eb80ec2 100644 --- a/tests/IrregularItemsTest.php +++ b/tests/IrregularItemsTest.php @@ -370,6 +370,30 @@ public static function testACompressibleRequestSurvivesTheWire(): void self::assertSame(['brick#1', 'cushion#1'], $placed); } + /** + * Same size and weight once made one lattice profile, so the soft type joined the rigid + * type's grid lattice and was stacked with no crush check: the answer came back + * `invalid_result` where a valid plan existed. The shape is part of the profile now. + */ + public static function testACushionThatWouldBeCrushedIsLeftOutRatherThanStackedInALattice(): void + { + $cube = ['length' => '50', 'width' => '50', 'height' => '50']; + $result = ArrayCodec::pack([ + 'units' => ['length' => 'mm'], + 'items' => [ + ['id' => 'rigid', 'dimensions' => $cube, 'weight' => ['value' => '1', 'unit' => 'kg']], + ['id' => 'soft', 'quantity' => 2, 'dimensions' => $cube, 'weight' => ['value' => '1', 'unit' => 'kg'], + 'shape_type' => 'compressible', 'compression_ratio' => 0.5, 'max_compression_pressure_kpa' => 1], + ], + 'containers' => [['id' => 'c', 'inner_dimensions' => ['length' => '50', 'width' => '50', 'height' => '150']]], + 'configuration' => ['max_containers' => 1, 'time_limit_ms' => 60000, 'effort_budget' => [ + 'max_candidates_evaluated' => 1000000, 'max_placement_attempts' => 1000000, 'max_search_nodes' => 1000000]], + ]); + + self::assertSame('best_found', $result['status']); + self::assertSame(['soft'], array_column($result['unpacked_items'], 'item_type')); + } + public static function testCompressionRefreshesVolumeBeforeReserveAdmission(): void { $request = self::wireRequest([[ diff --git a/tests/MadeToMeasureTest.php b/tests/MadeToMeasureTest.php index de2b247..ec7d761 100644 --- a/tests/MadeToMeasureTest.php +++ b/tests/MadeToMeasureTest.php @@ -4,11 +4,12 @@ namespace Packvium\Tests; use InvalidArgumentException; -use Packvium\Algorithm\{ContainerState, Deadline, SearchStats, SingleContainerSolution, SingleContainerSolver, SolverOrchestrator}; +use Packvium\Algorithm\{ContainerState, Deadline, SearchStats, SingleContainerSolution, SingleContainerSolver, SolverOrchestrator, TimeLimitReached}; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, Dimensions, Item, MadeToMeasure, PackedContainer, PackingRequest, Placement, Point, Rotation}; use Packvium\Serialization\{ArrayCodec, InvalidRequestException, UnsupportedFeatureException}; use Packvium\Unit\Length; +use Packvium\Support\ResultValidation\Validator; use Packvium\Validation\IndependentSolutionValidator; use ReflectionMethod; @@ -108,6 +109,21 @@ public static function testACountedLimitReachedMidChainStopsItWithTheBestSoFar() self::assertTrue($one->timeLimitReached); } + public static function testARungThatRunsOutOfTimeStopsTheChainWithTheBestSoFar(): void + { + $solver = new ScriptedRungSolver([[1, 100], [-1, 0], [3, 100], [3, 100]]); + [$one, $trials] = self::chain($solver); + self::assertSame(1, $trials); + self::assertCount(2, $solver->envelopes, 'no rung is tried after the one that ran out of time'); + self::assertSame(1, $one->state->placementCount()); + self::assertTrue($one->timeLimitReached); + } + + public static function testAFirstRungThatRunsOutOfTimeLeavesNothingToKeep(): void + { + self::assertThrows(TimeLimitReached::class, static fn() => self::chain(new ScriptedRungSolver([[-1, 0], [3, 100]]))); + } + public static function testTheWorkedOrderIsCutToA210MillimetreBox(): void { $packed = ArrayCodec::pack(self::request())['containers'][0]; @@ -147,7 +163,6 @@ public static function testEachRefusedCombinationIsNamed(): void $cases = [ 'container.made_to_measure+axles' => ['axles' => [['position' => '0'], ['position' => '1510']]], 'container.made_to_measure+obstacles' => ['obstacles' => [['id' => 'post', 'dimensions' => self::mm(10, 10, 10)]]], - 'container.made_to_measure+void_fill_reserve_ratio' => ['void_fill_reserve_ratio' => 0.5], ]; foreach ($cases as $name => $fields) { $request = self::request(); @@ -194,6 +209,68 @@ public static function testTheValidatorRecutsTheBoxFromTheDeclaredMachine(): voi self::assertSame(['made_to_measure_cost_mismatch'], $codes); } + public static function testAReserveTheTightBoxWouldBreakIsKeptByCuttingTheRung(): void + { + // A 210 mm cut holds the eight cubes but not half its volume in reserve; the + // 260 mm rung they were solved in does. + $request = self::reserved(); + $result = json_decode((string) json_encode(ArrayCodec::pack($request)), true); + $packed = $result['containers'][0]; + self::assertSame(['260', '263', '200'], [$packed['inner_dimensions']['length']['value'], $packed['outer_dimensions']['width']['value'], $packed['achieved_dimensions']['height']['value']]); + self::assertSame('feasible', $result['status']); + self::assertSame([], Validator::validate($request, $result)); + self::assertSame([], self::resultCodes($request, $result, 260)); + // Off the machine grid, or with no reserve to keep, the larger box is a mismatch. + self::assertContains('fabricated_dimensions_mismatch', self::resultCodes($request, $result, 261)); + $unreserved = $request; + unset($unreserved['containers'][0]['void_fill_reserve_ratio']); + self::assertContains('fabricated_dimensions_mismatch', self::resultCodes($unreserved, $result, 260)); + $unmeasured = $result; + // The reported used volume is a decimal string; a number is not read as one. + $unmeasured['containers'][0]['used_volume_ticks3'] = (int) $unmeasured['containers'][0]['used_volume_ticks3']; + self::assertContains('fabricated_dimensions_mismatch', self::resultCodes($request, $unmeasured, 260)); + } + + public static function testTheInternalValidatorAdmitsAReserveCutOnTheGrid(): void + { + $item = Item::create('cube', Dimensions::mm(100, 100, 100), 0, 8); + $placements = []; + foreach ($item->instances() as $index => $instance) { + $origin = new Point(($index % 2) * 100 * self::MM, (intdiv($index, 2) % 2) * 100 * self::MM, intdiv($index, 4) * 100 * self::MM); + $placements[] = new Placement($instance, $origin, Rotation::LWH, $instance->dimensions(), $origin, $instance->dimensions()); + } + $validator = new IndependentSolutionValidator(); + $codes = static function (float $reserve, array $sides) use ($item, $placements, $validator): array { + $declared = new Container('machine', Dimensions::mm(1510, 1510, 1510), costMinor: 40, voidFillReserveRatio: $reserve, madeToMeasure: self::machine(costPerSquareMetreMinor: 1000)); + $box = $declared->fabricate(self::ticks(...$sides)); + return array_map(static fn($issue) => $issue->code, $validator->validate(new PackingRequest([$item], [$declared]), [new PackedContainer($box, 1, $placements)])->issues); + }; + self::assertSame([], $codes(0.5, [260, 260, 260])); + self::assertSame([], $codes(0.5, [285, 260, 260])); + self::assertContains('fabricated_dimensions_mismatch', $codes(0.0, [260, 260, 260])); + // A cut the tight box already keeps the reserve in is no reserve cut. + self::assertContains('fabricated_dimensions_mismatch', $codes(0.1, [260, 260, 260])); + } + + /** @param array $request @param array $result @return list */ + private static function resultCodes(array $request, array $result, int $sideMm): array + { + foreach (['length', 'width', 'height'] as $side) { + $result['containers'][0]['inner_dimensions'][$side]['ticks'] = $sideMm * self::MM; + } + return array_values(array_unique(array_map(static fn($issue): string => $issue->code, Validator::validate($request, $result)))); + } + + /** @return array */ + private static function reserved(): array + { + $request = self::request(); + $request['configuration']['solver_profile'] = 'balanced'; + $request['containers'][0]['void_fill_reserve_ratio'] = 0.5; + $request['containers'][0]['made_to_measure']['tare_per_square_metre'] = '500'; + return $request; + } + /** @return array{0:SingleContainerSolution,1:int} */ private static function chain(ScriptedRungSolver $solver, ?Deadline $deadline = null): array { @@ -248,7 +325,10 @@ private static function request(): array } } -/** Places a scripted number of items per rung, along x at the scripted pitch in millimetres. */ +/** + * Places a scripted number of items per rung, along x at the scripted pitch in millimetres; a + * negative count is a rung whose solve runs out of time before it returns. + */ final class ScriptedRungSolver implements SingleContainerSolver { /** @var list */ @@ -268,6 +348,9 @@ public function packOne(Container $container, int $sequence, array $items, Packi { [$count, $pitch] = $this->script[count($this->envelopes)]; $this->envelopes[] = $container->innerDimensions; + if ($count < 0) { + throw new TimeLimitReached('Packing time limit reached'); + } $stats->searchNodesExpanded++; $state = new ContainerState($container, $sequence); foreach (array_slice($items, 0, $count) as $index => $instance) { diff --git a/tests/MeasureReadingTest.php b/tests/MeasureReadingTest.php index 6b2e192..25a8a44 100644 --- a/tests/MeasureReadingTest.php +++ b/tests/MeasureReadingTest.php @@ -23,6 +23,16 @@ public static function testAVastLengthIsPastTheCeilingAndANegativeOneIsNegative( self::assertSame(MeasureReading::NEGATIVE, MeasureReading::verdict('-' . self::VAST, Weight::class, 'g')); } + public static function testAMixedFractionWhoseWholePartIsTheSmallestIntIsNegative(): void + { + // abs(PHP_INT_MIN) is a float equal to PHP_INT_MAX: it once passed the range check and + // failed later as a type error, read as unreadable where Python says negative. + foreach (['-9223372036854775808 0/1', '-9223372036854775808 1/2'] as $text) { + self::assertSame(MeasureReading::NEGATIVE, MeasureReading::verdict($text, Length::class, 'ticks'), $text); + self::assertSame(MeasureReading::NEGATIVE, MeasureReading::verdict($text, Weight::class, 'g'), $text); + } + } + public static function testEverySpellingOfAVastLengthIsReadExactly(): void { foreach (['100000000000000000000 1/2', '922337203685477.5807', self::VAST . '/3', self::VAST . ' cm', self::VAST . 'ticks'] as $text) { diff --git a/tests/NestedTest.php b/tests/NestedTest.php index b274803..a0a75a1 100644 --- a/tests/NestedTest.php +++ b/tests/NestedTest.php @@ -5,8 +5,15 @@ use Packvium\Config\PackingConfig; use Packvium\Domain\Dimensions; +use Packvium\Domain\PackedContainer; use Packvium\Nested\NestedPacker; use Packvium\Nested\PackingLevel; +use Packvium\Result\PackingResult; +use Packvium\Serialization\ArrayCodec; +use Packvium\Support\RequestRules; +use InvalidArgumentException; +use ReflectionMethod; +use TypeError; use Packvium\Unit\Length; use Packvium\Unit\Weight; @@ -18,6 +25,12 @@ */ final class NestedTest extends TestCase { + /** + * The level beam's answers, held once for all four engines. A published copy of + * the package does not carry the corpus, so the test that reads it skips there. + */ + private const BEAM_SCENE = __DIR__ . '/../../conformance/scene/nested-beam.json'; + public static function testTwoLevelsArePackedInOrder(): void { $result = (new NestedPacker())->pack( @@ -126,4 +139,230 @@ public static function testASingleLevelBehavesLikeAnOrdinaryPack(): void self::assertCount(1, $result->levels); self::assertTrue($result->levels[0]->complete()); } + + public static function testALevelBeamWidthOfOneIsTheGreedyChain(): void + { + [$items, $levels] = self::deadEnd(); + + self::assertSame( + self::shape((new NestedPacker())->pack($items, $levels)->levels), + self::shape((new NestedPacker(1))->pack($items, $levels)->levels), + ); + } + + public static function testAWiderBeamFindsTheCartonSetThatFitsThePallet(): void + { + // The single long carton is the better carton level and cannot stand on the tower. + [$items, $levels] = self::deadEnd(); + + $greedy = (new NestedPacker(1))->pack($items, $levels); + $beam = (new NestedPacker(2))->pack($items, $levels); + + self::assertSame([true, false], array_map(static fn(PackingResult $l): bool => $l->complete(), $greedy->levels)); + self::assertSame([true, true], array_map(static fn(PackingResult $l): bool => $l->complete(), $beam->levels)); + self::assertSame(['single', 'single'], array_map( + static fn($c): string => $c->container->id, + $beam->levels[0]->containers, + )); + } + + public static function testHandoffsThatAreTheSameItemsOccupyOneBeamSlot(): void + { + // Packing against every carton and against `long` alone both hand up one `long#1`; + // counting that twice would fill a width of two and drop the chain that fits. + [$items, $levels] = self::deadEnd(); + + $result = (new NestedPacker(2))->pack($items, $levels); + + self::assertCount(2, $result->levels); + foreach ($result->levels as $level) { + self::assertTrue($level->complete()); + } + } + + public static function testNoLevelsIsAnEmptyAnswerAtAnyWidth(): void + { + self::assertSame([], (new NestedPacker(3))->pack([Support::item('cube', 100, 100, 100)], [])->levels); + } + + public static function testTheLevelBeamWidthIsAPositiveInteger(): void + { + foreach ([0, -1] as $width) { + self::assertThrows(InvalidArgumentException::class, static fn() => new NestedPacker($width)); + } + // Strict types refuse what Python refuses by its own check: a boolean, a float, text. + foreach ([true, 1.0, '2'] as $width) { + self::assertThrows(TypeError::class, static fn() => new NestedPacker($width)); + } + self::assertSame(2, (new NestedPacker(2))->levelBeamWidth); + } + + public static function testTheLevelBeamWidthRefusalNamesTheParameter(): void + { + try { + new NestedPacker(0); + } catch (InvalidArgumentException $error) { + self::assertSame('level_beam_width must be a positive integer', $error->getMessage()); + return; + } + self::assertTrue(false, 'a width of zero was accepted'); + } + + public static function testChainScoresCompareAsExactNumbersNotText(): void + { + // A component past PHP's integer range is a decimal string; as text, "1000..." < "999...". + $compare = new ReflectionMethod(NestedPacker::class, 'compareScores'); + $compare->setAccessible(true); + + self::assertSame(1, $compare->invoke(null, [0, '100000000000000000000'], [0, '99999999999999999999'])); + self::assertSame(-1, $compare->invoke(null, [0, 5], [0, '99999999999999999999'])); + self::assertSame(-1, $compare->invoke(null, [1.5], [2])); + self::assertSame(0, $compare->invoke(null, [3, 4], [3, 4])); + } + + public static function testAHandoffIsTheMultisetOfContainersNotTheirNumberingOrOrder(): void + { + // Engines may number and emit equal instances differently; the same containers + // handed up must still collapse to one beam slot. + $packed = Support::pack([Support::item('cube', 100, 100, 100, ['quantity' => 3])], + [Support::box('pair', 200, 100, 100, ['quantity' => 1]), Support::box('single', 100, 100, 100)]); + self::assertCount(2, $packed->containers); + $renumbered = array_map( + static fn(PackedContainer $c): PackedContainer => new PackedContainer($c->container, $c->sequence + 7, $c->placements), + array_reverse($packed->containers), + ); + $shuffled = new PackingResult($packed->status, $renumbered, $packed->unpacked, $packed->algorithm, $packed->score); + $fewer = new PackingResult($packed->status, [$packed->containers[0]], $packed->unpacked, $packed->algorithm, $packed->score); + + $key = new ReflectionMethod(NestedPacker::class, 'handoffKey'); + $key->setAccessible(true); + self::assertSame($key->invoke(null, $packed), $key->invoke(null, $shuffled)); + self::assertNotSame($key->invoke(null, $packed), $key->invoke(null, $fewer)); + } + + public static function testTheLevelBeamMatchesTheSharedScene(): void + { + if (!is_file(self::BEAM_SCENE)) { + self::skip('the shared cross-language scene corpus is not part of this package'); + } + $payload = json_decode((string) file_get_contents(self::BEAM_SCENE), true, flags: JSON_THROW_ON_ERROR); + self::assertNotSame([], $payload['cases'], 'an empty scene would pass without asserting anything'); + + foreach ($payload['cases'] as $case) { + self::assertSame(self::canonical($case['expected']), self::canonical(self::sceneAnswer($case)), "nested-beam case {$case['name']}"); + } + } + + /** @param array $case @return list> */ + private static function sceneAnswer(array $case): array + { + $items = []; + $levels = []; + foreach ($case['levels'] as $index => $entry) { + RequestRules::check($entry['request']); + [$config, , , $levelItems, $containers] = self::codec('model', $entry['request']); + if ($index === 0) { + $items = $levelItems; + } + $levels[] = new PackingLevel($entry['name'], $containers, $config); + } + $result = (new NestedPacker($case['level_beam_width']))->pack($items, $levels); + $answer = []; + foreach ($result->levels as $index => $level) { + $answer[] = self::projection($case['levels'][$index]['name'], $level->toArray('mm', 'g')); + } + return $answer; + } + + /** + * What the beam decides about a level, read from its JSON result as any engine emits it: + * the contract's multiset view, with instance numbers dropped and every list sorted. + * + * @param array $result @return array + */ + private static function projection(string $name, array $result): array + { + return [ + 'name' => $name, + 'complete' => $result['complete'], + 'score' => $result['score'], + 'containers' => array_map(static fn(array $container): array => [ + 'container_type' => $container['container_type'], + 'placements' => array_map(static fn(array $placement): array => [ + self::kind($placement['item_type']), + $placement['position']['x']['ticks'], + $placement['position']['y']['ticks'], + $placement['position']['z']['ticks'], + $placement['orientation'], + ], $container['placements']), + ], $result['containers']), + 'unpacked' => array_map(static fn(array $unpacked): string => self::kind($unpacked['item_type']), + $result['unpacked_items']), + ]; + } + + /** + * One order for both sides of the comparison. The generator sorts by Python's own + * ordering; equal multisets sort equal under any total order, so this is exactly as strict. + * + * @param list> $levels @return list> + */ + private static function canonical(array $levels): array + { + return array_map(static function (array $level): array { + $containers = array_map(static function (array $container): array { + $container['placements'] = self::sortedByJson($container['placements']); + return $container; + }, $level['containers']); + $level['containers'] = self::sortedByJson($containers); + $level['unpacked'] = self::sortedByJson($level['unpacked']); + return $level; + }, $levels); + } + + /** @param list $values @return list */ + private static function sortedByJson(array $values): array + { + usort($values, static fn($left, $right): int => strcmp( + json_encode($left, JSON_THROW_ON_ERROR), + json_encode($right, JSON_THROW_ON_ERROR), + )); + return $values; + } + + /** A handed-up item is named after its packed container, `quad#2`; its type is `quad`. */ + private static function kind(string $itemType): string + { + return explode('#', $itemType, 2)[0]; + } + + /** @return mixed */ + private static function codec(string $method, mixed ...$arguments) + { + $builder = new ReflectionMethod(ArrayCodec::class, $method); + $builder->setAccessible(true); + return $builder->invoke(null, ...$arguments); + } + + /** @return array{0:list<\Packvium\Domain\Item>,1:list} */ + private static function deadEnd(): array + { + return [ + [Support::item('cube', 100, 100, 100, ['quantity' => 2])], + [ + new PackingLevel('carton', [Support::box('long', 200, 100, 100), Support::box('single', 100, 100, 100)]), + new PackingLevel('pallet', [Support::box('tower', 100, 100, 200)]), + ], + ]; + } + + /** @param list $levels @return list,2:list}> */ + private static function shape(array $levels): array + { + return array_map(static fn(PackingResult $level): array => [ + $level->complete(), + array_map(static fn($c): string => $c->id(), $level->containers), + $level->score, + ], $levels); + } } diff --git a/tests/ObjectiveBoundsTest.php b/tests/ObjectiveBoundsTest.php index cd9ff8c..e6371fe 100644 --- a/tests/ObjectiveBoundsTest.php +++ b/tests/ObjectiveBoundsTest.php @@ -39,10 +39,33 @@ private static function scene(): array } $decoded = json_decode((string)file_get_contents($path), true); self::assertTrue(is_array($decoded), "the scene at $path is not readable JSON"); - self::assertSame('packvium-objective-bounds/v1', $decoded['format']); + self::assertSame('packvium-objective-bounds/v2', $decoded['format']); return $decoded; } + /** + * Every covered objective's vector for one normalised input, null where a ceiling + * withholds it -- the shape the scene's `objectives` records. + * + * @param list> $instances + * @param list> $containers + * @return array> + */ + private static function objectives(array $instances, array $containers): array + { + $vectors = []; + foreach (ObjectiveBounds::OBJECTIVE_ORDERS as $objective => $order) { + try { + $vectors[$objective] = ObjectiveBounds::objectiveVector($instances, $containers, $order); + } catch (BoundOverflowException $refused) { + $vectors[$objective] = null; + } + } + // Keyed by name: the scene lists them alphabetically, the constant by score family. + ksort($vectors); + return $vectors; + } + public static function testEveryCorpusCaseMatchesPythonExactly(): void { $scene = self::scene(); @@ -57,6 +80,9 @@ public static function testEveryCorpusCaseMatchesPythonExactly(): void "bounds diverge from Python on {$case['fixture']}: expected " . json_encode($case['bounds']) . ', got ' . json_encode($computed), ); + ksort($case['objectives']); + self::assertSame($case['objectives'], self::objectives($case['instances'], $case['containers']), + "objective vectors diverge from Python on {$case['fixture']}"); } } @@ -296,20 +322,39 @@ public static function testEverySceneEdgeIsAnsweredOrRefusedAsTheOraclePredicate self::assertSame($edge['bounds'], ObjectiveBounds::fromNormalised($edge['instances'], $containers), $edge['name']); } + ksort($edge['objectives']); + self::assertSame($edge['objectives'], self::objectives($edge['instances'], $edge['containers']), + "{$edge['name']}: objective vectors"); } } - /** `lowest_cost` reads the same five numbers in its own order; nothing else gets any. */ + /** + * `lowest_cost` reads the same five numbers in its own order; `maximum_value`, + * `open_dimension_height` and `maximum_volume` add the one key each ranks by alone + *; the two shipping objectives get none. + */ public static function testTheRequestBoundIsStatedOnlyForTheCoveredObjectives(): void { - $items = self::instancesOf(Item::create('i', Dimensions::mm(60, 50, 40)), 2); + $item = Item::create('i', Dimensions::mm(60, 50, 40), value: 4); + $items = self::instancesOf($item, 2); $crate = [Container::create('c', Dimensions::mm(100, 100, 100), costMinor: 7)]; $default = ObjectiveBounds::forRequest($items, $crate, 'default'); self::assertSame(ObjectiveBounds::compute($items, $crate), $default); [$unpacked, $count, $cost, $unused, $height] = $default; self::assertSame([$unpacked, $cost, $count, $unused, $height], ObjectiveBounds::forRequest($items, $crate, 'lowest_cost')); - foreach (['maximum_value', 'maximum_volume', 'open_dimension_height', 'shipping_cost'] as $objective) { + // Unlimited crates: nothing is forced out, so nothing is forgone and no volume is lost; + // the two boxes stand at least their volume over the crate's floor. + $floor = (100 * Length::TICKS_PER_MM) ** 2; + $placed = 2 * 60 * 50 * 40 * Length::TICKS_PER_MM ** 3; + $achieved = intdiv($placed + $floor - 1, $floor); + self::assertSame([$unpacked, 0, $count, $cost, $unused], + ObjectiveBounds::forRequest($items, $crate, 'maximum_value')); + self::assertSame([$unpacked, $achieved, $count, $cost, $unused], + ObjectiveBounds::forRequest($items, $crate, 'open_dimension_height')); + self::assertSame([0, $unpacked, $count, $cost, $unused], + ObjectiveBounds::forRequest($items, $crate, 'maximum_volume')); + foreach (['shipping_cost', 'lowest_landed_cost'] as $objective) { self::assertNull(ObjectiveBounds::forRequest($items, $crate, $objective), $objective); } @@ -320,6 +365,67 @@ public static function testTheRequestBoundIsStatedOnlyForTheCoveredObjectives(): self::assertNull(ObjectiveBounds::forRequest($items, $machine, 'default')); } + /** + * The oracle's hand-checked objective-only keys, so each branch of the three + * terms is pinned here and not only by whatever the corpus happens to contain. + */ + public static function testEachObjectiveReadsItsOwnKey(): void + { + $instance = static fn(int $value, bool $shrinks = false): array + => ['volume' => '600', 'weight' => 0, 'shrinks' => $shrinks, 'value' => $value]; + $container = static fn(int $area, int $height, ?int $quantity): array + => ['usable' => '1000', 'inner' => '1000', 'base_area' => $area, 'height' => $height, + 'payload' => null, 'max_items' => null, 'quantity' => $quantity, 'cost_minor' => 0]; + $oneSlot = [$container(100, 10, 1)]; + + // One of three fits: the two cheapest forgo 10 + 50, the one placed stands 600 / 100, + // and 800 of 1800 cannot fit, 444444.4 ppm rounded up. + $three = [$instance(50), $instance(10), $instance(90)]; + self::assertSame([ + 'default' => [2, 1, 0, 400000, 600000], + 'lowest_cost' => [2, 0, 1, 400000, 600000], + 'maximum_value' => [2, 60, 1, 0, 400000], + 'maximum_volume' => [444445, 2, 1, 0, 400000], + 'open_dimension_height' => [2, 6, 1, 0, 400000], + ], self::objectives($three, $oneSlot)); + + // The two cheapest values sum to 2^53: only maximum_value is withheld. + $max = (int)ObjectiveBounds::MAX_BOUND_VALUE; + $past = self::objectives([$instance($max), $instance(1), $instance($max)], $oneSlot); + self::assertNull($past['maximum_value']); + self::assertSame([2, 6, 1, 0, 400000], $past['open_dimension_height']); + + // The widest floor sets the height term, and unlimited stock forces no volume out. + $wide = self::objectives([$instance(0), $instance(0), $instance(0)], + [$container(100, 10, null), $container(250, 4, 1)]); + self::assertSame([0, 8, 2, 0, 199999], $wide['open_dimension_height']); + self::assertSame([0, 0, 2, 0, 199999], $wide['maximum_volume']); + + // An instance smaller than its box drops both volume terms. + $nested = self::objectives(array_fill(0, 3, $instance(3, true)), $oneSlot); + self::assertSame([0, 0, 1, 0, 0], $nested['open_dimension_height']); + self::assertSame([0, 0, 1, 0, 0], $nested['maximum_volume']); + + // No floor to stand on, and nothing requested: both terms claim nothing. + self::assertSame(0, self::objectives([$instance(0)], [$container(0, 10, 1)])['open_dimension_height'][1]); + $flat = ['volume' => '0', 'weight' => 0, 'shrinks' => false, 'value' => 0]; + self::assertSame(0, self::objectives([$flat], $oneSlot)['open_dimension_height'][1], + 'a placed volume of nothing stands no height'); + self::assertSame([1, 0, 0, 0, 0], self::objectives([$instance(0)], [])['maximum_value']); + self::assertSame(0, self::objectives([], $oneSlot)['maximum_volume'][0]); + } + + /** The value term selects the smallest values without sorting them all. */ + public static function testTheSmallestValuesAreSelectedWithoutASort(): void + { + $smallest = new \ReflectionMethod(ObjectiveBounds::class, 'smallestValues'); + self::assertSame([], $smallest->invoke(null, [5, 1, 3], 0)); + self::assertSame([5, 1, 3], $smallest->invoke(null, [5, 1, 3], 3)); + $two = $smallest->invoke(null, [5, 1, 9, 3, 7], 2); + sort($two); + self::assertSame([1, 3], $two); + } + /** A custom solution scorer ranks by positions the bound knows nothing about. */ public static function testACustomSolutionScorerGetsNoBound(): void { diff --git a/tests/OperationalArtifactTest.php b/tests/OperationalArtifactTest.php index 5105b69..b5d4fcf 100644 --- a/tests/OperationalArtifactTest.php +++ b/tests/OperationalArtifactTest.php @@ -434,6 +434,32 @@ public static function testAContainerNumberThatIsNotAnIntegerIsRefusedNotCompute } } + /** The sheet shows the index plus one, so 2^53 - 1 is already one past the ceiling. */ + public static function testAContainerNumberJavascriptCannotHoldIsRefusedRatherThanPrinted(): void + { + foreach ([9007199254740991, PHP_INT_MAX, 18446744073709551615] as $index) { + $artifact = self::artifact(); + $artifact['work_order']['containers'][0]['container_index'] = $index; + self::assertSame('number_out_of_range', self::code(static function () use ($artifact): void { + ArtifactExports::workOrderHtml($artifact); + }), (string) $index); + } + $artifact = self::artifact(); + $artifact['work_order']['containers'][0]['container_index'] = 9007199254740990; + self::assertTrue(str_contains(ArtifactExports::workOrderHtml($artifact), '

Container 9007199254740991: ')); + } + + public static function testAnyPrintedIntegerJavascriptCannotHoldIsRefused(): void + { + foreach ([-9007199254740992, 1.8446744073709552E+19] as $sequence) { + $artifact = self::artifact(); + $artifact['work_order']['containers'][0]['lines'][0]['sequence'] = $sequence; + self::assertSame('number_out_of_range', self::code(static function () use ($artifact): void { + ArtifactExports::csv($artifact); + })); + } + } + public static function testABooleanInAnyPrintedPositionIsRefused(): void { $artifact = self::artifact(); diff --git a/tests/PackingSequenceTest.php b/tests/PackingSequenceTest.php index 12074c7..7afbf1c 100644 --- a/tests/PackingSequenceTest.php +++ b/tests/PackingSequenceTest.php @@ -1101,4 +1101,32 @@ public static function testSafeRouteRemovalOrderDeadlockReportsStuckBoxes(): voi self::assertContains(1, $e->stuck); } } + + public static function testOutOfZOrderFloorBoxSlidingUnderElevatedBoxDeactivatesIsolatedFloorShortcut(): void + { + $heavyUpper = Item::create('upper', Dimensions::mm(10, 10, 5), weight: '5kg', stackingGroup: 'C'); + $fragileFloor = Item::create('floor-fragile', Dimensions::mm(10, 10, 5), weight: '1kg', maxTopLoad: '1kg'); + $nonStackFloor = Item::create('floor-ns', Dimensions::mm(10, 10, 5), stackable: false); + $groupFloor = Item::create('floor-grp', Dimensions::mm(10, 10, 5), acceptsStackingGroups: ['A']); + $container = Container::create('c', Dimensions::mm(10, 10, 20)); + + foreach ([ + [$fragileFloor, 'top_load_exceeded: floor-fragile#1'], + [$nonStackFloor, 'non_stackable_item_has_load: floor-ns#1'], + [$groupFloor, 'stacking_group_incompatible: floor-grp'], + ] as [$baseItem, $expectedReason]) { + $placements = [ + self::stackedPlacement($baseItem, 0, 0, 0), + self::stackedPlacement($heavyUpper, 0, 0, 5), + ]; + try { + LoadingDependencyGraph::verifyLoadingPrefixBusinessRules($placements, [1, 0], $container); + self::fail('expected SequenceReplayError'); + } catch (SequenceReplayError $error) { + self::assertSame(0, $error->index); + self::assertSame(1, $error->step); + self::assertSame($expectedReason, $error->reason); + } + } + } } diff --git a/tests/PalletOverhangTest.php b/tests/PalletOverhangTest.php new file mode 100644 index 0000000..903fdc9 --- /dev/null +++ b/tests/PalletOverhangTest.php @@ -0,0 +1,390 @@ + '50', 'width' => '50']; + + public static function testTheFrameWidensByTheLimitAndCarriesTheDeck(): void + { + $pallet = self::pallet(new OverhangLimit(Length::mm(50), Length::mm(30))); + $frame = PalletOverhang::solvingFrame($pallet); + self::assertSame([self::ticks(1300), self::ticks(860), self::ticks(1000)], self::sides($frame->innerDimensions)); + self::assertEquals(new Deck(self::ticks(50), self::ticks(30), self::ticks(1200), self::ticks(800)), $frame->deck); + self::assertNull($frame->palletOverhangLimit); + self::assertSame($frame, PalletOverhang::solvingFrame($frame)); + self::assertSame([self::ticks(1200), self::ticks(800), self::ticks(1000)], self::sides($frame->declaredInner())); + $deck = PalletOverhang::deckAlone($frame); + self::assertNull($deck->deck); + self::assertSame(self::sides($pallet->innerDimensions), self::sides($deck->innerDimensions)); + $plain = self::pallet(null); + self::assertSame($plain, PalletOverhang::solvingFrame($plain)); + } + + public static function testAFloorPlacementRestsOnItsOverlapWithTheDeck(): void + { + $deck = new Deck(self::ticks(50), self::ticks(50), self::ticks(1200), self::ticks(800)); + $onTheEdge = self::box(1200, 100, 100); + self::assertSame(1.0, PalletOverhang::floorSupportRatio(null, $onTheEdge)); + self::assertSame(0.5, PalletOverhang::floorSupportRatio($deck, $onTheEdge)); + self::assertSame(self::ticks(50) * self::ticks(100), PalletOverhang::deckContactArea($deck, $onTheEdge)); + self::assertSame(0, PalletOverhang::deckContactArea($deck, self::box(0, 0, 40))); + } + + public static function testTheSupportRuleJudgesTheDeckAsItsOnlySupporter(): void + { + $frame = PalletOverhang::solvingFrame(self::pallet(new OverhangLimit(Length::mm(50), Length::mm(50)))); + // 50 of 100 mm on the deck: a ratio of 0.5, centroid on the deck's edge. + self::assertSame([true, null], self::verdict($frame, 0.0, 1200)); + self::assertSame([false, 'insufficient_support'], self::verdict($frame, 0.75, 1200)); + self::assertSame([true, null], self::verdict($frame, 0.5, 1200)); + // 40 of 100 mm: the ratio passes at 0.4, but the centroid hangs past the deck. + self::assertSame([false, 'centre_of_gravity_unsupported'], self::verdict($frame, 0.4, 1210)); + // Without a deck the floor is whole support. + self::assertSame([true, null], self::verdict(self::pallet(null), 0.95, 1100)); + } + + public static function testTheDeckIsPackedFirstWhenItHoldsEverything(): void + { + $carton = ['id' => 'carton', 'quantity' => 6, 'weight' => '10 kg', + 'dimensions' => ['length' => '400', 'width' => '400', 'height' => '300']]; + $result = ArrayCodec::pack(self::request([$carton], [self::palletJson()])); + self::assertSame(true, $result['complete']); + $container = $result['containers'][0]; + self::assertSame([1200, 800], array_slice(self::millimetres($container['achieved_dimensions']), 0, 2)); + self::assertSame([1200, 800, 1000], self::millimetres($container['inner_dimensions'])); + foreach ($container['placements'] as $placement) { + $x = (int) $placement['position']['x']['value']; + $y = (int) $placement['position']['y']['value']; + self::assertTrue($x >= 50 && $x + 400 <= 1250 && $y >= 50 && $y + 400 <= 850, "{$x},{$y} overhangs"); + if ((int) $placement['position']['z']['value'] === 0) { + self::assertSame('1.000000', $placement['support_ratio']); + } + } + } + + public static function testTheOverhangIsUsedOnlyWhenItPlacesMore(): void + { + $result = ArrayCodec::pack(self::request([self::crate()], [self::palletJson()])); + self::assertSame(true, $result['complete']); + $container = $result['containers'][0]; + // Longer than the deck on both axes, so seated centred: 25 mm past every edge. + self::assertSame([1250, 850, 400], self::millimetres($container['achieved_dimensions'])); + self::assertSame(['25', '25'], [$container['placements'][0]['position']['x']['value'], $container['placements'][0]['position']['y']['value']]); + self::assertSame([1200, 800, 1000], self::millimetres($container['outer_dimensions'])); + + $forbidden = ArrayCodec::pack(self::request([self::crate()], [self::palletJson(['length' => '0', 'width' => '0'])])); + self::assertSame(false, $forbidden['complete']); + self::assertSame([], $forbidden['containers']); + } + + public static function testTheDeckRefusesALoadItCannotCarry(): void + { + $carton = ['id' => 'carton', 'quantity' => 2, 'weight' => '5 kg', 'dimensions' => ['length' => '400', 'width' => '300', 'height' => '200']]; + $result = ArrayCodec::pack(self::request([self::crate(), $carton], [self::palletJson()], ['minimum_support_ratio' => 0.95])); + self::assertSame(['insufficient_support'], array_column($result['unpacked_items'], 'reason')); + self::assertSame([1200, 800, 200], self::millimetres($result['containers'][0]['achieved_dimensions'])); + } + + public static function testAPalletIsBilledAtTheFootprintItsLoadReached(): void + { + $limit = new OverhangLimit(Length::mm(50), Length::mm(50)); + $crate = Item::create('crate', Dimensions::mm(1250, 850, 400), '10 kg', 1, [Rotation::LWH]); + $carton = Item::create('carton', Dimensions::mm(400, 400, 300), '10 kg', 1, [Rotation::LWH]); + $outer = Dimensions::mm(1210, 810, 1150); + self::assertSame([1250, 850, 1150], self::billedMm($crate, self::pallet($limit, $outer))); + self::assertSame([1250, 850, 1000], self::billedMm($crate, self::pallet($limit))); + self::assertSame([1210, 810, 1150], self::billedMm($carton, self::pallet($limit, $outer))); + self::assertSame([1200, 800, 1000], self::billedMm($carton, self::pallet($limit))); + $packed = (new Packer())->pack([$crate], [self::pallet($limit, $outer)])->containers[0]; + self::assertSame([self::ticks(1250), self::ticks(850), self::ticks(1150)], self::sides($packed->asItem()->dimensions)); + } + + public static function testEveryUnsupportedCombinationIsNamed(): void + { + $combinations = [ + 'access_directions' => ['access_directions' => ['+x']], + 'axles' => ['axles' => [['position' => '0'], ['position' => '100']]], + 'made_to_measure' => ['made_to_measure' => ['minimum' => ['length' => '10', 'width' => '10', 'height' => '10'], 'increment' => ['length' => '10', 'width' => '10', 'height' => '10']]], + 'obstacles' => ['obstacles' => [['id' => 'o', 'dimensions' => ['length' => '1', 'width' => '1', 'height' => '1']]]], + 'void_fill_reserve_ratio' => ['void_fill_reserve_ratio' => 0.1], + ]; + foreach ($combinations as $name => $fields) { + self::assertSame(["container.pallet_overhang_limit+{$name}"], ArrayCodec::palletOverhangCombinations(self::request([self::crate()], [self::palletJson() + $fields]))); + } + $inert = self::palletJson() + ['access_directions' => [], 'obstacles' => [], 'void_fill_reserve_ratio' => 0, 'axles' => null]; + self::assertSame([], ArrayCodec::palletOverhangCombinations(self::request([self::crate()], [$inert]))); + $routed = self::request([self::crate() + ['stop_index' => 1]], [self::palletJson()]); + self::assertSame(['container.pallet_overhang_limit+item.stop_index'], ArrayCodec::palletOverhangCombinations($routed)); + self::assertThrows(UnsupportedFeatureException::class, static fn() => ArrayCodec::pack($routed)); + $unpalleted = self::request([self::crate() + ['stop_index' => 1]], [self::palletJson(null)]); + self::assertSame([], ArrayCodec::palletOverhangCombinations($unpalleted)); + } + + public static function testAMalformedLimitIsRefusedWithItsPointer(): void + { + $cases = [ + ['50', '', 'wrong_type', 'must be an object'], + [['width' => '50'], '/length', 'missing_field', 'is required'], + [['length' => '50'], '/width', 'missing_field', 'is required'], + [['length' => '50', 'width' => '50', 'height' => '1', 'depth' => '1'], '/depth', 'not_allowed', 'is not a known field'], + [['length' => '-1', 'width' => '0'], '/length', 'negative_measure', 'cannot be negative'], + [['length' => ['value' => '4503599627370496', 'unit' => 'ticks'], 'width' => '0'], '/length', 'above_maximum', 'must be at most 9007199254740991 ticks'], + [['length' => '0', 'width' => ['value' => '4503599627370496', 'unit' => 'ticks']], '/width', 'above_maximum', 'must be at most 9007199254740991 ticks'], + [['length' => ['value' => '300000000000', 'unit' => 'ticks'], 'width' => ['value' => '300000000000', 'unit' => 'ticks']], '', 'above_maximum', 'must enclose at most 10^30 cubic ticks'], + ]; + foreach ($cases as [$limit, $suffix, $reason, $detail]) { + self::assertRefused(self::palletJson($limit), "/containers/0/pallet_overhang_limit{$suffix}", $reason, $detail); + } + $bag = self::palletJson() + ['deformable_boundary' => ['kind' => 'flat_bag']]; + self::assertRefused($bag, '/containers/0/pallet_overhang_limit', 'not_allowed', 'cannot be combined with deformable_boundary'); + } + + public static function testTheObjectPathRefusesWhatTheJsonPathRefuses(): void + { + $limit = new OverhangLimit(Length::mm(50), Length::mm(50)); + $inner = Dimensions::mm(1200, 800, 1000); + $axle = new \Packvium\Domain\Axle(Length::mm(0)); + $refusals = [ + 'obstacles' => static fn() => new Container('p', $inner, null, new Weight(0), null, 0, null, [new \Packvium\Domain\Obstacle('o', new AxisAlignedBox(new Point(0, 0, 0), Dimensions::mm(1, 1, 1)))], [], null, [], 0.0, [], null, null, null, [], [], null, null, $limit), + 'axles' => static fn() => new Container('p', $inner, null, new Weight(0), null, 0, null, [], [], null, [], 0.0, [], null, [$axle, new \Packvium\Domain\Axle(Length::mm(100))], null, [], [], null, null, $limit), + 'access_directions' => static fn() => new Container('p', $inner, null, new Weight(0), null, 0, null, [], [], null, [], 0.0, [], null, null, null, ['+x'], [], null, null, $limit), + 'void_fill_reserve_ratio' => static fn() => new Container('p', $inner, null, new Weight(0), null, 0, null, [], [], null, [], 0.1, [], null, null, null, [], [], null, null, $limit), + 'made_to_measure' => static fn() => new Container('p', $inner, null, new Weight(0), null, 0, null, [], [], null, [], 0.0, [], null, null, null, [], [], null, new \Packvium\Domain\MadeToMeasure([1, 1, 1], [1, 1, 1], 0, 0, [0, 0, 0]), $limit), + ]; + foreach ($refusals as $name => $build) { + $error = self::caught($build); + self::assertSame(['not_allowed', "{$name} cannot be combined with pallet_overhang_limit"], [$error->reason(), $error->detail()]); + } + $bag = self::caught(static fn() => new Container('p', $inner, null, new Weight(0), null, 0, null, [], [], null, [], 0.0, [], null, null, null, [], [], 'flat_bag', null, $limit)); + self::assertSame('pallet_overhang_limit cannot be combined with deformable_boundary', $bag->detail()); + $vast = new OverhangLimit(new Length(4503599627370496), new Length(0)); + $error = self::caught(static fn() => (new Packer())->pack([Item::create('c', Dimensions::mm(1, 1, 1))], [self::pallet($vast)])); + self::assertSame(['/containers/0/pallet_overhang_limit/length', 'above_maximum'], [$error->field(), $error->reason()]); + // A route beside a pallet is refused at the first routed item (follow-up). + $plain = Item::create('plain', Dimensions::mm(1, 1, 1)); + $routed = Item::create('routed', Dimensions::mm(1, 1, 1), 0, 1, [Rotation::LWH], false, true, false, null, 0.0, null, [], [], 0, [], null, [], null, null, 2); + $error = self::caught(static fn() => (new Packer())->pack([$plain, $routed], [new Container('box', Dimensions::mm(10, 10, 10)), self::pallet($limit)])); + self::assertSame(['/items/1/stop_index', 'not_allowed', 'cannot be combined with pallet_overhang_limit'], [$error->field(), $error->reason(), $error->detail()]); + self::assertCount(1, (new Packer())->pack([$routed], [self::pallet(null)])->containers); + // The outer size is held to the declared deck, not to the wider frame. + self::assertNotNull(PalletOverhang::solvingFrame(self::pallet($limit, Dimensions::mm(1210, 810, 1150)))->outerDimensions); + } + + public static function testTheResultValidatorReadsTheDeck(): void + { + $carton = ['id' => 'carton', 'quantity' => 1, 'weight' => '10 kg', 'allowed_rotations' => ['LWH'], + 'dimensions' => ['length' => '400', 'width' => '400', 'height' => '300']]; + $request = self::request([$carton], [self::palletJson()], ['minimum_support_ratio' => 0.95]); + $result = json_decode((string) json_encode(ArrayCodec::pack($request)), true); + self::assertSame([], Validator::validate($request, $result)); + + $mismatch = $result; + $mismatch['containers'][0]['achieved_dimensions']['width']['ticks'] += 1; + self::assertSame(['achieved_dimensions_mismatch'], self::codes(Validator::validate($request, $mismatch))); + $missing = $result; + unset($missing['containers'][0]['achieved_dimensions']); + self::assertSame(['achieved_dimensions_mismatch'], self::codes(Validator::validate($request, $missing))); + + // Into the overhang zone's corner: 350 x 350 of 400 x 400 mm on the deck, below 0.95. + $hanging = $result; + $hanging['containers'][0]['placements'][0]['position']['x']['ticks'] = 0; + $hanging['containers'][0]['placements'][0]['position']['y']['ticks'] = 0; + self::assertContains('insufficient_support', self::codes(Validator::validate($request, $hanging))); + } + + public static function testShippingCostBillsTheFootprintTheLoadReached(): void + { + $billing = ['objective' => 'shipping_cost', 'dimensional_weight_divisor' => 5000, + 'dimensional_weight_length_unit' => 'cm', 'dimensional_weight_weight_unit' => 'kg']; + $request = self::request([self::crate()], [self::palletJson() + ['outer_dimensions' => ['length' => '1210', 'width' => '810', 'height' => '1150']]], $billing); + $result = json_decode((string) json_encode(ArrayCodec::pack($request)), true); + // 125 x 85 x 115 cm / 5000 = 244.375 kg, above the crate's 10 kg. + self::assertSame(244375 * Weight::TICKS_PER_G, $result['score'][1]); + self::assertSame([], Validator::validate($request, $result)); + // A bag is billed on its package, as before. + $book = ['id' => 'book', 'quantity' => 1, 'weight' => '300 g', 'allowed_rotations' => ['LWH'], + 'dimensions' => ['length' => '200', 'width' => '100', 'height' => '20']]; + $bag = ['id' => 'mailer', 'inner_dimensions' => ['length' => '240', 'width' => '140', 'height' => '100'], 'deformable_boundary' => ['kind' => 'flat_bag']]; + $bagRequest = self::request([$book], [$bag], $billing); + self::assertSame([], Validator::validate($bagRequest, json_decode((string) json_encode(ArrayCodec::pack($bagRequest)), true))); + } + + public static function testTheDeckSupportCheckSkipsWhatItCannotJudge(): void + { + $carton = ['id' => 'carton', 'quantity' => 1, 'weight' => '10 kg', 'allowed_rotations' => ['LWH'], + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]; + $free = self::request([$carton], [self::palletJson()]); + $result = json_decode((string) json_encode(ArrayCodec::pack($free)), true); + // No ratio asked for: a placement half off the deck is not judged. + $hanging = $result; + $hanging['containers'][0]['placements'][0]['position']['x']['ticks'] = self::ticks(1200); + $codes = self::codes(Validator::validate($free, $hanging)); + self::assertNotContains('insufficient_support', $codes); + self::assertNotContains('centre_of_gravity_unsupported', $codes); + // An unknown item type is reported once, never judged on the deck. + $unknown = $result; + $unknown['containers'][0]['placements'][0]['item_type'] = 'ghost'; + self::assertNotContains('insufficient_support', self::codes(Validator::validate($free, $unknown))); + // 40 of 100 mm on the deck passes 0.4, but the centroid hangs past its edge. + $strict = self::request([$carton], [self::palletJson()], ['minimum_support_ratio' => 0.4]); + $past = json_decode((string) json_encode(ArrayCodec::pack($strict)), true); + $past['containers'][0]['placements'][0]['position']['x']['ticks'] = self::ticks(1210); + $codes = self::codes(Validator::validate($strict, $past)); + self::assertContains('centre_of_gravity_unsupported', $codes); + self::assertNotContains('insufficient_support', $codes); + } + + public static function testTheTrialKeepsTheDeckRungWhenTheFrameRunsOutOfTime(): void + { + $frame = PalletOverhang::solvingFrame(self::pallet(new OverhangLimit(Length::mm(50), Length::mm(50)))); + $items = Item::create('carton', Dimensions::mm(400, 400, 300), '10 kg', 3, [Rotation::LWH])->instances(); + $call = static fn(string $method, PackingConfig $config): PackingConfig => $config; + $deadline = Deadline::ofMilliseconds(60000); + [$timed, $solves] = PalletTrial::palletTrial($call, self::scripted(true), $frame, 1, $items, new PackingConfig(), new SearchStats(), $deadline); + self::assertSame([1, false, true], [$solves, $timed->exhaustive, $timed->timeLimitReached]); + self::assertSame([self::ticks(50), self::ticks(50)], [$timed->state->placements[0]->position->x, $timed->state->placements[0]->position->y]); + // A stacked placement keeps the ratio it rests on; only the floor is measured again. + self::assertSame(0.25, $timed->state->placements[1]->supportRatio); + [$kept, $solves] = PalletTrial::palletTrial($call, self::scripted(false), $frame, 1, $items, new PackingConfig(), new SearchStats(), $deadline); + self::assertSame([2, false], [$solves, $kept->exhaustive]); + self::assertCount(2, $kept->state->placements); + } + + /** + * A solver that places one carton on the floor and one on top of it on the deck rung, leaving + * the third, and + * on the frame either runs out of time or places nothing. + */ + private static function scripted(bool $frameTimesOut): SingleContainerSolver + { + return new class($frameTimesOut) implements SingleContainerSolver { + public function __construct(private bool $frameTimesOut) {} + public function name(): string { return 'scripted'; } + public function packOne(Container $container, int $sequence, array $items, PackingConfig $config, SearchStats $stats, Deadline $deadline): SingleContainerSolution + { + $state = new ContainerState($container, $sequence); + if ($container->deck !== null) { + if ($this->frameTimesOut) { + throw new TimeLimitReached('scripted'); + } + return new SingleContainerSolution($state, $items); + } + $dimensions = $items[0]->dimensions(); + $floor = new Point(0, 0, 0); + $top = new Point(0, 0, $dimensions->height->ticks); + $state->add(new Placement($items[0], $floor, Rotation::LWH, $dimensions, $floor, $dimensions)); + $state->add(new Placement($items[1], $top, Rotation::LWH, $dimensions, $top, $dimensions, 0.25)); + return new SingleContainerSolution($state, [$items[2]], true); + } + }; + } + + /** @return array{0:bool,1:?string} */ + private static function verdict(Container $container, float $minimum, int $xMm): array + { + $item = Item::create('box', Dimensions::mm(100, 100, 100), '1 kg', 1, [Rotation::LWH]); + $context = new ConstraintContext($container, [], new ItemInstance($item, 1), new Point(self::ticks($xMm), self::ticks(100), 0), + Rotation::LWH, $item->dimensions, $item->dimensions); + $result = (new SupportConstraint($minimum))->evaluate($context); + return [$result->allowed, $result->allowed ? null : $result->code]; + } + + /** @return list */ + private static function billedMm(Item $item, Container $pallet): array + { + $packed = (new Packer())->pack([$item], [$pallet])->containers[0]; + return array_map(static fn(int $ticks): int => intdiv($ticks, Length::TICKS_PER_MM), self::sides($packed->billedDimensions())); + } + + private static function pallet(?OverhangLimit $limit, ?Dimensions $outer = null): Container + { + return new Container('pallet', Dimensions::mm(1200, 800, 1000), $outer, new Weight(0), Weight::parse('1000 kg'), 0, null, [], [], null, [], 0.0, [], null, null, null, [], [], null, null, $limit); + } + + private static function box(int $xMm, int $yMm, int $lengthMm): AxisAlignedBox + { + return new AxisAlignedBox(new Point(self::ticks($xMm), self::ticks($yMm), 0), Dimensions::mm($lengthMm, 100, 100)); + } + + private static function ticks(int $millimetres): int + { + return Length::mm($millimetres)->ticks; + } + + /** @return list */ + private static function sides(Dimensions $dimensions): array + { + return [$dimensions->length->ticks, $dimensions->width->ticks, $dimensions->height->ticks]; + } + + /** @param array $dimensions @return list */ + private static function millimetres(array $dimensions): array + { + return array_map(static fn(string $side): int => (int) $dimensions[$side]['value'], ['length', 'width', 'height']); + } + + /** @param list<\Packvium\Validation\ResultIssue> $issues @return list */ + private static function codes(array $issues): array + { + return array_values(array_unique(array_map(static fn($issue): string => $issue->code, $issues))); + } + + private static function caught(callable $build): InvalidRequestException + { + try { + $build(); + } catch (InvalidRequestException $error) { + return $error; + } + throw new \RuntimeException('was not refused'); + } + + /** @param array $container */ + private static function assertRefused(array $container, string $field, string $reason, string $detail): void + { + $error = self::caught(static fn() => ArrayCodec::pack(self::request([self::crate()], [$container]))); + self::assertSame([$field, $reason, $detail], [$error->field(), $error->reason(), $error->detail()]); + } + + /** @return array */ + private static function crate(): array + { + return ['id' => 'crate', 'quantity' => 1, 'weight' => '10 kg', 'allowed_rotations' => ['LWH'], + 'dimensions' => ['length' => '1250', 'width' => '850', 'height' => '400']]; + } + + /** @param mixed $limit @return array */ + private static function palletJson($limit = self::LIMIT): array + { + return ['id' => 'pallet', 'inner_dimensions' => ['length' => '1200', 'width' => '800', 'height' => '1000'], + 'max_payload' => '1000 kg', 'pallet_overhang_limit' => $limit]; + } + + /** + * @param list> $items @param list> $containers @param array $configuration + * @return array + */ + private static function request(array $items, array $containers, array $configuration = []): array + { + return ['items' => $items, 'containers' => $containers, + 'configuration' => $configuration + ['solver_profile' => 'balanced', 'time_limit_ms' => 60000, 'effort_budget' => ['max_search_nodes' => 100000]]]; + } +} diff --git a/tests/PlacementIdTest.php b/tests/PlacementIdTest.php new file mode 100644 index 0000000..95f96ae --- /dev/null +++ b/tests/PlacementIdTest.php @@ -0,0 +1,293 @@ +detail, 'no placement_id, expected ["box#1",')); + } + + public static function testARepeatedIdIsADuplicate(): void + { + $result = ArrayCodec::pack(self::request()); + $result['containers'][0]['placements'][1]['placement_id'] = $result['containers'][0]['placements'][0]['placement_id']; + self::assertSame(['placement_id_mismatch', 'duplicate_placement_id'], self::codes(validate(self::request(), $result))); + } + + public static function testALatticeSummaryHasNoPlacementsAndSoNoIds(): void + { + $request = self::request('box', 2); + $request['configuration'] = ['solver_profile' => 'fast', 'require_placement_coordinates' => false]; + $result = ArrayCodec::pack($request); + foreach ($result['containers'] as $container) { + self::assertSame([], $container['placements']); + } + self::assertSame([], validate($request, $result)); + } + + // ------------------------------------------------------------------ fixed placements + + public static function testAFixedPlacementMayQuoteTheIdItsResultPlacementCarries(): void + { + $result = ArrayCodec::pack(self::fixedRequest(['placement_id' => self::ident('box#1', 100 * self::MM, 0, 0)])); + $fixed = \array_values(\array_filter($result['containers'][0]['placements'], static fn(array $p): bool => ($p['fixed'] ?? false) === true)); + self::assertSame([self::ident('box#1', 100 * self::MM, 0, 0)], \array_column($fixed, 'placement_id')); + self::assertSame('feasible', ArrayCodec::pack(self::fixedRequest(['placement_id' => null]))['status']); + } + + public static function testAFixedIdNamingAnotherPlaceIsRefused(): void + { + $error = self::refusal(self::fixedRequest(['placement_id' => self::ident('box#1', 0, 0, 0)])); + self::assertSame(['invalid_fixed_placement', 'invalid_value', '/fixed_placements/0/placement_id'], [$error->errorCode(), $error->reason(), $error->field()]); + self::assertSame('invalid_fixed_placement: fixed_placements[0].placement_id must be ' . \json_encode(self::ident('box#1', 100 * self::MM, 0, 0)), $error->getMessage()); + } + + public static function testAFixedIdCountsTheInstanceAndDefaultsItToOne(): void + { + $error = self::refusal(self::fixedRequest(['container_instance' => 2, 'position' => [], 'placement_id' => self::ident('box#1', 0, 0, 0)])); + self::assertTrue(\str_ends_with($error->detail(), \json_encode(self::ident('box#2', 0, 0, 0)))); + } + + public static function testAFixedIdPastEveryExactIntegerIsLeftToAdmission(): void + { + $error = self::refusal(self::fixedRequest([ + 'position' => ['x' => ['value' => '9007199254740992', 'unit' => 'ticks']], + 'placement_id' => self::ident('box#1', 0, 0, 0), + ])); + self::assertSame('cannot_hold', $error->reason()); + self::assertTrue(\str_contains($error->detail(), 'outside_container')); + } + + public static function testAFixedIdThatIsNotAStringIsMalformed(): void + { + $error = self::refusal(self::fixedRequest(['placement_id' => 7])); + self::assertSame(['malformed', '/fixed_placements/0/placement_id', 'fixed_placements[0].placement_id is a string'], [$error->reason(), $error->field(), $error->detail()]); + } + + public static function testTheObjectApiHoldsAFixedIdToTheSameRule(): void + { + self::assertTrue(self::objectPack(self::ident('box#1', 100 * self::MM, 0, 0))); + try { + self::objectPack(self::ident('box#1', 100 * self::MM, 0, 0, 'cube', 'WLH')); + self::assertTrue(false, 'a wrong id was accepted'); + } catch (FixedPlacementException $error) { + self::assertSame(['invalid_value', '/fixed_placements/0/placement_id'], [$error->reason(), $error->field()]); + } + } + + // ------------------------------------------------------------------ plan, artifact, revisions + + public static function testThePlanCopiesEachIdAndAProjectionWithoutIdsKeepsItsBytes(): void + { + $result = ArrayCodec::pack(self::request()); + $references = self::references(Plan::build(self::request(), $result)); + $ids = []; + foreach ($result['containers'] as $container) { + foreach ($container['placements'] as $placement) { + $ids[] = $placement['placement_id']; + } + } + self::assertSame($ids, \array_column($references, 'placement_id')); + foreach (self::references(Plan::build(self::request(), self::withoutIds($result))) as $reference) { + self::assertFalse(\array_key_exists('placement_id', $reference)); + } + $keys = \array_keys(Plan::placementReference(0, $result['containers'][0]['placements'][0])); + self::assertSame(['container_index', 'item_type', 'orientation', 'position_ticks'], $keys); + } + + public static function testAPlanWithANonStringIdIsRefused(): void + { + $result = ArrayCodec::pack(self::request()); + $result['containers'][0]['placements'][0]['placement_id'] = 3; + self::assertThrows(ExecutionPlanException::class, static fn() => Plan::build(self::request(), $result)); + } + + public static function testTheArtifactV1CarriesNoId(): void + { + $result = ArrayCodec::pack(self::request()); + $artifact = OperationalArtifact::build(self::request(), $result); + self::assertFalse(\str_contains(OperationalArtifact::canonicalJson($artifact), 'placement_id')); + self::assertSame($artifact, OperationalArtifact::build(self::request(), self::withoutIds($result))); + $decoded = \json_decode((string)\json_encode($result)); + self::assertSame( + OperationalArtifact::canonicalJson($artifact), + OperationalArtifact::canonicalJson(OperationalArtifact::build(\json_decode((string)\json_encode(self::request())), $decoded)) + ); + } + + public static function testALockEventMayCarryTheIdAndIsOneBoxWithTheSameEntryWithoutIt(): void + { + $base = self::request(); + $root = PlanRevision::root($base); + $artifact = OperationalArtifact::build($base, ArrayCodec::pack($base)); + $entry = ['item_type' => 'cube', 'container_type' => 'box', 'position' => ['x' => '0', 'y' => '0', 'z' => '0'], 'orientation' => 'LWH']; + $quoted = $entry + ['placement_id' => self::ident('box#1', 0, 0, 0)]; + $revision = PlanRevision::derive($root, $artifact, [ + ['sequence' => 1, 'type' => 'placement_locked', 'placement' => $quoted], + ['sequence' => 2, 'type' => 'placement_verified', 'placement' => $entry], + ]); + self::assertSame([$quoted], \json_decode((string)\json_encode($revision->request->fixed_placements), true)); + try { + PlanRevision::derive($root, $artifact, [['sequence' => 1, 'type' => 'placement_locked', 'placement' => $entry + ['placement_id' => 1]]]); + self::assertTrue(false, 'a non-string id was accepted'); + } catch (PlanRevisionException $error) { + self::assertSame(['invalid_event', 'placement.placement_id is a string'], [$error->errorCode(), $error->getMessage()]); + } + } + + // ------------------------------------------------------------------ helpers + + /** @return array */ + private static function request(string $containerId = 'box', int $quantity = 4): array + { + $dims = static fn(int $l, int $w, int $h): array => ['length' => (string)$l, 'width' => (string)$w, 'height' => (string)$h]; + return [ + 'configuration' => ['solver_profile' => 'balanced', 'time_limit_ms' => 300000, 'alternatives' => 3], + 'items' => [['id' => 'cube', 'quantity' => $quantity, 'dimensions' => $dims(100, 100, 100)]], + 'containers' => [['id' => $containerId, 'quantity' => 3, 'inner_dimensions' => $dims(200, 100, 100)]], + ]; + } + + /** @param array $placement @return array */ + private static function fixedRequest(array $placement): array + { + $request = self::request(); + $request['fixed_placements'] = [\array_replace(['item_type' => 'cube', 'container_type' => 'box', 'position' => ['x' => '100'], 'orientation' => 'LWH'], $placement)]; + return $request; + } + + private static function ident(string $containerId, int $x, int $y, int $z, string $itemType = 'cube', string $orientation = 'LWH'): string + { + return (string)\json_encode([$containerId, $x, $y, $z, $itemType, $orientation], \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_LINE_TERMINATORS); + } + + /** @param array $container @param array $placement */ + private static function expectedId(array $container, array $placement): string + { + $ticks = \array_map(static fn(string $axis): int => $placement['position'][$axis]['ticks'], ['x', 'y', 'z']); + return self::ident($container['id'], ...$ticks, ...[$placement['item_type'], $placement['orientation']]); + } + + /** @param array $result @return list,1:array}> */ + private static function everyPlacement(array $result): array + { + $out = []; + foreach ([$result, ...$result['alternatives']] as $document) { + foreach ($document['containers'] as $container) { + foreach ($container['placements'] as $placement) { + $out[] = [$container, $placement]; + } + } + } + return $out; + } + + /** @param array $result @return array */ + private static function withoutIds(array $result): array + { + foreach ($result['containers'] as $c => $container) { + foreach ($container['placements'] as $p => $placement) { + unset($result['containers'][$c]['placements'][$p]['placement_id']); + } + } + return $result; + } + + /** @param array $plan @return list> */ + private static function references(array $plan): array + { + $out = []; + foreach ($plan['containers'] as $container) { + foreach ($container['steps'] as $step) { + $out[] = $step['placement']; + } + } + return $out; + } + + /** @param array $request */ + private static function refusal(array $request): FixedPlacementException + { + try { + ArrayCodec::pack($request); + } catch (FixedPlacementException $error) { + return $error; + } + throw new \RuntimeException('the request was accepted'); + } + + private static function objectPack(string $placementId): bool + { + $side = Length::parse('100'); + $item = new Item('cube', new Dimensions($side, $side, $side), quantity: 2); + $container = new Container('box', new Dimensions(Length::parse('200'), $side, $side)); + $fixed = new FixedPlacement('cube', 'box', new Point(100 * self::MM, 0, 0), Rotation::LWH, 1, $placementId); + return (new Packer(new PackingConfig()))->pack([$item], [$container], [$fixed])->complete(); + } + + /** @param list $issues @return list */ + private static function codes(array $issues): array + { + return \array_map(static fn(ResultIssue $issue): string => $issue->code, $issues); + } + + /** @param array $request @param array $result @return list */ + private static function issues(array $request, array $result): array + { + return \array_map('strval', validate($request, $result)); + } +} diff --git a/tests/PlanRevisionTest.php b/tests/PlanRevisionTest.php index cacebc5..3d39381 100644 --- a/tests/PlanRevisionTest.php +++ b/tests/PlanRevisionTest.php @@ -6,6 +6,7 @@ use Packvium\Artifacts\OperationalArtifact; use Packvium\Revisions\{PlanRevision, PlanRevisionException}; use Packvium\Serialization\ArrayCodec; +use Packvium\Unit\Length; use stdClass; /** @@ -409,6 +410,99 @@ public static function testAParentThatIsNotADigestIsQuotedAsJson(): void self::assertTrue(str_starts_with($details[1], 'parent forged, expected sha256:'), $details[1]); } + public static function testABoxCutForTheApprovedPlanBecomesAStockContainer(): void + { + $request = self::measured(); + $artifact = self::artifact($request); + $revision = PlanRevision::derive(PlanRevision::root($request), $artifact, [self::lockedIn('machine', 2)]); + $containers = $revision->request->containers; + self::assertSame(['machine', 'machine@1#2'], array_map(static fn(stdClass $c): string => $c->id, $containers)); + self::assertSame(2, $containers[0]->quantity); + $stock = $containers[1]; + self::assertFalse(property_exists($stock, 'made_to_measure')); + self::assertSame(1, $stock->quantity); + $cut = $artifact['geometry']['containers'][1]['inner_dimensions']; + self::assertSame(['value' => $cut['length'], 'unit' => 'ticks'], (array) $stock->inner_dimensions->length); + self::assertSame((string) ((int) $cut['height'] + 3 * Length::TICKS_PER_MM), $stock->outer_dimensions->height->value); + self::assertSame('ticks', $stock->tare_weight->unit); + self::assertSame(['machine@1#2', 1], [$revision->request->fixed_placements[0]->container_type, $revision->request->fixed_placements[0]->container_instance]); + // The derived request solves: the stock box is an ordinary container. + self::assertTrue(ArrayCodec::pack(json_decode((string) json_encode($revision->request), true))['complete']); + self::assertSame([], PlanRevision::verifyChain([PlanRevision::root($request), $revision], [null, $artifact])); + self::assertSame([['artifact_required', 'fixed items in a made-to-measure box are checked against the approved artifact']], + self::issues(PlanRevision::verifyChain([PlanRevision::root($request), $revision]))); + } + + public static function testAStockBoxTakesTheLastOfItsMachinesQuantity(): void + { + $request = self::measured(); + $request['containers'][0]['quantity'] = 1; + $artifact = self::artifact($request); + $derived = PlanRevision::stockCutBoxes(PlanRevision::applyEvents($request, [self::lockedIn('machine', 1)]), $artifact, 4); + self::assertSame(['machine@4#1'], array_map(static fn(stdClass $c): string => $c->id, $derived->containers)); + unset($request['containers'][0]['quantity']); + $open = PlanRevision::stockCutBoxes(PlanRevision::applyEvents($request, [self::lockedIn('machine', 1), self::lockedIn('machine', 1, 2, '300')]), $artifact, 4); + self::assertSame(['machine', 'machine@4#1'], array_map(static fn(stdClass $c): string => $c->id, $open->containers)); + self::assertFalse(property_exists($open->containers[0], 'quantity')); + // A stock container is the machine's alone: other containers keep their place. + $mixed = $request; + array_unshift($mixed['containers'], ['id' => 'tote', 'inner_dimensions' => ['length' => '400', 'width' => '400', 'height' => '400']]); + $kept = PlanRevision::stockCutBoxes(PlanRevision::applyEvents($mixed, [self::lockedIn('machine', 1)]), self::artifact($mixed), 2); + self::assertSame(['tote', 'machine', 'machine@2#1'], array_map(static fn(stdClass $c): string => $c->id, $kept->containers)); + self::assertSame('invalid_revision', self::code(static fn() => PlanRevision::stockCutBoxes([1, 2], $artifact, 1))); + // An event that fixes nothing leaves nothing for the audit to cut. + $missing = PlanRevision::derive(PlanRevision::root($request), self::artifact($request), [self::missing('cube', 1)]); + self::assertSame([], PlanRevision::verifyChain([PlanRevision::root($request), $missing])); + // Nothing fixed in a machine, or no lists to read: the request is returned as it was. + self::assertSame(PlanRevision::canonicalJson(PlanRevision::applyEvents($request, [])), + PlanRevision::canonicalJson(PlanRevision::stockCutBoxes($request, $artifact, 4))); + self::assertSame('{"containers":{}}', PlanRevision::canonicalJson(PlanRevision::stockCutBoxes(PlanRevision::parse('{"containers":{}}'), $artifact, 1))); + } + + public static function testACutBoxTheArtifactCannotSizeIsRefused(): void + { + $request = self::measured(); + $artifact = self::artifact($request); + $fixed = PlanRevision::applyEvents($request, [self::lockedIn('machine', 7)]); + self::assertSame(['invalid_artifact', 'the approved plan holds no machine instance 7'], + self::refusal(static fn() => PlanRevision::stockCutBoxes($fixed, $artifact, 1))); + $mangled = $artifact; + $mangled['geometry']['containers'][0]['inner_dimensions']['width'] = '1.5'; + self::assertSame(['invalid_artifact', "a cut box's width is not a tick count"], + self::refusal(static fn() => PlanRevision::stockCutBoxes(PlanRevision::applyEvents($request, [self::lockedIn('machine', 1)]), $mangled, 1))); + $taken = $request; + $taken['containers'][] = ['id' => 'machine@1#1', 'inner_dimensions' => ['length' => '1', 'width' => '1', 'height' => '1']]; + self::assertSame(['event_conflict', 'a container is already named "machine@1#1"'], + self::refusal(static fn() => PlanRevision::stockCutBoxes(PlanRevision::applyEvents($taken, [self::lockedIn('machine', 1)]), $artifact, 1))); + $revision = PlanRevision::derive(PlanRevision::root($request), $artifact, [self::lockedIn('machine', 1)]); + $issues = self::issues(PlanRevision::verifyChain([PlanRevision::root($request), $revision], [null, ['work_order' => ['containers' => []]]])); + self::assertSame(['request_mismatch', 'the events do not apply: the approved plan holds no machine instance 1'], $issues[0]); + } + + /** @return array */ + private static function measured(): array + { + return [ + 'units' => ['length' => 'mm'], + 'configuration' => ['solver_profile' => 'balanced', 'time_limit_ms' => 300000, 'effort_budget' => ['max_search_nodes' => 1000000]], + 'items' => [['id' => 'cube', 'quantity' => 3, 'weight' => '100', 'dimensions' => ['length' => '300', 'width' => '300', 'height' => '300']]], + 'containers' => [['id' => 'machine', 'quantity' => 3, 'cost_minor' => 40, 'tare_weight' => '50', + 'inner_dimensions' => ['length' => '310', 'width' => '310', 'height' => '610'], + 'made_to_measure' => ['minimum' => ['length' => '60', 'width' => '60', 'height' => '60'], + 'increment' => ['length' => '25', 'width' => '25', 'height' => '25'], 'cost_per_square_metre_minor' => 1000, + 'tare_per_square_metre' => '500', 'outer_allowance' => ['length' => '3', 'width' => '3', 'height' => '3']]]], + ]; + } + + /** @return array */ + private static function lockedIn(string $container, int $instance, int $sequence = 1, string $z = '0'): array + { + return ['sequence' => $sequence, 'type' => 'placement_locked', 'placement' => [ + 'item_type' => 'cube', 'container_type' => $container, 'container_instance' => $instance, + 'position' => ['x' => '0', 'y' => '0', 'z' => $z], 'orientation' => 'LWH', + ]]; + } + /** @return array{0:list,1:list>} */ private static function chain(): array { diff --git a/tests/PrettyJsonStreamTest.php b/tests/PrettyJsonStreamTest.php index 1a06a19..d5ff154 100644 --- a/tests/PrettyJsonStreamTest.php +++ b/tests/PrettyJsonStreamTest.php @@ -50,6 +50,40 @@ public static function testAResultWithAlternativesStreamsAsItEncodes(): void } } + /** + * `bin/packvium`'s path: placements generated as they are written give the bytes the whole + * array encodes to. Two solves, so only their wall-clock fields may differ. + */ + public static function testAStreamedResultWritesWhatItsArrayEncodes(): void + { + $masked = static fn(string $json): string => (string) \preg_replace('/("[a-z_]*duration_ms": )[0-9.]+/', '$1', $json); + foreach (self::RESULT_SHAPE_REQUESTS as $name => $json) { + $request = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR); + self::assertSame( + $masked((string) \json_encode(ArrayCodec::pack($request), self::FLAGS)), + $masked(self::streamed(ArrayCodec::packStreamed($request))), + $name, + ); + } + } + + public static function testASequenceIsWrittenAsTheListOfItsValues(): void + { + $sequence = static function (array $values): \Generator { + yield from $values; + }; + $leaf = ['k' => 'v', 'n' => [1, 2]]; + $values = [$leaf, [], 'text', \array_fill(0, 70, 1)]; + self::assertSame(\json_encode($values, self::FLAGS), self::streamed($sequence($values))); + self::assertSame(\json_encode([], self::FLAGS), self::streamed($sequence([]))); + // Inside an array small enough to be encoded whole, which would write the generator as `{}`. + self::assertSame( + \json_encode(['a' => [$leaf], 'b' => []], self::FLAGS), + self::streamed(['a' => $sequence([$leaf]), 'b' => $sequence([])]), + ); + self::assertSame(\json_encode([[[[$leaf]]]], self::FLAGS), self::streamed([[$sequence([$sequence([$leaf])])]])); + } + public static function testEveryShapeJsonEncodeDistinguishesIsKept(): void { $leaf = ['path' => 'a/b', 'text' => "line\nbreak \u{2028} \u{e9}", 'float' => 0.1, 'whole' => 1.0, 'none' => null, 'yes' => true]; diff --git a/tests/RequestErrorTest.php b/tests/RequestErrorTest.php index 022ae87..48825a0 100644 --- a/tests/RequestErrorTest.php +++ b/tests/RequestErrorTest.php @@ -192,7 +192,9 @@ public static function testWhatTheRulesDoNotNameIsStillARequestError(): void public static function testARefusalWithItsOwnCodeIsNotRelabelled(): void { $request = self::request(); - $request['containers'][0]['pallet_overhang_limit'] = '10'; + // A pallet's axles are positioned in the declared frame its overhang widens. + $request['containers'][0]['pallet_overhang_limit'] = ['length' => '10', 'width' => '10']; + $request['containers'][0]['axles'] = [['position' => '0'], ['position' => '10']]; self::assertThrows(UnsupportedFeatureException::class, static fn() => ArrayCodec::pack($request)); $request = self::request(); diff --git a/tests/RequestObjectsCorpusTest.php b/tests/RequestObjectsCorpusTest.php index 293059e..61336a6 100644 --- a/tests/RequestObjectsCorpusTest.php +++ b/tests/RequestObjectsCorpusTest.php @@ -71,6 +71,10 @@ final class RequestObjectsCorpusTest extends TestCase 'item-side-missing' => 'Dimensions requires all three sides', 'container-made-to-measure-minimum-missing' => 'MadeToMeasure requires a minimum', 'container-made-to-measure-increment-missing' => 'MadeToMeasure requires an increment', + 'container-pallet-overhang-limit-not-object' => 'a limit that is not an object is not an OverhangLimit', + 'container-pallet-overhang-limit-length-missing' => 'OverhangLimit requires a length', + 'container-pallet-overhang-limit-width-missing' => 'OverhangLimit requires a width', + 'container-pallet-overhang-limit-key-unknown' => self::UNKNOWN_KEY, 'rate-brackets-not-list' => 'RateTable holds its brackets as a list', 'solver-profile-unknown' => 'SolverProfile has no such case', 'configuration-key-unknown-before-bad-value' => 'SolverProfile has no such case, and ' . self::UNKNOWN_KEY, @@ -80,6 +84,8 @@ final class RequestObjectsCorpusTest extends TestCase 'configuration-keys-unknown-first-in-code-point-order' => self::UNKNOWN_KEY, 'effort-key-unknown' => self::UNKNOWN_KEY, 'container-deformable-boundary-key-unknown' => self::UNKNOWN_KEY, + 'container-gusseted-bag-key-unknown' => self::UNKNOWN_KEY, + 'an-unknown-boundary-key-before-a-missing-gusset' => self::UNKNOWN_KEY, 'container-made-to-measure-key-unknown' => self::UNKNOWN_KEY, 'unknown-configuration-key-before-its-values' => self::UNKNOWN_KEY, 'unsupported-before-units' => 'an unsupported field has no object form', @@ -91,9 +97,11 @@ final class RequestObjectsCorpusTest extends TestCase 'effort-limit-text' => self::TYPED, 'item-accepts-stacking-groups-not-list' => self::TYPED, 'item-side-boolean' => self::TYPED, + 'container-gusseted-bag-side-gusset-depth-boolean' => self::TYPED, 'item-side-fraction' => self::TYPED, 'item-stacking-group-number' => self::TYPED, 'fixed-position-unparsable' => 'a Point holds integer ticks, not text', + 'fixed-placement-id-not-a-string' => self::TYPED, // A length past a native int has no `Length` to hold it. 'item-side-whole-beyond-exact' => self::TYPED, 'item-side-negative-beyond-exact' => self::TYPED, @@ -113,14 +121,28 @@ final class RequestObjectsCorpusTest extends TestCase 'item-allowed-rotation-lowercase' => 'Rotation has no such case', 'item-shape-type-unknown' => 'ShapeType has no such case', 'fixed-orientation-unknown' => 'Rotation has no such case', + 'item-allowed-rotation-reflection-on-a-hull' => 'Rotation has no such case', + 'item-allowed-rotation-legacy-spelled-signed-on-a-hull' => 'Rotation has no such case', + 'item-allowed-rotation-signed-beside-an-unknown-shape' => 'ShapeType has no such case', + 'fixed-orientation-reflection-on-a-hull' => 'Rotation has no such case', 'configuration-solvers-not-list' => self::TYPED, 'output-not-object' => self::OUTPUT, 'output-length-unit-unknown' => self::OUTPUT, 'output-weight-unit-unknown' => self::OUTPUT, 'output-before-configuration' => self::OUTPUT, + 'output-before-currency' => self::OUTPUT, + // A currency is held as `?string`; a number or a list has no object form. + 'currency-number' => self::TYPED, + 'currency-list' => self::TYPED, + 'rate-table-currency-number' => self::TYPED, // The request's length unit is an argument of each measure, not an object of its own. 'units-not-object' => self::UNITS, 'units-list' => self::UNITS, + 'units-weight' => self::UNITS, + 'units-unknown-key' => self::UNITS, + 'units-unknown-keys-first-in-code-point-order' => self::UNITS, + 'units-unknown-key-null' => self::UNITS, + 'unknown-units-key-before-its-length' => self::UNITS, 'units-length-object' => self::TYPED, 'units-length-list' => self::TYPED, // A bool property cannot hold anything else; the codec casts what it reads. @@ -157,6 +179,8 @@ final class RequestObjectsCorpusTest extends TestCase 'an-item-id-before-its-quantity' => self::CONSTRUCTOR_FIRST, 'item-ids-before-containers' => self::CONSTRUCTOR_FIRST, 'container-ids-before-fixed-placements' => self::CONSTRUCTOR_FIRST, + 'currency-before-configuration' => self::CONSTRUCTOR_FIRST, + 'item-boolean-before-empty-rotations' => self::CONSTRUCTOR_FIRST, 'item.nesting_height=2^53 ticks' => self::CEILING_SECOND, 'container.made_to_measure.minimum.length=2^53 ticks' => self::CEILING_SECOND, 'container.made_to_measure.minimum.width=2^53 ticks' => self::CEILING_SECOND, @@ -167,6 +191,7 @@ final class RequestObjectsCorpusTest extends TestCase 'container.obstacles.origin.y=2^53 ticks' => self::CEILING_SECOND, 'container.obstacles.origin.z=2^53 ticks' => self::CEILING_SECOND, 'container.obstacles.dimensions.length=2^53 ticks' => self::CEILING_SECOND, + 'container-gusseted-bag-side-gusset-depth-past-the-ceiling' => self::CEILING_SECOND, 'configuration-boolean-before-effort-budget' => 'two faults: the EffortBudget is built, and refuses its own ' . 'value, before the PackingConfig that holds it', 'item.weight=2^53 as a number' => self::JSON_NUMBER, @@ -178,7 +203,7 @@ final class RequestObjectsCorpusTest extends TestCase ]; /** Pinned, so the skip set cannot grow without this line changing too. */ - private const SKIPPED = 124; + private const SKIPPED = 148; public static function testTheSkipSetIsPinnedAndNamesOnlyCorpusCases(): void { @@ -273,7 +298,7 @@ private static function outcomes($request): array \restore_error_handler(); } try { - (new Packer($config))->pack($items, $containers, $fixed); + (new Packer($config))->pack($items, $containers, $fixed, $request['currency'] ?? null); } catch (Throwable $error) { return [$json, $error, 'pack']; } @@ -297,7 +322,7 @@ private static function objects($request): array foreach ($request['fixed_placements'] ?? [] as $raw) { $position = self::codec('point', $raw['position'] ?? [], $unit); $fixed[] = new FixedPlacement($raw['item_type'], $raw['container_type'], $position, - Rotation::from($raw['orientation']), $raw['container_instance'] ?? 1); + Rotation::from($raw['orientation']), $raw['container_instance'] ?? 1, $raw['placement_id'] ?? null); } return [$config, $items, $containers, $fixed]; } diff --git a/tests/ResultValidationBoundTest.php b/tests/ResultValidationBoundTest.php index 9326e2f..501c621 100644 --- a/tests/ResultValidationBoundTest.php +++ b/tests/ResultValidationBoundTest.php @@ -53,6 +53,7 @@ public static function testTheBoundMatchesEveryCaseAndEdgeOfTheSharedScene(): vo self::skip('the shared cross-language scene fixture is not part of this package'); } $scene = \json_decode((string)\file_get_contents($path), true); + self::assertSame('packvium-objective-bounds/v2', $scene['format']); $compared = 0; foreach (\array_merge($scene['cases'], $scene['edges']) as $case) { $containers = \array_map(static function (array $container): array { @@ -69,7 +70,15 @@ public static function testTheBoundMatchesEveryCaseAndEdgeOfTheSharedScene(): vo }, $case['containers']); $shrinks = \in_array(true, \array_column($case['instances'], 'shrinks'), true); $computed = Bound::lowerBound(self::runs($case['instances'], 'volume'), self::runs($case['instances'], 'weight'), $shrinks, $containers); - self::assertSame($case['bounds'], $computed, 'bound diverges from the oracle on ' . ($case['name'] ?? $case['fixture'])); + $name = $case['name'] ?? $case['fixture']; + self::assertSame($case['bounds'], $computed, "bound diverges from the oracle on {$name}"); + $volumes = self::runs($case['instances'], 'volume'); + $weights = self::runs($case['instances'], 'weight'); + $values = self::runs($case['instances'], 'value'); + foreach ($case['objectives'] as $objective => $expected) { + [$stated] = Bound::objectiveBound($volumes, $weights, $values, $shrinks, $containers, $objective); + self::assertSame($expected, $stated, "{$objective} diverges from the oracle on {$name}"); + } ++$compared; } self::assertGreaterThan(400, $compared); @@ -87,6 +96,39 @@ public static function testANegativeOrUnlimitedCapacityAndZeroVolumesAreReadAsTh self::assertSame([1, 0, 0, 0, 0], Bound::lowerBound([[1, 1]], [[0, 1]], false, [])); } + /**: an objective's own key past the portable ceiling withholds that objective alone. */ + public static function testAnObjectiveKeyPastThePortableCeilingWithholdsOnlyThatObjective(): void + { + $container = [ + 'inner_volume' => 1000, 'base_area' => 100, 'height' => 10, 'usable' => 1000, 'cost_minor' => 0, + 'payload' => null, 'max_items' => null, 'quantity' => 1, + ]; + $values = Bound::runs([[9007199254740991, 2], [1, 1]]); + self::assertSame([null, 'the maximum_value key is past the portable ceiling'], + Bound::objectiveBound([[600, 3]], [[0, 3]], $values, false, [$container], 'maximum_value')); + self::assertSame([[444445, 2, 1, 0, 400000], ''], + Bound::objectiveBound([[600, 3]], [[0, 3]], $values, false, [$container], 'maximum_volume')); + self::assertSame([[0, 0, 1, 0, 0], ''], + Bound::objectiveBound([[600, 3]], [[0, 3]], $values, true, [$container], 'open_dimension_height')); + // An unlimited inventory and a request of nothing both force no volume out. + $container['quantity'] = null; + self::assertSame(0, Bound::objectiveBound([[600, 3]], [[0, 3]], $values, false, [$container], 'maximum_volume')[0][0]); + self::assertSame(0, Bound::objectiveBound([], [], [], false, [$container], 'maximum_volume')[0][0]); + } + + /**: a request's `value` reaches the stated `maximum_value` bound end to end. */ + public static function testAMaximumValueBoundIsReadFromTheRequestsValues(): void + { + $request = self::REQUEST; + $request['items'][0]['quantity'] = 3; + $request['items'][0]['value'] = 5; + $request['containers'][0]['quantity'] = 1; + $request['configuration'] = ['objective' => 'maximum_value']; + $result = ArrayCodec::pack($request); + $result['optimality'] = ['code' => 'not_proven', 'lower_bound' => [1, 6]]; + self::assertContains('reported [1, 6], recomputed [1, 5]', \array_map(static function (ResultIssue $issue): string { return $issue->detail; }, validate($request, $result))); + } + /** @param array $optimality @return list */ private static function codes(array $optimality, ?callable $change = null): array { diff --git a/tests/ResultValidationEdgesTest.php b/tests/ResultValidationEdgesTest.php new file mode 100644 index 0000000..caf391b --- /dev/null +++ b/tests/ResultValidationEdgesTest.php @@ -0,0 +1,274 @@ + [['id' => 'cube', 'quantity' => 2, 'weight' => '1500', 'dimensions' => ['length' => '10', 'width' => '10', 'height' => '10']]], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '20', 'width' => '10', 'height' => '10']]], + ]; + + private const OVERSIZED = [ + 'items' => [['id' => 'big', 'dimensions' => ['length' => '50', 'width' => '10', 'height' => '10']]], + 'containers' => [['id' => 'box', 'inner_dimensions' => ['length' => '20', 'width' => '10', 'height' => '10']]], + ]; + + private const AS_OF = 1704067200000; + + // ------------------------------------------------------------------ accounting + + public static function testAPolicyRuleWhoseAppliesToIsNotAnObjectIsRefused(): void + { + $request = self::REQUEST; + $request['policy'] = ['as_of' => 1, 'rules' => [[ + 'id' => 'r', 'version' => 1, 'applies_to' => ['x'], + 'require_container_tag' => ['item_tag' => 'a', 'container_tag' => 'b'], + ]]]; + self::assertRefused(MalformedResult::SHAPE, 'applies_to must be an object', $request, ArrayCodec::pack(self::REQUEST)); + } + + public static function testAPolicyRejectionIsRefutedOnceAContainerCarriesTheRequiredTag(): void + { + $request = [ + 'units' => ['length' => 'mm'], + 'policy' => ['as_of' => self::AS_OF, 'rules' => [[ + 'id' => 'cold-chain', 'version' => 7, 'effective_at' => self::AS_OF, 'priority' => 10, + 'require_container_tag' => ['item_tag' => 'food', 'container_tag' => 'reefer'], + ]]], + 'items' => [['id' => 'carton', 'quantity' => 1, 'tags' => ['food'], 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]], + 'containers' => [['id' => 'pallet', 'quantity' => 4, 'inner_dimensions' => ['length' => '300', 'width' => '300', 'height' => '300']]], + ]; + $result = ArrayCodec::pack($request); + self::assertSame('policy_rule', $result['unpacked_items'][0]['reason']); + self::assertSame([], validate($request, $result)); + + $request['containers'][0]['tags'] = ['reefer']; + self::assertIssues( + ['invalid_proven_reason: carton#1: no participating policy rule rules it out of every container'], + $request, $result, + ); + } + + public static function testAnInfeasibleStatusWithEveryRejectionProvenIsValid(): void + { + $result = ArrayCodec::pack(self::OVERSIZED); + self::assertSame('proven', $result['unpacked_items'][0]['proof']['level']); + $result['status'] = 'infeasible'; + $result['feasibility'] = ['code' => 'infeasible']; + $result['optimality'] = ['code' => 'proven_infeasible']; + self::assertSame([], validate(self::OVERSIZED, $result)); + } + + // ------------------------------------------------------------------ container specs + + public static function testASingleAxleIsRefusedRatherThanReadAsAFrontAndRearPair(): void + { + $request = self::REQUEST; + $request['containers'][0]['axles'] = [['position' => '5', 'max_load' => '100000']]; + self::assertRefused(MalformedResult::SHAPE, 'box#1: axles must name exactly a front and a rear axle', $request, ArrayCodec::pack(self::REQUEST)); + } + + public static function testTagLimitsThatAreNotAnObjectAreRefused(): void + { + $request = self::REQUEST; + $request['containers'][0]['tag_limits'] = ['x']; + self::assertRefused(MalformedResult::SHAPE, 'tag_limits must be an object', $request, ArrayCodec::pack(self::REQUEST)); + } + + public static function testAPressureLimitWithoutACompressionRatioIsRefused(): void + { + $request = self::REQUEST; + $request['items'][0]['max_compression_pressure_kpa'] = 10; + self::assertRefused(MalformedResult::SHAPE, 'cube: max_compression_pressure_kpa without compression_ratio', $request, ArrayCodec::pack(self::REQUEST)); + } + + public static function testAContainerWithNoVolumeAddsNothingToTheUnusedVolumeTerm(): void + { + $request = self::REQUEST; + $request['containers'][] = ['id' => 'flat', 'inner_dimensions' => ['length' => '20', 'width' => '10', 'height' => '0']]; + $result = ArrayCodec::pack(self::REQUEST); + $result['containers'][0]['container_type'] = 'flat'; + self::assertIssues([ + 'outside_container: cube#1 in box#1', + 'outside_container: cube#2 in box#1', + 'void_fill_reserve_exceeded: box#1: used 8192000000000000 > usable 0', + 'score_mismatch: reported [0, 1, 0, 0, 1000000], recomputed [0, 1, 0, 0, 0]', + ], $request, $result); + } + + // ------------------------------------------------------------------ objective + + public static function testAnObjectiveThatIsNotAStringIsUnknown(): void + { + $request = self::REQUEST; + $request['configuration'] = ['objective' => 5]; + self::assertRefused(MalformedResult::CONTRACT, 'unknown requested objective 5', $request, ArrayCodec::pack(self::REQUEST)); + } + + public static function testARateTableWithFewerPricesThanBracketsPricesOnlyThePairedBrackets(): void + { + [$request, $result] = self::landedCost(['weight_brackets_g' => [1, 2], 'prices_minor' => [100]]); + self::assertRefused( + MalformedResult::CONTRACT, + "container 'box' bills at 3000 g, above its rate table's last bracket (2 g); the shipment has no published price", + $request, $result, + ); + } + + public static function testAnEmptyRateTableIsRefused(): void + { + [$request, $result] = self::landedCost(['weight_brackets_g' => [], 'prices_minor' => []]); + self::assertRefused(MalformedResult::SHAPE, 'an empty rate table', $request, $result); + } + + // ------------------------------------------------------------------ stacking + + public static function testAFloatingItemUnderAVanishingSupportRatioHasNoSupportHull(): void + { + // 1e-7 rounds to 0 ppm, so the required area is nothing and the centroid rule decides. + $request = self::REQUEST; + $request['configuration'] = ['minimum_support_ratio' => 0.0000001]; + $result = ArrayCodec::pack(self::REQUEST); + $result['containers'][0]['placements'][1]['position']['z'] = ['ticks' => 5 * self::MM]; + $result['containers'][0]['placements'][1] = Support::restatedId($result['containers'][0]['placements'][1], 'box#1'); + self::assertIssues([ + 'outside_container: cube#2 in box#1', + 'centre_of_gravity_unsupported: cube#2: centroid outside its support hull', + 'score_mismatch: reported [0, 1, 0, 0, 1000000], recomputed [0, 1, 0, 0, 1500000]', + ], $request, $result); + } + + public static function testANestedItemKeepsItsOtherSupportersInIndexOrderAfterItsPredecessor(): void + { + $lower = self::entry('cup#1', 'cup', 0, 0, 100); + $upper = self::entry('cup#2', 'cup', 0, 20, 100); + $block = self::entry('block#1', 'block', 0, 0, 20); + [$supporters, $directAbove] = Stacking::supportGraph([$lower, $upper, $block]); + $base = 50 * self::MM * 50 * self::MM; + self::assertSame([[], [[0, $base], [2, $base]], []], $supporters); + self::assertSame([[1 => true], [], [1 => true]], $directAbove); + } + + public static function testOnlyTheSameTypeOnTheSameFootprintNests(): void + { + $lower = self::entry('cup#1', 'cup', 0, 0, 100); + self::assertTrue(Stacking::validNesting($lower, self::entry('cup#2', 'cup', 0, 20, 100))); + self::assertFalse(Stacking::validNesting($lower, self::entry('mug#1', 'mug', 0, 20, 100)), 'another type with the same nesting height'); + self::assertFalse(Stacking::validNesting($lower, self::entry('cup#3', 'cup', 10, 20, 100)), 'the same type, shifted along x'); + } + + public static function testAHullWhoseEnvelopeDisagreesWithItsDimensionsOccupiesTheWholeEnvelope(): void + { + $wedge = self::specs()->get('wedge'); + $fitting = new Cuboid(0, 0, 0, 10 * self::MM, 10 * self::MM, 10 * self::MM); + self::assertSame( + [[0, 0, 0], [10 * self::MM, 0, 0], [0, 10 * self::MM, 0], [0, 0, 10 * self::MM]], + Stacking::placedHull($fitting, ['orientation' => 'LWH'], $wedge), + ); + $wide = new Cuboid(0, 0, 0, 12 * self::MM, 10 * self::MM, 10 * self::MM); + self::assertSame($wide->vertices(), Stacking::placedHull($wide, ['orientation' => 'LWH'], $wedge)); + } + + public static function testAnItemWithoutAPressureLimitKeepsItsHeightUnderAnyLoad(): void + { + self::assertSame(100, Stacking::compressedHeight(100, 1, self::specs()->get('block'), 5_000_000)); + } + + // ------------------------------------------------------------------ primitives + + public static function testListsOfDifferentLengthsAreNeverEqual(): void + { + self::assertFalse(Json::equals([1, 2], [1])); + self::assertFalse(Json::equals(['a' => 1], ['a' => 1, 'b' => 2])); + self::assertTrue(Json::equals([1, 2], [1, 2])); + } + + /** Python's `float(Fraction)` where the float estimate of the quotient's magnitude is off by one bit. */ + public static function testTheNearestDoubleSurvivesAMisjudgedMagnitude(): void + { + // log2 rounds 2^60 - 1 up to 60, and rounding the 53-bit quotient carries into 2^53. + self::assertSame(2.0 ** 60, Ratio::integer((1 << 60) - 1)->toFloat()); + // log2(7 * 2^62) - log2(7) comes out just below 62. + self::assertSame(2.0 ** 62, Ratio::of(Exact::add(Exact::mul(7, Exact::powerOfTwo(62)), 1), 7)->toFloat()); + } + + public static function testTextThatIsNotUtf8IsEscapedByteByByte(): void + { + self::assertSame("'a\\x80b'", PyFormat::stringRepr("a\x80b")); + } + + // ------------------------------------------------------------------ helpers + + /** @param array $rateTable @return array{0:array,1:array} */ + private static function landedCost(array $rateTable): array + { + $request = self::REQUEST; + $request['configuration'] = ['objective' => 'lowest_landed_cost', 'dimensional_weight_divisor' => 5000]; + $request['containers'][0]['rate_table'] = $rateTable; + $result = ArrayCodec::pack(self::REQUEST); + $result['objective'] = 'lowest_landed_cost'; + return [$request, $result]; + } + + private static function specs(): Ordered + { + $corner = static fn(string $x, string $y, string $z): array => ['x' => $x, 'y' => $y, 'z' => $z]; + return Spec::items(['items' => [ + ['id' => 'cup', 'nesting_height' => '80', 'dimensions' => ['length' => '50', 'width' => '50', 'height' => '100']], + ['id' => 'mug', 'nesting_height' => '80', 'dimensions' => ['length' => '50', 'width' => '50', 'height' => '100']], + ['id' => 'block', 'dimensions' => ['length' => '50', 'width' => '50', 'height' => '20']], + ['id' => 'wedge', 'shape_type' => 'convex_hull', 'dimensions' => ['length' => '10', 'width' => '10', 'height' => '10'], + 'hull_vertices' => [$corner('0', '0', '0'), $corner('10', '0', '0'), $corner('0', '10', '0'), $corner('0', '0', '10')]], + ]], 'mm'); + } + + /** A 50 x 50 mm footprint at `x`, `z` millimetres, `height` millimetres tall. */ + private static function entry(string $id, string $type, int $x, int $z, int $height): Entry + { + $envelope = new Cuboid($x * self::MM, 0, $z * self::MM, 50 * self::MM, 50 * self::MM, $height * self::MM); + return new Entry($id, $envelope, ['item_type' => $type], self::specs()->get($type)); + } + + /** @param list $expected @param array $request @param array $result */ + private static function assertIssues(array $expected, array $request, array $result): void + { + self::assertSame($expected, array_map('strval', validate($request, $result))); + } + + /** @param array $request @param array $result */ + private static function assertRefused(string $kind, string $message, array $request, array $result): void + { + try { + validate($request, $result); + } catch (MalformedResult $refusal) { + self::assertSame($kind, $refusal->kind); + self::assertSame($message, $refusal->getMessage()); + return; + } + self::assertTrue(false, "expected a {$kind} refusal: {$message}"); + } +} diff --git a/tests/ResultValidationTest.php b/tests/ResultValidationTest.php index 754d9b1..eb3fdbc 100644 --- a/tests/ResultValidationTest.php +++ b/tests/ResultValidationTest.php @@ -59,8 +59,11 @@ public static function testTwoItemsInOnePlaceAreACollisionNamedAsTheReferenceNam { $result = ArrayCodec::pack(self::REQUEST); $result['containers'][0]['placements'][1]['position'] = $result['containers'][0]['placements'][0]['position']; + $result['containers'][0]['placements'][1] = Support::restatedId($result['containers'][0]['placements'][1], 'box#1'); $issues = validate(self::REQUEST, $result); - self::assertCount(1, $issues); + // Two items in one place also share one id; the collision is still named first. + self::assertCount(2, $issues); + self::assertSame('duplicate_placement_id', $issues[1]->code); self::assertTrue($issues[0] instanceof ResultIssue); self::assertSame('collision: cube#1 with cube#2 in box#1', (string)$issues[0]); } @@ -327,10 +330,14 @@ public static function testGeometryAndUnitsRefuseWhatTheyCannotRead(): void // WLH is an odd permutation, so the hull is mirrored back into a proper rotation // (`_rotate_hull` gives ((1, 0, 0), (1, 2, 0), (0, 0, 0)) for the same three vertices). self::assertSame([[1, 0, 0], [1, 2, 0], [0, 0, 0]], - Geometry::rotateHull([[0, 0, 0], [2, 0, 0], [0, 1, 0]], Geometry::axes('WLH'))); + Geometry::rotateHull([[0, 0, 0], [2, 0, 0], [0, 1, 0]], 'WLH')); + // -L-W+H is the half-turn about the vertical: x and y both change sign. + self::assertSame([[2, 1, 0], [0, 1, 0], [2, 0, 0]], + Geometry::rotateHull([[0, 0, 0], [2, 0, 0], [0, 1, 0]], '-L-W+H')); $refusals = [ static function (): void { Geometry::axes('XYZ'); }, - static function (): void { Geometry::rotateHull([], [0, 1, 2]); }, + static function (): void { Geometry::rotateHull([], 'LWH'); }, + static function (): void { Geometry::rotateHull([[0, 0, 0]], '+L+W+H'); }, static function (): void { Units::perUnit(Units::LENGTH, 'furlong'); }, static function (): void { Units::parseFraction('1e999'); }, ]; @@ -339,6 +346,30 @@ static function (): void { Units::parseFraction('1e999'); }, } } + /** + * `units` is closed; the first unknown key in code-point order is named before + * `length` is read. U+FFFD sorts before U+1F600 by code point, after it in UTF-16, and a + * numeric key that PHP turns into an int is named as the string it was. + */ + public static function testAUnitsKeyOtherThanLengthIsAContractBreak(): void + { + $cases = [ + 'units.weight is not a known field' => ['length' => 'furlong', 'weight' => 'kg'], + "units.\u{FFFD} is not a known field" => ["\u{1F600}" => 1, "\u{FFFD}" => 1], + 'units.1 is not a known field' => ['1' => 'kg', 'length' => 'mm'], + ]; + foreach ($cases as $expected => $units) { + $message = null; + try { + Units::lengthUnit(['units' => $units]); + } catch (MalformedResult $error) { + $message = $error->getMessage(); + } + self::assertSame($expected, $message); + } + self::assertSame('cm', Units::lengthUnit(['units' => ['length' => 'cm']])); + } + /** The reference prints a missing id as `?`; the port refuses an issue it would have to name so. */ public static function testAnIssueOnAContainerWithoutAnIdIsRefused(): void { diff --git a/tests/SerializationTest.php b/tests/SerializationTest.php index a9ff47f..2bd84f5 100644 --- a/tests/SerializationTest.php +++ b/tests/SerializationTest.php @@ -233,7 +233,8 @@ public static function testAPlacementReportsEverythingACallerNeedsToReproduceIt( $keys = array_keys($placement); sort($keys); - self::assertSame(['dimensions', 'item_id', 'item_type', 'orientation', 'position', 'support_ratio', 'top_load'], $keys); + self::assertSame(['dimensions', 'item_id', 'item_type', 'orientation', 'placement_id', 'position', 'support_ratio', 'top_load'], $keys); + self::assertSame('["c#1",0,0,0,"a","' . $placement['orientation'] . '"]', $placement['placement_id']); self::assertSame('a#1', $placement['item_id']); self::assertSame('a', $placement['item_type']); self::assertContains($placement['orientation'], ['LWH', 'LHW', 'WLH', 'WHL', 'HLW', 'HWL']); diff --git a/tests/SignedRotationsTest.php b/tests/SignedRotationsTest.php new file mode 100644 index 0000000..4cad19e --- /dev/null +++ b/tests/SignedRotationsTest.php @@ -0,0 +1,255 @@ +value, Orientations::sourceAxes($rotation), Orientations::signs($rotation)]; + } + self::assertSame(self::TABLE, $rows); + self::assertSame(\array_column(self::TABLE, 0), \array_keys(Orientations::TABLE)); + $distinct = []; + foreach (self::TABLE as [, $axes, $signs]) { + self::assertSame(1, self::determinant($axes, $signs)); + $distinct[\json_encode([$axes, $signs])] = true; + } + self::assertCount(24, $distinct); + } + + public static function testTheLegacyVocabularyAndItsDefaultsAreUnchanged(): void + { + self::assertSame(Orientations::LEGACY_CODES, \array_map(static fn(Rotation $r): string => $r->value, Rotation::all())); + self::assertSame([Rotation::LWH, Rotation::WLH], Rotation::upright()); + self::assertSame(Rotation::cases(), Rotation::every()); + $upright = \array_values(\array_filter(Rotation::every(), static fn(Rotation $r): bool => Orientations::isUpright($r))); + self::assertSame(['LWH', 'WLH', '-L-W+H', '+W-L+H'], \array_map(static fn(Rotation $r): string => $r->value, $upright)); + self::assertSame([], \array_filter(Rotation::all(), static fn(Rotation $r): bool => Orientations::isSigned($r))); + self::assertCount(18, \array_filter(\array_slice(Rotation::every(), 6), static fn(Rotation $r): bool => Orientations::isSigned($r))); + } + + public static function testABoxIgnoresTheSigns(): void + { + $dimensions = Support::dims(1, 2, 3); + $legacyByAxes = []; + foreach (Rotation::all() as $legacy) { + $legacyByAxes[\implode(',', Orientations::sourceAxes($legacy))] = $legacy; + } + foreach (Rotation::every() as $rotation) { + $legacy = $legacyByAxes[\implode(',', Orientations::sourceAxes($rotation))]; + self::assertEquals($dimensions->rotated($legacy), $dimensions->rotated($rotation), $rotation->value); + } + } + + public static function testAHullTurnsByItsSignedMatrixThenBackToTheOrigin(): void + { + $volume = HullShape::of(self::WEDGE)->volume; + foreach (self::TABLE as [$code, $axes, $signs]) { + $turned = \array_map(static fn(array $v): array => [$signs[0] * $v[$axes[0]], $signs[1] * $v[$axes[1]], $signs[2] * $v[$axes[2]]], self::WEDGE); + $low = [\min(\array_column($turned, 0)), \min(\array_column($turned, 1)), \min(\array_column($turned, 2))]; + $expected = \array_map(static fn(array $v): array => [$v[0] - $low[0], $v[1] - $low[1], $v[2] - $low[2]], $turned); + $rotated = HullShape::rotate(self::WEDGE, Rotation::from($code)); + self::assertSame($expected, $rotated, $code); + self::assertSame($volume, HullShape::of($rotated)->volume, $code); + } + } + + public static function testThe24RotationsOfAChiralHullAreCachedApart(): void + { + $shapes = []; + foreach (Rotation::every() as $rotation) { + $shapes[$rotation->value] = HullShape::shapeFor(self::WEDGE, $rotation); + } + // The half-turn about z is the wedge's complement in its box, not the wedge itself. + self::assertTrue($shapes['-L-W+H'] != $shapes['LWH'], 'the half-turn is a different solid'); + foreach (Rotation::every() as $rotation) { + self::assertTrue(HullShape::shapeFor(self::WEDGE, $rotation) === $shapes[$rotation->value], $rotation->value); + } + } + + public static function testASignedCodeIsAHullOnlyRuleOnTheObjectPath(): void + { + $refusal = self::caught(static fn() => Item::create('box', Support::dims(1, 2, 3), allowedRotations: [Rotation::NL_NW_PH])); + self::assertTrue($refusal instanceof ObjectRefusal, 'an ObjectRefusal'); + self::assertSame(['invalid_value', Orientations::SIGNED_CODE_NEEDS_A_HULL], [$refusal->reason(), $refusal->detail()]); + self::assertSame([Rotation::NL_NW_PH], self::wedge(allowedRotations: [Rotation::NL_NW_PH])->allowedRotations); + } + + public static function testKeepUprightKeepsTheCodesWhoseZEntryIsPlusH(): void + { + $kept = self::wedge(allowedRotations: Rotation::every(), keepUpright: true)->allowedRotations; + self::assertSame(Orientations::UPRIGHT_CODES, \array_map(static fn(Rotation $r): string => $r->value, $kept)); + self::assertSame(Rotation::upright(), Item::create('a', Support::dims(1, 2, 3), keepUpright: true)->allowedRotations); + } + + public static function testTheJsonPathNamesTheCodeItRefuses(): void + { + $cases = [ + [['allowed_rotations' => ['LWH', '-L-W+H']], 'invalid_value', '/items/0/allowed_rotations/1'], + [['allowed_rotations' => ['+L+W+H']], 'not_allowed', '/items/0/allowed_rotations/0'], + [['shape_type' => 'convex_hull', 'hull_vertices' => [], 'allowed_rotations' => ['-L+W+H']], 'not_allowed', '/items/0/allowed_rotations/0'], + ]; + foreach ($cases as [$item, $reason, $field]) { + $error = self::caught(static fn() => ArrayCodec::pack(self::request($item))); + self::assertTrue($error instanceof InvalidRequestException, $field); + self::assertSame([$reason, $field], [$error->reason(), $error->field()]); + } + $legacy = self::caught(static fn() => ArrayCodec::pack(self::request(['allowed_rotations' => ['XYZ']]))); + self::assertSame('must be one of ["LWH","LHW","WLH","WHL","HLW","HWL"]', $legacy->detail()); + } + + public static function testTwoChiralWedgesShareACrateOnlyUnderASignedCode(): void + { + $crates = [Support::box('crate', 10, 10, 10)]; + $config = new PackingConfig(maxContainers: 1); + $legacy = Support::pack([self::wedge(quantity: 2)], $crates, $config); + self::assertCount(1, $legacy->unpacked); + $items = [self::wedge(quantity: 2, allowedRotations: Rotation::every())]; + $every = Support::pack($items, $crates, $config); + self::assertSame([], Support::problems($every, $items, $crates)); + self::assertSame([], $every->unpacked); + self::assertSame(['LWH', '-L-W+H'], \array_map(static fn($p): string => $p->rotation->value, $every->containers[0]->placements)); + } + + public static function testAHullMayBeFixedInASignedOrientation(): void + { + $result = ArrayCodec::pack(self::chiral('-L-W+H')); + $placements = $result['containers'][0]['placements']; + self::assertSame([['-L-W+H', true], ['LWH', false]], + \array_map(static fn(array $p): array => [$p['orientation'], $p['fixed'] ?? false], $placements)); + } + + public static function testAFixedHullOrientationIsReadFromItsVocabularyAndItsList(): void + { + foreach ([['-L+W+H', 'malformed', 'must be one of ["LWH"'], ['+L-W-H', 'cannot_hold', 'may not be placed in orientation +L-W-H']] as [$orientation, $reason, $detail]) { + $request = self::chiral($orientation); + $request['items'][0]['allowed_rotations'] = ['LWH', '-L-W+H']; + $error = self::caught(static fn() => ArrayCodec::pack($request)); + self::assertTrue($error instanceof FixedPlacementException, $orientation); + self::assertSame($reason, $error->reason()); + self::assertTrue(\str_contains($error->getMessage(), $detail), $error->getMessage()); + } + } + + public static function testASignedOrientationCannotFixABoxOnEitherPath(): void + { + $request = self::chiral('-L-W+H'); + unset($request['items'][0]['shape_type'], $request['items'][0]['hull_vertices'], $request['items'][0]['allowed_rotations']); + $fromJson = self::caught(static fn() => ArrayCodec::pack($request)); + self::assertTrue($fromJson instanceof FixedPlacementException, 'the JSON path'); + self::assertSame(['invalid_value', '/fixed_placements/0/orientation'], [$fromJson->reason(), $fromJson->field()]); + $box = Item::create('wedge', Support::dims(10, 10, 10), quantity: 2); + $fromObjects = self::caught(static fn() => (new Packer(new PackingConfig()))->pack( + [$box], [Support::box('crate', 10, 10, 10)], [new FixedPlacement('wedge', 'crate', new Point(0, 0, 0), Rotation::NL_NW_PH)])); + self::assertSame($fromJson->getMessage(), $fromObjects->getMessage()); + } + + public static function testARevisionLocksAHullInASignedOrientationAndRefusesOneOnABox(): void + { + $request = self::chiral('LWH'); + unset($request['fixed_placements']); + $lock = ['sequence' => 1, 'type' => 'placement_locked', + 'placement' => ['item_type' => 'wedge', 'container_type' => 'crate', 'orientation' => '-L-W+H']]; + $derived = PlanRevision::applyEvents($request, [$lock]); + self::assertSame('-L-W+H', $derived->fixed_placements[0]->orientation); + $request['items'][0]['shape_type'] = 'rigid_cuboid'; + $error = self::caught(static fn() => PlanRevision::applyEvents($request, [$lock])); + self::assertTrue($error instanceof PlanRevisionException, 'a revision refusal'); + self::assertTrue(\str_contains($error->getMessage(), 'placement.orientation: a signed rotation code requires'), $error->getMessage()); + } + + public static function testARequestWithNoItemListNamesNoHull(): void + { + self::assertSame([], FixedPlacementShape::hullItemTypes(null)); + self::assertSame(['w'], FixedPlacementShape::hullItemTypes([['id' => 'w', 'shape_type' => 'convex_hull'], 'x', ['id' => 5, 'shape_type' => 'convex_hull']])); + } + + /** @param array{0:int,1:int,2:int} $axes @param array{0:int,1:int,2:int} $signs */ + private static function determinant(array $axes, array $signs): int + { + $m = []; + for ($row = 0; $row < 3; ++$row) { + for ($column = 0; $column < 3; ++$column) { + $m[$row][$column] = $column === $axes[$row] ? $signs[$row] : 0; + } + } + return $m[0][0] * ($m[1][1] * $m[2][2] - $m[1][2] * $m[2][1]) + - $m[0][1] * ($m[1][0] * $m[2][2] - $m[1][2] * $m[2][0]) + + $m[0][2] * ($m[1][0] * $m[2][1] - $m[1][1] * $m[2][0]); + } + + /** @param list $allowedRotations */ + private static function wedge(int $quantity = 1, array $allowedRotations = [Rotation::LWH, Rotation::LHW, Rotation::WLH, Rotation::WHL, Rotation::HLW, Rotation::HWL], bool $keepUpright = false): Item + { + return Item::create('wedge', Dimensions::mm(10, 10, 10), quantity: $quantity, allowedRotations: $allowedRotations, + keepUpright: $keepUpright, shapeType: ShapeType::CONVEX_HULL, hullVertices: self::WEDGE); + } + + /** @param array $item @return array */ + private static function request(array $item): array + { + return ['items' => [['id' => 'a', 'dimensions' => ['length' => '10', 'width' => '10', 'height' => '10']] + $item], + 'containers' => [['id' => 'c', 'inner_dimensions' => ['length' => '10', 'width' => '10', 'height' => '10']]]]; + } + + /** @return array */ + private static function chiral(string $orientation): array + { + $corners = \array_map(static fn(array $c): array => ['x' => (string)$c[0], 'y' => (string)$c[1], 'z' => (string)$c[2]], + [[0, 0, 0], [10, 0, 0], [0, 10, 0], [0, 0, 10], [10, 0, 10], [0, 10, 10]]); + return ['items' => [['id' => 'wedge', 'quantity' => 2, 'dimensions' => ['length' => '10', 'width' => '10', 'height' => '10'], + 'shape_type' => 'convex_hull', 'hull_vertices' => $corners, 'allowed_rotations' => \array_keys(Orientations::TABLE)]], + 'containers' => [['id' => 'crate', 'quantity' => 1, 'inner_dimensions' => ['length' => '10', 'width' => '10', 'height' => '10']]], + 'fixed_placements' => [['item_type' => 'wedge', 'container_type' => 'crate', 'orientation' => $orientation]]]; + } + + private static function caught(callable $call): \Throwable + { + try { + $call(); + } catch (\Throwable $error) { + return $error; + } + throw new \RuntimeException('expected a refusal, nothing was thrown'); + } +} diff --git a/tests/StockCutIndexTest.php b/tests/StockCutIndexTest.php new file mode 100644 index 0000000..dee42f5 --- /dev/null +++ b/tests/StockCutIndexTest.php @@ -0,0 +1,91 @@ + '10', 'width' => '10', 'height' => '10']; + $request = ['items' => [['id' => 'cube', 'dimensions' => $sides]], 'containers' => [ + ['id' => 'machine', 'inner_dimensions' => $sides, 'made_to_measure' => ['minimum' => $sides, 'increment' => $sides]], + ]]; + $artifact = OperationalArtifact::build($request, ArrayCodec::pack($request)); + foreach ([['made_to_measure', true, 'made_to_measure is not an object'], + ['cost_minor', 'price', 'cost_minor is not an integer'], ['tare_weight', 'heavy', 'tare_weight is not a measure']] as [$field, $value, $detail]) { + $replacement = $request['containers'][0]; + $replacement[$field] = $value; + $events = [['sequence' => 1, 'type' => 'container_substituted', 'container_type' => 'machine', 'replacement' => $replacement], + ['sequence' => 2, 'type' => 'placement_locked', 'placement' => ['item_type' => 'cube', 'container_type' => 'machine', 'orientation' => 'LWH']]]; + try { + PlanRevision::derive(PlanRevision::root($request), $artifact, $events); + self::assertTrue(false, 'an unreadable stock field was accepted'); + } catch (PlanRevisionException $error) { + self::assertSame('invalid_revision', $error->errorCode()); + self::assertSame("a made-to-measure container's {$detail}", $error->getMessage()); + } + } + $revision = PlanRevision::derive(PlanRevision::root($request), $artifact, [['sequence' => 1, 'type' => 'placement_locked', + 'placement' => ['item_type' => 'cube', 'container_type' => 'machine', 'orientation' => 'LWH', 'position' => ['x' => '999999']]]]); + self::assertSame('999999', $revision->request->fixed_placements[0]->position->x); + foreach ([[[], 'units is not an object'], [['length' => []], 'units.length is not a string']] as [$units, $detail]) { + $fixed = $request; + $fixed['units'] = $units; + $fixed['fixed_placements'] = [['container_type' => 'machine']]; + try { + PlanRevision::stockCutBoxes($fixed, $artifact, 1); + self::assertTrue(false, 'an unreadable measure context was accepted'); + } catch (PlanRevisionException $error) { + self::assertSame('invalid_revision', $error->errorCode()); + self::assertSame("a made-to-measure container's {$detail}", $error->getMessage()); + } + } + foreach ([null, 0, 1, 1.0, -1] as $cost) { + $fixed = $request; + $fixed['containers'][0]['cost_minor'] = $cost; + $fixed['fixed_placements'] = [['container_type' => 'machine']]; + self::assertSame((int) ($cost ?? 0), PlanRevision::stockCutBoxes($fixed, $artifact, 1)->containers[1]->cost_minor); + } + } + + public static function testStockingKeepsFirstLockOrder(): void + { + $fixed = $orders = $shapes = []; + for ($i = 100; $i >= 1; --$i) { + $fixed[] = ['container_type' => 'machine', 'container_instance' => $i]; + } + for ($i = 1; $i <= 100; ++$i) { + $orders[] = ['container_type' => 'machine']; + $shapes[] = ['inner_dimensions' => ['length' => (string) $i, 'width' => '2', 'height' => '3']]; + } + $request = ['containers' => [['id' => 'machine', 'quantity' => 100, 'made_to_measure' => (object) []]], 'fixed_placements' => $fixed]; + $artifact = ['work_order' => ['containers' => $orders], 'geometry' => ['containers' => $shapes]]; + $stocked = PlanRevision::stockCutBoxes($request, $artifact, 7); + self::assertSame(100, count($stocked->containers)); + self::assertSame('machine@7#100', $stocked->containers[0]->id); + self::assertSame('machine@7#1', $stocked->containers[99]->id); + self::assertSame('100', $stocked->containers[0]->inner_dimensions->length->value); + self::assertSame('1', $stocked->containers[99]->inner_dimensions->length->value); + } + + public static function testStockingJoinsTypesAndLeavesUnselectedMalformedGeometryUnread(): void + { + $request = ['containers' => [ + ['id' => 'machine', 'made_to_measure' => (object) [], 'cost_minor' => 1], + ['id' => 'machine', 'made_to_measure' => (object) [], 'cost_minor' => 9], + ], 'fixed_placements' => [['container_type' => 'machine', 'container_instance' => 2]]]; + $artifact = ['work_order' => ['containers' => [ + ['container_type' => 'machine'], ['container_type' => 'other'], + ['container_type' => 'machine'], ['container_type' => 'machine'], + ]], 'geometry' => ['containers' => [null, null, ['inner_dimensions' => ['length' => '1', 'width' => '2', 'height' => '3']]]]]; + $stocked = PlanRevision::stockCutBoxes($request, $artifact, 1); + self::assertSame(9, $stocked->containers[1]->cost_minor); + self::assertSame('1', $stocked->containers[1]->inner_dimensions->length->value); + } +} diff --git a/tests/Support.php b/tests/Support.php index 56e494d..078aa14 100644 --- a/tests/Support.php +++ b/tests/Support.php @@ -9,6 +9,8 @@ use Packvium\Domain\Item; use Packvium\Domain\PackedContainer; use Packvium\Domain\PackingRequest; +use Packvium\Domain\Placement; +use Packvium\Domain\Point; use Packvium\Domain\UnpackedItem; use Packvium\Packer; use Packvium\Result\PackingResult; @@ -100,6 +102,20 @@ public static function problems(PackingResult $result, array $items, array $cont return $problems; } + /** + * A serialized placement's `placement_id` restated for wherever a test has moved it (1.10), + * so a mutation is judged by the rule it targets rather than by the id it left stale. + * + * @param array $placement + * @return array + */ + public static function restatedId(array $placement, string $containerId): array + { + $ticks = array_map(static fn(string $axis): int => (int)$placement['position'][$axis]['ticks'], ['x', 'y', 'z']); + $placement['placement_id'] = Placement::identifier($containerId, new Point(...$ticks), $placement['item_type'], $placement['orientation']); + return $placement; + } + /** @param list $containers @return list */ public static function placedIds(array $containers): array {