diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml index 196b437..897b66c 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.10.0 (PHP)" + placeholder: "packvium/packvium 1.11.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 ccf74c3..d6b9bfa 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.10.0 (PHP)" + placeholder: "packvium/packvium 1.11.0 (PHP)" validations: required: false - type: textarea diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 2de712d..27d266c 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.10.0. - placeholder: "1.10.0" + description: The exact version installed, for example 1.11.0. + placeholder: "1.11.0" validations: required: true - type: input @@ -101,5 +101,5 @@ body: options: - label: I searched the existing issues and did not find this one. required: true - - label: I read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-php/blob/HEAD/docs/GUARANTEES.md) and this is not something it says the library does not guarantee. + - label: I read [docs/GUARANTEES.md](https://github.com/packvium/packvium-php/blob/HEAD/docs/GUARANTEES.md) and this is not something it says the library does not guarantee. required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 8cda1f8..1f0575c 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,10 +1,10 @@ blank_issues_enabled: false contact_links: - name: Question or help with a request - url: https://github.com/toxakara/packvium-php/discussions/categories/q-a + url: https://github.com/packvium/packvium-php/discussions/categories/q-a about: Ask in Discussions → Q&A. Answers there help the next person too. - name: Report a security vulnerability - url: https://github.com/toxakara/packvium-php/security/advisories/new + url: https://github.com/packvium/packvium-php/security/advisories/new about: Report privately. Do not open a public issue for a security problem. - name: Documentation url: https://packvium.com/docs diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index c3cf3a1..1964ea3 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.10.0" + placeholder: "1.11.0" validations: required: true - type: textarea diff --git a/CHANGELOG.md b/CHANGELOG.md index b026519..d366e45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ What changed in `packvium/packvium` on Packagist, release by release. The format [Keep a Changelog](https://keepachangelog.com/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.11.0] + +Bottom gussets and standing pouches, a certified bound for the shipping objectives, one money +ceiling, and ids that sort as text. + +### Added + +- **`bottom_gusset_depth` and `orientation: "standing"`** on a `gusseted_bag`: `Container` + gains `$bottomGussetDepth`, `$bagOrientation` and `$uprightFrame`, and the new `Domain\Girth` + holds both loops. +- **`optimality.lower_bound` and the gap under `shipping_cost` and `lowest_landed_cost`** + (`ObjectiveBounds`, `BoundWithheldException`); the validator checks them. +- **`HullShape::MAXIMUM_VERTICES = 32`**: a longer `hull_vertices` list is `above_maximum`. +- **`examples/checkout.php` and `examples/fulfilment.php`.** + +### Changed + +- **A `rate_table` priced above 9007199254740991 minor units** at its top bracket is refused at + admission. A commerce quote refuses an amount above it, where it used to answer up to + `PHP_INT_MAX` and throw a `TypeError` past it. `AccessorialCharge::chargeMinor()` takes and + returns `int|string`. +- **Ids sort as text, not numbers:** containers named `"9"` and `"10"` open `"10"` first, as in + every other engine. Group names in validation reports, fixed-placement issues, policy + citations and grid lattice tags follow code-point order too. +- **The "why unpacked" reason no longer depends on a 2 s clock,** and is decided once per item + type: 900 items take 0.1–0.2 s instead of 1.6 s. + +### Fixed + +- **`WeightRebalancer` fataled on a compact lattice result.** +- **The support diagnosis could throw `TimeLimitReached` out of `Packer::pack`.** +- **`bin/packvium` read `tag_limits: {"0": 1}` as a list.** +- **`effort_budget` limits written as `1000.0`** threw a `TypeError`; they now read as integers. + ## [1.10.0] Overhanging pallets, gusseted bags, 24 rotations for a hull, a declared currency, an id on every diff --git a/CITATION.cff b/CITATION.cff index 05482d3..0d65eaf 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,10 +5,10 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.10.0" +version: "1.11.0" license: MIT url: "https://packvium.com" -repository-code: "https://github.com/toxakara/packvium-php" +repository-code: "https://github.com/packvium/packvium-php" repository-artifact: "https://packagist.org/packages/packvium/packvium" abstract: >- Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results. diff --git a/README.md b/README.md index 16be37a..af2b83f 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,29 @@ # Packvium for PHP -Deterministic 3D cartonization and rectangular bin packing. Pure PHP, **no runtime -dependencies**, exact integer geometry. +Deterministic 3D bin packing and cartonization in pure PHP. No runtime dependencies, no +extensions, and exact integer geometry instead of floats. Use it to pick the smallest carton for an order, build a pallet, load a shipping container, or load a truck within its axle ratings and delivery-stop order. Every answer comes back as coordinates and rotations for each item, with a reason for anything that did not fit. -Full documentation, the constraint reference and benchmarks live at -[packvium.com](https://packvium.com). - -> **Version 1.10.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.11.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) +> Read [docs/GUARANTEES.md](https://github.com/packvium/packvium-php/blob/main/docs/GUARANTEES.md) > before relying on a result. +## Install + ```bash composer require packvium/packvium ``` The library runs on PHP 7.3 and newer. The quick start below and the shipped examples are -written for **PHP 8.2 or newer**; [Older PHP](#older-php-73-to-81) shows what changes below -that. +written for PHP 8.2 or newer; [Older PHP](#older-php-73-to-81) shows what changes below +that. It is framework-independent: no facades, no static state, no container bindings. +Construct a `Packer`, or call `ArrayCodec::pack`, from a Laravel job, a Symfony service or +a WordPress hook alike. ## Quick start @@ -70,69 +71,30 @@ echo '{"items":[{"id":"box","quantity":8,"dimensions":{"length":"50","width":"50 | vendor/bin/packvium ``` -Support is not required by default: `minimum_support_ratio` is 0, so an item may rest on -nothing above the container floor, and the result then says so in `warnings` -(`unsupported_placements: N placement(s) rest on nothing above the container floor; ...`). -To require support, set it above 0 — `'configuration' => ['minimum_support_ratio' => 0.75]`, or -`new PackingConfig(minimumSupportRatio: 0.75)` in the object API. - -The library is framework-independent: no facades, no static state, no container bindings. -Construct a `Packer` and call it. - -## Units - -Every length is an integer number of ticks of 1/16000 mm, and every weight an integer -number of 1/8 µg. Nothing on the path from request to score is a float, so no placement -decision depends on rounding, and an imperial spec sheet and a metric container agree -without a tolerance: - -```php -Dimensions::inches('12 3/8', '8 1/2', '3/4'); // exact: fractions, mixed fractions, decimals -Dimensions::mm('210', '140', '30'); -Item::create('mug', Dimensions::mm('100', '100', '120'), '12 oz'); -``` - -Lengths accept `mm`, `cm`, `m`, `in`, `ft` and ticks; weights `mg`, `g`, `kg`, `oz` and `lb`. -Pass numbers as strings or integers — the API has no float parameters for a measure. Round -item exteriors outward and container interiors inward before building the request. -Volumes that exceed `PHP_INT_MAX` are handled in exact decimal-string arithmetic rather -than losing precision. A JSON request's `units` sets only the length unit; a weight takes its -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). - -## Determinism - -The same request, seed and budget give the same result. The one thing that can break that -is the wall clock: `time_limit_ms` (`timeLimitMs`) stops the search when time runs out, and -how far a search gets in that time depends on the machine and its load. A search that -finishes inside its limit is reproducible; one the clock stopped is not. - -`effort_budget` bounds the search by counted work instead — candidates evaluated, -placements attempted, search nodes expanded, portfolio restarts — so it stops at the same -point everywhere. Keep `time_limit_ms` as a generous safety fuse beside it: +## Using it in your project -```php -$result = ArrayCodec::pack([ - 'configuration' => [ - 'effort_budget' => ['max_search_nodes' => 20000], - 'time_limit_ms' => 60000, - ], - // items, containers ... -]); -$result['termination']['code']; // "complete", "effort_limit" or "time_limit" -``` - -`termination` says which one stopped the search; only `time_limit` is a result you cannot -replay. In the object API the budget is `new PackingConfig(effortBudget: new EffortBudget(...))`, -with `Packvium\Config\EffortBudget`, part of the frozen API since 1.6.0. -[`reproducibility.php`](https://github.com/toxakara/packvium-php/blob/main/examples/reproducibility.php) -shows all three outcomes. +Two examples are written the way application code is written, with your own product and +order records on one side and the library call in the middle. Start from the one closer to +what you are building. -`effort_limit` means the budget stopped work the search still had: a search that finishes on -exactly its budget reads `complete`, and under a budget `time_limit_ms` is one fuse for the -whole solve, not a slice per start. `termination.any_start_truncated` says whether the budget -cut a start that might have won. +| You are building | Start from | What it does | +| --- | --- | --- | +| A checkout or cart page | [`checkout.php`](https://github.com/packvium/packvium-php/blob/main/examples/checkout.php) | Maps a cart onto a request, picks the cheapest cartons, and reads the parcels back for the page. Two functions hold everything Packvium-specific. | +| A warehouse or fulfilment job | [`fulfilment.php`](https://github.com/packvium/packvium-php/blob/main/examples/fulfilment.php) | Runs an order from paid to labelled: a shipping rule picks the carrier service, the order is packed under its constraints, `validate` checks the plan, and every parcel is priced from a pinned tariff. | +| An HTTP endpoint that packs | [`errors.php`](https://github.com/packvium/packvium-php/blob/main/examples/errors.php) | Turns each kind of refused request into a 422 that names the item and the value. | +| A dock or driver screen | [`execution.php`](https://github.com/packvium/packvium-php/blob/main/examples/execution.php), [`trucking.php`](https://github.com/packvium/packvium-php/blob/main/examples/trucking.php) | Turns a result into numbered loading steps, and loads a van by stop and axle rating. | + +Rules that most projects need on day one: + +- An item that does not fit is not an error. The result lists it in `unpacked_items` with a + reason, and everything else is still packed. +- Support is not required by default: `minimum_support_ratio` is 0, so an item may rest on + nothing above the container floor, and the result then says so in `warnings` + (`unsupported_placements: N placement(s) rest on nothing above the container floor; ...`). + To require support, set it above 0: `'configuration' => ['minimum_support_ratio' => 0.75]`, or + `new PackingConfig(minimumSupportRatio: 0.75)` in the object API. +- Set an `effort_budget` for any answer you store or show twice. See + [Getting the same answer every time](#getting-the-same-answer-every-time). ## Errors @@ -177,7 +139,7 @@ try { A request that is valid but does not fit completely is not an error: the result lists what was left out, and why, in `unpacked_items`. -[`errors.php`](https://github.com/toxakara/packvium-php/blob/main/examples/errors.php) turns +[`errors.php`](https://github.com/packvium/packvium-php/blob/main/examples/errors.php) turns each kind of refusal into the answer a web handler would send. ## Checking a result @@ -203,109 +165,170 @@ It shares no code with the engine, so it judges any engine's result, not only th result without the documented shape throws `Packvium\Validation\MalformedResult`, whose `kind` is `contract` or `shape`. +## Units + +Every length is an integer number of ticks of 1/16000 mm, and every weight an integer +number of 1/8 µg. Nothing on the path from request to score is a float, so no placement +decision depends on rounding, and an imperial spec sheet and a metric container agree +without a tolerance: + +```php +Dimensions::inches('12 3/8', '8 1/2', '3/4'); // exact: fractions, mixed fractions, decimals +Dimensions::mm('210', '140', '30'); +Item::create('mug', Dimensions::mm('100', '100', '120'), '12 oz'); +``` + +Lengths accept `mm`, `cm`, `m`, `in`, `ft` and ticks; weights `mg`, `g`, `kg`, `oz` and `lb`. +Pass numbers as strings or integers; the API has no float parameters for a measure. Round +item exteriors outward and container interiors inward before building the request. +Volumes that exceed `PHP_INT_MAX` are handled in exact decimal-string arithmetic rather +than losing precision. A JSON request's `units` sets only the length unit; a weight takes its +unit from the measure or is grams; any other `units` key, `weight` included, is refused. See +[docs/UNITS-AND-NUMERICS.md](https://github.com/packvium/packvium-php/blob/main/docs/UNITS-AND-NUMERICS.md) +and [`units.php`](https://github.com/packvium/packvium-php/blob/main/examples/units.php). + +## Getting the same answer every time + +The same request, seed and budget give the same result. The one thing that can break that +is the wall clock: `time_limit_ms` (`timeLimitMs`) stops the search when time runs out, and +how far a search gets in that time depends on the machine and its load. A search that +finishes inside its limit is reproducible; one the clock stopped is not. + +`effort_budget` bounds the search by counted work instead (candidates evaluated, +placements attempted, search nodes expanded, portfolio restarts), so it stops at the same +point everywhere. Keep `time_limit_ms` as a generous safety fuse beside it: + +```php +$result = ArrayCodec::pack([ + 'configuration' => [ + 'effort_budget' => ['max_search_nodes' => 20000], + 'time_limit_ms' => 60000, + ], + // items, containers ... +]); +$result['termination']['code']; // "complete", "effort_limit" or "time_limit" +``` + +`termination` says which one stopped the search; only `time_limit` is a result you cannot +replay. In the object API the budget is `new PackingConfig(effortBudget: new EffortBudget(...))`, +with `Packvium\Config\EffortBudget`, part of the frozen API since 1.6.0. +[`reproducibility.php`](https://github.com/packvium/packvium-php/blob/main/examples/reproducibility.php) +shows all three outcomes. + +`effort_limit` means the budget stopped work the search still had: a search that finishes on +exactly its budget reads `complete`, and under a budget `time_limit_ms` is one fuse for the +whole solve, not a slice per start. `termination.any_start_truncated` says whether the budget +cut a start that might have won. + ## Examples -Runnable, in [`examples/`](https://github.com/toxakara/packvium-php/tree/main/examples). Each +Runnable, in [`examples/`](https://github.com/packvium/packvium-php/tree/main/examples). Each one is a single file you can read top to bottom and execute without a project around it. Every one of them is executed by the test suite on each release, so none of them can quietly stop working. They are PHP 8.2 code (named arguments, enums); run them on 8.2 or newer. -New here? Read `basic.php`, then `objectives.php` — between them they cover what most -callers need. `units.php` and `serialization.php` explain the two design choices that +New here? Read `basic.php`, then `objectives.php`. Between them they cover what most +callers need, and `checkout.php` shows the same call inside a project. `units.php` and `serialization.php` explain the two design choices that 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 — 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 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 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. | +| [`checkout.php`](https://github.com/packvium/packvium-php/blob/main/examples/checkout.php) | A shop's checkout: a cart mapped onto a request and the parcels read back, with the cheapest cartons chosen. | +| [`fulfilment.php`](https://github.com/packvium/packvium-php/blob/main/examples/fulfilment.php) | An order from paid to labelled: a policy rule picks the service, the order is packed under its constraints, `validate` checks the plan, and each parcel is priced from a pinned tariff. | +| [`basic.php`](https://github.com/packvium/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/packvium/packvium-php/blob/main/examples/objectives.php) | Six of the seven objectives (all but `maximum_volume`) on scenes where they 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/packvium/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/packvium/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/packvium/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/packvium/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/packvium/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/packvium/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/packvium/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/packvium/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/packvium/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/packvium/packvium-php/blob/main/examples/nested.php) | Units into cartons, cartons onto a pallet, in one call. | +| [`packaging.php`](https://github.com/packvium/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/packvium/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/packvium/packvium-php/blob/main/examples/commerce.php) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | +| [`execution.php`](https://github.com/packvium/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 absent. Byte-identical to the other three engines. | +| [`artifacts.php`](https://github.com/packvium/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/packvium/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 ``` `limits.php`, `fixed_placements.php`, `nested.php` and `shapes.php` print byte for byte -what their [Python counterparts](https://github.com/toxakara/packvium-python/tree/main/examples) +what their [Python counterparts](https://github.com/packvium/packvium-python/tree/main/examples) print. `trucking.php`, `errors.php`, `reproducibility.php` and `constraints.php` differ only where a line names a PHP spelling (`stopIndex`, `allowedRotations`, `true`) or a -language's own exception class. That is the cross-language contract this port is held to — -identical placements for the same request — not a coincidence. The other examples print +language's own exception class. That is the cross-language contract this port is held to: +identical placements for the same request. The other examples print PHP values (`[0,1,180]` where Python prints `(0, 1, 180)`), so their text differs even where their answers agree. -## What it does - -- **Exact arithmetic.** Length is measured in ticks of 1/16000 mm and weight in 1/8 µg. - No coordinate is ever a float, so no placement decision depends on rounding. -- **Real constraints.** Weight and payload limits, permitted rotations, keep-upright, - 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 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; `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 +## What it covers + +- Exact arithmetic. Length is measured in ticks of 1/16000 mm and weight in 1/8 µg, so no + coordinate is a float and no placement depends on rounding. +- Constraints: weight and payload limits, permitted rotations, keep-upright, 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. +- Several solvers, chosen by problem shape and profile: regular-grid, layer, extreme-point, + maximal-space and bounded exact search. +- Every solution is re-validated by logic independent of the search. Unplaced items come + back with a reason code. +- 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 packing. `new NestedPacker(K)` carries the K best carton sets + up a level, so the pallet decides between them. +- Your own constraints, item orderings, candidate scorers, container selectors or complete + solvers, registered through `ExtensionRegistry`. +- Loading and unloading order. `Packvium\Sequence` answers which placements a door can reach right now and gives a safe loading order, or an unloading order that empties each stop before the next. -- **Work orders and portable artifacts.** `Packvium\Execution\Plan` turns a result into an +- Work orders and portable artifacts. `Packvium\Execution\Plan` turns a result into an operator's step list. `Packvium\Artifacts\OperationalArtifact` wraps that plan with - geometry, display values and the request that produced it, and `ArtifactExports` writes it - as canonical JSON, CSV or a self-contained HTML work order, byte for byte what the Python, - 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`. 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. + geometry, display values and the request that produced it, and `ArtifactExports` writes + it as canonical JSON, CSV or a self-contained HTML work order, byte for byte what the + Python, 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`. 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. +- Carrier quotes, shipping rules and catalog versions through `Packvium\Commerce`. ## Documentation | Document | Covers | | --- | --- | -| [docs/GUARANTEES.md](https://github.com/toxakara/packvium-php/blob/main/docs/GUARANTEES.md) | What is promised and what is not. Start here. | -| [docs/PUBLIC-API.md](https://github.com/toxakara/packvium-php/blob/main/docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | -| [docs/UNITS-AND-NUMERICS.md](https://github.com/toxakara/packvium-php/blob/main/docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | -| [docs/COMMERCE-API.md](https://github.com/toxakara/packvium-php/blob/main/docs/COMMERCE-API.md) | Carrier rating, policy evaluation and catalog versions. | +| [docs/GUARANTEES.md](https://github.com/packvium/packvium-php/blob/main/docs/GUARANTEES.md) | What is promised and what is not. Start here. | +| [docs/PUBLIC-API.md](https://github.com/packvium/packvium-php/blob/main/docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | +| [docs/UNITS-AND-NUMERICS.md](https://github.com/packvium/packvium-php/blob/main/docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | +| [docs/COMMERCE-API.md](https://github.com/packvium/packvium-php/blob/main/docs/COMMERCE-API.md) | Carrier rating, policy evaluation and catalog versions. | + +The constraint reference and the benchmarks are at [packvium.com](https://packvium.com). ## Requirements -PHP 7.3 or newer. No extensions required — `bcmath` and `gmp` are deliberately not +PHP 7.3 or newer. No extensions required: `bcmath` and `gmp` are deliberately not depended upon. -One package name covers the whole range. It carries two source trees — the canonical -PHP 8.2+ `src/` and `src-legacy/`, generated from it by a pinned AST downgrade — and +One package name covers the whole range. It carries two source trees, the canonical +PHP 8.2+ `src/` and `src-legacy/` generated from it by a pinned AST downgrade, and `autoload.php` selects one by `PHP_VERSION_ID` before Composer's PSR-4 map gets a chance to load the wrong one. PHP parses only what it loads. There is no wrapper, no second package and nothing to configure; namespaces, classes and results are identical either @@ -313,7 +336,7 @@ way, and both trees are held to the same committed placement results on every su version. PHP 7.3, 7.4, 8.0 and 8.1 are end-of-life and receive no upstream security fixes. Packvium -runs there so that an upgrade does not have to block your project — not so that it can be +runs there so that an upgrade does not have to block your project, not so that it can be postponed. ### Older PHP (7.3 to 8.1) @@ -325,7 +348,7 @@ other is how the downgraded tree represents enums. defaults you skip: `Item::create('book', $dimensions, '450 g', 4)`. - **Enums are strings.** Below 8.2 `PackingStatus`, `Rotation`, `SolverProfile`, `ShapeType` and `Rounding` are classes of string constants, so `$result->status` is the - string `'feasible'` itself — there is no `->value`. `Rotation::LWH` is the string `'LWH'`. + string `'feasible'` itself; there is no `->value`. `Rotation::LWH` is the string `'LWH'`. ```php $result = (new Packer(PackingConfig::balanced(60000)))->pack( @@ -368,38 +391,35 @@ PHP are held to byte-identical canonical results; Rust and the JavaScript fallba to independent validity and a per-fixture objective floor. Pick the package for your stack; mixing them in one system is safe. -Documentation, the constraint reference and the benchmarks are at -[packvium.com](https://packvium.com). - | Package | Install | Source | | --- | --- | --- | -| 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.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) | -| Python native selector — `packvium-native` | from source until the native wheels ship | [packvium-python-adapter](https://github.com/toxakara/packvium-python-adapter) | +| Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/packvium/packvium-python) | +| PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/packvium/packvium-php) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.11"` | [packvium-rust](https://github.com/packvium/packvium-rust) | +| Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/packvium/packvium-node) | +| Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/packvium/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/packvium/packvium-php-bridge) | +| Python native selector — `packvium-native` | from source until the native wheels ship | [packvium-python-adapter](https://github.com/packvium/packvium-python-adapter) | ## Contributing -See [CONTRIBUTING.md](https://github.com/toxakara/packvium-php/blob/main/CONTRIBUTING.md). +See [CONTRIBUTING.md](https://github.com/packvium/packvium-php/blob/main/CONTRIBUTING.md). Security reports go through the process in -[SECURITY.md](https://github.com/toxakara/packvium-php/blob/main/SECURITY.md), not public +[SECURITY.md](https://github.com/packvium/packvium-php/blob/main/SECURITY.md), not public issues. ## Citation If Packvium supports your research, cite it as software. GitHub's **Cite this repository** -button reads [`CITATION.cff`](https://github.com/toxakara/packvium-php/blob/main/CITATION.cff), and -[`codemeta.json`](https://github.com/toxakara/packvium-php/blob/main/codemeta.json) carries the same record in +button reads [`CITATION.cff`](https://github.com/packvium/packvium-php/blob/main/CITATION.cff), and +[`codemeta.json`](https://github.com/packvium/packvium-php/blob/main/codemeta.json) carries the same record in CodeMeta form. ```bibtex @software{packvium_php, author = {{Packvium contributors}}, title = {Packvium for PHP}, - version = {1.10.0}, + version = {1.11.0}, license = {MIT}, url = {https://packvium.com} } @@ -407,4 +427,4 @@ CodeMeta form. ## License -MIT. See [LICENSE](https://github.com/toxakara/packvium-php/blob/main/LICENSE). +MIT. See [LICENSE](https://github.com/packvium/packvium-php/blob/main/LICENSE). diff --git a/bin/packvium b/bin/packvium index 2f385c2..eee467d 100755 --- a/bin/packvium +++ b/bin/packvium @@ -4,9 +4,10 @@ declare(strict_types=1); require dirname(__DIR__) . '/autoload.php'; use Packvium\Serialization\ArrayCodec; use Packvium\Support\PrettyJsonStream; +use Packvium\Support\RequestJson; $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, // 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"); } +try { $result=ArrayCodec::packStreamed(RequestJson::decode($input)); 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 2bf1dcf..a5a440a 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.10.0", + "version": "1.11.0", "license": "https://spdx.org/licenses/MIT", "author": [ { @@ -13,8 +13,8 @@ } ], "url": "https://packvium.com", - "codeRepository": "https://github.com/toxakara/packvium-php", - "issueTracker": "https://github.com/toxakara/packvium-php/issues", + "codeRepository": "https://github.com/packvium/packvium-php", + "issueTracker": "https://github.com/packvium/packvium-php/issues", "programmingLanguage": "PHP", "keywords": [ "3d-bin-packing", diff --git a/composer.json b/composer.json index 7b3c315..56ff995 100644 --- a/composer.json +++ b/composer.json @@ -29,9 +29,9 @@ "homepage": "https://packvium.com", "support": { "docs": "https://packvium.com/docs", - "issues": "https://github.com/toxakara/packvium-php/issues", - "source": "https://github.com/toxakara/packvium-php", - "security": "https://github.com/toxakara/packvium-php/blob/main/SECURITY.md" + "issues": "https://github.com/packvium/packvium-php/issues", + "source": "https://github.com/packvium/packvium-php", + "security": "https://github.com/packvium/packvium-php/blob/main/SECURITY.md" }, "require": { "php": ">=7.3" diff --git a/docs/COMMERCE-API.md b/docs/COMMERCE-API.md index 6f4e4b7..44a835e 100644 --- a/docs/COMMERCE-API.md +++ b/docs/COMMERCE-API.md @@ -417,9 +417,19 @@ existing rule-pool storage. difference — `JSON.parse` gives the same `Number` for `1` and `1.0` — so this is the one shape where the four implementations cannot be made to agree, and the contract resolves it by requiring callers not to emit it. No fixture uses one. -- JavaScript refuses, rather than rounds, a quote whose components exceed - `Number.MAX_SAFE_INTEGER`. The arithmetic itself runs in `BigInt`, so nothing drifts - through a double; what cannot be done is *reporting* a value a JSON number cannot hold - exactly. Python has no such ceiling, Rust takes every product in `i128`, and PHP falls - back to decimal-string arithmetic. The bound is far above any real tariff — nine - quadrillion minor currency units. +- Every engine refuses, rather than rounds, a quote that reports an amount above + `2^53 - 1` (`9007199254740991`): `dimensional_weight_g`, `billed_weight_g`, + `base_charge_minor`, `fuel_surcharge_minor`, any accessorial charge, or `total_minor`, + checked in that order. The arithmetic itself is exact in all four -- unbounded integers + in Python, `BigInt` in JavaScript, `i128` in Rust, decimal strings in PHP -- so nothing + drifts or wraps on the way; what cannot be done is *reporting* a value a JSON number + cannot hold exactly. The refusal is the input error of the language, with the message + `quote amount {value} is above 9007199254740991 and cannot be represented exactly`. + Until 1.11 only JavaScript refused; Python answered without a ceiling, and Rust and PHP + answered up to `2^63 - 1`. The bound is far above any real tariff — nine quadrillion + minor currency units. +- JavaScript refuses an input integer above `2^53 - 1` with `expected an exact integer`: + `JSON.parse` has already rounded it, so no exact arithmetic after that can recover the + value the caller sent. Python computes from such an input exactly and PHP and Rust read it + up to `2^63 - 1`, so an engine may answer a quote JavaScript refuses; callers should not + send one. No fixture does. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index f0b05e9..929e28f 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.10.0` freezes the public API. Field names, status codes, the objective +Version `1.11.0` freezes the public API. Field names, status codes, the objective vector, the numeric policy and the validation rules do not change without a major version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde constraint on `1.0` is enough; an exact pin is no longer required. diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index c09c8e8..624c9d0 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -10,6 +10,8 @@ One internal length tick is `1/16000 mm`. Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. A binary float with a fractional part is intentionally rejected by the Python API, by `Length` and `Weight` alike (`TypeError`); an integral float such as `100.0` is exact, and is what JavaScript sends for `100`, so it is accepted as that integer. PHP type declarations accept only integer/string/structured values. +The written grammar is one and the same in all four engines (1.11): an optional sign, ASCII digits, and an optional fraction part with at least one digit on each side of the point and at most 18 after it; or a fraction `n/d`; or a mixed fraction `w n/d`. A unit suffix is matched ignoring ASCII case (`100 MM`, `1 KG`). Nothing else is a measure -- not `100.`, `.5`, `0x64`, `1e2`, `1_0`, nor digits outside ASCII -- and each is refused as `wrong_type`, `must be a measure`. Until 1.11 each language's own number parser decided the edge cases, and they disagreed. + ## Weight One weight tick is `1/8 microgram`, allowing exact common metric units and exact international avoirdupois conversions used by the package. diff --git a/examples/checkout.php b/examples/checkout.php new file mode 100644 index 0000000..c4aaaba --- /dev/null +++ b/examples/checkout.php @@ -0,0 +1,144 @@ + ['size_cm' => [24, 22, 26], 'weight_g' => 1300, 'this_side_up' => true], + 'mug' => ['size_cm' => [12, 9, 10], 'weight_g' => 350, 'this_side_up' => false], + 'cookbook' => ['size_cm' => [28, 22, 3], 'weight_g' => 900, 'this_side_up' => false], + 'floor-lamp' => ['size_cm' => [150, 30, 30], 'weight_g' => 4200, 'this_side_up' => false], +]; + +// The cartons on your packing bench, with what each one costs you in cents. +const BOXES = [ + 'small' => ['inner_cm' => [30, 25, 15], 'max_kg' => 5, 'cost_cents' => 45], + 'medium' => ['inner_cm' => [40, 30, 30], 'max_kg' => 12, 'cost_cents' => 80], + 'large' => ['inner_cm' => [60, 40, 40], 'max_kg' => 20, 'cost_cents' => 140], +]; + +/** + * @param array{0:int,1:int,2:int} $edges + * @return array{length:string,width:string,height:string} + */ +function measures(array $edges): array +{ + return ['length' => (string) $edges[0], 'width' => (string) $edges[1], 'height' => (string) $edges[2]]; +} + +/** + * Your cart (`[sku => quantity]`) as a Packvium request. + * + * @param array $cart + * @return array + */ +function toRequest(array $cart): array +{ + $items = []; + foreach ($cart as $sku => $quantity) { + $product = PRODUCTS[$sku]; + $items[] = [ + 'id' => $sku, + 'quantity' => $quantity, + 'weight' => $product['weight_g'] . ' g', + 'keep_upright' => $product['this_side_up'], + 'dimensions' => measures($product['size_cm']), + ]; + } + $containers = []; + foreach (BOXES as $id => $box) { + $containers[] = [ + 'id' => $id, + 'max_payload' => $box['max_kg'] . ' kg', + 'cost_minor' => $box['cost_cents'], + 'inner_dimensions' => measures($box['inner_cm']), + ]; + } + return [ + 'units' => ['length' => 'cm'], + 'configuration' => [ + // Pay as little as possible for cartons, after packing everything that fits. + 'objective' => 'lowest_cost', + // Counted work decides where the search stops, so the same cart always gets + // the same parcels. The time limit is a fuse against a hang, not a search limit. + 'effort_budget' => ['max_candidates_evaluated' => 200000], + 'time_limit_ms' => 60000, + ], + 'items' => $items, + 'containers' => $containers, + ]; +} + +/** + * The parcels to ship, and the SKUs that fit no carton you stock. + * + * @param array $cart + * @return array{0:list,weight:string}>,1:list} + */ +function parcels(array $cart): array +{ + $result = ArrayCodec::pack(toRequest($cart)); + $shipped = []; + foreach ($result['containers'] as $container) { + $contents = []; + foreach ($container['placements'] as $placement) { + $contents[$placement['item_type']] = ($contents[$placement['item_type']] ?? 0) + 1; + } + ksort($contents); + $shipped[] = [ + 'box' => $container['container_type'], + 'contents' => $contents, + // `value` is the exact weight rendered in `unit`; here that is whole grams. + 'weight' => $container['gross_weight']['value'] . ' ' . $container['gross_weight']['unit'], + ]; + } + // An item that fits nowhere is not an error. It comes back with a reason, and the rest + // of the cart is still packed. + $leftOut = array_values(array_unique(array_column($result['unpacked_items'], 'item_type'))); + sort($leftOut); + return [$shipped, $leftOut]; +} + +/** @param array $cart */ +function show(string $title, array $cart): void +{ + [$shipped, $leftOut] = parcels($cart); + echo PHP_EOL, $title, PHP_EOL; + $boxCost = 0; + foreach ($shipped as $index => $parcel) { + $contents = []; + foreach ($parcel['contents'] as $sku => $count) { + $contents[] = "{$count} x {$sku}"; + } + printf(" parcel %d: %-6s %7s %s\n", $index + 1, $parcel['box'], $parcel['weight'], implode(', ', $contents)); + $boxCost += BOXES[$parcel['box']]['cost_cents']; + } + echo " cartons cost {$boxCost} cents", PHP_EOL; + foreach ($leftOut as $sku) { + echo " {$sku} fits none of our cartons: ship it in its own packaging", PHP_EOL; + } +} + +show('a small order', ['mug' => 2, 'cookbook' => 1]); +show('a bigger order', ['kettle' => 4, 'mug' => 6, 'cookbook' => 4]); +show('an order with something oversized', ['floor-lamp' => 1, 'mug' => 4]); diff --git a/examples/fulfilment.php b/examples/fulfilment.php new file mode 100644 index 0000000..4f8f9df --- /dev/null +++ b/examples/fulfilment.php @@ -0,0 +1,258 @@ + 1` below always means the same prices. +const COMMERCE = [ + 'tariffs' => [ + [ + 'carrier_id' => 'postway', 'service_id' => 'air', + 'versions' => [[ + 'effective_at' => 0, + 'dimensional_weight_divisor' => 5000, + 'cost_per_dimensional_kg_minor' => ['domestic' => 520, 'eu' => 890], + 'minimum_charge_minor' => 950, + 'fuel_surcharge_permille' => 140, + 'accessorials' => [], + ]], + ], + [ + 'carrier_id' => 'postway', 'service_id' => 'ground', + 'versions' => [[ + 'effective_at' => 0, + 'dimensional_weight_divisor' => 6000, + 'cost_per_dimensional_kg_minor' => ['domestic' => 210, 'eu' => 380], + 'minimum_charge_minor' => 590, + 'fuel_surcharge_permille' => 90, + 'accessorials' => [], + ]], + ], + ], + 'policy_rules' => [ + [ + 'rule_id' => 'lithium-stays-on-the-ground', + 'versions' => [[ + 'scope' => 'service', 'action' => 'reject', 'priority' => 10, 'effective_at' => 0, + 'reason' => 'lithium batteries do not fly with this carrier', + 'predicates' => [ + ['scope' => 'service', 'field' => 'service', 'operator' => 'equals', 'value' => 'air'], + ['scope' => 'service', 'field' => 'battery', 'operator' => 'equals', 'value' => 'lithium'], + ], + ]], + ], + ], + 'catalogs' => [], +]; + +const PRODUCTS = [ + 'laptop' => ['mm' => [360, 250, 30], 'g' => 2100, 'battery' => 'lithium'], + 'monitor' => ['mm' => [680, 430, 140], 'g' => 5400, 'keep_upright' => true, 'stackable' => false], + 'bleach' => ['mm' => [90, 90, 280], 'g' => 1100, 'keep_upright' => true, + 'tags' => ['chemical'], 'incompatible_tags' => ['food']], + 'coffee' => ['mm' => [120, 80, 220], 'g' => 1000, 'tags' => ['food']], + 'desk' => ['mm' => [1600, 800, 60], 'g' => 28000], +]; + +const BOXES = [ + ['id' => 'S', 'mm' => [300, 200, 300], 'tare_g' => 180, 'max_kg' => 8, 'cost_minor' => 50], + ['id' => 'M', 'mm' => [400, 300, 300], 'tare_g' => 260, 'max_kg' => 15, 'cost_minor' => 85], + ['id' => 'L', 'mm' => [700, 450, 450], 'tare_g' => 520, 'max_kg' => 25, 'cost_minor' => 160], +]; + +/** + * @param array{0:int,1:int,2:int} $edges + * @return array{length:string,width:string,height:string} + */ +function measures(array $edges): array +{ + return ['length' => (string) $edges[0], 'width' => (string) $edges[1], 'height' => (string) $edges[2]]; +} + +/** + * The service the customer chose, or ground when a rule forbids it, and why. + * + * @param array $order + * @return array{0:string,1:?string} + */ +function allowedService(array $order): array +{ + foreach (array_keys($order['lines']) as $sku) { + $decision = evaluatePolicy(COMMERCE, [ + 'scope' => 'service', + 'context' => ['service' => $order['service'], 'battery' => PRODUCTS[$sku]['battery'] ?? 'none'], + 'as_of' => 0, + ])['decision']; + if (!$decision['allowed']) { + return ['ground', "{$sku}: {$decision['citation']['reason']}"]; + } + } + return [$order['service'], null]; +} + +/** + * @param array $order + * @return array + */ +function packingRequest(array $order): array +{ + $items = []; + foreach ($order['lines'] as $sku => $quantity) { + $product = PRODUCTS[$sku]; + $item = ['id' => $sku, 'quantity' => $quantity, 'weight' => $product['g'] . ' g', + 'dimensions' => measures($product['mm'])]; + // Only the rules a product actually has are sent; an absent field means "no rule". + foreach (['keep_upright', 'stackable', 'tags', 'incompatible_tags'] as $rule) { + if (array_key_exists($rule, $product)) { + $item[$rule] = $product[$rule]; + } + } + $items[] = $item; + } + $containers = []; + foreach (BOXES as $box) { + $containers[] = [ + 'id' => $box['id'], 'inner_dimensions' => measures($box['mm']), 'cost_minor' => $box['cost_minor'], + 'tare_weight' => $box['tare_g'] . ' g', 'max_payload' => $box['max_kg'] . ' kg', + ]; + } + return [ + 'units' => ['length' => 'mm'], + 'configuration' => [ + 'objective' => 'lowest_cost', + // Nothing may hang in the air: three quarters of every base must rest on something. + 'minimum_support_ratio' => 0.75, + 'effort_budget' => ['max_candidates_evaluated' => 200000], + 'time_limit_ms' => 60000, + ], + 'items' => $items, + 'containers' => $containers, + ]; +} + +/** + * One parcel through the pinned tariff. Whole grams and millimetres, rounded up. + * + * The answer is either a quote or a rejection with a code: a zone the tariff does not + * price is never a zero. + * + * @param array $container + * @return array + */ +function price(array $container, string $service, string $zone): array +{ + $grams = intdiv($container['gross_weight']['ticks'] + TICKS_PER_GRAM - 1, TICKS_PER_GRAM); + $volume = 1; + foreach (['length', 'width', 'height'] as $edge) { + $volume *= intdiv($container['outer_dimensions'][$edge]['ticks'] + TICKS_PER_MM - 1, TICKS_PER_MM); + } + return quote(COMMERCE, [ + 'carrier_id' => 'postway', 'service_id' => $service, 'tariff_version' => 1, + 'zone' => $zone, 'actual_weight_g' => $grams, 'volume_mm3' => $volume, + ]); +} + +/** @param array $order */ +function fulfil(array $order): void +{ + echo PHP_EOL, "order {$order['id']} to zone {$order['zone']}, customer chose {$order['service']}", PHP_EOL; + [$service, $why] = allowedService($order); + if ($why !== null) { + echo " moved to {$service}: {$why}", PHP_EOL; + } + + $request = packingRequest($order); + try { + $result = ArrayCodec::pack($request); + } catch (InvalidRequestException $error) { + // `field()` is a JSON Pointer into the request, `reason()` one of a closed set. + echo " on hold: {$error->reason()} at {$error->field()} ({$error->detail()})", PHP_EOL; + return; + } + + $issues = validate($request, $result); + if ($issues !== []) { + $found = array_map(static fn ($issue): string => "{$issue->code}: {$issue->detail}", $issues); + echo ' on hold: the plan failed its check: ', implode('; ', $found), PHP_EOL; + return; + } + echo ' plan checked: ', count($result['containers']), ' parcel(s), no issues', PHP_EOL; + + $answers = []; + foreach ($result['containers'] as $container) { + $answer = price($container, $service, $order['zone']); + if ($answer['status'] !== 'ok') { + echo " on hold: no {$service} price for zone {$order['zone']} ({$answer['error']['code']})", PHP_EOL; + return; + } + $answers[] = $answer; + } + + $total = 0; + foreach ($result['containers'] as $index => $container) { + $contents = []; + foreach ($container['placements'] as $placement) { + $contents[$placement['item_type']] = ($contents[$placement['item_type']] ?? 0) + 1; + } + ksort($contents); + $listing = []; + foreach ($contents as $sku => $count) { + $listing[] = "{$count} x {$sku}"; + } + $quoted = $answers[$index]['quote']; + $total += $quoted['total_minor']; + printf(" %-4s %s\n", $container['id'], implode(', ', $listing)); + echo " {$quoted['actual_weight_g']} g on the scale, billed as ", + "{$quoted['billed_weight_g']} g, {$quoted['total_minor']} minor units", PHP_EOL; + } + echo " shipping by {$service}: {$total} minor units", PHP_EOL; + + foreach ($result['unpacked_items'] as $entry) { + echo " {$entry['item_id']} goes to freight: {$entry['reason']}", PHP_EOL; + } +} + +fulfil(['id' => 'A-1001', 'zone' => 'domestic', 'service' => 'air', + 'lines' => ['coffee' => 6, 'bleach' => 2]]); +fulfil(['id' => 'A-1002', 'zone' => 'eu', 'service' => 'air', + 'lines' => ['laptop' => 1, 'monitor' => 1, 'desk' => 1]]); +fulfil(['id' => 'A-1003', 'zone' => 'domestic', 'service' => 'ground', + 'lines' => ['coffee' => 0]]); +fulfil(['id' => 'A-1004', 'zone' => 'overseas', 'service' => 'ground', + 'lines' => ['coffee' => 1]]); diff --git a/src-legacy/Algorithm/BoundWithheldException.php b/src-legacy/Algorithm/BoundWithheldException.php new file mode 100644 index 0000000..04d62f8 --- /dev/null +++ b/src-legacy/Algorithm/BoundWithheldException.php @@ -0,0 +1,17 @@ +innerDimensions; $limitX=$inner->length->ticks;$limitY=$inner->width->ticks;$limitZ=$inner->height->ticks; - // 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(); + // A bag also needs both loops of film round the running extents grown by the + // candidate: lying flat 2(a + c) <= 2L + K and b + c <= W + G, standing + // 2(b + c) <= 2L + K and a + b <= W + G (1.10 side gussets, bottom + // gussets; `Girth`). O(1), and the extents only grow, so no verdict flips. Both limits + // are summed once per call. + $girth=$container->girth(); + $bag=$girth!==null; $bagX=$state->maxX;$bagY=$state->maxY;$bagZ=$state->maxZ; - $girthY=$limitY+$container->sideGussetTicks(); + $along=$bag?$girth->alongLimit:0;$across=$bag?$girth->acrossLimit:0; + $standing=$bag&&$container->uprightFrame; $clearance=$config->clearance->ticks; // Envelope and extents depend only on the rotation, so they are built once // instead of once per (point, rotation) pair. @@ -136,7 +140,7 @@ private static function prepare(ContainerState $state,ItemInstance $item,Packing $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, + $limitX,$limitY,$limitZ,$bag,$bagX,$bagY,$bagZ,$along,$across,$standing,$clearance, ]; } @@ -151,7 +155,7 @@ private static function scanPoints(array $prepared,array $scan,?int $max,SearchS $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, + $limitX,$limitY,$limitZ,$bag,$bagX,$bagY,$bagZ,$along,$across,$standing,$clearance, ]=$prepared; $out=[];$best=null; $retained=$max!==null&&$max>1?new \SplPriorityQueue():null; @@ -170,9 +174,13 @@ private static function scanPoints(array $prepared,array $scan,?int $max,SearchS $x2=$x1+$dx;$y2=$y1+$dy;$z2=$z1+$dz; if($x2>$limitX||$y2>$limitY||$z2>$limitZ)continue; 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>$girthY)continue; + // Ternaries rather than max() or a Girth call: the call made this test dearer + // (44 ns against 74 ns for max()). + $grownZ=$z2>$bagZ?$z2:$bagZ; + if($standing){ + $grownY=$y2>$bagY?$y2:$bagY; + if(2*($grownY+$grownZ)>$along||($x2>$bagX?$x2:$bagX)+$grownY>$across)continue; + }elseif(2*(($x2>$bagX?$x2:$bagX)+$grownZ)>$along||($y2>$bagY?$y2:$bagY)+$grownZ>$across)continue; } $tentative=null; if($nesting){ diff --git a/src-legacy/Algorithm/GridSolver.php b/src-legacy/Algorithm/GridSolver.php index 02562b9..8f4ce3c 100644 --- a/src-legacy/Algorithm/GridSolver.php +++ b/src-legacy/Algorithm/GridSolver.php @@ -29,9 +29,9 @@ private static function latticeProfile(\Packvium\Domain\Item $item):string foreach($item->dimensions->uniqueRotations($item->allowedRotations) as [, $physical]) $footprints[]="{$physical->length->ticks}x{$physical->width->ticks}x{$physical->height->ticks}"; sort($footprints); - $tags=$item->tags;sort($tags); - $incompatibleTags=$item->incompatibleTags;sort($incompatibleTags); - $eligibleContainerTags=$item->eligibleContainerTags;sort($eligibleContainerTags); + $tags=$item->tags;sort($tags,SORT_STRING); + $incompatibleTags=$item->incompatibleTags;sort($incompatibleTags,SORT_STRING); + $eligibleContainerTags=$item->eligibleContainerTags;sort($eligibleContainerTags,SORT_STRING); $acceptsStackingGroups=$item->acceptsStackingGroups;sort($acceptsStackingGroups,SORT_STRING); return json_encode([ $footprints,$item->weight->ticks,$item->stackable,$item->mustBeOnFloor, diff --git a/src-legacy/Algorithm/HomogeneousBlockSolver.php b/src-legacy/Algorithm/HomogeneousBlockSolver.php index 319f5e1..8fb1e11 100644 --- a/src-legacy/Algorithm/HomogeneousBlockSolver.php +++ b/src-legacy/Algorithm/HomogeneousBlockSolver.php @@ -162,7 +162,7 @@ private static function leads(array $candidate,array $best,string $mode):bool if($order===0){ $mine=$candidate['space']->origin;$theirs=$best['space']->origin; $order=($mine->z<=>$theirs->z)?:($mine->y<=>$theirs->y)?:($mine->x<=>$theirs->x) - ?:($candidate['itemId']<=>$best['itemId'])?:($candidate['rotationName']<=>$best['rotationName']) + ?:strcmp((string)$candidate['itemId'],(string)$best['itemId'])?:($candidate['rotationName']<=>$best['rotationName']) ?:($candidate['nx']<=>$best['nx'])?:($candidate['ny']<=>$best['ny'])?:($candidate['nz']<=>$best['nz']); } return $order<0; diff --git a/src-legacy/Algorithm/Internal/ContainerPlanBeam.php b/src-legacy/Algorithm/Internal/ContainerPlanBeam.php index 211b2c7..214ea7a 100644 --- a/src-legacy/Algorithm/Internal/ContainerPlanBeam.php +++ b/src-legacy/Algorithm/Internal/ContainerPlanBeam.php @@ -31,7 +31,7 @@ public static function acrossContainerPlans(\Closure $call,SingleContainerSolver return $container->quantity??count($items); },$containers)); $ordered=StableSorter::sortBy($containers,static function (Container $container): array { - return array_merge([$container->costMinor], $container->innerDimensions->volumeKey(), [$container->id]); + return array_merge([$container->costMinor], $container->innerDimensions->volumeKey(), [StableSorter::textKey($container->id)]); }); // A beam wider than its node budget used to stop after trying the first // container in static order, so the order chose it, not the objective. The budget is at diff --git a/src-legacy/Algorithm/ObjectiveBoundScope.php b/src-legacy/Algorithm/ObjectiveBoundScope.php index 0f525fd..c457434 100644 --- a/src-legacy/Algorithm/ObjectiveBoundScope.php +++ b/src-legacy/Algorithm/ObjectiveBoundScope.php @@ -14,8 +14,16 @@ final class ObjectiveBoundScope '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], + 'shipping_cost' => [0, 'billed_weight', 1, 3, 4], + 'lowest_landed_cost' => [0, 'landed_charge', 1, 3, 4], ]; + /** + * The objectives whose own key is what a carrier bills, which needs the configuration's + * dimensional-weight divisor and units as well as the request. + */ + public const BILLED_OBJECTIVES = ['shipping_cost', 'lowest_landed_cost']; + /** * O(containers) time, O(1) space; no instances or arithmetic are needed to refuse. * @param list $containers diff --git a/src-legacy/Algorithm/ObjectiveBounds.php b/src-legacy/Algorithm/ObjectiveBounds.php index ac1ff9e..3a80299 100644 --- a/src-legacy/Algorithm/ObjectiveBounds.php +++ b/src-legacy/Algorithm/ObjectiveBounds.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Algorithm; +use Packvium\Config\PackingConfig; use Packvium\Constraint\VolumeReserve; use Packvium\Domain\Container; use Packvium\Domain\Item; @@ -10,6 +11,7 @@ use Packvium\Support\BigInt; use Packvium\Support\ExactGeometry; use Packvium\Support\ExactInteger; +use Packvium\Unit\Weight; /** * Lower bounds on the objective vector, and the gap against an incumbent. @@ -31,7 +33,8 @@ * Complexity. `O(n log n + c log c)` for `n` instances and `c` container types, the same as * the Python port: one sort of the volumes, one of the weights, one of the container types * by cost. The volume sort compares decimal strings through `BigInt::compare` rather than - * PHP's default string order, where "9" would sort after "10". + * PHP's default string order, where "9" would sort after "10". The two billed keys + * add `O(n + c b log n + c b log(c b))` for `b` rate-table brackets per type. * * Which instances, and when. The bound is a property of the request: `Packer` computes it * once per pack through `forRequest`, over every instance the request declares -- fixed @@ -74,25 +77,32 @@ final class ObjectiveBounds * `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. + * `shipping_cost` and `lowest_landed_cost` add one each for what a carrier bills, + * read from the configuration's dimensional-weight divisor. */ public const OBJECTIVE_ORDERS = ObjectiveBoundScope::OBJECTIVE_ORDERS; + /** The objectives whose own key needs the configuration's divisor and units. */ + public const BILLED_OBJECTIVES = ObjectiveBoundScope::BILLED_OBJECTIVES; + /** * The request's bound in `$objective`'s own score order, or null where none is stated. * - * Null for an objective with no bound, for a request with a `made_to_measure` container - * (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 + * Null for an objective with no bound, for a billed objective whose inventory cannot carry + * a packing that attains `L0` at a price, for a request with a `made_to_measure` + * container (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). 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 + * @param ?PackingConfig $config the billed objectives' divisor and units; nothing else reads it * @return list|null */ - public static function forRequest(array $instances, array $containers, string $objective): ?array + public static function forRequest(array $instances, array $containers, string $objective, + ?PackingConfig $config = null): ?array { $order = ObjectiveBoundScope::order($containers, $objective); if ($order === null) { @@ -100,19 +110,79 @@ public static function forRequest(array $instances, array $containers, string $o } try { [$normalisedInstances, $normalisedContainers] = self::normalise($instances, $containers); + if (in_array($objective, self::BILLED_OBJECTIVES, true)) { + $normalisedContainers = self::withBilling($containers, $normalisedContainers, $config); + } return self::objectiveVector($normalisedInstances, $normalisedContainers, $order); - } catch (BoundOverflowException $refused) { + } catch (BoundOverflowException | BoundWithheldException $withheld) { return null; } } + /** + * Each type's normalised numbers with what a carrier can bill it, at the least. + * + * `tare` and `dimensional` are weight ticks: an opened container is billed + * `max(tare + payload, dimensional)`, so `max(tare, dimensional)` is its floor whatever it + * carries. A rigid container is billed on its declared outer size, else its declared inner + * one; a pallet whose load overhangs is billed larger per side, never smaller, and + * dimensional weight only grows with each side, so the declared size is a floor. A bag is + * billed on the package its contents make, which can be smaller than declared, so its + * floor is 0. `brackets` is the rate table as `[upper bound in weight ticks, charge]`, or + * empty where the objective prices nothing. `O(c b)` for `b` brackets per type. + * + * @param list $containers + * @param list> $normalised `normalise`'s containers, in the same order + * @return list> + */ + private static function withBilling(array $containers, array $normalised, ?PackingConfig $config): array + { + if ($config === null || $config->dimensionalWeightDivisor === null) { + throw new BoundWithheldException('a billed objective needs configuration.dimensional_weight_divisor'); + } + $landed = $config->objective === 'lowest_landed_cost'; + foreach ($containers as $index => $container) { + $normalised[$index]['tare'] = $container->tareWeight->ticks; + $normalised[$index]['dimensional'] = $container->isFlatBag() ? 0 + : ($container->outerDimensions ?? $container->declaredInner())->dimensionalWeight( + $config->dimensionalWeightDivisor, + $config->dimensionalWeightLengthUnit, + $config->dimensionalWeightWeightUnit, + )->ticks; + $normalised[$index]['brackets'] = $landed ? self::brackets($container) : []; + } + return $normalised; + } + + /** + * The rate table as `[bound in weight ticks, charge]`; the charge at a bracket's bound is + * that bracket's charge, since the bound is the heaviest weight it prices. + * + * @return list + */ + private static function brackets(Container $container): array + { + $table = $container->rateTable; + if ($table === null) { + return []; + } + return array_map(static function (int $bound) use ($table): array { + return [ + ExactInteger::mul($bound, Weight::TICKS_PER_G), + $table->chargeMinorOrNull($bound), + ]; + }, $table->weightBracketsG); + } + /** * 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. + * reads plus each instance's `value` -- and, for a billed objective, each container's + * `tare`, `dimensional` and `brackets` (`withBilling`) -- throwing `BoundOverflowException` + * where a ceiling withholds it, the one predicate's or the objective's own key's, and + * `BoundWithheldException` where a billed objective has no priceable answer to bound. * * @param list $instances - * @param list $containers + * @param list}> $containers * @param list $order an `OBJECTIVE_ORDERS` entry * @return list */ @@ -120,10 +190,10 @@ public static function objectiveVector(array $instances, array $containers, arra { $evaluated = self::evaluate($instances, $containers); $vector = $evaluated['vector']; - return array_map(static function ($position) use ($vector, $instances, $evaluated): int { + return array_map(static function ($position) use ($vector, $instances, $containers, $evaluated): int { return is_int($position) ? $vector[$position] - : self::objectiveTerm($position, $instances, $evaluated); + : self::objectiveTerm($position, $instances, $containers, $evaluated); }, $order); } @@ -137,17 +207,26 @@ public static function objectiveVector(array $instances, array $containers, arra * 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)`. + * the container types the request bound stays `O(n log n + c log c)`; the billed keys add + * `O(n + c b log n + c b log(c b))` for `b` brackets per type. * * @param list $instances - * @param array{vector:array{int,int,int,int,int},volumes:list,shrinks:bool,areas:list,capacity:?string} $evaluated + * @param list> $containers + * @param array{vector:array{int,int,int,int,int},volumes:list,weights:list,shrinks:bool,areas:list,capacity:?string} $evaluated */ - private static function objectiveTerm(string $name, array $instances, array $evaluated): int + private static function objectiveTerm(string $name, array $instances, array $containers, array $evaluated): int { - $unpacked = $evaluated['vector'][0]; + [$unpacked, $opened] = $evaluated['vector']; if ($name === 'value_forgone') { return self::valueForgoneBound(array_column($instances, 'value'), $unpacked); } + if ($name === 'billed_weight') { + return self::billedWeightBound($evaluated['weights'], $containers, $unpacked, $opened); + } + if ($name === 'landed_charge') { + return self::landedChargeBound($evaluated['weights'], $evaluated['volumes'], + $evaluated['shrinks'], $containers, $unpacked, $opened); + } if ($name === 'achieved_height') { return self::achievedHeightBound($evaluated['volumes'], $evaluated['shrinks'], count($instances) - $unpacked, $evaluated['areas']); @@ -156,6 +235,236 @@ private static function objectiveTerm(string $name, array $instances, array $eva $evaluated['capacity']); } + /** + * `shipping_cost`'s second key, summed billed weight in ticks. + * + * A packing that leaves exactly `$unpacked` behind opens at least `$opened` containers and + * carries at least the lightest `n - unpacked` instances. Each opened container is billed + * `max(tare + payload, dimensional)`, at least its floor, and a sum of maxima is at least + * either sum on its own, so the two can be taken over different types. Every term is + * non-negative, so opening more only adds. `O(n + c log c)`. + * + * @param list $weights ascending + * @param list> $containers + */ + private static function billedWeightBound(array $weights, array $containers, int $unpacked, int $opened): int + { + if ($opened === 0) { + return 0; + } + $quantities = array_map(static function (array $c): ?int { + return $c['quantity']; + }, $containers); + $floors = self::smallestFromInventory(array_map(\Closure::fromCallable([self::class, 'billedFloor']), $containers), $quantities, $opened); + $tares = self::smallestFromInventory( + array_map(static function (array $c) { + return $c['tare']; + }, $containers), $quantities, $opened); + if ($floors === null || $tares === null) { + throw new BoundWithheldException('the inventory holds fewer containers than must be opened'); + } + $payload = ExactInteger::normalize(self::sumBig(array_map(\Closure::fromCallable('strval'), + array_slice($weights, 0, count($weights) - $unpacked)))); + return self::guardOutput((string)ExactInteger::max($floors, ExactInteger::add($tares, $payload)), + 'billed weight'); + } + + /** + * `lowest_landed_cost`'s second key, the summed carrier charge in minor units. + * + * Every opened container is billed in exactly one bracket and pays its charge. A container + * in bracket `[bound, charge]` weighs at most `bound`, so it is reachable only when its + * floor is within it, carries at most `bound - tare` of payload (and its `max_payload`), + * and at most as many instances as the lightest-first count under that payload, its usable + * volume and `max_items`. Three relaxations of that assignment hold, and the largest is the + * bound: the cheapest reachable charge per container over `$opened` containers; the least + * cost covering the placed weight; the least cost covering the placed count. Prices need + * not rise with weight, which is why a bracket is chosen rather than read off the floor. A + * type no bracket prices offers nothing: a packing that opens one is refused, never + * returned. `O(n + c b log n + c b log(c b))` for `b` brackets per type: the two + * prefix sums, a binary search per bracket and one sort of the offers. + * + * @param list $weights ascending + * @param list $volumes ascending + * @param list> $containers + */ + private static function landedChargeBound(array $weights, array $volumes, bool $shrinks, + array $containers, int $unpacked, int $opened): int + { + $placed = count($weights) - $unpacked; + if ($opened === 0 || $placed === 0) { + return 0; + } + $payloadPrefix = self::prefixSums($weights); + $volumePrefix = $shrinks ? null : self::prefixSums($volumes); + $cheapest = []; + $quantities = []; + $offers = []; + foreach ($containers as $container) { + $floor = self::billedFloor($container); + $reachable = array_values(array_filter($container['brackets'], + static function (array $bracket) use ($floor): bool { + return $bracket[1] !== null + && ExactInteger::compare($floor, $bracket[0]) <= 0; + })); + if ($reachable === []) { + continue; + } + $cheapest[] = min(array_column($reachable, 1)); + $quantities[] = $container['quantity']; + // The volume limit is the type's, not the bracket's: asked once per type. + $roomy = $volumePrefix === null ? null + : self::fitPrefix($volumePrefix, ExactInteger::normalize($container['usable'])); + foreach ($reachable as [$bound, $charge]) { + $carried = ExactInteger::sub($bound, $container['tare']); + if ($container['payload'] !== null && ExactInteger::compare($container['payload'], $carried) < 0) { + $carried = $container['payload']; + } + $count = self::fitPrefix($payloadPrefix, $carried); + if ($roomy !== null) { + $count = min($count, $roomy); + } + if ($container['max_items'] !== null) { + $count = min($count, $container['max_items']); + } + $offers[] = [$charge, $carried, $count, $container['quantity']]; + } + } + $byCount = self::smallestFromInventory($cheapest, $quantities, $opened); + $byWeight = self::cover(array_map(static function (array $o): array { + return [$o[0], $o[1], $o[3]]; + }, $offers), + $payloadPrefix[$placed - 1]); + $byItems = self::cover(array_map(static function (array $o): array { + return [$o[0], $o[2], $o[3]]; + }, $offers), $placed); + if ($byCount === null || $byWeight === null || $byItems === null) { + throw new BoundWithheldException('no priceable inventory carries a packing that attains L0'); + } + return self::guardOutput((string)ExactInteger::max($byCount, ExactInteger::max($byWeight, $byItems)), + 'landed charge'); + } + + /** + * What one container is billed whatever it carries, `max(tare, dimensional)`. + * + * @param array $container + * @return int|string + */ + private static function billedFloor(array $container) + { + return ExactInteger::max($container['tare'], ExactInteger::normalize($container['dimensional'])); + } + + /** + * The sum of the `$count` smallest of `{value repeated quantity}`, or null when the + * inventory holds fewer. Sorting the types and taking `min(quantity, still needed)` of + * each is `L2`'s rule, `O(c log c)`, without building the multiset. + * + * @param list $values + * @param list $quantities + * @return int|string|null + */ + private static function smallestFromInventory(array $values, array $quantities, int $count) + { + $order = array_keys($values); + usort($order, static function (int $a, int $b) use ($values): int { + return ExactInteger::compare($values[$a], $values[$b]); + }); + $total = 0; + $needed = $count; + foreach ($order as $index) { + if ($needed === 0) { + break; + } + $quantity = $quantities[$index]; + $taken = $quantity === null ? $needed : min($quantity, $needed); + $total = ExactInteger::add($total, ExactInteger::mul($values[$index], $taken)); + $needed -= $taken; + } + return $needed > 0 ? null : $total; + } + + /** + * Running totals of ascending non-negative values, native for as long as they fit. + * + * @param list $ascending + * @return list + */ + private static function prefixSums(array $ascending): array + { + $totals = []; + $running = 0; + foreach ($ascending as $value) { + $running = ExactInteger::add($running, ExactInteger::normalize($value)); + $totals[] = $running; + } + return $totals; + } + + /** + * How many of the smallest values sum to at most `$capacity`, by binary search over their + * prefix sums: `O(log n)` per question. + * + * @param list $prefix ascending + * @param int|string $capacity + */ + private static function fitPrefix(array $prefix, $capacity): int + { + $low = 0; + $high = count($prefix); + while ($low < $high) { + $middle = intdiv($low + $high, 2); + if (ExactInteger::compare($prefix[$middle], $capacity) <= 0) { + $low = $middle + 1; + } else { + $high = $middle; + } + } + return $low; + } + + /** + * The least cost covering `$need` units from `[cost, capacity, quantity]` offers, taken + * fractionally and rounded up, or null when the offers cannot cover it. + * + * A fractional covering problem with one constraint is solved exactly by taking offers in + * order of cost per unit, compared by cross-multiplication. Only the last offer is taken + * in part, so the cost is an integer plus one ceiling and no fraction is carried. Offers + * of equal cost per unit give the same total in either order, so the order needs no + * tie-break. Each offer is limited by its type's whole inventory, which only weakens the + * bound. `O(k log k)` for `k` offers. + * + * @param list $offers + * @param int|string $need + * @return int|string|null + */ + private static function cover(array $offers, $need) + { + if (ExactInteger::sign($need) <= 0) { + return 0; + } + $ranked = array_values(array_filter($offers, + static function (array $offer): bool { + return ExactInteger::sign($offer[1]) > 0; + })); + usort($ranked, static function (array $a, array $b): int { + return ExactInteger::compare( + ExactInteger::mul($a[0], $b[1]), ExactInteger::mul($b[0], $a[1])); + }); + $total = 0; + foreach ($ranked as [$cost, $capacity, $quantity]) { + if ($quantity === null || ExactInteger::compare(ExactInteger::mul($quantity, $capacity), $need) >= 0) { + // ceil(cost * need / capacity), as the negated floor of its negation. + return ExactInteger::add($total, ExactInteger::negate(ExactInteger::floorDiv( + ExactInteger::negate(ExactInteger::mul($cost, $need)), $capacity))); + } + $total = ExactInteger::add($total, ExactInteger::mul($cost, $quantity)); + $need = ExactInteger::sub($need, ExactInteger::mul($capacity, $quantity)); + } + return null; + } + /** * `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 @@ -403,12 +712,12 @@ public static function fromNormalised(array $instances, array $containers): arra /** * `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). + * than recompute: the ascending volumes and weights, 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} + * @return array{vector:array{int,int,int,int,int},volumes:list,weights:list,shrinks:bool,areas:list,capacity:?string} */ private static function evaluate(array $instances, array $containers): array { @@ -477,7 +786,7 @@ private static function evaluate(array $instances, array $containers): array self::guardOutput((string)$unused, 'unused volume'), self::guardOutput((string)$height, 'stack height'), ]; - return ['vector' => $vector, 'volumes' => $volumes, 'shrinks' => $shrinks, + return ['vector' => $vector, 'volumes' => $volumes, 'weights' => $weights, 'shrinks' => $shrinks, 'areas' => $areas, 'capacity' => $capacities['volume']]; } diff --git a/src-legacy/Algorithm/SolverOrchestrator.php b/src-legacy/Algorithm/SolverOrchestrator.php index c2a04e8..82ddcf3 100644 --- a/src-legacy/Algorithm/SolverOrchestrator.php +++ b/src-legacy/Algorithm/SolverOrchestrator.php @@ -37,6 +37,8 @@ final class SolverOrchestrator * (`...:late_:beam`), as Python's `LATE_TYPE_REFINEMENT_WIDTH`. */ private const LATE_TYPE_REFINEMENT_WIDTH=4; + /** @var array{config:PackingConfig,packed:list,states:array,verdicts:array}|null */ + private $supportDiagnostic; public function __construct(array $customConstraints=[], array $customOrders=[], array $customSolvers=[], ?CandidateScorer $candidateScorer=null, ?ContainerSelector $containerSelector=null) { $this->customConstraints = $customConstraints; @@ -256,12 +258,13 @@ function ($i) use ($containers) { } /** - * Whether one box of these dimensions fits this container empty: the frame, and for a flat - * bag the girth rule too, so a bag too thin for an item proves it unplaceable. + * Whether one box of these dimensions fits this container empty: the frame, and for a bag + * the girth rule too, so a bag too thin for an item proves it unplaceable. */ private static function fitsAlone(Container $container,Dimensions $dimensions):bool { - return $container->isFlatBag()?FlatBag::fitsAlone($container->innerDimensions,$dimensions,$container->sideGussetTicks()):$dimensions->fitsInside($container->innerDimensions); + $girth=$container->girth(); + return $girth!==null?FlatBag::fitsAlone($container->innerDimensions,$dimensions,$girth):$dimensions->fitsInside($container->innerDimensions); } /** @param list $containers */ @@ -389,6 +392,18 @@ private static function axlesAdmitAlone(Container $container,array $envelopes,in * @param list $packed */ private function supportIsTheBlocker(ItemInstance $item,array $packed,PackingConfig $config):bool + { + // The answer is a function of the item's declared attributes and the final layout, + // so every instance of a type shares one verdict -- unless a caller's own constraint + // or scorer may read the instance itself, in which case each instance is asked. + // The packed-container states are likewise built once per layout, not once per item. + if($this->supportDiagnostic===null||$this->supportDiagnostic['config']!==$config||$this->supportDiagnostic['packed']!==$packed) + $this->supportDiagnostic=['config'=>$config,'packed'=>$packed,'states'=>[],'verdicts'=>[]]; + $key=$this->customConstraints===[]&&$this->candidateScorer===null?$item->item->id:$item->id(); + return $this->supportDiagnostic['verdicts'][$key] = $this->supportDiagnostic['verdicts'][$key] ?? $this->observeSupportBlocker($item,$config); + } + + private function observeSupportBlocker(ItemInstance $item,PackingConfig $config):bool { $constraints=ConstraintSet::defaults($config->minimumSupportRatio,$this->customConstraints,$config->accessDirections); $hasSupport=false; @@ -399,20 +414,33 @@ private function supportIsTheBlocker(ItemInstance $item,array $packed,PackingCon return !($c instanceof SupportConstraint); })); $scorer=$this->candidateScorer??new DefaultCandidateScorer(); - // A small, fixed local budget -- independent of the caller's own deadline, - // which may already be exhausted -- so this diagnostic can never itself hang - // the solve; it is a best-effort explanation, not a required step. - $budget=Deadline::ofMilliseconds(2000); - foreach($packed as $packedContainer){ - if($budget->expired())return false; - $state=new ContainerState($packedContainer->container,$packedContainer->sequence); - foreach($packedContainer->placements as $placement)$state->add($placement); - if(CandidateFinder::find($state,$item,$config,$withoutSupport,new SearchStats(),$budget,$scorer,1)===[])continue; - if(CandidateFinder::find($state,$item,$config,$constraints,new SearchStats(),$budget,$scorer,1)===[])return true; + // No wall clock: the reason an item is reported unpacked must be a function of the + // request and the layout, never of machine load. A frozen clock leaves nothing to + // expire; the search is bounded by the layout's own candidate points (max one + // candidate wanted), and `supportIsTheBlocker` memoises one verdict per item type. + $budget=new Deadline(PHP_INT_MAX,static function (): int { + return 0; + }); + try{ + foreach($this->supportDiagnostic['packed'] as $index=>$packedContainer){ + $state=($this->supportDiagnostic['states'][$index] = $this->supportDiagnostic['states'][$index] ?? self::replayedState($packedContainer)); + if(CandidateFinder::find($state,$item,$config,$withoutSupport,new SearchStats(),$budget,$scorer,1)===[])continue; + if(CandidateFinder::find($state,$item,$config,$constraints,new SearchStats(),$budget,$scorer,1)===[])return true; + } + }catch(TimeLimitReached $exception){ + // Only a caller's own scorer or constraint can raise it now; no verdict, as before. + return false; } return false; } + private static function replayedState(PackedContainer $packedContainer):ContainerState + { + $state=new ContainerState($packedContainer->container,$packedContainer->sequence); + foreach($packedContainer->placements as $placement)$state->add($placement); + return $state; + } + /** * The block start `fast` and `balanced` add to their own, or `null`. * @@ -654,7 +682,7 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem $billed=max($gross,$dimensional); $placed=$one->state->placementCount(); if($config->objective==='shipping_cost'){ - $candidateScore=[-$placed,$billed,$container->id]; + $candidateScore=[-$placed,$billed,StableSorter::textKey($container->id)]; }else{ // Landed cost ranks the round by the money the finished score will // charge, not by the grams it is derived from. This loop commits the @@ -669,7 +697,7 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem $charge??LandedCostSolutionScorer::UNPRICEABLE_MINOR, intdiv(count($roundItems)+max($placed,1)-1,max($placed,1)), -$placed, - $container->id, + StableSorter::textKey($container->id), ]; } }elseif($config->objective==='maximum_volume'&&$selector instanceof DefaultContainerSelector){ @@ -679,7 +707,7 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem $leftover=BigInt::chunks(BigInt::subtract($container->innerDimensions->volumeString(),$used)); $candidateScore=array_merge(array_map(static function (int $c): int { return -$c; - },BigInt::chunks($used)), [$container->costMinor], $leftover, [$container->id]); + },BigInt::chunks($used)), [$container->costMinor], $leftover, [StableSorter::textKey($container->id)]); }else{ $candidateScore=$selector->score($container,$one); } @@ -731,7 +759,7 @@ private function acrossContainers(SingleContainerSolver $solver,array $items,arr return $c->quantity??count($items); },$containers)); $ordered=StableSorter::sortBy($containers,static function (Container $c): array { - return array_merge([$c->costMinor], $c->innerDimensions->volumeKey(), [$c->id]); + return array_merge([$c->costMinor], $c->innerDimensions->volumeKey(), [StableSorter::textKey($c->id)]); }); $selector=$this->containerSelector??new DefaultContainerSelector(); while($remaining!==[]&&count($packed)<$maximum&&!$reached){ diff --git a/src-legacy/Algorithm/WeightRebalancer.php b/src-legacy/Algorithm/WeightRebalancer.php index 41a5a18..cb38098 100644 --- a/src-legacy/Algorithm/WeightRebalancer.php +++ b/src-legacy/Algorithm/WeightRebalancer.php @@ -87,7 +87,17 @@ public static function rebalance( } $validator = new IndependentSolutionValidator(); $deadline = Deadline::ofMilliseconds($timeLimitMs); - $working = array_values($containers); + // A compact lattice container carries no per-item placements; the pass below + // reads and moves individual placements, so expand it the way Packer does + // before validation. + $working = array_map( + static function (PackedContainer $c): PackedContainer { + return $c->latticeSummary !== null + ? new PackedContainer($c->container, $c->sequence, $c->expandPlacements()) + : $c; + }, + array_values($containers), + ); $moves = []; for ($round = 0; $round < $maxMoves; $round++) { @@ -104,7 +114,8 @@ public static function rebalance( $sourceIndex = self::argMax($weights); $source = $working[$sourceIndex]; - $rankedItems = range(0, count($source->placements) - 1); + // Not `range(0, count - 1)`: for an empty container PHP's range counts down to [0, -1]. + $rankedItems = $source->placements === [] ? [] : range(0, count($source->placements) - 1); usort($rankedItems, static function (int $a, int $b) use ($source): int { return ($source->placements[$b]->instance->weight()->ticks <=> $source->placements[$a]->instance->weight()->ticks) ?: ($a <=> $b); @@ -164,7 +175,8 @@ static function (int $i) use ($sourceIndex): bool { $working = $trial; } - return new RebalanceResult($working, $moves); + // Nothing moved: hand back the containers as given, compact ones still compact. + return new RebalanceResult($moves === [] ? array_values($containers) : $working, $moves); } /** diff --git a/src-legacy/Artifacts/OperationalArtifact.php b/src-legacy/Artifacts/OperationalArtifact.php index 7561c3c..49383e2 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.10.0'; + public const SUITE_VERSION = '1.11.0'; /** The deterministic part of `result.algorithm`; `duration_ms` is wall-clock time. */ private const SOLVER_FIELDS = ['profile', 'solver', 'seed', 'time_limit_reached', 'effort_limit_reached']; diff --git a/src-legacy/Commerce/Document.php b/src-legacy/Commerce/Document.php index 458c7e6..9329a8b 100644 --- a/src-legacy/Commerce/Document.php +++ b/src-legacy/Commerce/Document.php @@ -102,8 +102,17 @@ private static function publishTariffVersions(CarrierRegistry $registry, string ['minimum_charge_minor', 'fuel_surcharge_permille', 'accessorials'], ); $costs = []; - foreach (Shape::map($fields['cost_per_dimensional_kg_minor'], "{$path}.cost_per_dimensional_kg_minor") as $zone => $cost) { - $costs[(string)$zone] = Shape::integer($cost, "{$path}.cost_per_dimensional_kg_minor[{$zone}]"); + $zones = Shape::map($fields['cost_per_dimensional_kg_minor'], "{$path}.cost_per_dimensional_kg_minor"); + // Validated in code-point order of the zone key (PHP turns numeric-looking keys into ints), + // so the first error never depends on the order a language iterates the mapping in. + $zoneKeys = array_map('strval', array_keys($zones)); + usort($zoneKeys, 'strcmp'); + foreach ($zoneKeys as $zone) { + Shape::integer($zones[$zone], "{$path}.cost_per_dimensional_kg_minor[{$zone}]"); + } + // Insertion order is kept for the tariff itself. + foreach ($zones as $zone => $cost) { + $costs[(string)$zone] = $cost; } Shape::model($path, static function () use ($registry, $carrierId, $serviceId, $fields, $path, $costs) { return $registry->publish( diff --git a/src-legacy/Commerce/Rating/AccessorialCharge.php b/src-legacy/Commerce/Rating/AccessorialCharge.php index 01eb826..5035b37 100644 --- a/src-legacy/Commerce/Rating/AccessorialCharge.php +++ b/src-legacy/Commerce/Rating/AccessorialCharge.php @@ -41,8 +41,12 @@ public function __construct( if ($permilleOfBase !== null && $permilleOfBase < 0) { throw new \InvalidArgumentException('permille_of_base cannot be negative'); } } - public function chargeMinor(int $baseChargeMinor): int + /** + * @param int|string $baseChargeMinor + * @return int|string + */ + public function chargeMinor($baseChargeMinor) { - return $this->flatChargeMinor ?? Arithmetic::mulDivCeil($baseChargeMinor, (int)$this->permilleOfBase, 1000); + return $this->flatChargeMinor ?? Arithmetic::mulDivCeilExact($baseChargeMinor, (int)$this->permilleOfBase, 1000); } } diff --git a/src-legacy/Commerce/Rating/CarrierRegistry.php b/src-legacy/Commerce/Rating/CarrierRegistry.php index 6a0e595..c01babd 100644 --- a/src-legacy/Commerce/Rating/CarrierRegistry.php +++ b/src-legacy/Commerce/Rating/CarrierRegistry.php @@ -2,7 +2,10 @@ declare(strict_types=1); namespace Packvium\Commerce\Rating; +use Packvium\Commerce\CommerceInputException; use Packvium\Support\Arithmetic; +use Packvium\Support\CanonicalJson; +use Packvium\Support\ExactInteger; /** * Per-(carrier_id, service_id) append-only tariff history, and the rating itself. @@ -111,33 +114,53 @@ public static function rateTariff(Tariff $tariff, RatingRequest $request): RateB throw new UnavailableServiceException("tariff {$tariff->carrierId}/{$tariff->serviceId} v{$tariff->version} does not offer requested accessorial(s)", null, $unknown); } - // 1 mm^3 of volume divided by the tariff's divisor gives dimensional weight in - // grams, rounded up -- never down, never through a float. - $dimensionalWeightG = Arithmetic::mulDivCeil($request->volumeMm3, 1, $tariff->dimensionalWeightDivisor); - $billedWeightG = max($request->actualWeightG, $dimensionalWeightG); + // Every amount is computed exactly and then held to the one ceiling an engine can + // report without rounding (M2): the first reported amount above it refuses the quote. + $dimensionalWeightG = Arithmetic::mulDivCeilExact($request->volumeMm3, 1, $tariff->dimensionalWeightDivisor); + $billedWeightG = ExactInteger::max($request->actualWeightG, $dimensionalWeightG); - $rawBaseChargeMinor = Arithmetic::mulDivCeil($billedWeightG, $tariff->costPerDimensionalKgMinor[$request->zone], 1000); - $minimumApplied = $rawBaseChargeMinor < $tariff->minimumChargeMinor; + $rawBaseChargeMinor = Arithmetic::mulDivCeilExact($billedWeightG, $tariff->costPerDimensionalKgMinor[$request->zone], 1000); + $minimumApplied = ExactInteger::compare($rawBaseChargeMinor, $tariff->minimumChargeMinor) < 0; $baseChargeMinor = $minimumApplied ? $tariff->minimumChargeMinor : $rawBaseChargeMinor; - - $fuelSurchargeMinor = Arithmetic::mulDivCeil($baseChargeMinor, $tariff->fuelSurchargePermille, 1000); + $fuelSurchargeMinor = Arithmetic::mulDivCeilExact($baseChargeMinor, $tariff->fuelSurchargePermille, 1000); $accessorialCharges = []; $accessorialTotal = 0; foreach ($request->requestedAccessorials as $accessorialId) { $amount = $tariff->accessorials[$accessorialId]->chargeMinor($baseChargeMinor); $accessorialCharges[] = [$accessorialId, $amount]; - $accessorialTotal += $amount; + $accessorialTotal = ExactInteger::add($accessorialTotal, $amount); + } + $totalMinor = ExactInteger::add(ExactInteger::add($baseChargeMinor, $fuelSurchargeMinor), $accessorialTotal); + + $reported = [$dimensionalWeightG, $billedWeightG, $baseChargeMinor, $fuelSurchargeMinor]; + foreach ($accessorialCharges as [, $amount]) { + $reported[] = $amount; + } + $reported[] = $totalMinor; + foreach ($reported as $value) { + self::requireReportable($value); } return new RateBreakdown( $tariff->carrierId, $tariff->serviceId, $tariff->version, $request->zone, $request->actualWeightG, $dimensionalWeightG, $billedWeightG, $baseChargeMinor, - $minimumApplied, $fuelSurchargeMinor, $accessorialCharges, - $baseChargeMinor + $fuelSurchargeMinor + $accessorialTotal, + $minimumApplied, $fuelSurchargeMinor, $accessorialCharges, $totalMinor, ); } + /** + * @param int|string $value + */ + private static function requireReportable($value): void + { + if (ExactInteger::compare($value, CanonicalJson::MAX_EXACT_MAGNITUDE) > 0) { + throw new CommerceInputException( + "quote amount {$value} is above " . CanonicalJson::MAX_EXACT_MAGNITUDE . ' and cannot be represented exactly' + ); + } + } + private static function key(string $carrierId, string $serviceId): string { return strlen($carrierId) . ':' . $carrierId . $serviceId; diff --git a/src-legacy/Constraint/StopAccessibilityConstraint.php b/src-legacy/Constraint/StopAccessibilityConstraint.php index 39c3ee2..781b8af 100644 --- a/src-legacy/Constraint/StopAccessibilityConstraint.php +++ b/src-legacy/Constraint/StopAccessibilityConstraint.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use InvalidArgumentException; +use Packvium\Domain\AxisAlignedBox; use Packvium\Domain\Dimensions; use Packvium\Domain\Placement; use Packvium\Domain\SweptRegion; @@ -48,6 +49,14 @@ final class StopAccessibilityConstraint implements PlacementConstraint private $clear=[]; /** @var list */ private $stops=[]; + /** @var list */ + private $boxes=[]; + /** @var list> */ + private $sweeps=[]; + /** + * @var bool + */ + private $stopsVary=false; /** @param list $directions */ public function __construct(array $directions=[]) @@ -96,6 +105,10 @@ private static function stopOf(Placement $p) * with different doors have different answers for the same boxes, and nothing else in * the key separates them. * + * The same entry holds what only depends on those placements: their envelope boxes, the + * region each finite-stop box sweeps towards each door, and whether their stops differ. + * A placement is immutable, so none of it can go stale while the key holds. + * * @param list $placements * @param list $directions * @return array{0:list>,1:list} @@ -105,15 +118,15 @@ private function baseFor(array $placements,Dimensions $container,array $directio if($this->placements===$placements&&$this->container==$container&&$this->directions===$directions)return [$this->clear,$this->stops]; $stops=[];$boxes=[]; foreach($placements as $p){$stops[]=self::stopOf($p);$boxes[]=$p->envelopeBox();} - $clear=[]; + $clear=[];$sweeps=[]; foreach($boxes as $index=>$box){ - $open=[]; + $open=[];$swept=[]; if($stops[$index]===INF){ // Never unloaded, so it needs no door of its own -- it only ever blocks. foreach($directions as $d)$open[$d]=true; }else{ foreach($directions as $d){ - $sweep=SweptRegion::volume($box,$container,$d); + $sweep=$swept[$d]=SweptRegion::volume($box,$container,$d); $blocked=false; foreach($boxes as $other=>$otherBox){ if($other!==$index&&$stops[$other]>$stops[$index]&&SweptRegion::intersects($sweep,$otherBox)){$blocked=true;break;} @@ -121,9 +134,11 @@ private function baseFor(array $placements,Dimensions $container,array $directio if(!$blocked)$open[$d]=true; } } - $clear[]=$open; + $clear[]=$open;$sweeps[]=$swept; } $this->placements=$placements;$this->container=$container;$this->directions=$directions;$this->clear=$clear;$this->stops=$stops; + $this->boxes=$boxes;$this->sweeps=$sweeps; + $this->stopsVary=count(array_unique($stops,SORT_REGULAR))>1; return [$clear,$stops]; } @@ -155,8 +170,7 @@ public function evaluate(ConstraintContext $c):ConstraintResult // One distinct stop means nothing can be due before anything else, so no corridor // can be blocked by a later item. Checked over the candidate too, or the first // placement into an empty container would skip a check it should make. - $distinct=$stops;$distinct[]=$candidateStop; - if(count(array_unique($distinct,SORT_REGULAR))<2)return ConstraintResult::allow(); + if(!$this->stopsVary&&($stops===[]||$candidateStop===$stops[0]))return ConstraintResult::allow(); $candidate=$c->envelopeBox(); foreach($c->placements as $index=>$placement){ @@ -164,7 +178,7 @@ public function evaluate(ConstraintContext $c):ConstraintResult if($clear[$index]===[])continue; $stillOpen=false; foreach(array_keys($clear[$index]) as $d){ - if(!SweptRegion::intersects(SweptRegion::volume($placement->envelopeBox(),$inner,$d),$candidate)){$stillOpen=true;break;} + if(!SweptRegion::intersects($this->sweeps[$index][$d],$candidate)){$stillOpen=true;break;} } if(!$stillOpen){ $stop=$stops[$index]; @@ -177,8 +191,8 @@ public function evaluate(ConstraintContext $c):ConstraintResult foreach($directions as $d){ $sweep=SweptRegion::volume($candidate,$inner,$d); $blocked=false; - foreach($c->placements as $other=>$placement){ - if($stops[$other]>$candidateStop&&SweptRegion::intersects($sweep,$placement->envelopeBox())){$blocked=true;break;} + foreach($this->boxes as $other=>$otherBox){ + if($stops[$other]>$candidateStop&&SweptRegion::intersects($sweep,$otherBox)){$blocked=true;break;} } if(!$blocked)return ConstraintResult::allow(); } diff --git a/src-legacy/Domain/Container.php b/src-legacy/Domain/Container.php index c1da598..2d2efd8 100644 --- a/src-legacy/Domain/Container.php +++ b/src-legacy/Domain/Container.php @@ -117,6 +117,21 @@ final class Container * @var \Packvium\Unit\Length|null */ public $sideGussetDepth; + /** + * @readonly + * @var \Packvium\Unit\Length|null + */ + public $bottomGussetDepth; + /** + * @readonly + * @var string + */ + public $bagOrientation = 'flat'; + /** + * @readonly + * @var bool + */ + public $uprightFrame = false; /** * Which walls this container can be unloaded through. * @@ -144,8 +159,14 @@ final class Container * * `$deformableBoundary`: `'flat_bag'` makes this a flexible bag whose package conforms to its * 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. + * `$sideGussetDepth` (1.10) and whose length girth is lengthened by `$bottomGussetDepth` + * (1.11): that kind declares either or both, and every other container refuses + * them. null is a rigid container. + * + * `$bagOrientation`: `'flat'` or `'standing'`: a gusseted bag with a bottom gusset + * may stand on it. `$uprightFrame`: set only by `PalletOverhang::solvingFrame`, whose + * `$innerDimensions` is then the standing W x H x L frame, which `declaredInner` turns back. + * A frame is never turned twice. * * `$palletOverhangLimit`: how far a load may pass this pallet deck's edges (, * `PalletOverhang`). `$deck`: the deck inside a solving frame, set only by @@ -154,7 +175,7 @@ final class Container * * @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,?OverhangLimit $palletOverhangLimit=null,?Deck $deck=null,?Length $sideGussetDepth=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,?Length $bottomGussetDepth=null,string $bagOrientation='flat',bool $uprightFrame=false) {$tareWeight = $tareWeight ?? new Weight(0); $this->id = $id; $this->innerDimensions = $innerDimensions; @@ -178,7 +199,10 @@ public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $ $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"); + $this->bottomGussetDepth = $bottomGussetDepth; + $this->bagOrientation = $bagOrientation; + $this->uprightFrame = $uprightFrame; + 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,self::declaredInnerOf($innerDimensions,$deck,$uprightFrame),$sideGussetDepth,$bottomGussetDepth,$bagOrientation,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio,$palletOverhangLimit);else self::refuseGussetFields($sideGussetDepth,$bottomGussetDepth,$bagOrientation);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,$uprightFrame)->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 @@ -187,10 +211,26 @@ 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,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth);} + 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,$this->bottomGussetDepth,$this->bagOrientation,$this->uprightFrame);} 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 bottom gusset depth K in ticks; 0 where none is declared. */ + public function bottomGussetTicks():int{return $this->bottomGussetDepth===null?0:$this->bottomGussetDepth->ticks;} + /** A bag's two loops in the frame it is packed in; null for a rigid container. */ + public function girth():?Girth + { + if($this->deformableBoundary===null)return null; + $declared=$this->declaredInner(); + return FlatBag::girthFor($declared->length->ticks,$declared->width->ticks,$this->sideGussetTicks(),$this->bottomGussetTicks(),$this->uprightFrame); + } + /** + * The same bag packed in its standing W x H x L frame: how `PalletOverhang` builds a + * standing bag's solving frame. O(1). + * + * @internal + */ + public function upright():self{return new self($this->id,FlatBag::standingDimensions($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,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth,$this->bottomGussetDepth,$this->bagOrientation,true);} /** * 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 @@ -198,10 +238,17 @@ public function sideGussetTicks():int{return $this->sideGussetDepth===null?0:$th * * @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);} + 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,$this->bottomGussetDepth,$this->bagOrientation,$this->uprightFrame);} + /** + * The inner size the caller declared: a solving frame's deck at its height, a standing bag's + * frame turned back to L x W x H, else `innerDimensions`. + */ + public function declaredInner():Dimensions{return self::declaredInnerOf($this->innerDimensions,$this->deck,$this->uprightFrame);} + private static function declaredInnerOf(Dimensions $inner,?Deck $deck,bool $uprightFrame):Dimensions + { + if($uprightFrame)return new Dimensions($inner->height,$inner->length,$inner->width); + 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);} /** @@ -224,7 +271,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,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth);} + 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,$this->bottomGussetDepth,$this->bagOrientation,$this->uprightFrame);} /** @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]));} /** @@ -234,26 +281,40 @@ 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,Dimensions $inner,?Length $sideGussetDepth,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio,?OverhangLimit $palletOverhangLimit):void + private static function requireBagFields(string $kind,Dimensions $declared,?Length $sideGussetDepth,?Length $bottomGussetDepth,string $bagOrientation,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}"); - self::requireGussetRule($kind===FlatBag::GUSSETED_BAG,$inner,$sideGussetDepth); + self::requireGussetRule($kind===FlatBag::GUSSETED_BAG,$declared,$sideGussetDepth,$bottomGussetDepth,$bagOrientation); $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). + * Gusset depths and a standing orientation describe a gusseted bag and nothing else. `'flat'` + * is `FlatBag::FLAT` spelled out, so a rigid container never loads `FlatBag`. + */ + private static function refuseGussetFields(?Length $sideGussetDepth,?Length $bottomGussetDepth,string $bagOrientation):void + { + $present=['side_gusset_depth'=>$sideGussetDepth!==null,'bottom_gusset_depth'=>$bottomGussetDepth!==null,'orientation'=>$bagOrientation!=='flat']; + foreach($present as $name=>$set)if($set)throw new ObjectRefusal('not_allowed',"{$name} requires deformable_boundary gusseted_bag"); + } + /** + * A gusseted bag declares a side gusset, a bottom gusset or both, each positive. A side + * gusset is no deeper than the bag is wide and a bottom one no deeper than twice its length: + * a deeper fold would have no flat sheet left to fold from. Standing needs a bottom gusset to + * stand on. A flat bag takes none of them. O(1). */ - private static function requireGussetRule(bool $gusseted,Dimensions $inner,?Length $sideGussetDepth):void + private static function requireGussetRule(bool $gusseted,Dimensions $declared,?Length $sideGussetDepth,?Length $bottomGussetDepth,string $bagOrientation):void { - if($sideGussetDepth===null){ - if($gusseted)throw new ObjectRefusal('missing_field','a gusseted_bag requires side_gusset_depth'); - return; + if(!$gusseted){self::refuseGussetFields($sideGussetDepth,$bottomGussetDepth,$bagOrientation);return;} + if($sideGussetDepth===null&&$bottomGussetDepth===null)throw new ObjectRefusal('missing_field','a gusseted_bag requires side_gusset_depth'); + $folds=[['side_gusset_depth',$sideGussetDepth,$declared->width->ticks,'inner_dimensions width'],['bottom_gusset_depth',$bottomGussetDepth,2*$declared->length->ticks,'twice inner_dimensions length']]; + foreach($folds as [$name,$depth,$limit,$what]){ + if($depth===null)continue; + if($depth->ticks<=0)throw new ObjectRefusal('invalid_value',"{$name} must be positive"); + if($depth->ticks>$limit)throw new ObjectRefusal('invalid_value',"{$name} exceeds {$what}"); } - 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'); + if(!in_array($bagOrientation,FlatBag::ORIENTATIONS,true))throw new ObjectRefusal('not_allowed',"orientation must be one of ['flat', 'standing']"); + if($bagOrientation===FlatBag::STANDING&&$bottomGussetDepth===null)throw new ObjectRefusal('missing_field','bottom_gusset_depth is required when orientation is standing'); } /** * The fields a pallet with an overhang limit refuses: each reads the declared frame or a wall @@ -272,5 +333,5 @@ private static function requirePalletFields(array $obstacles,?array $axles,array * @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,?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);} + 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,?Length $bottomGussetDepth=null,string $bagOrientation='flat'):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,$bottomGussetDepth,$bagOrientation);} } diff --git a/src-legacy/Domain/FlatBag.php b/src-legacy/Domain/FlatBag.php index d1f7e24..5691e90 100644 --- a/src-legacy/Domain/FlatBag.php +++ b/src-legacy/Domain/FlatBag.php @@ -17,24 +17,61 @@ * * 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. + * b + c <= W + G, and G = 0 is the flat bag. Every method here takes the gusset depths in + * ticks, 0 where none is declared. + * + * A bottom gusset (1.11) is one panel of depth K folded into the closed end: the loop + * along the bag runs front, bottom, back, 2L + K, so the length sum becomes 2(a + c) <= 2L + K, + * doubled to stay in integers. A gusseted bag with a bottom gusset may stand on it + * (`orientation: standing`): the solving frame is then W x H x L, the floor is the opened + * bottom, and the same two loops go round other axes -- a + b <= W + G across, 2(b + c) <= 2L + K + * along. `Girth` holds the two loops for either frame. */ final class FlatBag { public const GUSSETED_BAG='gusseted_bag'; public const KINDS=['flat_bag',self::GUSSETED_BAG]; + public const FLAT='flat'; + public const STANDING='standing'; + public const ORIENTATIONS=[self::FLAT,self::STANDING]; + /** The keys a gusseted bag's boundary may carry (1.10 side gusset; 1.11 bottom gusset and orientation). */ + public const GUSSETED_BAG_FIELDS=['bottom_gusset_depth','kind','orientation','side_gusset_depth']; - /** 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,int $gusset=0):bool + /** + * Whether a package of extents (a, b, c) passes both girth sums of a bag lying flat in + * `$inner`; the frame is the caller's. + */ + public static function girthAdmits(Dimensions $inner,int $a,int $b,int $c,int $gusset=0,int $bottomGusset=0):bool { - return $a+$c<=$inner->length->ticks&&$b+$c<=$inner->width->ticks+$gusset; + return self::girthFor($inner->length->ticks,$inner->width->ticks,$gusset,$bottomGusset,false)->admits([$a,$b,$c]); } - /** 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 + /** + * The loops of a bag declared `$length x $width` with the two gusset depths, 0 where none is + * declared, in its flat or standing frame. O(1). + */ + public static function girthFor(int $length,int $width,int $sideGusset,int $bottomGusset,bool $standing):Girth + { + if($standing)return new Girth([1,2],2*$length+$bottomGusset,[0,1],$width+$sideGusset); + return new Girth([0,2],2*$length+$bottomGusset,[1,2],$width+$sideGusset); + } + + /** The W x H x L frame a bag declared L x W x H stands in. */ + public static function standingDimensions(Dimensions $declared):Dimensions + { + return new Dimensions($declared->width,$declared->height,$declared->length); + } + + /** + * Whether one box of these dimensions, alone at the origin of the frame `$inner`, fits a bag: + * against its `Girth`, or lying flat with a side gusset of `$gusset` ticks. The parameter keeps + * its 1.10 name, which a named argument may spell. + * @param int|\Packvium\Domain\Girth $gusset + */ + public static function fitsAlone(Dimensions $inner,Dimensions $box,$gusset=0):bool { - return $box->fitsInside($inner)&&self::girthAdmits($inner,$box->length->ticks,$box->width->ticks,$box->height->ticks,$gusset); + $girth=$gusset instanceof Girth?$gusset:self::girthFor($inner->length->ticks,$inner->width->ticks,$gusset,0,false); + return $box->fitsInside($inner)&&$girth->admits([$box->length->ticks,$box->width->ticks,$box->height->ticks]); } /** diff --git a/src-legacy/Domain/Girth.php b/src-legacy/Domain/Girth.php new file mode 100644 index 0000000..161ad6a --- /dev/null +++ b/src-legacy/Domain/Girth.php @@ -0,0 +1,53 @@ +along = $along; + $this->alongLimit = $alongLimit; + $this->across = $across; + $this->acrossLimit = $acrossLimit; + } + + /** + * Whether a package of extents (a, b, c) passes both loops. The rigid boundary is the + * caller's own check and stays where it already is; only the two sums are new. O(1). + * + * @param array{0:int,1:int,2:int} $extent + */ + public function admits(array $extent):bool + { + return 2*($extent[$this->along[0]]+$extent[$this->along[1]])<=$this->alongLimit + &&$extent[$this->across[0]]+$extent[$this->across[1]]<=$this->acrossLimit; + } +} diff --git a/src-legacy/Domain/HullShape.php b/src-legacy/Domain/HullShape.php index 248248a..6a15857 100644 --- a/src-legacy/Domain/HullShape.php +++ b/src-legacy/Domain/HullShape.php @@ -4,6 +4,7 @@ use InvalidArgumentException; use Packvium\Support\BigInt; +use Packvium\Support\ObjectRefusal; use Packvium\Support\SignedBigInt; /** @@ -61,6 +62,17 @@ final class HullShape /** Smallest number of vertices that can enclose a volume. */ public const MINIMUM_VERTICES = 4; + /** Most vertices an item's hull may list; refused at admission, before any per-vertex work. */ + public const MAXIMUM_VERTICES = 32; + + /** @throws ObjectRefusal */ + public static function admitVertexCount(int $count): void + { + if ($count > self::MAXIMUM_VERTICES) { + throw new ObjectRefusal('above_maximum', 'hull_vertices must have at most ' . self::MAXIMUM_VERTICES . ' vertices'); + } + } + /** Both the face normals and the edge directions of any axis-aligned box. */ private const UNIT_AXES = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]; @@ -103,6 +115,37 @@ private function __construct(array $vertices, array $faceAxes, array $edgeDirect /** @var array */ private static $shapeCache = []; + /** + * How many separating axes the pair memo holds, before it is dropped and refilled -- the + * policy of the shape memo above. Counted in axes rather than pairs because a pair's size + * is the product of its shapes' edge counts: a 32-vertex pair is about 3900 axes and 1 MB, + * a box against a hull a few dozen. This ceiling is about 8 MB, under the shape memo's. + */ + private const PAIR_CACHE_AXES = 16384; + + /** Axis structure of every `box()`: its face normals and edge directions are always the unit axes. */ + private const BOX_STRUCTURE = -1; + + /** Next axis structure id handed to a memoised hull; ids are never reused, so a stale entry can only be unreachable. + * @var int */ + private static $nextStructure = 1; + + /** @var array,left:array,right:array}> */ + private static $pairCache = []; + + /** + * @var int + */ + private static $pairCacheAxes = 0; + + /** + * Identifies the face normals and edge directions this shape contributes to a pair's axes: + * a `shapeFor` hull has its own id, a `box()` the shared `BOX_STRUCTURE`, and any other + * shape 0, which opts out of the pair memo. + * @var int + */ + private $structure = 0; + /** * The rotated hull of one item in one orientation, built at most once. * @@ -130,6 +173,7 @@ static function (array $vertex): string { return self::$shapeCache[$key]; } $shape = self::of(self::rotate($vertices, $rotation)); + $shape->structure = self::$nextStructure++; if (count(self::$shapeCache) >= self::SHAPE_CACHE_ENTRIES) { self::$shapeCache = []; } @@ -187,7 +231,7 @@ public static function box(int $length, int $width, int $height): self } } } - return new self( + $box = new self( $vertices, self::UNIT_AXES, self::UNIT_AXES, @@ -195,6 +239,8 @@ public static function box(int $length, int $width, int $height): self max($length, $width, $height), 1, ); + $box->structure = self::BOX_STRUCTURE; + return $box; } /** @@ -302,15 +348,17 @@ public static function collide( ): bool { $reach = max($left->maxCoordinate, $right->maxCoordinate) + max(self::largestComponent([$leftOrigin]), self::largestComponent([$rightOrigin])); - foreach (self::separatingAxes($left, $right) as $axis) { + $memoKey = self::rememberPair($left, $right); + $axes = $memoKey === null ? self::separatingAxes($left, $right) : self::$pairCache[$memoKey]['axes']; + foreach ($axes as $index => $axis) { if (!self::axisFitsNatively($reach, $axis)) { if (self::separatedExactly($left, $leftOrigin, $right, $rightOrigin, $axis)) { return false; } continue; } - [$leftLow, $leftHigh] = $left->projection($axis); - [$rightLow, $rightHigh] = $right->projection($axis); + [$leftLow, $leftHigh] = $left->projectionOnce($memoKey, 'left', $index, $axis); + [$rightLow, $rightHigh] = $right->projectionOnce($memoKey, 'right', $index, $axis); $leftShift = self::dot($leftOrigin, $axis); $rightShift = self::dot($rightOrigin, $axis); if ($leftHigh + $leftShift <= $rightLow + $rightShift @@ -321,6 +369,46 @@ public static function collide( return true; } + /** + * Make sure the ordered pair's axis list is memoised and return its key, or null when + * either shape opts out. The axes depend only on the two shapes' face normals and edge + * directions, never on where they stand. + */ + private static function rememberPair(self $left, self $right): ?string + { + if ($left->structure === 0 || $right->structure === 0) { + return null; + } + $key = $left->structure . '|' . $right->structure; + if (isset(self::$pairCache[$key])) { + return $key; + } + $axes = self::separatingAxes($left, $right); + if (self::$pairCacheAxes + count($axes) > self::PAIR_CACHE_AXES) { + self::$pairCache = []; + self::$pairCacheAxes = 0; + } + self::$pairCache[$key] = ['axes' => $axes, 'left' => [], 'right' => []]; + self::$pairCacheAxes += count($axes); + return $key; + } + + /** + * This shape's projection interval on a pair's `$index`th axis, computed once per memoised + * pair. A box is cheap to project and varies by size, so only hulls are kept. + * + * @param 'left'|'right' $side + * @param array{int,int,int} $axis + * @return array{int,int} + */ + private function projectionOnce(?string $memoKey, string $side, int $index, array $axis): array + { + if ($memoKey === null || $this->structure === self::BOX_STRUCTURE) { + return $this->projection($axis); + } + return self::$pairCache[$memoKey][$side][$index] = self::$pairCache[$memoKey][$side][$index] ?? $this->projection($axis); + } + /** * Both hulls' face normals plus every edge-against-edge direction, deduplicated. * diff --git a/src-legacy/Domain/Item.php b/src-legacy/Domain/Item.php index 85101dd..4002b36 100644 --- a/src-legacy/Domain/Item.php +++ b/src-legacy/Domain/Item.php @@ -176,6 +176,8 @@ public static function create(string $id,Dimensions $dimensions,$weight=0,int $q */ private static function admitShape(string $shapeType,?array $hullVertices,?int $ratioPpm,?int $limitKpa,Dimensions $dimensions,?Length $nestingHeight):?array { + // First, so an oversized hull is refused before any per-vertex work runs. + if($hullVertices!==null)HullShape::admitVertexCount(count($hullVertices)); switch ($shapeType) { case ShapeType::CONVEX_HULL: $foreign = ['compression_ratio'=>$ratioPpm,'max_compression_pressure_kpa'=>$limitKpa]; diff --git a/src-legacy/Domain/PalletOverhang.php b/src-legacy/Domain/PalletOverhang.php index 6b3ad3a..f20a445 100644 --- a/src-legacy/Domain/PalletOverhang.php +++ b/src-legacy/Domain/PalletOverhang.php @@ -20,11 +20,13 @@ final class PalletOverhang { /** - * The container every solver packs: itself without a limit, else the widened frame carrying - * its deck. The frame states no limit, so a second call returns it unchanged. O(1). + * The container every solver packs: a standing bag turned to its W x H x L frame, + * a pallet with a limit widened to the frame carrying its deck, else itself. A frame is + * marked as one, so a second call returns it unchanged. O(1). */ public static function solvingFrame(Container $container):Container { + if($container->bagOrientation===FlatBag::STANDING&&!$container->uprightFrame)return $container->upright(); $limit=$container->palletOverhangLimit; if($limit===null)return $container; $inner=$container->innerDimensions; diff --git a/src-legacy/Domain/RateTable.php b/src-legacy/Domain/RateTable.php index a2ae7af..10d9844 100644 --- a/src-legacy/Domain/RateTable.php +++ b/src-legacy/Domain/RateTable.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; +use Packvium\Support\Arithmetic; use Packvium\Support\ObjectRefusal; /** @@ -107,8 +108,8 @@ public function chargeMinorOrNull(int $billedWeightG): ?int $base = max($this->pricesMinor[$index], $this->minimumChargeMinor); // Ceiling division, never a float: the surcharge is a share of the base, // and rounding down would let a fractional unit of revenue vanish. - $surcharge = intdiv($base * $this->fuelSurchargePermille + 999, 1000); - return $base + $surcharge; + $surcharge = Arithmetic::mulDivCeil($base, $this->fuelSurchargePermille, 1000); + return Arithmetic::addNonNegative($base, $surcharge); } } return null; diff --git a/src-legacy/Extension/DefaultContainerSelector.php b/src-legacy/Extension/DefaultContainerSelector.php index 4c8a720..f0505b7 100644 --- a/src-legacy/Extension/DefaultContainerSelector.php +++ b/src-legacy/Extension/DefaultContainerSelector.php @@ -5,6 +5,7 @@ use Packvium\Domain\Container; use Packvium\Domain\Nesting; use Packvium\Support\BigInt; +use Packvium\Support\StableSorter; /** Prefers the container that holds the most items, then the cheapest, then the tightest. */ final class DefaultContainerSelector implements ContainerSelector { @@ -12,6 +13,6 @@ public function score(Container $c,SingleContainerSolution $s):array { $used=$s->state->latticeSummary!==null?$s->state->latticeSummary->usedVolumeString():Nesting::usedVolume($s->state->placements); $leftover=BigInt::chunks(BigInt::subtract($c->innerDimensions->volumeString(),$used)); - return array_merge([-$s->state->placementCount(), $c->costMinor], $leftover, [$c->id]); + return array_merge([-$s->state->placementCount(), $c->costMinor], $leftover, [StableSorter::textKey($c->id)]); } } diff --git a/src-legacy/Packer.php b/src-legacy/Packer.php index 8809f68..8453eeb 100644 --- a/src-legacy/Packer.php +++ b/src-legacy/Packer.php @@ -66,7 +66,7 @@ private function objectiveBound(PackingRequest $request): ?array return null; } return ObjectiveBounds::forRequest($request->instances(), $request->containers, - $this->config->objective); + $this->config->objective, $this->config); } /** @@ -118,12 +118,13 @@ public function pack(array $items, array $containers, array $fixedPlacements = [ */ private function solve(array $items, array $containers, array $fixedPlacements, ?string $currency = null): PackingResult { - // 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. + // A pallet with an overhang limit is packed as its widened frame from here on, and a + // standing bag as its turned one, so no solver, bound or validator needs to know the + // limit or the orientation exists. + // Any other container is its own frame; asking only for one with a limit or standing + // 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); + return $container->palletOverhangLimit === null && $container->bagOrientation === 'flat' ? $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 diff --git a/src-legacy/Policy/PolicyRuleSet.php b/src-legacy/Policy/PolicyRuleSet.php index 4875201..481de08 100644 --- a/src-legacy/Policy/PolicyRuleSet.php +++ b/src-legacy/Policy/PolicyRuleSet.php @@ -72,7 +72,7 @@ private static function resolve(array $rules, int $asOf, ShipmentContext $shipme // Ties go to the lexicographically smallest id -- never to array insertion // order, which would follow the order the caller happened to write. usort($resolved, static function (PolicyRule $a, PolicyRule $b): int { - return ($b->priority <=> $a->priority) ?: ($a->id <=> $b->id); + return ($b->priority <=> $a->priority) ?: strcmp($a->id, $b->id); }); return $resolved; } diff --git a/src-legacy/Revisions/PlanRevision.php b/src-legacy/Revisions/PlanRevision.php index 8e29b1a..1078442 100644 --- a/src-legacy/Revisions/PlanRevision.php +++ b/src-legacy/Revisions/PlanRevision.php @@ -865,11 +865,20 @@ private static function stockBox(stdClass $request, stdClass $machine, string $s $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->cost_minor = self::safeCost(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; } + /** C-13: the exact cost as an int, or a refusal in the wording of the admission rule; a cut box larger than its machine's declared size can pass 2^53 - 1. */ + private static function safeCost(string $cost): int + { + if (BigInt::compare($cost, MadeToMeasure::MAX_EXACT_INTEGER) > 0) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's cost_per_square_metre_minor prices the largest box above " . MadeToMeasure::MAX_EXACT_INTEGER); + } + return (int) $cost; + } + /** @param mixed $value */ private static function stockObject($value, string $name, bool $optional = false): stdClass { diff --git a/src-legacy/Serialization/ArrayCodec.php b/src-legacy/Serialization/ArrayCodec.php index 26790db..ea0eec0 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,OverhangLimit,Point,RateTable,Rotation,ShapeType}; +use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,HullShape,Item,MadeToMeasure,Obstacle,OverhangLimit,Point,RateTable,Rotation,ShapeType}; use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; use Packvium\Policy\PolicyRuleSet; @@ -17,7 +17,11 @@ use ValueError; final class ArrayCodec { - private static function effortBudget(?array $r):?EffortBudget{if($r===null)return null;return new EffortBudget($r['max_candidates_evaluated']??null,$r['max_placement_attempts']??null,$r['max_search_nodes']??null,$r['max_restarts']??null);} + // Each limit by value, as admission read it: `1000.0` is the integer 1000 (JavaScript cannot tell them apart). + private static function effortBudget(?array $r):?EffortBudget{if($r===null)return null;$limit=static function (string $name) use ($r): ?int { + return isset($r[$name])?\Packvium\Support\JsonValue::integer($r[$name]):null; + }; + return new EffortBudget($limit('max_candidates_evaluated'),$limit('max_placement_attempts'),$limit('max_search_nodes'),$limit('max_restarts'));} /** @return array{0:Axle,1:Axle}|null */ private static function axles(?array $r,string $unit):?array{if($r===null)return null;[$front,$rear]=$r;return [new Axle(Length::parse($front['position'],$unit),isset($front['max_load'])?Weight::parse($front['max_load']):null),new Axle(Length::parse($rear['position'],$unit),isset($rear['max_load'])?Weight::parse($rear['max_load']):null)];} /** @@ -355,6 +359,7 @@ private static function item(array $r,string $unit):Item{$rot=array_map(function private static function hullVertices(?array $raw,string $unit):?array { if($raw===null)return null; + HullShape::admitVertexCount(count($raw)); $out=[]; foreach($raw as $vertex)$out[]=[ Length::parse($vertex['x'],$unit)->ticks, @@ -392,11 +397,11 @@ private static function container(array $r,string $unit):Container{$obs=[];forea 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) { + },(array)($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),self::palletOverhangLimit($r['pallet_overhang_limit']??null,$unit),null,self::sideGussetDepth($r['deformable_boundary']??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::gussetDepth($r['deformable_boundary']??null,'side_gusset_depth',$unit),self::gussetDepth($r['deformable_boundary']??null,'bottom_gusset_depth',$unit),(string)($r['deformable_boundary']['orientation']??'flat'));} /** @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));} + private static function gussetDepth(?array $r,string $name,string $unit):?Length{return ($r[$name]??null)===null?null:new Length(MeasureReading::ticks($r[$name],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 */ diff --git a/src-legacy/Support/Arithmetic.php b/src-legacy/Support/Arithmetic.php index 0e6f14f..c0907f5 100644 --- a/src-legacy/Support/Arithmetic.php +++ b/src-legacy/Support/Arithmetic.php @@ -41,6 +41,41 @@ public static function mulDivCeil(int $a, int $b, int $d): int $product = BigInt::multiply((string)$a, (string)$b); $quotient = BigInt::divide($product, (string)$d); $exact = BigInt::compare(BigInt::multiply($quotient, (string)$d), $product) === 0; - return (int)$quotient + ($exact ? 0 : 1); + $ceiling = $exact ? $quotient : BigInt::add($quotient, '1'); + if (BigInt::compare($ceiling, (string)PHP_INT_MAX) > 0) { + throw self::beyondInteger(); + } + return (int)$ceiling; + } + + /** + * Exact ceil(a * b / d) for non-negative inputs at any size: an int while it fits one, + * a decimal string beyond. For callers that must compare the result to a ceiling of + * their own rather than refuse at the 64-bit one. + * @param int|string $a + * @param int|string $b + * @return int|string + */ + public static function mulDivCeilExact($a, $b, int $d) + { + if ($d <= 0) { throw new \InvalidArgumentException('Divisor must be positive'); } + return ExactInteger::floorDiv(ExactInteger::add(ExactInteger::mul($a, $b), $d - 1), $d); + } + + /** + * a + b for non-negative minor-unit amounts, refusing a sum a 64-bit int cannot hold + * where plain `+` would silently become a float. + */ + public static function addNonNegative(int $a, int $b): int + { + if ($a > PHP_INT_MAX - $b) { + throw self::beyondInteger(); + } + return $a + $b; + } + + private static function beyondInteger(): ObjectRefusal + { + return new ObjectRefusal('above_maximum', 'amount must be at most ' . PHP_INT_MAX . ' minor units'); } } diff --git a/src-legacy/Support/Internal/RareRequestRules.php b/src-legacy/Support/Internal/RareRequestRules.php index a32be6d..ec5dba6 100644 --- a/src-legacy/Support/Internal/RareRequestRules.php +++ b/src-legacy/Support/Internal/RareRequestRules.php @@ -99,9 +99,9 @@ public static function palletOverhangLimit(\Closure $call, $container, $raw, str } /** - * 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). + * The bag's own shape top to bottom -- kind, unknown keys, a gusseted bag's + * gussets and orientation (1.10) -- then every container field a bag refuses, in + * the order of `BAG_EXCLUSIONS`. O(1). * * @param stdClass|array $container * @param mixed $raw @@ -115,9 +115,9 @@ public static function deformableBoundary(\Closure $call, $container, $raw, stri throw $call('refuse', 'not_allowed', "{$field}/kind", 'must be one of ' . CanonicalJson::spelling(FlatBag::KINDS)); } $gusseted = $kind === FlatBag::GUSSETED_BAG; - $call('knownFields', $boundary, $field, $gusseted ? ['kind', 'side_gusset_depth'] : ['kind']); + $call('knownFields', $boundary, $field, $gusseted ? FlatBag::GUSSETED_BAG_FIELDS : ['kind']); if ($gusseted) { - self::sideGussetDepth($call, $container, $call('required', $boundary, 'side_gusset_depth', $field), "{$field}/side_gusset_depth", $unit); + self::gussetedBag($call, $container, $boundary, $field, $unit); } foreach (RequestRules::BAG_EXCLUSIONS as $name) { if ($call('setBesideABag', $name, JsonValue::get($container, $name))) { @@ -127,20 +127,51 @@ public static function deformableBoundary(\Closure $call, $container, $raw, stri } /** - * A length, positive once read in ticks, and no deeper than the bag's inner width. + * The side gusset, then the bottom one, each a positive length within its fold; with + * neither, the side gusset is reported missing as in 1.10. Then the orientation, and a + * standing bag's bottom gusset. O(1). * * @param stdClass|array $container + * @param stdClass|array $boundary + */ + private static function gussetedBag(\Closure $call, $container, $boundary, string $field, string $unit): void + { + $side = JsonValue::get($boundary, 'side_gusset_depth'); + $bottom = JsonValue::get($boundary, 'bottom_gusset_depth'); + if ($side === null && $bottom === null) { + $call('required', $boundary, 'side_gusset_depth', $field); + } + $inner = $call('sideTicks', JsonValue::get($container, 'inner_dimensions'), $unit); + if ($side !== null) { + self::gussetDepth($call, $side, "{$field}/side_gusset_depth", $inner[1], 'exceeds inner_dimensions width', $unit); + } + if ($bottom !== null) { + self::gussetDepth($call, $bottom, "{$field}/bottom_gusset_depth", 2 * $inner[0], 'exceeds twice inner_dimensions length', $unit); + } + $orientation = JsonValue::get($boundary, 'orientation'); + if ($orientation === null) { + return; + } + $call('oneOf', $orientation, "{$field}/orientation", FlatBag::ORIENTATIONS); + if ($orientation === FlatBag::STANDING && $bottom === null) { + throw $call('refuse', 'missing_field', "{$field}/bottom_gusset_depth", 'is required when orientation is standing'); + } + } + + /** + * A length, positive once read in ticks, and no deeper than its fold allows. + * * @param mixed $value */ - private static function sideGussetDepth(\Closure $call, $container, $value, string $field, string $unit): void + private static function gussetDepth(\Closure $call, $value, string $field, int $deepest, string $tooDeep, 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'); + if ($depth > $deepest) { + throw $call('refuse', 'invalid_value', $field, $tooDeep); } } @@ -167,6 +198,13 @@ public static function rateTable(\Closure $call, $raw, string $where, ?string $c if ($code !== null) { RequestRules::rateTableCurrency($code, "{$where}/currency", $currency); } + $prices = JsonValue::get($table, 'prices_minor'); + RequestRules::rateTableCeiling( + $prices === null ? [] : \array_map([JsonValue::class, 'integer'], \array_values((array) $prices)), + JsonValue::integer(JsonValue::get($table, 'minimum_charge_minor') ?? 0), + JsonValue::integer(JsonValue::get($table, 'fuel_surcharge_permille') ?? 0), + $where + ); } /** @param mixed $raw @param array{0:int,1:int,2:int} $inner */ diff --git a/src-legacy/Support/RequestJson.php b/src-legacy/Support/RequestJson.php new file mode 100644 index 0000000..aca228e --- /dev/null +++ b/src-legacy/Support/RequestJson.php @@ -0,0 +1,62 @@ +containers[$index]->tag_limits ?? null; + if ($limits instanceof stdClass) { + $data['containers'][$index]['tag_limits'] = $limits; + } + } + return $data; + } + + /** + * Containers whose `tag_limits` decoded as a non-empty list: an array, or an object keyed 0..n-1. + * + * @param mixed $data + * @return list + */ + private static function ambiguousContainers($data): array + { + $containers = \is_array($data) ? ($data['containers'] ?? null) : null; + if (!\is_array($containers) || !JsonValue::isList($containers)) { + return []; + } + $found = []; + foreach ($containers as $index => $container) { + $limits = \is_array($container) ? ($container['tag_limits'] ?? null) : null; + if (\is_array($limits) && $limits !== [] && JsonValue::isList($limits)) { + $found[] = $index; + } + } + return $found; + } +} diff --git a/src-legacy/Support/RequestObjects.php b/src-legacy/Support/RequestObjects.php index fcd9f64..313bfc7 100644 --- a/src-legacy/Support/RequestObjects.php +++ b/src-legacy/Support/RequestObjects.php @@ -240,6 +240,7 @@ private static function rateTable(RateTable $table, string $where, ?string $curr if ($table->currency !== null) { RequestRules::rateTableCurrency($table->currency, "{$where}/currency", $currency); } + RequestRules::rateTableCeiling($table->pricesMinor, $table->minimumChargeMinor, $table->fuelSurchargePermille, $where); } /** diff --git a/src-legacy/Support/RequestRules.php b/src-legacy/Support/RequestRules.php index 32b906f..ccfff37 100644 --- a/src-legacy/Support/RequestRules.php +++ b/src-legacy/Support/RequestRules.php @@ -3,6 +3,7 @@ namespace Packvium\Support; use Packvium\Domain\FlatBag; +use Packvium\Domain\HullShape; use Packvium\Domain\MadeToMeasure; use Packvium\Domain\Orientations; use Packvium\Serialization\InvalidRequestException; @@ -243,6 +244,7 @@ private static function item($raw, string $where, string $unit): void self::optionalAllowedRotations($item, $where); self::optionalOneOf($item, 'ground_contact_rule', $where, self::GROUND_CONTACT_RULES); self::optionalOneOf($item, 'shape_type', $where, self::SHAPE_TYPES); + self::optionalHullVertexCount($item, $where); foreach (self::ITEM_BOOLEANS as $name) { self::optionalBoolean($item, $name, $where); } @@ -258,6 +260,23 @@ private static function item($raw, string $where, string $unit): void } } + /** + * Only the count: the cap exists so no per-vertex work runs on an oversized hull. O(1). + * + * @param stdClass|array $item + */ + private static function optionalHullVertexCount($item, string $where): void + { + $vertices = JsonValue::get($item, 'hull_vertices'); + if ($vertices === null) { + return; + } + $field = "{$where}/hull_vertices"; + if (\count(self::listAt($vertices, $field)) > HullShape::MAXIMUM_VERTICES) { + throw self::refuse('above_maximum', $field, 'must have at most ' . HullShape::MAXIMUM_VERTICES . ' vertices'); + } + } + /** * 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 @@ -561,6 +580,30 @@ private static function tagLimits($raw, string $where): void } } + /** + * The dearest bracket's landed cost, fuel surcharge included, must stay an exact integer + * (M1): `base = max(dearest price, minimum charge)`, `landed = base + ceil(base * permille / 1000)`, + * in decimal-string arithmetic because the product of two values near 2^53 passes PHP_INT_MAX. + * A table with no prices is left to the rules that refuse it. O(p) for p prices. + * + * @param list $prices every field already passed its own check + */ + public static function rateTableCeiling(array $prices, int $minimumCharge, int $fuelSurchargePermille, string $where): void + { + if ($prices === []) { + return; + } + $base = (string) \max(\max($prices), $minimumCharge); + $product = BigInt::multiply($base, (string) $fuelSurchargePermille); + $quotient = BigInt::divide($product, '1000'); + $exact = BigInt::compare(BigInt::multiply($quotient, '1000'), $product) === 0; + $landed = BigInt::add($base, $exact ? $quotient : BigInt::add($quotient, '1')); + if (BigInt::compare($landed, CanonicalJson::MAX_EXACT_MAGNITUDE) > 0) { + throw self::refuse('above_maximum', $where, 'must price its top bracket at most ' + . CanonicalJson::MAX_EXACT_MAGNITUDE . ' minor units with the fuel surcharge'); + } + } + /** @param mixed $raw */ /** @param mixed $value */ public static function integer($value, string $field, int $minimum): void diff --git a/src-legacy/Support/ResultValidation/Accounting.php b/src-legacy/Support/ResultValidation/Accounting.php index 4459d5a..6f67b3c 100644 --- a/src-legacy/Support/ResultValidation/Accounting.php +++ b/src-legacy/Support/ResultValidation/Accounting.php @@ -148,9 +148,7 @@ public static function fitsEmpty(ContainerSpec $container, array $size): bool return false; } } - return !$container->flatBag - || (Exact::compare(Exact::add($size[0], $size[2]), $container->inner[0]) <= 0 - && Exact::compare(Exact::add($size[1], $size[2]), Exact::add($container->inner[1], $container->sideGusset)) <= 0); + return !$container->flatBag || ContainerCheck::girthBreach($container, $size[0], $size[1], $size[2]) === null; } /** diff --git a/src-legacy/Support/ResultValidation/Bound.php b/src-legacy/Support/ResultValidation/Bound.php index 0ad119d..7098d69 100644 --- a/src-legacy/Support/ResultValidation/Bound.php +++ b/src-legacy/Support/ResultValidation/Bound.php @@ -12,7 +12,8 @@ * The reference's own copy of docs/OPTIMALITY-CERTIFICATES.md's formulas and its one refusal * predicate, shared with nothing in the PHP engine (`Algorithm\ObjectiveBounds` is what it checks). * Exact at any size through `Exact`. O(t log t + c log c) for `t` item types and `c` container - * types, O(t + c) memory, once per result. + * types, O(t + c) memory, once per result; a billed objective's key adds O(c b (t + log(c b))) + * for `b` rate-table brackets per type. */ final class Bound { @@ -26,7 +27,11 @@ final class Bound '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], + 'shipping_cost' => [0, 'billed_weight', 1, 3, 4], + 'lowest_landed_cost' => [0, 'landed_charge', 1, 3, 4], ]; + /** The objectives whose own key is what a carrier bills. */ + private const BILLED = ['shipping_cost', 'lowest_landed_cost']; private const MAX_BOUND_SUM = '1000000000000000000000000000000'; private const MAX_BOUND_VALUE = 9007199254740991; private const SCORE_SCALE = 1000000; @@ -158,7 +163,64 @@ private static function stated($request, $status, Ordered $items, Ordered $conta return [null, "status is 'invalid_result'"]; } [$volumes, $weights, $values, $shrinks, $types] = self::inputs($items, $containers); - return self::objectiveBound($volumes, $weights, $values, $shrinks, $types, $name); + $billing = \in_array($name, self::BILLED, true) + ? self::billing(Json::get($request, 'configuration', []), $containers) : null; + return self::objectiveBound($volumes, $weights, $values, $shrinks, $types, $name, $billing); + } + + /** + * What a carrier can bill each type at the least, or null without a divisor: + * `floor` is `max(tare, dimensional)` -- the dimensional weight of the declared outer size, + * else the declared floor and height, and 0 for a bag, whose billed package can be smaller + * -- and `brackets` the rate table as `[bound in weight ticks, charge]`, the minimum charge + * and the surcharge rounded up already applied. O(c b) for `b` brackets per type. + * + * @param mixed $configuration @param Ordered $containers + * @return list}>|null + */ + private static function billing($configuration, Ordered $containers): ?array + { + $divisor = Json::get($configuration, 'dimensional_weight_divisor'); + if ($divisor === null) { + return null; + } + $lengthUnit = Json::text(Json::get($configuration, 'dimensional_weight_length_unit', 'in'), 'dimensional_weight_length_unit'); + $weightUnit = Json::text(Json::get($configuration, 'dimensional_weight_weight_unit', 'lb'), 'dimensional_weight_weight_unit'); + $billing = []; + foreach ($containers->values() as $spec) { + $size = $spec->outer ?? ($spec->deck === null ? $spec->inner : [$spec->deck[2], $spec->deck[3], $spec->inner[2]]); + $dimensional = $spec->flatBag ? 0 : ObjectiveCheck::dimensionalWeight($size, Json::int($divisor, 'dimensional_weight_divisor'), $lengthUnit, $weightUnit); + $billing[] = [ + 'floor' => Exact::max($spec->tareWeight, $dimensional), + 'tare' => $spec->tareWeight, + 'brackets' => self::brackets($spec->rateTable), + ]; + } + return $billing; + } + + /** @param mixed $table @return list */ + private static function brackets($table): array + { + if ($table === null) { + return []; + } + $read = static function ($value, string $what) { return Json::pyInt($value, $what); }; + $prices = Json::items(Json::at($table, 'prices_minor'), 'prices_minor'); + $minimum = $read(Json::get($table, 'minimum_charge_minor', 0), 'minimum_charge_minor'); + $permille = $read(Json::get($table, 'fuel_surcharge_permille', 0), 'fuel_surcharge_permille'); + $brackets = []; + foreach (Json::items(Json::at($table, 'weight_brackets_g'), 'weight_brackets_g') as $index => $grams) { + if (!\array_key_exists($index, $prices)) { + break; + } + $base = Exact::max($read($prices[$index], 'price'), $minimum); + $brackets[] = [ + Exact::mul($read($grams, 'bracket'), Units::TICKS_PER_GRAM), + Exact::add($base, Exact::ceilDiv(Exact::mul($base, $permille), 1000)), + ]; + } + return $brackets; } /** @@ -169,16 +231,28 @@ private static function stated($request, $status, Ordered $items, Ordered $conta * @param list $volumes value runs sorted ascending * @param list $weights @param list $values * @param list> $containers + * @param list}>|null $billing + * per type, in `$containers`' order; read by the billed objectives only, null without a divisor * @return array{0:list|null,1:string} */ - public static function objectiveBound(array $volumes, array $weights, array $values, bool $shrinks, array $containers, string $objective): array + public static function objectiveBound(array $volumes, array $weights, array $values, bool $shrinks, array $containers, string $objective, ?array $billing = null): array { $bound = self::lowerBound($volumes, $weights, $shrinks, $containers); if ($bound === null) { return [null, 'the request is past a declared ceiling']; } - $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]); + $billed = null; + if (\in_array($objective, self::BILLED, true)) { + $billed = $billing === null ? null : self::billedTerm($objective, $billing, $volumes, $weights, $shrinks, $containers, $bound); + if ($billed === null) { + return [null, 'no priceable inventory carries a packing that attains the count bound']; + } + } + $stated = \array_map(static function ($position) use ($bound, $billed, $volumes, $values, $shrinks, $containers) { + if (\is_int($position)) { + return $bound[$position]; + } + return $billed ?? 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) { @@ -217,6 +291,129 @@ private static function objectiveTerm(string $name, array $volumes, array $value return Exact::ceilDiv(Exact::mul(Exact::max(0, Exact::sub($requested, $capacity)), self::SCORE_SCALE), $requested); } + /** + * The billed key of `shipping_cost` or `lowest_landed_cost`, or null when no + * priceable inventory carries a packing that leaves exactly `L0` behind. + * + * Each opened container bills at least its floor and at least its tare plus what it + * carries. A rate-table bracket is reachable from a floor within it; there a container + * carries at most the bracket's bound less its tare (and its `max_payload`), so at most the + * lightest-first count under that, its usable volume and `max_items`. The cheapest + * reachable charge over the `L1` containers, the cheapest cover of the placed weight and of + * the placed count each bound the charge; the largest is stated. O(t + c b (t + log(c b))) + * for `t` runs and `b` brackets per type. + * + * @param list}> $billing + * @param list $volumes @param list $weights + * @param list> $containers @param list $bound @return int|string|null + */ + private static function billedTerm(string $objective, array $billing, array $volumes, array $weights, bool $shrinks, array $containers, array $bound) + { + [$unpacked, $opened] = $bound; + $placed = Exact::sub(self::runCount($volumes), $unpacked); + if ($objective === 'shipping_cost') { + if (Exact::sign($opened) === 0) { + return 0; + } + $quantities = self::column($containers, 'quantity'); + $byFloor = self::leastOfInventory(\array_column($billing, 'floor'), $quantities, $opened); + $byTare = self::leastOfInventory(\array_column($billing, 'tare'), $quantities, $opened); + if ($byFloor === null || $byTare === null) { + return null; + } + return Exact::max($byFloor, Exact::add($byTare, self::smallest($weights, $placed))); + } + if (Exact::sign($opened) === 0 || Exact::sign($placed) === 0) { + return 0; + } + $cheapest = $cheapestQuantities = $byWeight = $byItems = []; + foreach ($billing as $index => $billed) { + $container = $containers[$index]; + $charges = []; + foreach ($billed['brackets'] as [$limit, $charge]) { + if ($charge === null || Exact::compare($billed['floor'], $limit) > 0) { + continue; + } + $carried = Exact::sub($limit, $billed['tare']); + if ($container['payload'] !== null) { + $carried = self::min($carried, $container['payload']); + } + $count = self::fit($weights, $carried); + if (!$shrinks) { + $count = self::min($count, self::fit($volumes, $container['usable'])); + } + if ($container['max_items'] !== null) { + $count = self::min($count, $container['max_items']); + } + $charges[] = $charge; + $byWeight[] = [$charge, $carried, $container['quantity']]; + $byItems[] = [$charge, $count, $container['quantity']]; + } + if ($charges !== []) { + $cheapest[] = \array_reduce($charges, static function ($least, $charge) { return self::min($least, $charge); }, $charges[0]); + $cheapestQuantities[] = $container['quantity']; + } + } + $terms = [ + self::leastOfInventory($cheapest, $cheapestQuantities, $opened), + self::fractionalCover($byWeight, self::smallest($weights, $placed)), + self::fractionalCover($byItems, $placed), + ]; + return \in_array(null, $terms, true) ? null : self::largest($terms); + } + + /** + * The `count` smallest of `{value repeated quantity}`, summed; null if fewer exist. + * + * @param list $values @param list $quantities @param int|string $count @return int|string|null + */ + private static function leastOfInventory(array $values, array $quantities, $count) + { + $order = \array_keys($values); + \usort($order, static function (int $left, int $right) use ($values): int { + return Exact::compare($values[$left], $values[$right]) ?: $left <=> $right; + }); + $total = 0; + foreach ($order as $index) { + if (Exact::sign($count) <= 0) { + break; + } + $taken = $quantities[$index] === null ? $count : self::min($quantities[$index], $count); + $total = Exact::add($total, Exact::mul($values[$index], $taken)); + $count = Exact::sub($count, $taken); + } + return Exact::sign($count) > 0 ? null : $total; + } + + /** + * Least cost covering `need` from `[cost, capacity, quantity]` offers taken fractionally, + * rounded up; greedy by cost per unit is optimal for one covering constraint. Exact: whole + * offers sum as integers and the one share taken in part is the only fraction, rounded once. + * + * @param list $offers @param int|string $need @return int|string|null + */ + private static function fractionalCover(array $offers, $need) + { + if (Exact::sign($need) <= 0) { + return 0; + } + $ranked = \array_values(\array_filter($offers, static function (array $offer): bool { return Exact::sign($offer[1]) > 0; })); + $order = \array_keys($ranked); + \usort($order, static function (int $left, int $right) use ($ranked): int { + return Exact::compare(Exact::mul($ranked[$left][0], $ranked[$right][1]), Exact::mul($ranked[$right][0], $ranked[$left][1])) ?: $left <=> $right; + }); + $total = 0; + foreach ($order as $index) { + [$cost, $capacity, $quantity] = $ranked[$index]; + if ($quantity === null || Exact::compare(Exact::mul($quantity, $capacity), $need) >= 0) { + return Exact::add($total, Exact::ceilDiv(Exact::mul($cost, $need), $capacity)); + } + $total = Exact::add($total, Exact::mul($cost, $quantity)); + $need = Exact::sub($need, Exact::mul($capacity, $quantity)); + } + return null; + } + /** * The request as the bound reads it: every instance, fixed ones included, and every type. * diff --git a/src-legacy/Support/ResultValidation/ContainerCheck.php b/src-legacy/Support/ResultValidation/ContainerCheck.php index 389162d..5eb187d 100644 --- a/src-legacy/Support/ResultValidation/ContainerCheck.php +++ b/src-legacy/Support/ResultValidation/ContainerCheck.php @@ -124,13 +124,43 @@ 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), 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}"); + $breach = $spec->flatBag ? self::girthBreach($spec, $a, $b, $c) : null; + if ($breach !== null) { + $issues[] = new ResultIssue('bag_girth_exceeded', "{$packedId}: {$breach}"); } $packedId->verify(); } + /** + * How a bag's package of extents (a, b, c) breaks a loop of film, or null. + * + * Lying flat on an L x W bag: 2(a + c) <= 2L + K and b + c <= W + G. Standing in its + * W x H x L frame: 2(b + c) <= 2L + K and a + b <= W + G (1.10). G and K + * are the side and bottom gussets, 0 where none is declared. + * + * @param int|string $a @param int|string $b @param int|string $c + */ + public static function girthBreach(ContainerSpec $spec, $a, $b, $c): ?string + { + if ($spec->standing) { + [$width, $length] = [$spec->inner[0], $spec->inner[2]]; + [$along, $across] = [Exact::add($b, $c), Exact::add($a, $b)]; + } else { + [$length, $width] = [$spec->inner[0], $spec->inner[1]]; + [$along, $across] = [Exact::add($a, $c), Exact::add($b, $c)]; + } + $alongLimit = Exact::add(Exact::add($length, $length), $spec->bottomGusset); + if (Exact::compare(Exact::add($along, $along), $alongLimit) <= 0 + && Exact::compare($across, Exact::add($width, $spec->sideGusset)) <= 0) { + return null; + } + $sums = $spec->standing + ? "b + c = {$along}, a + b = {$across}, standing, length {$length}, width {$width}" + : "a + c = {$along}, b + c = {$across}, flat size {$length} x {$width}"; + return $sums . (Exact::sign($spec->sideGusset) === 0 ? '' : ", side gusset {$spec->sideGusset}") + . (Exact::sign($spec->bottomGusset) === 0 ? '' : ", bottom gusset {$spec->bottomGusset}"); + } + /** @param list|null $stated @param list $expected */ private static function matches(?array $stated, array $expected): bool { diff --git a/src-legacy/Support/ResultValidation/ContainerSpec.php b/src-legacy/Support/ResultValidation/ContainerSpec.php index 949f8cb..cbc1403 100644 --- a/src-legacy/Support/ResultValidation/ContainerSpec.php +++ b/src-legacy/Support/ResultValidation/ContainerSpec.php @@ -46,6 +46,20 @@ final class ContainerSpec * @var int|string */ public $sideGusset = 0; + /** + * 1.11: a gusseted bag's bottom gusset depth K in ticks, which lengthens the + * length girth to 2(a + c) <= 2L + K; 0 where none is declared. + * + * @var int|string + */ + public $bottomGusset = 0; + /** + * A bag standing on its bottom gusset, whose `$inner` is then the W x H x L frame + * it is packed in. + * + * @var bool + */ + public $standing = false; /** @var bool */ public $reportsAchievedExtent; /** @var MachineSpec|null */ diff --git a/src-legacy/Support/ResultValidation/ObjectiveCheck.php b/src-legacy/Support/ResultValidation/ObjectiveCheck.php index ddd76bf..0dfe3cf 100644 --- a/src-legacy/Support/ResultValidation/ObjectiveCheck.php +++ b/src-legacy/Support/ResultValidation/ObjectiveCheck.php @@ -147,7 +147,7 @@ private static function objective($result, Context $context, Ordered $fabricated } /** `floor(volume * weight ticks per unit / (length ticks per unit ^ 3 * divisor))`. @param array $size @return int|string */ - private static function dimensionalWeight(array $size, int $divisor, string $lengthUnit, string $weightUnit) + public static function dimensionalWeight(array $size, int $divisor, string $lengthUnit, string $weightUnit) { $length = Units::perUnit(Units::LENGTH, $lengthUnit); $weight = Units::perUnit(Units::WEIGHT, $weightUnit); diff --git a/src-legacy/Support/ResultValidation/Spec.php b/src-legacy/Support/ResultValidation/Spec.php index 44891c0..55f6161 100644 --- a/src-legacy/Support/ResultValidation/Spec.php +++ b/src-legacy/Support/ResultValidation/Spec.php @@ -90,7 +90,13 @@ 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, $spec->deck] = self::frameAndDeck(Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit), Json::get($raw, 'pallet_overhang_limit'), $unit); + $boundary = Json::get($raw, 'deformable_boundary'); + $standing = $boundary !== null && Json::get($boundary, 'orientation') === 'standing'; + $declared = Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit); + if ($standing) { + $declared = [$declared[1], $declared[2], $declared[0]]; + } + [$spec->inner, $spec->deck] = self::frameAndDeck($declared, 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); @@ -106,8 +112,10 @@ public static function containers($request, string $unit): Ordered $spec->axles = self::axles($raw, $unit); $spec->maxStackDensity = self::measured($raw, 'max_stack_density', 'g', Units::WEIGHT); $spec->rateTable = Json::get($raw, 'rate_table'); - $spec->flatBag = Json::get($raw, 'deformable_boundary') !== null; - $spec->sideGusset = self::sideGusset(Json::get($raw, 'deformable_boundary'), $unit); + $spec->flatBag = $boundary !== null; + $spec->sideGusset = self::gusset($boundary, 'side_gusset_depth', $unit); + $spec->bottomGusset = self::gusset($boundary, 'bottom_gusset_depth', $unit); + $spec->standing = $standing; $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); @@ -117,13 +125,13 @@ public static function containers($request, string $unit): Ordered } /** - * A gusseted bag's side gusset depth in ticks, else 0. + * A gusseted bag's side or bottom gusset depth in ticks, else 0. * * @param mixed $boundary @return int|string */ - private static function sideGusset($boundary, string $unit) + private static function gusset($boundary, string $name, string $unit) { - $depth = $boundary === null ? null : Json::get($boundary, 'side_gusset_depth'); + $depth = $boundary === null ? null : Json::get($boundary, $name); return $depth === null ? 0 : Units::toTicks($depth, $unit, Units::LENGTH); } diff --git a/src-legacy/Support/StableSorter.php b/src-legacy/Support/StableSorter.php index f116d7a..a18158e 100644 --- a/src-legacy/Support/StableSorter.php +++ b/src-legacy/Support/StableSorter.php @@ -3,6 +3,17 @@ namespace Packvium\Support; final class StableSorter { + /** + * A user-supplied id as a sort-key element that compares by bytes. PHP's `<=>` reads two + * numeric-looking strings as numbers ("9" < "10", "1e1" == "10"); the other engines order + * ids by code point. The shared non-numeric prefix forces string comparison and leaves + * the order of the ids themselves untouched. + */ + public static function textKey(string $id): string + { + return 'id:'.$id; + } + /** @template T @param list $values @param callable(T,T):int $compare @return list */ public static function sort(array $values, callable $compare): array { diff --git a/src-legacy/Validation/IndependentSolutionValidator.php b/src-legacy/Validation/IndependentSolutionValidator.php index 5471a08..ee2e25b 100644 --- a/src-legacy/Validation/IndependentSolutionValidator.php +++ b/src-legacy/Validation/IndependentSolutionValidator.php @@ -99,11 +99,12 @@ 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()){ + $girth=$packed->container->girth(); + if($girth!==null){ // 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,$packed->container->sideGussetTicks()))$issues[]=new ValidationIssue('bag_girth_exceeded',$packed->id()); + // (1.10) and lengthened by a bottom one, flat or standing; the frame + // is checked above. + if(!$girth->admits(FlatBag::extentOf($packed->placements)))$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){ @@ -124,12 +125,12 @@ public function validate(PackingRequest $request,array $containers,float $minimu } $missing=[]; foreach($expected as $id=>$_)if(!isset($seen[$id]))$missing[]=$id; - sort($missing); + sort($missing,SORT_STRING); foreach($missing as $id)$issues[]=new ValidationIssue('missing_item',$id); } $unknown=[]; foreach($seen as $id=>$_)if(!isset($expected[$id]))$unknown[]=$id; - sort($unknown); + sort($unknown,SORT_STRING); foreach($unknown as $id)$issues[]=new ValidationIssue('unknown_item',$id); foreach(self::splitGroups($containers) as $detail)$issues[]=new ValidationIssue('group_split',$detail); array_push($issues,...self::madeToMeasureIssues($request,$containers)); @@ -265,7 +266,7 @@ private static function unloadingOrderViolation(PackedContainer $packed):?Valida $stuckIds=array_map(static function (int $i) use ($placements) { return $placements[$i]->instance->id(); },$error->stuck); - sort($stuckIds); + sort($stuckIds,SORT_STRING); return new ValidationIssue( 'unloading_order_violation', $packed->id().': stop '.$error->stop.' cannot be fully unloaded ('.implode(', ',$stuckIds).' still blocked)', @@ -331,7 +332,8 @@ private static function sortedKeys(array $keys):array $list=array_map('strval',array_keys($keys)); usort($list,static function(string $left,string $right):int{ $a=explode("\0",$left);$b=explode("\0",$right); - return [$a[0],$a[1],(int)$a[2],(int)$a[3],(int)$a[4],$a[5]]<=>[$b[0],$b[1],(int)$b[2],(int)$b[3],(int)$b[4],$b[5]]; + // strcmp on the ids: `<=>` compares numeric strings as numbers ("9" < "10"), Python as text. + return strcmp($a[0],$b[0])?:strcmp($a[1],$b[1])?:[(int)$a[2],(int)$a[3],(int)$a[4],$a[5]]<=>[(int)$b[2],(int)$b[3],(int)$b[4],$b[5]]; }); return $list; } @@ -351,11 +353,11 @@ private static function splitGroups(array $containers):array if($group===null)continue; $located[$group][$packed->id()]=true; } - ksort($located); + ksort($located,SORT_STRING); $out=[]; foreach($located as $group=>$where){ if(count($where)<=1)continue; - $ids=array_keys($where);sort($ids); + $ids=array_keys($where);sort($ids,SORT_STRING); $out[]=$group.': '.implode(', ',$ids); } return $out; @@ -374,7 +376,7 @@ private static function partialGroups(PackingRequest $request,array $containers) $group=$placement->instance->item->group; if($group!==null)$placed[$group][$placement->instance->id()]=true; } - ksort($expected);$out=[]; + ksort($expected,SORT_STRING);$out=[]; foreach($expected as $group=>$members){ $count=count($placed[$group]??[]); if($count>0&&$countinnerDimensions; $limitX=$inner->length->ticks;$limitY=$inner->width->ticks;$limitZ=$inner->height->ticks; - // 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(); + // A bag also needs both loops of film round the running extents grown by the + // candidate: lying flat 2(a + c) <= 2L + K and b + c <= W + G, standing + // 2(b + c) <= 2L + K and a + b <= W + G (1.10 side gussets, bottom + // gussets; `Girth`). O(1), and the extents only grow, so no verdict flips. Both limits + // are summed once per call. + $girth=$container->girth(); + $bag=$girth!==null; $bagX=$state->maxX;$bagY=$state->maxY;$bagZ=$state->maxZ; - $girthY=$limitY+$container->sideGussetTicks(); + $along=$bag?$girth->alongLimit:0;$across=$bag?$girth->acrossLimit:0; + $standing=$bag&&$container->uprightFrame; $clearance=$config->clearance->ticks; // Envelope and extents depend only on the rotation, so they are built once // instead of once per (point, rotation) pair. @@ -132,7 +136,7 @@ private static function prepare(ContainerState $state,ItemInstance $item,Packing $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, + $limitX,$limitY,$limitZ,$bag,$bagX,$bagY,$bagZ,$along,$across,$standing,$clearance, ]; } @@ -147,7 +151,7 @@ private static function scanPoints(array $prepared,array $scan,?int $max,SearchS $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, + $limitX,$limitY,$limitZ,$bag,$bagX,$bagY,$bagZ,$along,$across,$standing,$clearance, ]=$prepared; $out=[];$best=null; $retained=$max!==null&&$max>1?new \SplPriorityQueue():null; @@ -166,9 +170,13 @@ private static function scanPoints(array $prepared,array $scan,?int $max,SearchS $x2=$x1+$dx;$y2=$y1+$dy;$z2=$z1+$dz; if($x2>$limitX||$y2>$limitY||$z2>$limitZ)continue; 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>$girthY)continue; + // Ternaries rather than max() or a Girth call: the call made this test dearer + // (44 ns against 74 ns for max()). + $grownZ=$z2>$bagZ?$z2:$bagZ; + if($standing){ + $grownY=$y2>$bagY?$y2:$bagY; + if(2*($grownY+$grownZ)>$along||($x2>$bagX?$x2:$bagX)+$grownY>$across)continue; + }elseif(2*(($x2>$bagX?$x2:$bagX)+$grownZ)>$along||($y2>$bagY?$y2:$bagY)+$grownZ>$across)continue; } $tentative=null; if($nesting){ diff --git a/src/Algorithm/GridSolver.php b/src/Algorithm/GridSolver.php index 0c8e282..368539d 100644 --- a/src/Algorithm/GridSolver.php +++ b/src/Algorithm/GridSolver.php @@ -29,9 +29,9 @@ private static function latticeProfile(\Packvium\Domain\Item $item):string foreach($item->dimensions->uniqueRotations($item->allowedRotations) as [, $physical]) $footprints[]="{$physical->length->ticks}x{$physical->width->ticks}x{$physical->height->ticks}"; sort($footprints); - $tags=$item->tags;sort($tags); - $incompatibleTags=$item->incompatibleTags;sort($incompatibleTags); - $eligibleContainerTags=$item->eligibleContainerTags;sort($eligibleContainerTags); + $tags=$item->tags;sort($tags,SORT_STRING); + $incompatibleTags=$item->incompatibleTags;sort($incompatibleTags,SORT_STRING); + $eligibleContainerTags=$item->eligibleContainerTags;sort($eligibleContainerTags,SORT_STRING); $acceptsStackingGroups=$item->acceptsStackingGroups;sort($acceptsStackingGroups,SORT_STRING); return json_encode([ $footprints,$item->weight->ticks,$item->stackable,$item->mustBeOnFloor, diff --git a/src/Algorithm/HomogeneousBlockSolver.php b/src/Algorithm/HomogeneousBlockSolver.php index 7b7492d..50d6bba 100644 --- a/src/Algorithm/HomogeneousBlockSolver.php +++ b/src/Algorithm/HomogeneousBlockSolver.php @@ -141,7 +141,7 @@ private static function leads(array $candidate,array $best,string $mode):bool if($order===0){ $mine=$candidate['space']->origin;$theirs=$best['space']->origin; $order=($mine->z<=>$theirs->z)?:($mine->y<=>$theirs->y)?:($mine->x<=>$theirs->x) - ?:($candidate['itemId']<=>$best['itemId'])?:($candidate['rotationName']<=>$best['rotationName']) + ?:strcmp((string)$candidate['itemId'],(string)$best['itemId'])?:($candidate['rotationName']<=>$best['rotationName']) ?:($candidate['nx']<=>$best['nx'])?:($candidate['ny']<=>$best['ny'])?:($candidate['nz']<=>$best['nz']); } return $order<0; diff --git a/src/Algorithm/Internal/ContainerPlanBeam.php b/src/Algorithm/Internal/ContainerPlanBeam.php index 097116f..dbacba8 100644 --- a/src/Algorithm/Internal/ContainerPlanBeam.php +++ b/src/Algorithm/Internal/ContainerPlanBeam.php @@ -28,7 +28,7 @@ public static function acrossContainerPlans(\Closure $call,SingleContainerSolver $beam=$reached?[]:[$initial];$incumbent=$initial;$nodes=0; $incumbentScore=self::planScore($incumbent,$incumbent['remaining'],$config); $maximum=$config->maxContainers??array_sum(array_map(static fn(Container $container):int=>$container->quantity??count($items),$containers)); - $ordered=StableSorter::sortBy($containers,static fn(Container $container):array=>[$container->costMinor,...$container->innerDimensions->volumeKey(),$container->id]); + $ordered=StableSorter::sortBy($containers,static fn(Container $container):array=>[$container->costMinor,...$container->innerDimensions->volumeKey(),StableSorter::textKey($container->id)]); // A beam wider than its node budget used to stop after trying the first // container in static order, so the order chose it, not the objective. The budget is at // least one trial per container type for every plan the beam keeps. diff --git a/src/Algorithm/ObjectiveBoundScope.php b/src/Algorithm/ObjectiveBoundScope.php index 0f525fd..c457434 100644 --- a/src/Algorithm/ObjectiveBoundScope.php +++ b/src/Algorithm/ObjectiveBoundScope.php @@ -14,8 +14,16 @@ final class ObjectiveBoundScope '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], + 'shipping_cost' => [0, 'billed_weight', 1, 3, 4], + 'lowest_landed_cost' => [0, 'landed_charge', 1, 3, 4], ]; + /** + * The objectives whose own key is what a carrier bills, which needs the configuration's + * dimensional-weight divisor and units as well as the request. + */ + public const BILLED_OBJECTIVES = ['shipping_cost', 'lowest_landed_cost']; + /** * O(containers) time, O(1) space; no instances or arithmetic are needed to refuse. * @param list $containers diff --git a/src/Algorithm/ObjectiveBounds.php b/src/Algorithm/ObjectiveBounds.php index a71a873..dcfd099 100644 --- a/src/Algorithm/ObjectiveBounds.php +++ b/src/Algorithm/ObjectiveBounds.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Algorithm; +use Packvium\Config\PackingConfig; use Packvium\Constraint\VolumeReserve; use Packvium\Domain\Container; use Packvium\Domain\Item; @@ -10,6 +11,7 @@ use Packvium\Support\BigInt; use Packvium\Support\ExactGeometry; use Packvium\Support\ExactInteger; +use Packvium\Unit\Weight; /** * Lower bounds on the objective vector, and the gap against an incumbent. @@ -31,7 +33,8 @@ * Complexity. `O(n log n + c log c)` for `n` instances and `c` container types, the same as * the Python port: one sort of the volumes, one of the weights, one of the container types * by cost. The volume sort compares decimal strings through `BigInt::compare` rather than - * PHP's default string order, where "9" would sort after "10". + * PHP's default string order, where "9" would sort after "10". The two billed keys + * add `O(n + c b log n + c b log(c b))` for `b` rate-table brackets per type. * * Which instances, and when. The bound is a property of the request: `Packer` computes it * once per pack through `forRequest`, over every instance the request declares -- fixed @@ -74,25 +77,32 @@ final class ObjectiveBounds * `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. + * `shipping_cost` and `lowest_landed_cost` add one each for what a carrier bills, + * read from the configuration's dimensional-weight divisor. */ public const OBJECTIVE_ORDERS = ObjectiveBoundScope::OBJECTIVE_ORDERS; + /** The objectives whose own key needs the configuration's divisor and units. */ + public const BILLED_OBJECTIVES = ObjectiveBoundScope::BILLED_OBJECTIVES; + /** * The request's bound in `$objective`'s own score order, or null where none is stated. * - * Null for an objective with no bound, for a request with a `made_to_measure` container - * (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 + * Null for an objective with no bound, for a billed objective whose inventory cannot carry + * a packing that attains `L0` at a price, for a request with a `made_to_measure` + * container (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). 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 + * @param ?PackingConfig $config the billed objectives' divisor and units; nothing else reads it * @return list|null */ - public static function forRequest(array $instances, array $containers, string $objective): ?array + public static function forRequest(array $instances, array $containers, string $objective, + ?PackingConfig $config = null): ?array { $order = ObjectiveBoundScope::order($containers, $objective); if ($order === null) { @@ -100,19 +110,77 @@ public static function forRequest(array $instances, array $containers, string $o } try { [$normalisedInstances, $normalisedContainers] = self::normalise($instances, $containers); + if (in_array($objective, self::BILLED_OBJECTIVES, true)) { + $normalisedContainers = self::withBilling($containers, $normalisedContainers, $config); + } return self::objectiveVector($normalisedInstances, $normalisedContainers, $order); - } catch (BoundOverflowException $refused) { + } catch (BoundOverflowException | BoundWithheldException $withheld) { return null; } } + /** + * Each type's normalised numbers with what a carrier can bill it, at the least. + * + * `tare` and `dimensional` are weight ticks: an opened container is billed + * `max(tare + payload, dimensional)`, so `max(tare, dimensional)` is its floor whatever it + * carries. A rigid container is billed on its declared outer size, else its declared inner + * one; a pallet whose load overhangs is billed larger per side, never smaller, and + * dimensional weight only grows with each side, so the declared size is a floor. A bag is + * billed on the package its contents make, which can be smaller than declared, so its + * floor is 0. `brackets` is the rate table as `[upper bound in weight ticks, charge]`, or + * empty where the objective prices nothing. `O(c b)` for `b` brackets per type. + * + * @param list $containers + * @param list> $normalised `normalise`'s containers, in the same order + * @return list> + */ + private static function withBilling(array $containers, array $normalised, ?PackingConfig $config): array + { + if ($config === null || $config->dimensionalWeightDivisor === null) { + throw new BoundWithheldException('a billed objective needs configuration.dimensional_weight_divisor'); + } + $landed = $config->objective === 'lowest_landed_cost'; + foreach ($containers as $index => $container) { + $normalised[$index]['tare'] = $container->tareWeight->ticks; + $normalised[$index]['dimensional'] = $container->isFlatBag() ? 0 + : ($container->outerDimensions ?? $container->declaredInner())->dimensionalWeight( + $config->dimensionalWeightDivisor, + $config->dimensionalWeightLengthUnit, + $config->dimensionalWeightWeightUnit, + )->ticks; + $normalised[$index]['brackets'] = $landed ? self::brackets($container) : []; + } + return $normalised; + } + + /** + * The rate table as `[bound in weight ticks, charge]`; the charge at a bracket's bound is + * that bracket's charge, since the bound is the heaviest weight it prices. + * + * @return list + */ + private static function brackets(Container $container): array + { + $table = $container->rateTable; + if ($table === null) { + return []; + } + return array_map(static fn(int $bound): array => [ + ExactInteger::mul($bound, Weight::TICKS_PER_G), + $table->chargeMinorOrNull($bound), + ], $table->weightBracketsG); + } + /** * 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. + * reads plus each instance's `value` -- and, for a billed objective, each container's + * `tare`, `dimensional` and `brackets` (`withBilling`) -- throwing `BoundOverflowException` + * where a ceiling withholds it, the one predicate's or the objective's own key's, and + * `BoundWithheldException` where a billed objective has no priceable answer to bound. * * @param list $instances - * @param list $containers + * @param list}> $containers * @param list $order an `OBJECTIVE_ORDERS` entry * @return list */ @@ -122,7 +190,7 @@ public static function objectiveVector(array $instances, array $containers, arra $vector = $evaluated['vector']; return array_map(static fn(int|string $position): int => is_int($position) ? $vector[$position] - : self::objectiveTerm($position, $instances, $evaluated), $order); + : self::objectiveTerm($position, $instances, $containers, $evaluated), $order); } /** @@ -135,17 +203,26 @@ public static function objectiveVector(array $instances, array $containers, arra * 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)`. + * the container types the request bound stays `O(n log n + c log c)`; the billed keys add + * `O(n + c b log n + c b log(c b))` for `b` brackets per type. * * @param list $instances - * @param array{vector:array{int,int,int,int,int},volumes:list,shrinks:bool,areas:list,capacity:?string} $evaluated + * @param list> $containers + * @param array{vector:array{int,int,int,int,int},volumes:list,weights:list,shrinks:bool,areas:list,capacity:?string} $evaluated */ - private static function objectiveTerm(string $name, array $instances, array $evaluated): int + private static function objectiveTerm(string $name, array $instances, array $containers, array $evaluated): int { - $unpacked = $evaluated['vector'][0]; + [$unpacked, $opened] = $evaluated['vector']; if ($name === 'value_forgone') { return self::valueForgoneBound(array_column($instances, 'value'), $unpacked); } + if ($name === 'billed_weight') { + return self::billedWeightBound($evaluated['weights'], $containers, $unpacked, $opened); + } + if ($name === 'landed_charge') { + return self::landedChargeBound($evaluated['weights'], $evaluated['volumes'], + $evaluated['shrinks'], $containers, $unpacked, $opened); + } if ($name === 'achieved_height') { return self::achievedHeightBound($evaluated['volumes'], $evaluated['shrinks'], count($instances) - $unpacked, $evaluated['areas']); @@ -154,6 +231,215 @@ private static function objectiveTerm(string $name, array $instances, array $eva $evaluated['capacity']); } + /** + * `shipping_cost`'s second key, summed billed weight in ticks. + * + * A packing that leaves exactly `$unpacked` behind opens at least `$opened` containers and + * carries at least the lightest `n - unpacked` instances. Each opened container is billed + * `max(tare + payload, dimensional)`, at least its floor, and a sum of maxima is at least + * either sum on its own, so the two can be taken over different types. Every term is + * non-negative, so opening more only adds. `O(n + c log c)`. + * + * @param list $weights ascending + * @param list> $containers + */ + private static function billedWeightBound(array $weights, array $containers, int $unpacked, int $opened): int + { + if ($opened === 0) { + return 0; + } + $quantities = array_map(static fn(array $c): ?int => $c['quantity'], $containers); + $floors = self::smallestFromInventory(array_map(self::billedFloor(...), $containers), $quantities, $opened); + $tares = self::smallestFromInventory( + array_map(static fn(array $c): int|string => $c['tare'], $containers), $quantities, $opened); + if ($floors === null || $tares === null) { + throw new BoundWithheldException('the inventory holds fewer containers than must be opened'); + } + $payload = ExactInteger::normalize(self::sumBig(array_map(strval(...), + array_slice($weights, 0, count($weights) - $unpacked)))); + return self::guardOutput((string)ExactInteger::max($floors, ExactInteger::add($tares, $payload)), + 'billed weight'); + } + + /** + * `lowest_landed_cost`'s second key, the summed carrier charge in minor units. + * + * Every opened container is billed in exactly one bracket and pays its charge. A container + * in bracket `[bound, charge]` weighs at most `bound`, so it is reachable only when its + * floor is within it, carries at most `bound - tare` of payload (and its `max_payload`), + * and at most as many instances as the lightest-first count under that payload, its usable + * volume and `max_items`. Three relaxations of that assignment hold, and the largest is the + * bound: the cheapest reachable charge per container over `$opened` containers; the least + * cost covering the placed weight; the least cost covering the placed count. Prices need + * not rise with weight, which is why a bracket is chosen rather than read off the floor. A + * type no bracket prices offers nothing: a packing that opens one is refused, never + * returned. `O(n + c b log n + c b log(c b))` for `b` brackets per type: the two + * prefix sums, a binary search per bracket and one sort of the offers. + * + * @param list $weights ascending + * @param list $volumes ascending + * @param list> $containers + */ + private static function landedChargeBound(array $weights, array $volumes, bool $shrinks, + array $containers, int $unpacked, int $opened): int + { + $placed = count($weights) - $unpacked; + if ($opened === 0 || $placed === 0) { + return 0; + } + $payloadPrefix = self::prefixSums($weights); + $volumePrefix = $shrinks ? null : self::prefixSums($volumes); + $cheapest = []; + $quantities = []; + $offers = []; + foreach ($containers as $container) { + $floor = self::billedFloor($container); + $reachable = array_values(array_filter($container['brackets'], + static fn(array $bracket): bool => $bracket[1] !== null + && ExactInteger::compare($floor, $bracket[0]) <= 0)); + if ($reachable === []) { + continue; + } + $cheapest[] = min(array_column($reachable, 1)); + $quantities[] = $container['quantity']; + // The volume limit is the type's, not the bracket's: asked once per type. + $roomy = $volumePrefix === null ? null + : self::fitPrefix($volumePrefix, ExactInteger::normalize($container['usable'])); + foreach ($reachable as [$bound, $charge]) { + $carried = ExactInteger::sub($bound, $container['tare']); + if ($container['payload'] !== null && ExactInteger::compare($container['payload'], $carried) < 0) { + $carried = $container['payload']; + } + $count = self::fitPrefix($payloadPrefix, $carried); + if ($roomy !== null) { + $count = min($count, $roomy); + } + if ($container['max_items'] !== null) { + $count = min($count, $container['max_items']); + } + $offers[] = [$charge, $carried, $count, $container['quantity']]; + } + } + $byCount = self::smallestFromInventory($cheapest, $quantities, $opened); + $byWeight = self::cover(array_map(static fn(array $o): array => [$o[0], $o[1], $o[3]], $offers), + $payloadPrefix[$placed - 1]); + $byItems = self::cover(array_map(static fn(array $o): array => [$o[0], $o[2], $o[3]], $offers), $placed); + if ($byCount === null || $byWeight === null || $byItems === null) { + throw new BoundWithheldException('no priceable inventory carries a packing that attains L0'); + } + return self::guardOutput((string)ExactInteger::max($byCount, ExactInteger::max($byWeight, $byItems)), + 'landed charge'); + } + + /** + * What one container is billed whatever it carries, `max(tare, dimensional)`. + * + * @param array $container + */ + private static function billedFloor(array $container): int|string + { + return ExactInteger::max($container['tare'], ExactInteger::normalize($container['dimensional'])); + } + + /** + * The sum of the `$count` smallest of `{value repeated quantity}`, or null when the + * inventory holds fewer. Sorting the types and taking `min(quantity, still needed)` of + * each is `L2`'s rule, `O(c log c)`, without building the multiset. + * + * @param list $values + * @param list $quantities + */ + private static function smallestFromInventory(array $values, array $quantities, int $count): int|string|null + { + $order = array_keys($values); + usort($order, static fn(int $a, int $b): int => ExactInteger::compare($values[$a], $values[$b])); + $total = 0; + $needed = $count; + foreach ($order as $index) { + if ($needed === 0) { + break; + } + $quantity = $quantities[$index]; + $taken = $quantity === null ? $needed : min($quantity, $needed); + $total = ExactInteger::add($total, ExactInteger::mul($values[$index], $taken)); + $needed -= $taken; + } + return $needed > 0 ? null : $total; + } + + /** + * Running totals of ascending non-negative values, native for as long as they fit. + * + * @param list $ascending + * @return list + */ + private static function prefixSums(array $ascending): array + { + $totals = []; + $running = 0; + foreach ($ascending as $value) { + $running = ExactInteger::add($running, ExactInteger::normalize($value)); + $totals[] = $running; + } + return $totals; + } + + /** + * How many of the smallest values sum to at most `$capacity`, by binary search over their + * prefix sums: `O(log n)` per question. + * + * @param list $prefix ascending + */ + private static function fitPrefix(array $prefix, int|string $capacity): int + { + $low = 0; + $high = count($prefix); + while ($low < $high) { + $middle = intdiv($low + $high, 2); + if (ExactInteger::compare($prefix[$middle], $capacity) <= 0) { + $low = $middle + 1; + } else { + $high = $middle; + } + } + return $low; + } + + /** + * The least cost covering `$need` units from `[cost, capacity, quantity]` offers, taken + * fractionally and rounded up, or null when the offers cannot cover it. + * + * A fractional covering problem with one constraint is solved exactly by taking offers in + * order of cost per unit, compared by cross-multiplication. Only the last offer is taken + * in part, so the cost is an integer plus one ceiling and no fraction is carried. Offers + * of equal cost per unit give the same total in either order, so the order needs no + * tie-break. Each offer is limited by its type's whole inventory, which only weakens the + * bound. `O(k log k)` for `k` offers. + * + * @param list $offers + */ + private static function cover(array $offers, int|string $need): int|string|null + { + if (ExactInteger::sign($need) <= 0) { + return 0; + } + $ranked = array_values(array_filter($offers, + static fn(array $offer): bool => ExactInteger::sign($offer[1]) > 0)); + usort($ranked, static fn(array $a, array $b): int => ExactInteger::compare( + ExactInteger::mul($a[0], $b[1]), ExactInteger::mul($b[0], $a[1]))); + $total = 0; + foreach ($ranked as [$cost, $capacity, $quantity]) { + if ($quantity === null || ExactInteger::compare(ExactInteger::mul($quantity, $capacity), $need) >= 0) { + // ceil(cost * need / capacity), as the negated floor of its negation. + return ExactInteger::add($total, ExactInteger::negate(ExactInteger::floorDiv( + ExactInteger::negate(ExactInteger::mul($cost, $need)), $capacity))); + } + $total = ExactInteger::add($total, ExactInteger::mul($cost, $quantity)); + $need = ExactInteger::sub($need, ExactInteger::mul($capacity, $quantity)); + } + return null; + } + /** * `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 @@ -401,12 +687,12 @@ public static function fromNormalised(array $instances, array $containers): arra /** * `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). + * than recompute: the ascending volumes and weights, 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} + * @return array{vector:array{int,int,int,int,int},volumes:list,weights:list,shrinks:bool,areas:list,capacity:?string} */ private static function evaluate(array $instances, array $containers): array { @@ -459,7 +745,7 @@ private static function evaluate(array $instances, array $containers): array self::guardOutput((string)$unused, 'unused volume'), self::guardOutput((string)$height, 'stack height'), ]; - return ['vector' => $vector, 'volumes' => $volumes, 'shrinks' => $shrinks, + return ['vector' => $vector, 'volumes' => $volumes, 'weights' => $weights, 'shrinks' => $shrinks, 'areas' => $areas, 'capacity' => $capacities['volume']]; } diff --git a/src/Algorithm/SolverOrchestrator.php b/src/Algorithm/SolverOrchestrator.php index 56e6fc8..b2530d0 100644 --- a/src/Algorithm/SolverOrchestrator.php +++ b/src/Algorithm/SolverOrchestrator.php @@ -17,6 +17,8 @@ final class SolverOrchestrator * (`...:late_:beam`), as Python's `LATE_TYPE_REFINEMENT_WIDTH`. */ private const LATE_TYPE_REFINEMENT_WIDTH=4; + /** @var array{config:PackingConfig,packed:list,states:array,verdicts:array}|null */ + private ?array $supportDiagnostic=null; public function __construct(private array $customConstraints=[],private array $customOrders=[],private array $customSolvers=[],private ?CandidateScorer $candidateScorer=null,private ?ContainerSelector $containerSelector=null){} /** @return list */ @@ -219,12 +221,13 @@ private function finishPortfolio(array $items,array $containers,Deadline $deadli } /** - * Whether one box of these dimensions fits this container empty: the frame, and for a flat - * bag the girth rule too, so a bag too thin for an item proves it unplaceable. + * Whether one box of these dimensions fits this container empty: the frame, and for a bag + * the girth rule too, so a bag too thin for an item proves it unplaceable. */ private static function fitsAlone(Container $container,Dimensions $dimensions):bool { - return $container->isFlatBag()?FlatBag::fitsAlone($container->innerDimensions,$dimensions,$container->sideGussetTicks()):$dimensions->fitsInside($container->innerDimensions); + $girth=$container->girth(); + return $girth!==null?FlatBag::fitsAlone($container->innerDimensions,$dimensions,$girth):$dimensions->fitsInside($container->innerDimensions); } /** @param list $containers */ @@ -350,6 +353,18 @@ private static function axlesAdmitAlone(Container $container,array $envelopes,in * @param list $packed */ private function supportIsTheBlocker(ItemInstance $item,array $packed,PackingConfig $config):bool + { + // The answer is a function of the item's declared attributes and the final layout, + // so every instance of a type shares one verdict -- unless a caller's own constraint + // or scorer may read the instance itself, in which case each instance is asked. + // The packed-container states are likewise built once per layout, not once per item. + if($this->supportDiagnostic===null||$this->supportDiagnostic['config']!==$config||$this->supportDiagnostic['packed']!==$packed) + $this->supportDiagnostic=['config'=>$config,'packed'=>$packed,'states'=>[],'verdicts'=>[]]; + $key=$this->customConstraints===[]&&$this->candidateScorer===null?$item->item->id:$item->id(); + return $this->supportDiagnostic['verdicts'][$key]??=$this->observeSupportBlocker($item,$config); + } + + private function observeSupportBlocker(ItemInstance $item,PackingConfig $config):bool { $constraints=ConstraintSet::defaults($config->minimumSupportRatio,$this->customConstraints,$config->accessDirections); $hasSupport=false; @@ -358,20 +373,31 @@ private function supportIsTheBlocker(ItemInstance $item,array $packed,PackingCon if(!$hasSupport)return false; $withoutSupport=array_values(array_filter($constraints,static fn($c)=>!($c instanceof SupportConstraint))); $scorer=$this->candidateScorer??new DefaultCandidateScorer(); - // A small, fixed local budget -- independent of the caller's own deadline, - // which may already be exhausted -- so this diagnostic can never itself hang - // the solve; it is a best-effort explanation, not a required step. - $budget=Deadline::ofMilliseconds(2_000); - foreach($packed as $packedContainer){ - if($budget->expired())return false; - $state=new ContainerState($packedContainer->container,$packedContainer->sequence); - foreach($packedContainer->placements as $placement)$state->add($placement); - if(CandidateFinder::find($state,$item,$config,$withoutSupport,new SearchStats(),$budget,$scorer,1)===[])continue; - if(CandidateFinder::find($state,$item,$config,$constraints,new SearchStats(),$budget,$scorer,1)===[])return true; + // No wall clock: the reason an item is reported unpacked must be a function of the + // request and the layout, never of machine load. A frozen clock leaves nothing to + // expire; the search is bounded by the layout's own candidate points (max one + // candidate wanted), and `supportIsTheBlocker` memoises one verdict per item type. + $budget=new Deadline(PHP_INT_MAX,static fn():int=>0); + try{ + foreach($this->supportDiagnostic['packed'] as $index=>$packedContainer){ + $state=$this->supportDiagnostic['states'][$index]??=self::replayedState($packedContainer); + if(CandidateFinder::find($state,$item,$config,$withoutSupport,new SearchStats(),$budget,$scorer,1)===[])continue; + if(CandidateFinder::find($state,$item,$config,$constraints,new SearchStats(),$budget,$scorer,1)===[])return true; + } + }catch(TimeLimitReached){ + // Only a caller's own scorer or constraint can raise it now; no verdict, as before. + return false; } return false; } + private static function replayedState(PackedContainer $packedContainer):ContainerState + { + $state=new ContainerState($packedContainer->container,$packedContainer->sequence); + foreach($packedContainer->placements as $placement)$state->add($placement); + return $state; + } + /** * The block start `fast` and `balanced` add to their own, or `null`. * @@ -587,7 +613,7 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem $billed=max($gross,$dimensional); $placed=$one->state->placementCount(); if($config->objective==='shipping_cost'){ - $candidateScore=[-$placed,$billed,$container->id]; + $candidateScore=[-$placed,$billed,StableSorter::textKey($container->id)]; }else{ // Landed cost ranks the round by the money the finished score will // charge, not by the grams it is derived from. This loop commits the @@ -602,7 +628,7 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem $charge??LandedCostSolutionScorer::UNPRICEABLE_MINOR, intdiv(count($roundItems)+max($placed,1)-1,max($placed,1)), -$placed, - $container->id, + StableSorter::textKey($container->id), ]; } }elseif($config->objective==='maximum_volume'&&$selector instanceof DefaultContainerSelector){ @@ -610,7 +636,7 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem // that seated the most pieces. A caller's own selector is left alone. $used=$one->state->usedVolume; $leftover=BigInt::chunks(BigInt::subtract($container->innerDimensions->volumeString(),$used)); - $candidateScore=[...array_map(static fn(int $c):int=>-$c,BigInt::chunks($used)),$container->costMinor,...$leftover,$container->id]; + $candidateScore=[...array_map(static fn(int $c):int=>-$c,BigInt::chunks($used)),$container->costMinor,...$leftover,StableSorter::textKey($container->id)]; }else{ $candidateScore=$selector->score($container,$one); } @@ -659,7 +685,7 @@ private function acrossContainers(SingleContainerSolver $solver,array $items,arr $remaining=$opened['remaining'];$packed=$opened['packed'];$exhaustive=$opened['exhaustive'];$dominantLattice=$opened['dominant']; $inventory=$opened['inventory'];$seq=$opened['sequences']; $maximum=$config->maxContainers??array_sum(array_map(static fn($c)=>$c->quantity??count($items),$containers)); - $ordered=StableSorter::sortBy($containers,static fn(Container $c):array=>[$c->costMinor,...$c->innerDimensions->volumeKey(),$c->id]); + $ordered=StableSorter::sortBy($containers,static fn(Container $c):array=>[$c->costMinor,...$c->innerDimensions->volumeKey(),StableSorter::textKey($c->id)]); $selector=$this->containerSelector??new DefaultContainerSelector(); while($remaining!==[]&&count($packed)<$maximum&&!$reached){ if($deadline->expired()){$reached=true;break;} diff --git a/src/Algorithm/WeightRebalancer.php b/src/Algorithm/WeightRebalancer.php index 3369c2e..9da56bb 100644 --- a/src/Algorithm/WeightRebalancer.php +++ b/src/Algorithm/WeightRebalancer.php @@ -87,7 +87,15 @@ public static function rebalance( } $validator = new IndependentSolutionValidator(); $deadline = Deadline::ofMilliseconds($timeLimitMs); - $working = array_values($containers); + // A compact lattice container carries no per-item placements; the pass below + // reads and moves individual placements, so expand it the way Packer does + // before validation. + $working = array_map( + static fn(PackedContainer $c): PackedContainer => $c->latticeSummary !== null + ? new PackedContainer($c->container, $c->sequence, $c->expandPlacements()) + : $c, + array_values($containers), + ); $moves = []; for ($round = 0; $round < $maxMoves; $round++) { @@ -102,7 +110,8 @@ public static function rebalance( $sourceIndex = self::argMax($weights); $source = $working[$sourceIndex]; - $rankedItems = range(0, count($source->placements) - 1); + // Not `range(0, count - 1)`: for an empty container PHP's range counts down to [0, -1]. + $rankedItems = $source->placements === [] ? [] : range(0, count($source->placements) - 1); usort($rankedItems, static fn(int $a, int $b): int => ($source->placements[$b]->instance->weight()->ticks <=> $source->placements[$a]->instance->weight()->ticks) ?: ($a <=> $b)); @@ -157,7 +166,8 @@ public static function rebalance( $working = $trial; } - return new RebalanceResult($working, $moves); + // Nothing moved: hand back the containers as given, compact ones still compact. + return new RebalanceResult($moves === [] ? array_values($containers) : $working, $moves); } /** diff --git a/src/Artifacts/OperationalArtifact.php b/src/Artifacts/OperationalArtifact.php index 7561c3c..49383e2 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.10.0'; + public const SUITE_VERSION = '1.11.0'; /** The deterministic part of `result.algorithm`; `duration_ms` is wall-clock time. */ private const SOLVER_FIELDS = ['profile', 'solver', 'seed', 'time_limit_reached', 'effort_limit_reached']; diff --git a/src/Commerce/Document.php b/src/Commerce/Document.php index f554d74..dcbf7e7 100644 --- a/src/Commerce/Document.php +++ b/src/Commerce/Document.php @@ -80,8 +80,17 @@ private static function publishTariffVersions(CarrierRegistry $registry, string ['minimum_charge_minor', 'fuel_surcharge_permille', 'accessorials'], ); $costs = []; - foreach (Shape::map($fields['cost_per_dimensional_kg_minor'], "{$path}.cost_per_dimensional_kg_minor") as $zone => $cost) { - $costs[(string)$zone] = Shape::integer($cost, "{$path}.cost_per_dimensional_kg_minor[{$zone}]"); + $zones = Shape::map($fields['cost_per_dimensional_kg_minor'], "{$path}.cost_per_dimensional_kg_minor"); + // Validated in code-point order of the zone key (PHP turns numeric-looking keys into ints), + // so the first error never depends on the order a language iterates the mapping in. + $zoneKeys = array_map('strval', array_keys($zones)); + usort($zoneKeys, 'strcmp'); + foreach ($zoneKeys as $zone) { + Shape::integer($zones[$zone], "{$path}.cost_per_dimensional_kg_minor[{$zone}]"); + } + // Insertion order is kept for the tariff itself. + foreach ($zones as $zone => $cost) { + $costs[(string)$zone] = $cost; } Shape::model($path, static fn() => $registry->publish( $carrierId, $serviceId, diff --git a/src/Commerce/Rating/AccessorialCharge.php b/src/Commerce/Rating/AccessorialCharge.php index ba2a928..6f2ed12 100644 --- a/src/Commerce/Rating/AccessorialCharge.php +++ b/src/Commerce/Rating/AccessorialCharge.php @@ -23,8 +23,8 @@ public function __construct( if ($permilleOfBase !== null && $permilleOfBase < 0) { throw new \InvalidArgumentException('permille_of_base cannot be negative'); } } - public function chargeMinor(int $baseChargeMinor): int + public function chargeMinor(int|string $baseChargeMinor): int|string { - return $this->flatChargeMinor ?? Arithmetic::mulDivCeil($baseChargeMinor, (int)$this->permilleOfBase, 1000); + return $this->flatChargeMinor ?? Arithmetic::mulDivCeilExact($baseChargeMinor, (int)$this->permilleOfBase, 1000); } } diff --git a/src/Commerce/Rating/CarrierRegistry.php b/src/Commerce/Rating/CarrierRegistry.php index de1bafc..df2d455 100644 --- a/src/Commerce/Rating/CarrierRegistry.php +++ b/src/Commerce/Rating/CarrierRegistry.php @@ -2,7 +2,10 @@ declare(strict_types=1); namespace Packvium\Commerce\Rating; +use Packvium\Commerce\CommerceInputException; use Packvium\Support\Arithmetic; +use Packvium\Support\CanonicalJson; +use Packvium\Support\ExactInteger; /** * Per-(carrier_id, service_id) append-only tariff history, and the rating itself. @@ -114,33 +117,50 @@ public static function rateTariff(Tariff $tariff, RatingRequest $request): RateB ); } - // 1 mm^3 of volume divided by the tariff's divisor gives dimensional weight in - // grams, rounded up -- never down, never through a float. - $dimensionalWeightG = Arithmetic::mulDivCeil($request->volumeMm3, 1, $tariff->dimensionalWeightDivisor); - $billedWeightG = max($request->actualWeightG, $dimensionalWeightG); + // Every amount is computed exactly and then held to the one ceiling an engine can + // report without rounding (M2): the first reported amount above it refuses the quote. + $dimensionalWeightG = Arithmetic::mulDivCeilExact($request->volumeMm3, 1, $tariff->dimensionalWeightDivisor); + $billedWeightG = ExactInteger::max($request->actualWeightG, $dimensionalWeightG); - $rawBaseChargeMinor = Arithmetic::mulDivCeil($billedWeightG, $tariff->costPerDimensionalKgMinor[$request->zone], 1000); - $minimumApplied = $rawBaseChargeMinor < $tariff->minimumChargeMinor; + $rawBaseChargeMinor = Arithmetic::mulDivCeilExact($billedWeightG, $tariff->costPerDimensionalKgMinor[$request->zone], 1000); + $minimumApplied = ExactInteger::compare($rawBaseChargeMinor, $tariff->minimumChargeMinor) < 0; $baseChargeMinor = $minimumApplied ? $tariff->minimumChargeMinor : $rawBaseChargeMinor; - - $fuelSurchargeMinor = Arithmetic::mulDivCeil($baseChargeMinor, $tariff->fuelSurchargePermille, 1000); + $fuelSurchargeMinor = Arithmetic::mulDivCeilExact($baseChargeMinor, $tariff->fuelSurchargePermille, 1000); $accessorialCharges = []; $accessorialTotal = 0; foreach ($request->requestedAccessorials as $accessorialId) { $amount = $tariff->accessorials[$accessorialId]->chargeMinor($baseChargeMinor); $accessorialCharges[] = [$accessorialId, $amount]; - $accessorialTotal += $amount; + $accessorialTotal = ExactInteger::add($accessorialTotal, $amount); + } + $totalMinor = ExactInteger::add(ExactInteger::add($baseChargeMinor, $fuelSurchargeMinor), $accessorialTotal); + + $reported = [$dimensionalWeightG, $billedWeightG, $baseChargeMinor, $fuelSurchargeMinor]; + foreach ($accessorialCharges as [, $amount]) { + $reported[] = $amount; + } + $reported[] = $totalMinor; + foreach ($reported as $value) { + self::requireReportable($value); } return new RateBreakdown( $tariff->carrierId, $tariff->serviceId, $tariff->version, $request->zone, $request->actualWeightG, $dimensionalWeightG, $billedWeightG, $baseChargeMinor, - $minimumApplied, $fuelSurchargeMinor, $accessorialCharges, - $baseChargeMinor + $fuelSurchargeMinor + $accessorialTotal, + $minimumApplied, $fuelSurchargeMinor, $accessorialCharges, $totalMinor, ); } + private static function requireReportable(int|string $value): void + { + if (ExactInteger::compare($value, CanonicalJson::MAX_EXACT_MAGNITUDE) > 0) { + throw new CommerceInputException( + "quote amount {$value} is above " . CanonicalJson::MAX_EXACT_MAGNITUDE . ' and cannot be represented exactly' + ); + } + } + private static function key(string $carrierId, string $serviceId): string { return strlen($carrierId) . ':' . $carrierId . $serviceId; diff --git a/src/Constraint/StopAccessibilityConstraint.php b/src/Constraint/StopAccessibilityConstraint.php index c452cb0..9b3b37e 100644 --- a/src/Constraint/StopAccessibilityConstraint.php +++ b/src/Constraint/StopAccessibilityConstraint.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use InvalidArgumentException; +use Packvium\Domain\AxisAlignedBox; use Packvium\Domain\Dimensions; use Packvium\Domain\Placement; use Packvium\Domain\SweptRegion; @@ -45,6 +46,11 @@ final class StopAccessibilityConstraint implements PlacementConstraint private array $clear=[]; /** @var list */ private array $stops=[]; + /** @var list */ + private array $boxes=[]; + /** @var list> */ + private array $sweeps=[]; + private bool $stopsVary=false; /** @param list $directions */ public function __construct(array $directions=[]) @@ -90,6 +96,10 @@ private static function stopOf(Placement $p):int|float * with different doors have different answers for the same boxes, and nothing else in * the key separates them. * + * The same entry holds what only depends on those placements: their envelope boxes, the + * region each finite-stop box sweeps towards each door, and whether their stops differ. + * A placement is immutable, so none of it can go stale while the key holds. + * * @param list $placements * @param list $directions * @return array{0:list>,1:list} @@ -99,15 +109,15 @@ private function baseFor(array $placements,Dimensions $container,array $directio if($this->placements===$placements&&$this->container==$container&&$this->directions===$directions)return [$this->clear,$this->stops]; $stops=[];$boxes=[]; foreach($placements as $p){$stops[]=self::stopOf($p);$boxes[]=$p->envelopeBox();} - $clear=[]; + $clear=[];$sweeps=[]; foreach($boxes as $index=>$box){ - $open=[]; + $open=[];$swept=[]; if($stops[$index]===INF){ // Never unloaded, so it needs no door of its own -- it only ever blocks. foreach($directions as $d)$open[$d]=true; }else{ foreach($directions as $d){ - $sweep=SweptRegion::volume($box,$container,$d); + $sweep=$swept[$d]=SweptRegion::volume($box,$container,$d); $blocked=false; foreach($boxes as $other=>$otherBox){ if($other!==$index&&$stops[$other]>$stops[$index]&&SweptRegion::intersects($sweep,$otherBox)){$blocked=true;break;} @@ -115,9 +125,11 @@ private function baseFor(array $placements,Dimensions $container,array $directio if(!$blocked)$open[$d]=true; } } - $clear[]=$open; + $clear[]=$open;$sweeps[]=$swept; } $this->placements=$placements;$this->container=$container;$this->directions=$directions;$this->clear=$clear;$this->stops=$stops; + $this->boxes=$boxes;$this->sweeps=$sweeps; + $this->stopsVary=count(array_unique($stops,SORT_REGULAR))>1; return [$clear,$stops]; } @@ -149,8 +161,7 @@ public function evaluate(ConstraintContext $c):ConstraintResult // One distinct stop means nothing can be due before anything else, so no corridor // can be blocked by a later item. Checked over the candidate too, or the first // placement into an empty container would skip a check it should make. - $distinct=$stops;$distinct[]=$candidateStop; - if(count(array_unique($distinct,SORT_REGULAR))<2)return ConstraintResult::allow(); + if(!$this->stopsVary&&($stops===[]||$candidateStop===$stops[0]))return ConstraintResult::allow(); $candidate=$c->envelopeBox(); foreach($c->placements as $index=>$placement){ @@ -158,7 +169,7 @@ public function evaluate(ConstraintContext $c):ConstraintResult if($clear[$index]===[])continue; $stillOpen=false; foreach(array_keys($clear[$index]) as $d){ - if(!SweptRegion::intersects(SweptRegion::volume($placement->envelopeBox(),$inner,$d),$candidate)){$stillOpen=true;break;} + if(!SweptRegion::intersects($this->sweeps[$index][$d],$candidate)){$stillOpen=true;break;} } if(!$stillOpen){ $stop=$stops[$index]; @@ -171,8 +182,8 @@ public function evaluate(ConstraintContext $c):ConstraintResult foreach($directions as $d){ $sweep=SweptRegion::volume($candidate,$inner,$d); $blocked=false; - foreach($c->placements as $other=>$placement){ - if($stops[$other]>$candidateStop&&SweptRegion::intersects($sweep,$placement->envelopeBox())){$blocked=true;break;} + foreach($this->boxes as $other=>$otherBox){ + if($stops[$other]>$candidateStop&&SweptRegion::intersects($sweep,$otherBox)){$blocked=true;break;} } if(!$blocked)return ConstraintResult::allow(); } diff --git a/src/Domain/Container.php b/src/Domain/Container.php index 544a861..a0b169d 100644 --- a/src/Domain/Container.php +++ b/src/Domain/Container.php @@ -33,8 +33,14 @@ * * `$deformableBoundary`: `'flat_bag'` makes this a flexible bag whose package conforms to its * 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. + * `$sideGussetDepth` (1.10) and whose length girth is lengthened by `$bottomGussetDepth` + * (1.11): that kind declares either or both, and every other container refuses + * them. null is a rigid container. + * + * `$bagOrientation`: `'flat'` or `'standing'`: a gusseted bag with a bottom gusset + * may stand on it. `$uprightFrame`: set only by `PalletOverhang::solvingFrame`, whose + * `$innerDimensions` is then the standing W x H x L frame, which `declaredInner` turns back. + * A frame is never turned twice. * * `$palletOverhangLimit`: how far a load may pass this pallet deck's edges (, * `PalletOverhang`). `$deck`: the deck inside a solving frame, set only by @@ -43,18 +49,34 @@ * * @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,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"); + 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,public ?Length $bottomGussetDepth=null,public string $bagOrientation='flat',public bool $uprightFrame=false) + {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,self::declaredInnerOf($innerDimensions,$deck,$uprightFrame),$sideGussetDepth,$bottomGussetDepth,$bagOrientation,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio,$palletOverhangLimit);else self::refuseGussetFields($sideGussetDepth,$bottomGussetDepth,$bagOrientation);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,$uprightFrame)->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,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth);} + 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,$this->bottomGussetDepth,$this->bagOrientation,$this->uprightFrame);} 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 bottom gusset depth K in ticks; 0 where none is declared. */ + public function bottomGussetTicks():int{return $this->bottomGussetDepth===null?0:$this->bottomGussetDepth->ticks;} + /** A bag's two loops in the frame it is packed in; null for a rigid container. */ + public function girth():?Girth + { + if($this->deformableBoundary===null)return null; + $declared=$this->declaredInner(); + return FlatBag::girthFor($declared->length->ticks,$declared->width->ticks,$this->sideGussetTicks(),$this->bottomGussetTicks(),$this->uprightFrame); + } + /** + * The same bag packed in its standing W x H x L frame: how `PalletOverhang` builds a + * standing bag's solving frame. O(1). + * + * @internal + */ + public function upright():self{return new self($this->id,FlatBag::standingDimensions($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,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth,$this->bottomGussetDepth,$this->bagOrientation,true);} /** * 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 @@ -62,10 +84,17 @@ public function sideGussetTicks():int{return $this->sideGussetDepth===null?0:$th * * @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);} + 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,$this->bottomGussetDepth,$this->bagOrientation,$this->uprightFrame);} + /** + * The inner size the caller declared: a solving frame's deck at its height, a standing bag's + * frame turned back to L x W x H, else `innerDimensions`. + */ + public function declaredInner():Dimensions{return self::declaredInnerOf($this->innerDimensions,$this->deck,$this->uprightFrame);} + private static function declaredInnerOf(Dimensions $inner,?Deck $deck,bool $uprightFrame):Dimensions + { + if($uprightFrame)return new Dimensions($inner->height,$inner->length,$inner->width); + 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);} /** @@ -88,7 +117,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,$this->palletOverhangLimit,$this->deck,$this->sideGussetDepth);} + 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,$this->bottomGussetDepth,$this->bagOrientation,$this->uprightFrame);} /** @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]));} /** @@ -98,26 +127,40 @@ 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,Dimensions $inner,?Length $sideGussetDepth,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio,?OverhangLimit $palletOverhangLimit):void + private static function requireBagFields(string $kind,Dimensions $declared,?Length $sideGussetDepth,?Length $bottomGussetDepth,string $bagOrientation,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}"); - self::requireGussetRule($kind===FlatBag::GUSSETED_BAG,$inner,$sideGussetDepth); + self::requireGussetRule($kind===FlatBag::GUSSETED_BAG,$declared,$sideGussetDepth,$bottomGussetDepth,$bagOrientation); $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). + * Gusset depths and a standing orientation describe a gusseted bag and nothing else. `'flat'` + * is `FlatBag::FLAT` spelled out, so a rigid container never loads `FlatBag`. + */ + private static function refuseGussetFields(?Length $sideGussetDepth,?Length $bottomGussetDepth,string $bagOrientation):void + { + $present=['side_gusset_depth'=>$sideGussetDepth!==null,'bottom_gusset_depth'=>$bottomGussetDepth!==null,'orientation'=>$bagOrientation!=='flat']; + foreach($present as $name=>$set)if($set)throw new ObjectRefusal('not_allowed',"{$name} requires deformable_boundary gusseted_bag"); + } + /** + * A gusseted bag declares a side gusset, a bottom gusset or both, each positive. A side + * gusset is no deeper than the bag is wide and a bottom one no deeper than twice its length: + * a deeper fold would have no flat sheet left to fold from. Standing needs a bottom gusset to + * stand on. A flat bag takes none of them. O(1). */ - private static function requireGussetRule(bool $gusseted,Dimensions $inner,?Length $sideGussetDepth):void + private static function requireGussetRule(bool $gusseted,Dimensions $declared,?Length $sideGussetDepth,?Length $bottomGussetDepth,string $bagOrientation):void { - if($sideGussetDepth===null){ - if($gusseted)throw new ObjectRefusal('missing_field','a gusseted_bag requires side_gusset_depth'); - return; + if(!$gusseted){self::refuseGussetFields($sideGussetDepth,$bottomGussetDepth,$bagOrientation);return;} + if($sideGussetDepth===null&&$bottomGussetDepth===null)throw new ObjectRefusal('missing_field','a gusseted_bag requires side_gusset_depth'); + $folds=[['side_gusset_depth',$sideGussetDepth,$declared->width->ticks,'inner_dimensions width'],['bottom_gusset_depth',$bottomGussetDepth,2*$declared->length->ticks,'twice inner_dimensions length']]; + foreach($folds as [$name,$depth,$limit,$what]){ + if($depth===null)continue; + if($depth->ticks<=0)throw new ObjectRefusal('invalid_value',"{$name} must be positive"); + if($depth->ticks>$limit)throw new ObjectRefusal('invalid_value',"{$name} exceeds {$what}"); } - 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'); + if(!in_array($bagOrientation,FlatBag::ORIENTATIONS,true))throw new ObjectRefusal('not_allowed',"orientation must be one of ['flat', 'standing']"); + if($bagOrientation===FlatBag::STANDING&&$bottomGussetDepth===null)throw new ObjectRefusal('missing_field','bottom_gusset_depth is required when orientation is standing'); } /** * The fields a pallet with an overhang limit refuses: each reads the declared frame or a wall @@ -131,5 +174,5 @@ private static function requirePalletFields(array $obstacles,?array $axles,array $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);} + 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,?Length $bottomGussetDepth=null,string $bagOrientation='flat'):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,$bottomGussetDepth,$bagOrientation);} } diff --git a/src/Domain/FlatBag.php b/src/Domain/FlatBag.php index d1f7e24..04b6c2a 100644 --- a/src/Domain/FlatBag.php +++ b/src/Domain/FlatBag.php @@ -17,24 +17,60 @@ * * 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. + * b + c <= W + G, and G = 0 is the flat bag. Every method here takes the gusset depths in + * ticks, 0 where none is declared. + * + * A bottom gusset (1.11) is one panel of depth K folded into the closed end: the loop + * along the bag runs front, bottom, back, 2L + K, so the length sum becomes 2(a + c) <= 2L + K, + * doubled to stay in integers. A gusseted bag with a bottom gusset may stand on it + * (`orientation: standing`): the solving frame is then W x H x L, the floor is the opened + * bottom, and the same two loops go round other axes -- a + b <= W + G across, 2(b + c) <= 2L + K + * along. `Girth` holds the two loops for either frame. */ final class FlatBag { public const GUSSETED_BAG='gusseted_bag'; public const KINDS=['flat_bag',self::GUSSETED_BAG]; + public const FLAT='flat'; + public const STANDING='standing'; + public const ORIENTATIONS=[self::FLAT,self::STANDING]; + /** The keys a gusseted bag's boundary may carry (1.10 side gusset; 1.11 bottom gusset and orientation). */ + public const GUSSETED_BAG_FIELDS=['bottom_gusset_depth','kind','orientation','side_gusset_depth']; - /** 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,int $gusset=0):bool + /** + * Whether a package of extents (a, b, c) passes both girth sums of a bag lying flat in + * `$inner`; the frame is the caller's. + */ + public static function girthAdmits(Dimensions $inner,int $a,int $b,int $c,int $gusset=0,int $bottomGusset=0):bool { - return $a+$c<=$inner->length->ticks&&$b+$c<=$inner->width->ticks+$gusset; + return self::girthFor($inner->length->ticks,$inner->width->ticks,$gusset,$bottomGusset,false)->admits([$a,$b,$c]); } - /** 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 + /** + * The loops of a bag declared `$length x $width` with the two gusset depths, 0 where none is + * declared, in its flat or standing frame. O(1). + */ + public static function girthFor(int $length,int $width,int $sideGusset,int $bottomGusset,bool $standing):Girth + { + if($standing)return new Girth([1,2],2*$length+$bottomGusset,[0,1],$width+$sideGusset); + return new Girth([0,2],2*$length+$bottomGusset,[1,2],$width+$sideGusset); + } + + /** The W x H x L frame a bag declared L x W x H stands in. */ + public static function standingDimensions(Dimensions $declared):Dimensions + { + return new Dimensions($declared->width,$declared->height,$declared->length); + } + + /** + * Whether one box of these dimensions, alone at the origin of the frame `$inner`, fits a bag: + * against its `Girth`, or lying flat with a side gusset of `$gusset` ticks. The parameter keeps + * its 1.10 name, which a named argument may spell. + */ + public static function fitsAlone(Dimensions $inner,Dimensions $box,int|Girth $gusset=0):bool { - return $box->fitsInside($inner)&&self::girthAdmits($inner,$box->length->ticks,$box->width->ticks,$box->height->ticks,$gusset); + $girth=$gusset instanceof Girth?$gusset:self::girthFor($inner->length->ticks,$inner->width->ticks,$gusset,0,false); + return $box->fitsInside($inner)&&$girth->admits([$box->length->ticks,$box->width->ticks,$box->height->ticks]); } /** diff --git a/src/Domain/Girth.php b/src/Domain/Girth.php new file mode 100644 index 0000000..5429389 --- /dev/null +++ b/src/Domain/Girth.php @@ -0,0 +1,27 @@ +along[0]]+$extent[$this->along[1]])<=$this->alongLimit + &&$extent[$this->across[0]]+$extent[$this->across[1]]<=$this->acrossLimit; + } +} diff --git a/src/Domain/HullShape.php b/src/Domain/HullShape.php index 1b666c9..291eb01 100644 --- a/src/Domain/HullShape.php +++ b/src/Domain/HullShape.php @@ -4,6 +4,7 @@ use InvalidArgumentException; use Packvium\Support\BigInt; +use Packvium\Support\ObjectRefusal; use Packvium\Support\SignedBigInt; /** @@ -31,6 +32,17 @@ final class HullShape /** Smallest number of vertices that can enclose a volume. */ public const MINIMUM_VERTICES = 4; + /** Most vertices an item's hull may list; refused at admission, before any per-vertex work. */ + public const MAXIMUM_VERTICES = 32; + + /** @throws ObjectRefusal */ + public static function admitVertexCount(int $count): void + { + if ($count > self::MAXIMUM_VERTICES) { + throw new ObjectRefusal('above_maximum', 'hull_vertices must have at most ' . self::MAXIMUM_VERTICES . ' vertices'); + } + } + /** Both the face normals and the edge directions of any axis-aligned box. */ private const UNIT_AXES = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]; @@ -73,6 +85,32 @@ private function __construct( /** @var array */ private static array $shapeCache = []; + /** + * How many separating axes the pair memo holds, before it is dropped and refilled -- the + * policy of the shape memo above. Counted in axes rather than pairs because a pair's size + * is the product of its shapes' edge counts: a 32-vertex pair is about 3900 axes and 1 MB, + * a box against a hull a few dozen. This ceiling is about 8 MB, under the shape memo's. + */ + private const PAIR_CACHE_AXES = 16384; + + /** Axis structure of every `box()`: its face normals and edge directions are always the unit axes. */ + private const BOX_STRUCTURE = -1; + + /** Next axis structure id handed to a memoised hull; ids are never reused, so a stale entry can only be unreachable. */ + private static int $nextStructure = 1; + + /** @var array,left:array,right:array}> */ + private static array $pairCache = []; + + private static int $pairCacheAxes = 0; + + /** + * Identifies the face normals and edge directions this shape contributes to a pair's axes: + * a `shapeFor` hull has its own id, a `box()` the shared `BOX_STRUCTURE`, and any other + * shape 0, which opts out of the pair memo. + */ + private int $structure = 0; + /** * The rotated hull of one item in one orientation, built at most once. * @@ -98,6 +136,7 @@ public static function shapeFor(array $vertices, Rotation $rotation): self return self::$shapeCache[$key]; } $shape = self::of(self::rotate($vertices, $rotation)); + $shape->structure = self::$nextStructure++; if (count(self::$shapeCache) >= self::SHAPE_CACHE_ENTRIES) { self::$shapeCache = []; } @@ -155,7 +194,7 @@ public static function box(int $length, int $width, int $height): self } } } - return new self( + $box = new self( $vertices, self::UNIT_AXES, self::UNIT_AXES, @@ -163,6 +202,8 @@ public static function box(int $length, int $width, int $height): self max($length, $width, $height), 1, ); + $box->structure = self::BOX_STRUCTURE; + return $box; } /** @@ -270,15 +311,17 @@ public static function collide( ): bool { $reach = max($left->maxCoordinate, $right->maxCoordinate) + max(self::largestComponent([$leftOrigin]), self::largestComponent([$rightOrigin])); - foreach (self::separatingAxes($left, $right) as $axis) { + $memoKey = self::rememberPair($left, $right); + $axes = $memoKey === null ? self::separatingAxes($left, $right) : self::$pairCache[$memoKey]['axes']; + foreach ($axes as $index => $axis) { if (!self::axisFitsNatively($reach, $axis)) { if (self::separatedExactly($left, $leftOrigin, $right, $rightOrigin, $axis)) { return false; } continue; } - [$leftLow, $leftHigh] = $left->projection($axis); - [$rightLow, $rightHigh] = $right->projection($axis); + [$leftLow, $leftHigh] = $left->projectionOnce($memoKey, 'left', $index, $axis); + [$rightLow, $rightHigh] = $right->projectionOnce($memoKey, 'right', $index, $axis); $leftShift = self::dot($leftOrigin, $axis); $rightShift = self::dot($rightOrigin, $axis); if ($leftHigh + $leftShift <= $rightLow + $rightShift @@ -289,6 +332,46 @@ public static function collide( return true; } + /** + * Make sure the ordered pair's axis list is memoised and return its key, or null when + * either shape opts out. The axes depend only on the two shapes' face normals and edge + * directions, never on where they stand. + */ + private static function rememberPair(self $left, self $right): ?string + { + if ($left->structure === 0 || $right->structure === 0) { + return null; + } + $key = $left->structure . '|' . $right->structure; + if (isset(self::$pairCache[$key])) { + return $key; + } + $axes = self::separatingAxes($left, $right); + if (self::$pairCacheAxes + count($axes) > self::PAIR_CACHE_AXES) { + self::$pairCache = []; + self::$pairCacheAxes = 0; + } + self::$pairCache[$key] = ['axes' => $axes, 'left' => [], 'right' => []]; + self::$pairCacheAxes += count($axes); + return $key; + } + + /** + * This shape's projection interval on a pair's `$index`th axis, computed once per memoised + * pair. A box is cheap to project and varies by size, so only hulls are kept. + * + * @param 'left'|'right' $side + * @param array{int,int,int} $axis + * @return array{int,int} + */ + private function projectionOnce(?string $memoKey, string $side, int $index, array $axis): array + { + if ($memoKey === null || $this->structure === self::BOX_STRUCTURE) { + return $this->projection($axis); + } + return self::$pairCache[$memoKey][$side][$index] ??= $this->projection($axis); + } + /** * Both hulls' face normals plus every edge-against-edge direction, deduplicated. * diff --git a/src/Domain/Item.php b/src/Domain/Item.php index de593c9..9c83d47 100644 --- a/src/Domain/Item.php +++ b/src/Domain/Item.php @@ -73,6 +73,8 @@ public static function create(string $id,Dimensions $dimensions,Weight|int|strin */ private static function admitShape(ShapeType $shapeType,?array $hullVertices,?int $ratioPpm,?int $limitKpa,Dimensions $dimensions,?Length $nestingHeight):?array { + // First, so an oversized hull is refused before any per-vertex work runs. + if($hullVertices!==null)HullShape::admitVertexCount(count($hullVertices)); $foreign=match($shapeType){ ShapeType::CONVEX_HULL=>['compression_ratio'=>$ratioPpm,'max_compression_pressure_kpa'=>$limitKpa], ShapeType::COMPRESSIBLE=>['hull_vertices'=>$hullVertices], diff --git a/src/Domain/PalletOverhang.php b/src/Domain/PalletOverhang.php index 0ca82b6..9ab3f4a 100644 --- a/src/Domain/PalletOverhang.php +++ b/src/Domain/PalletOverhang.php @@ -20,11 +20,13 @@ final class PalletOverhang { /** - * The container every solver packs: itself without a limit, else the widened frame carrying - * its deck. The frame states no limit, so a second call returns it unchanged. O(1). + * The container every solver packs: a standing bag turned to its W x H x L frame, + * a pallet with a limit widened to the frame carrying its deck, else itself. A frame is + * marked as one, so a second call returns it unchanged. O(1). */ public static function solvingFrame(Container $container):Container { + if($container->bagOrientation===FlatBag::STANDING&&!$container->uprightFrame)return $container->upright(); $limit=$container->palletOverhangLimit; if($limit===null)return $container; $inner=$container->innerDimensions; diff --git a/src/Domain/RateTable.php b/src/Domain/RateTable.php index 8c2aecc..01e37e4 100644 --- a/src/Domain/RateTable.php +++ b/src/Domain/RateTable.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; +use Packvium\Support\Arithmetic; use Packvium\Support\ObjectRefusal; /** @@ -77,8 +78,8 @@ public function chargeMinorOrNull(int $billedWeightG): ?int $base = max($this->pricesMinor[$index], $this->minimumChargeMinor); // Ceiling division, never a float: the surcharge is a share of the base, // and rounding down would let a fractional unit of revenue vanish. - $surcharge = intdiv($base * $this->fuelSurchargePermille + 999, 1000); - return $base + $surcharge; + $surcharge = Arithmetic::mulDivCeil($base, $this->fuelSurchargePermille, 1000); + return Arithmetic::addNonNegative($base, $surcharge); } } return null; diff --git a/src/Extension/DefaultContainerSelector.php b/src/Extension/DefaultContainerSelector.php index 9c091ab..bf7a8e4 100644 --- a/src/Extension/DefaultContainerSelector.php +++ b/src/Extension/DefaultContainerSelector.php @@ -5,6 +5,7 @@ use Packvium\Domain\Container; use Packvium\Domain\Nesting; use Packvium\Support\BigInt; +use Packvium\Support\StableSorter; /** Prefers the container that holds the most items, then the cheapest, then the tightest. */ final class DefaultContainerSelector implements ContainerSelector { @@ -12,6 +13,6 @@ public function score(Container $c,SingleContainerSolution $s):array { $used=$s->state->latticeSummary!==null?$s->state->latticeSummary->usedVolumeString():Nesting::usedVolume($s->state->placements); $leftover=BigInt::chunks(BigInt::subtract($c->innerDimensions->volumeString(),$used)); - return [-$s->state->placementCount(),$c->costMinor,...$leftover,$c->id]; + return [-$s->state->placementCount(),$c->costMinor,...$leftover,StableSorter::textKey($c->id)]; } } diff --git a/src/Packer.php b/src/Packer.php index cb0239a..e20e92a 100644 --- a/src/Packer.php +++ b/src/Packer.php @@ -43,7 +43,7 @@ private function objectiveBound(PackingRequest $request): ?array return null; } return ObjectiveBounds::forRequest($request->instances(), $request->containers, - $this->config->objective); + $this->config->objective, $this->config); } /** @@ -95,11 +95,12 @@ public function pack(array $items, array $containers, array $fixedPlacements = [ */ private function solve(array $items, array $containers, array $fixedPlacements, ?string $currency = null): PackingResult { - // 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); + // A pallet with an overhang limit is packed as its widened frame from here on, and a + // standing bag as its turned one, so no solver, bound or validator needs to know the + // limit or the orientation exists. + // Any other container is its own frame; asking only for one with a limit or standing + // 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->bagOrientation === 'flat' ? $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, diff --git a/src/Policy/PolicyRuleSet.php b/src/Policy/PolicyRuleSet.php index 1b71776..d955d73 100644 --- a/src/Policy/PolicyRuleSet.php +++ b/src/Policy/PolicyRuleSet.php @@ -61,7 +61,7 @@ private static function resolve(array $rules, int $asOf, ShipmentContext $shipme // Ties go to the lexicographically smallest id -- never to array insertion // order, which would follow the order the caller happened to write. usort($resolved, static fn(PolicyRule $a, PolicyRule $b): int - => ($b->priority <=> $a->priority) ?: ($a->id <=> $b->id)); + => ($b->priority <=> $a->priority) ?: strcmp($a->id, $b->id)); return $resolved; } diff --git a/src/Revisions/PlanRevision.php b/src/Revisions/PlanRevision.php index c66cac9..1878e91 100644 --- a/src/Revisions/PlanRevision.php +++ b/src/Revisions/PlanRevision.php @@ -863,11 +863,20 @@ private static function stockBox(stdClass $request, stdClass $machine, string $s $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->cost_minor = self::safeCost(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; } + /** C-13: the exact cost as an int, or a refusal in the wording of the admission rule; a cut box larger than its machine's declared size can pass 2^53 - 1. */ + private static function safeCost(string $cost): int + { + if (BigInt::compare($cost, MadeToMeasure::MAX_EXACT_INTEGER) > 0) { + throw new PlanRevisionException('invalid_revision', "a made-to-measure container's cost_per_square_metre_minor prices the largest box above " . MadeToMeasure::MAX_EXACT_INTEGER); + } + return (int) $cost; + } + /** @param mixed $value */ private static function stockObject($value, string $name, bool $optional = false): stdClass { diff --git a/src/Serialization/ArrayCodec.php b/src/Serialization/ArrayCodec.php index 2126b84..47b179c 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,OverhangLimit,Point,RateTable,Rotation,ShapeType}; +use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,HullShape,Item,MadeToMeasure,Obstacle,OverhangLimit,Point,RateTable,Rotation,ShapeType}; use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; use Packvium\Policy\PolicyRuleSet; @@ -17,7 +17,9 @@ use ValueError; final class ArrayCodec { - private static function effortBudget(?array $r):?EffortBudget{if($r===null)return null;return new EffortBudget($r['max_candidates_evaluated']??null,$r['max_placement_attempts']??null,$r['max_search_nodes']??null,$r['max_restarts']??null);} + // Each limit by value, as admission read it: `1000.0` is the integer 1000 (JavaScript cannot tell them apart). + private static function effortBudget(?array $r):?EffortBudget{if($r===null)return null;$limit=static fn(string $name):?int=>isset($r[$name])?\Packvium\Support\JsonValue::integer($r[$name]):null; + return new EffortBudget($limit('max_candidates_evaluated'),$limit('max_placement_attempts'),$limit('max_search_nodes'),$limit('max_restarts'));} /** @return array{0:Axle,1:Axle}|null */ private static function axles(?array $r,string $unit):?array{if($r===null)return null;[$front,$rear]=$r;return [new Axle(Length::parse($front['position'],$unit),isset($front['max_load'])?Weight::parse($front['max_load']):null),new Axle(Length::parse($rear['position'],$unit),isset($rear['max_load'])?Weight::parse($rear['max_load']):null)];} /** @@ -344,6 +346,7 @@ private static function item(array $r,string $unit):Item{$rot=array_map(fn($v)=> private static function hullVertices(?array $raw,string $unit):?array { if($raw===null)return null; + HullShape::admitVertexCount(count($raw)); $out=[]; foreach($raw as $vertex)$out[]=[ Length::parse($vertex['x'],$unit)->ticks, @@ -375,9 +378,9 @@ private static function fixedPlacements($raw,string $unit,$items):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,$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));} + 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,(array)($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::gussetDepth($r['deformable_boundary']??null,'side_gusset_depth',$unit),self::gussetDepth($r['deformable_boundary']??null,'bottom_gusset_depth',$unit),(string)($r['deformable_boundary']['orientation']??'flat'));} /** @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));} + private static function gussetDepth(?array $r,string $name,string $unit):?Length{return ($r[$name]??null)===null?null:new Length(MeasureReading::ticks($r[$name],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 */ diff --git a/src/Support/Arithmetic.php b/src/Support/Arithmetic.php index 0e6f14f..2f87c24 100644 --- a/src/Support/Arithmetic.php +++ b/src/Support/Arithmetic.php @@ -41,6 +41,38 @@ public static function mulDivCeil(int $a, int $b, int $d): int $product = BigInt::multiply((string)$a, (string)$b); $quotient = BigInt::divide($product, (string)$d); $exact = BigInt::compare(BigInt::multiply($quotient, (string)$d), $product) === 0; - return (int)$quotient + ($exact ? 0 : 1); + $ceiling = $exact ? $quotient : BigInt::add($quotient, '1'); + if (BigInt::compare($ceiling, (string)PHP_INT_MAX) > 0) { + throw self::beyondInteger(); + } + return (int)$ceiling; + } + + /** + * Exact ceil(a * b / d) for non-negative inputs at any size: an int while it fits one, + * a decimal string beyond. For callers that must compare the result to a ceiling of + * their own rather than refuse at the 64-bit one. + */ + public static function mulDivCeilExact(int|string $a, int|string $b, int $d): int|string + { + if ($d <= 0) { throw new \InvalidArgumentException('Divisor must be positive'); } + return ExactInteger::floorDiv(ExactInteger::add(ExactInteger::mul($a, $b), $d - 1), $d); + } + + /** + * a + b for non-negative minor-unit amounts, refusing a sum a 64-bit int cannot hold + * where plain `+` would silently become a float. + */ + public static function addNonNegative(int $a, int $b): int + { + if ($a > PHP_INT_MAX - $b) { + throw self::beyondInteger(); + } + return $a + $b; + } + + private static function beyondInteger(): ObjectRefusal + { + return new ObjectRefusal('above_maximum', 'amount must be at most ' . PHP_INT_MAX . ' minor units'); } } diff --git a/src/Support/Internal/RareRequestRules.php b/src/Support/Internal/RareRequestRules.php index a32be6d..ec5dba6 100644 --- a/src/Support/Internal/RareRequestRules.php +++ b/src/Support/Internal/RareRequestRules.php @@ -99,9 +99,9 @@ public static function palletOverhangLimit(\Closure $call, $container, $raw, str } /** - * 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). + * The bag's own shape top to bottom -- kind, unknown keys, a gusseted bag's + * gussets and orientation (1.10) -- then every container field a bag refuses, in + * the order of `BAG_EXCLUSIONS`. O(1). * * @param stdClass|array $container * @param mixed $raw @@ -115,9 +115,9 @@ public static function deformableBoundary(\Closure $call, $container, $raw, stri throw $call('refuse', 'not_allowed', "{$field}/kind", 'must be one of ' . CanonicalJson::spelling(FlatBag::KINDS)); } $gusseted = $kind === FlatBag::GUSSETED_BAG; - $call('knownFields', $boundary, $field, $gusseted ? ['kind', 'side_gusset_depth'] : ['kind']); + $call('knownFields', $boundary, $field, $gusseted ? FlatBag::GUSSETED_BAG_FIELDS : ['kind']); if ($gusseted) { - self::sideGussetDepth($call, $container, $call('required', $boundary, 'side_gusset_depth', $field), "{$field}/side_gusset_depth", $unit); + self::gussetedBag($call, $container, $boundary, $field, $unit); } foreach (RequestRules::BAG_EXCLUSIONS as $name) { if ($call('setBesideABag', $name, JsonValue::get($container, $name))) { @@ -127,20 +127,51 @@ public static function deformableBoundary(\Closure $call, $container, $raw, stri } /** - * A length, positive once read in ticks, and no deeper than the bag's inner width. + * The side gusset, then the bottom one, each a positive length within its fold; with + * neither, the side gusset is reported missing as in 1.10. Then the orientation, and a + * standing bag's bottom gusset. O(1). * * @param stdClass|array $container + * @param stdClass|array $boundary + */ + private static function gussetedBag(\Closure $call, $container, $boundary, string $field, string $unit): void + { + $side = JsonValue::get($boundary, 'side_gusset_depth'); + $bottom = JsonValue::get($boundary, 'bottom_gusset_depth'); + if ($side === null && $bottom === null) { + $call('required', $boundary, 'side_gusset_depth', $field); + } + $inner = $call('sideTicks', JsonValue::get($container, 'inner_dimensions'), $unit); + if ($side !== null) { + self::gussetDepth($call, $side, "{$field}/side_gusset_depth", $inner[1], 'exceeds inner_dimensions width', $unit); + } + if ($bottom !== null) { + self::gussetDepth($call, $bottom, "{$field}/bottom_gusset_depth", 2 * $inner[0], 'exceeds twice inner_dimensions length', $unit); + } + $orientation = JsonValue::get($boundary, 'orientation'); + if ($orientation === null) { + return; + } + $call('oneOf', $orientation, "{$field}/orientation", FlatBag::ORIENTATIONS); + if ($orientation === FlatBag::STANDING && $bottom === null) { + throw $call('refuse', 'missing_field', "{$field}/bottom_gusset_depth", 'is required when orientation is standing'); + } + } + + /** + * A length, positive once read in ticks, and no deeper than its fold allows. + * * @param mixed $value */ - private static function sideGussetDepth(\Closure $call, $container, $value, string $field, string $unit): void + private static function gussetDepth(\Closure $call, $value, string $field, int $deepest, string $tooDeep, 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'); + if ($depth > $deepest) { + throw $call('refuse', 'invalid_value', $field, $tooDeep); } } @@ -167,6 +198,13 @@ public static function rateTable(\Closure $call, $raw, string $where, ?string $c if ($code !== null) { RequestRules::rateTableCurrency($code, "{$where}/currency", $currency); } + $prices = JsonValue::get($table, 'prices_minor'); + RequestRules::rateTableCeiling( + $prices === null ? [] : \array_map([JsonValue::class, 'integer'], \array_values((array) $prices)), + JsonValue::integer(JsonValue::get($table, 'minimum_charge_minor') ?? 0), + JsonValue::integer(JsonValue::get($table, 'fuel_surcharge_permille') ?? 0), + $where + ); } /** @param mixed $raw @param array{0:int,1:int,2:int} $inner */ diff --git a/src/Support/RequestJson.php b/src/Support/RequestJson.php new file mode 100644 index 0000000..aca228e --- /dev/null +++ b/src/Support/RequestJson.php @@ -0,0 +1,62 @@ +containers[$index]->tag_limits ?? null; + if ($limits instanceof stdClass) { + $data['containers'][$index]['tag_limits'] = $limits; + } + } + return $data; + } + + /** + * Containers whose `tag_limits` decoded as a non-empty list: an array, or an object keyed 0..n-1. + * + * @param mixed $data + * @return list + */ + private static function ambiguousContainers($data): array + { + $containers = \is_array($data) ? ($data['containers'] ?? null) : null; + if (!\is_array($containers) || !JsonValue::isList($containers)) { + return []; + } + $found = []; + foreach ($containers as $index => $container) { + $limits = \is_array($container) ? ($container['tag_limits'] ?? null) : null; + if (\is_array($limits) && $limits !== [] && JsonValue::isList($limits)) { + $found[] = $index; + } + } + return $found; + } +} diff --git a/src/Support/RequestObjects.php b/src/Support/RequestObjects.php index 0d6a721..27b7854 100644 --- a/src/Support/RequestObjects.php +++ b/src/Support/RequestObjects.php @@ -226,6 +226,7 @@ private static function rateTable(RateTable $table, string $where, ?string $curr if ($table->currency !== null) { RequestRules::rateTableCurrency($table->currency, "{$where}/currency", $currency); } + RequestRules::rateTableCeiling($table->pricesMinor, $table->minimumChargeMinor, $table->fuelSurchargePermille, $where); } /** diff --git a/src/Support/RequestRules.php b/src/Support/RequestRules.php index a6019fb..e984097 100644 --- a/src/Support/RequestRules.php +++ b/src/Support/RequestRules.php @@ -3,6 +3,7 @@ namespace Packvium\Support; use Packvium\Domain\FlatBag; +use Packvium\Domain\HullShape; use Packvium\Domain\MadeToMeasure; use Packvium\Domain\Orientations; use Packvium\Serialization\InvalidRequestException; @@ -239,6 +240,7 @@ private static function item($raw, string $where, string $unit): void self::optionalAllowedRotations($item, $where); self::optionalOneOf($item, 'ground_contact_rule', $where, self::GROUND_CONTACT_RULES); self::optionalOneOf($item, 'shape_type', $where, self::SHAPE_TYPES); + self::optionalHullVertexCount($item, $where); foreach (self::ITEM_BOOLEANS as $name) { self::optionalBoolean($item, $name, $where); } @@ -254,6 +256,23 @@ private static function item($raw, string $where, string $unit): void } } + /** + * Only the count: the cap exists so no per-vertex work runs on an oversized hull. O(1). + * + * @param stdClass|array $item + */ + private static function optionalHullVertexCount($item, string $where): void + { + $vertices = JsonValue::get($item, 'hull_vertices'); + if ($vertices === null) { + return; + } + $field = "{$where}/hull_vertices"; + if (\count(self::listAt($vertices, $field)) > HullShape::MAXIMUM_VERTICES) { + throw self::refuse('above_maximum', $field, 'must have at most ' . HullShape::MAXIMUM_VERTICES . ' vertices'); + } + } + /** * 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 @@ -555,6 +574,30 @@ private static function tagLimits($raw, string $where): void } } + /** + * The dearest bracket's landed cost, fuel surcharge included, must stay an exact integer + * (M1): `base = max(dearest price, minimum charge)`, `landed = base + ceil(base * permille / 1000)`, + * in decimal-string arithmetic because the product of two values near 2^53 passes PHP_INT_MAX. + * A table with no prices is left to the rules that refuse it. O(p) for p prices. + * + * @param list $prices every field already passed its own check + */ + public static function rateTableCeiling(array $prices, int $minimumCharge, int $fuelSurchargePermille, string $where): void + { + if ($prices === []) { + return; + } + $base = (string) \max(\max($prices), $minimumCharge); + $product = BigInt::multiply($base, (string) $fuelSurchargePermille); + $quotient = BigInt::divide($product, '1000'); + $exact = BigInt::compare(BigInt::multiply($quotient, '1000'), $product) === 0; + $landed = BigInt::add($base, $exact ? $quotient : BigInt::add($quotient, '1')); + if (BigInt::compare($landed, CanonicalJson::MAX_EXACT_MAGNITUDE) > 0) { + throw self::refuse('above_maximum', $where, 'must price its top bracket at most ' + . CanonicalJson::MAX_EXACT_MAGNITUDE . ' minor units with the fuel surcharge'); + } + } + /** @param mixed $raw */ /** @param mixed $value */ public static function integer($value, string $field, int $minimum): void diff --git a/src/Support/ResultValidation/Accounting.php b/src/Support/ResultValidation/Accounting.php index 4459d5a..6f67b3c 100644 --- a/src/Support/ResultValidation/Accounting.php +++ b/src/Support/ResultValidation/Accounting.php @@ -148,9 +148,7 @@ public static function fitsEmpty(ContainerSpec $container, array $size): bool return false; } } - return !$container->flatBag - || (Exact::compare(Exact::add($size[0], $size[2]), $container->inner[0]) <= 0 - && Exact::compare(Exact::add($size[1], $size[2]), Exact::add($container->inner[1], $container->sideGusset)) <= 0); + return !$container->flatBag || ContainerCheck::girthBreach($container, $size[0], $size[1], $size[2]) === null; } /** diff --git a/src/Support/ResultValidation/Bound.php b/src/Support/ResultValidation/Bound.php index 0ad119d..7098d69 100644 --- a/src/Support/ResultValidation/Bound.php +++ b/src/Support/ResultValidation/Bound.php @@ -12,7 +12,8 @@ * The reference's own copy of docs/OPTIMALITY-CERTIFICATES.md's formulas and its one refusal * predicate, shared with nothing in the PHP engine (`Algorithm\ObjectiveBounds` is what it checks). * Exact at any size through `Exact`. O(t log t + c log c) for `t` item types and `c` container - * types, O(t + c) memory, once per result. + * types, O(t + c) memory, once per result; a billed objective's key adds O(c b (t + log(c b))) + * for `b` rate-table brackets per type. */ final class Bound { @@ -26,7 +27,11 @@ final class Bound '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], + 'shipping_cost' => [0, 'billed_weight', 1, 3, 4], + 'lowest_landed_cost' => [0, 'landed_charge', 1, 3, 4], ]; + /** The objectives whose own key is what a carrier bills. */ + private const BILLED = ['shipping_cost', 'lowest_landed_cost']; private const MAX_BOUND_SUM = '1000000000000000000000000000000'; private const MAX_BOUND_VALUE = 9007199254740991; private const SCORE_SCALE = 1000000; @@ -158,7 +163,64 @@ private static function stated($request, $status, Ordered $items, Ordered $conta return [null, "status is 'invalid_result'"]; } [$volumes, $weights, $values, $shrinks, $types] = self::inputs($items, $containers); - return self::objectiveBound($volumes, $weights, $values, $shrinks, $types, $name); + $billing = \in_array($name, self::BILLED, true) + ? self::billing(Json::get($request, 'configuration', []), $containers) : null; + return self::objectiveBound($volumes, $weights, $values, $shrinks, $types, $name, $billing); + } + + /** + * What a carrier can bill each type at the least, or null without a divisor: + * `floor` is `max(tare, dimensional)` -- the dimensional weight of the declared outer size, + * else the declared floor and height, and 0 for a bag, whose billed package can be smaller + * -- and `brackets` the rate table as `[bound in weight ticks, charge]`, the minimum charge + * and the surcharge rounded up already applied. O(c b) for `b` brackets per type. + * + * @param mixed $configuration @param Ordered $containers + * @return list}>|null + */ + private static function billing($configuration, Ordered $containers): ?array + { + $divisor = Json::get($configuration, 'dimensional_weight_divisor'); + if ($divisor === null) { + return null; + } + $lengthUnit = Json::text(Json::get($configuration, 'dimensional_weight_length_unit', 'in'), 'dimensional_weight_length_unit'); + $weightUnit = Json::text(Json::get($configuration, 'dimensional_weight_weight_unit', 'lb'), 'dimensional_weight_weight_unit'); + $billing = []; + foreach ($containers->values() as $spec) { + $size = $spec->outer ?? ($spec->deck === null ? $spec->inner : [$spec->deck[2], $spec->deck[3], $spec->inner[2]]); + $dimensional = $spec->flatBag ? 0 : ObjectiveCheck::dimensionalWeight($size, Json::int($divisor, 'dimensional_weight_divisor'), $lengthUnit, $weightUnit); + $billing[] = [ + 'floor' => Exact::max($spec->tareWeight, $dimensional), + 'tare' => $spec->tareWeight, + 'brackets' => self::brackets($spec->rateTable), + ]; + } + return $billing; + } + + /** @param mixed $table @return list */ + private static function brackets($table): array + { + if ($table === null) { + return []; + } + $read = static function ($value, string $what) { return Json::pyInt($value, $what); }; + $prices = Json::items(Json::at($table, 'prices_minor'), 'prices_minor'); + $minimum = $read(Json::get($table, 'minimum_charge_minor', 0), 'minimum_charge_minor'); + $permille = $read(Json::get($table, 'fuel_surcharge_permille', 0), 'fuel_surcharge_permille'); + $brackets = []; + foreach (Json::items(Json::at($table, 'weight_brackets_g'), 'weight_brackets_g') as $index => $grams) { + if (!\array_key_exists($index, $prices)) { + break; + } + $base = Exact::max($read($prices[$index], 'price'), $minimum); + $brackets[] = [ + Exact::mul($read($grams, 'bracket'), Units::TICKS_PER_GRAM), + Exact::add($base, Exact::ceilDiv(Exact::mul($base, $permille), 1000)), + ]; + } + return $brackets; } /** @@ -169,16 +231,28 @@ private static function stated($request, $status, Ordered $items, Ordered $conta * @param list $volumes value runs sorted ascending * @param list $weights @param list $values * @param list> $containers + * @param list}>|null $billing + * per type, in `$containers`' order; read by the billed objectives only, null without a divisor * @return array{0:list|null,1:string} */ - public static function objectiveBound(array $volumes, array $weights, array $values, bool $shrinks, array $containers, string $objective): array + public static function objectiveBound(array $volumes, array $weights, array $values, bool $shrinks, array $containers, string $objective, ?array $billing = null): array { $bound = self::lowerBound($volumes, $weights, $shrinks, $containers); if ($bound === null) { return [null, 'the request is past a declared ceiling']; } - $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]); + $billed = null; + if (\in_array($objective, self::BILLED, true)) { + $billed = $billing === null ? null : self::billedTerm($objective, $billing, $volumes, $weights, $shrinks, $containers, $bound); + if ($billed === null) { + return [null, 'no priceable inventory carries a packing that attains the count bound']; + } + } + $stated = \array_map(static function ($position) use ($bound, $billed, $volumes, $values, $shrinks, $containers) { + if (\is_int($position)) { + return $bound[$position]; + } + return $billed ?? 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) { @@ -217,6 +291,129 @@ private static function objectiveTerm(string $name, array $volumes, array $value return Exact::ceilDiv(Exact::mul(Exact::max(0, Exact::sub($requested, $capacity)), self::SCORE_SCALE), $requested); } + /** + * The billed key of `shipping_cost` or `lowest_landed_cost`, or null when no + * priceable inventory carries a packing that leaves exactly `L0` behind. + * + * Each opened container bills at least its floor and at least its tare plus what it + * carries. A rate-table bracket is reachable from a floor within it; there a container + * carries at most the bracket's bound less its tare (and its `max_payload`), so at most the + * lightest-first count under that, its usable volume and `max_items`. The cheapest + * reachable charge over the `L1` containers, the cheapest cover of the placed weight and of + * the placed count each bound the charge; the largest is stated. O(t + c b (t + log(c b))) + * for `t` runs and `b` brackets per type. + * + * @param list}> $billing + * @param list $volumes @param list $weights + * @param list> $containers @param list $bound @return int|string|null + */ + private static function billedTerm(string $objective, array $billing, array $volumes, array $weights, bool $shrinks, array $containers, array $bound) + { + [$unpacked, $opened] = $bound; + $placed = Exact::sub(self::runCount($volumes), $unpacked); + if ($objective === 'shipping_cost') { + if (Exact::sign($opened) === 0) { + return 0; + } + $quantities = self::column($containers, 'quantity'); + $byFloor = self::leastOfInventory(\array_column($billing, 'floor'), $quantities, $opened); + $byTare = self::leastOfInventory(\array_column($billing, 'tare'), $quantities, $opened); + if ($byFloor === null || $byTare === null) { + return null; + } + return Exact::max($byFloor, Exact::add($byTare, self::smallest($weights, $placed))); + } + if (Exact::sign($opened) === 0 || Exact::sign($placed) === 0) { + return 0; + } + $cheapest = $cheapestQuantities = $byWeight = $byItems = []; + foreach ($billing as $index => $billed) { + $container = $containers[$index]; + $charges = []; + foreach ($billed['brackets'] as [$limit, $charge]) { + if ($charge === null || Exact::compare($billed['floor'], $limit) > 0) { + continue; + } + $carried = Exact::sub($limit, $billed['tare']); + if ($container['payload'] !== null) { + $carried = self::min($carried, $container['payload']); + } + $count = self::fit($weights, $carried); + if (!$shrinks) { + $count = self::min($count, self::fit($volumes, $container['usable'])); + } + if ($container['max_items'] !== null) { + $count = self::min($count, $container['max_items']); + } + $charges[] = $charge; + $byWeight[] = [$charge, $carried, $container['quantity']]; + $byItems[] = [$charge, $count, $container['quantity']]; + } + if ($charges !== []) { + $cheapest[] = \array_reduce($charges, static function ($least, $charge) { return self::min($least, $charge); }, $charges[0]); + $cheapestQuantities[] = $container['quantity']; + } + } + $terms = [ + self::leastOfInventory($cheapest, $cheapestQuantities, $opened), + self::fractionalCover($byWeight, self::smallest($weights, $placed)), + self::fractionalCover($byItems, $placed), + ]; + return \in_array(null, $terms, true) ? null : self::largest($terms); + } + + /** + * The `count` smallest of `{value repeated quantity}`, summed; null if fewer exist. + * + * @param list $values @param list $quantities @param int|string $count @return int|string|null + */ + private static function leastOfInventory(array $values, array $quantities, $count) + { + $order = \array_keys($values); + \usort($order, static function (int $left, int $right) use ($values): int { + return Exact::compare($values[$left], $values[$right]) ?: $left <=> $right; + }); + $total = 0; + foreach ($order as $index) { + if (Exact::sign($count) <= 0) { + break; + } + $taken = $quantities[$index] === null ? $count : self::min($quantities[$index], $count); + $total = Exact::add($total, Exact::mul($values[$index], $taken)); + $count = Exact::sub($count, $taken); + } + return Exact::sign($count) > 0 ? null : $total; + } + + /** + * Least cost covering `need` from `[cost, capacity, quantity]` offers taken fractionally, + * rounded up; greedy by cost per unit is optimal for one covering constraint. Exact: whole + * offers sum as integers and the one share taken in part is the only fraction, rounded once. + * + * @param list $offers @param int|string $need @return int|string|null + */ + private static function fractionalCover(array $offers, $need) + { + if (Exact::sign($need) <= 0) { + return 0; + } + $ranked = \array_values(\array_filter($offers, static function (array $offer): bool { return Exact::sign($offer[1]) > 0; })); + $order = \array_keys($ranked); + \usort($order, static function (int $left, int $right) use ($ranked): int { + return Exact::compare(Exact::mul($ranked[$left][0], $ranked[$right][1]), Exact::mul($ranked[$right][0], $ranked[$left][1])) ?: $left <=> $right; + }); + $total = 0; + foreach ($order as $index) { + [$cost, $capacity, $quantity] = $ranked[$index]; + if ($quantity === null || Exact::compare(Exact::mul($quantity, $capacity), $need) >= 0) { + return Exact::add($total, Exact::ceilDiv(Exact::mul($cost, $need), $capacity)); + } + $total = Exact::add($total, Exact::mul($cost, $quantity)); + $need = Exact::sub($need, Exact::mul($capacity, $quantity)); + } + return null; + } + /** * The request as the bound reads it: every instance, fixed ones included, and every type. * diff --git a/src/Support/ResultValidation/ContainerCheck.php b/src/Support/ResultValidation/ContainerCheck.php index 389162d..5eb187d 100644 --- a/src/Support/ResultValidation/ContainerCheck.php +++ b/src/Support/ResultValidation/ContainerCheck.php @@ -124,13 +124,43 @@ 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), 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}"); + $breach = $spec->flatBag ? self::girthBreach($spec, $a, $b, $c) : null; + if ($breach !== null) { + $issues[] = new ResultIssue('bag_girth_exceeded', "{$packedId}: {$breach}"); } $packedId->verify(); } + /** + * How a bag's package of extents (a, b, c) breaks a loop of film, or null. + * + * Lying flat on an L x W bag: 2(a + c) <= 2L + K and b + c <= W + G. Standing in its + * W x H x L frame: 2(b + c) <= 2L + K and a + b <= W + G (1.10). G and K + * are the side and bottom gussets, 0 where none is declared. + * + * @param int|string $a @param int|string $b @param int|string $c + */ + public static function girthBreach(ContainerSpec $spec, $a, $b, $c): ?string + { + if ($spec->standing) { + [$width, $length] = [$spec->inner[0], $spec->inner[2]]; + [$along, $across] = [Exact::add($b, $c), Exact::add($a, $b)]; + } else { + [$length, $width] = [$spec->inner[0], $spec->inner[1]]; + [$along, $across] = [Exact::add($a, $c), Exact::add($b, $c)]; + } + $alongLimit = Exact::add(Exact::add($length, $length), $spec->bottomGusset); + if (Exact::compare(Exact::add($along, $along), $alongLimit) <= 0 + && Exact::compare($across, Exact::add($width, $spec->sideGusset)) <= 0) { + return null; + } + $sums = $spec->standing + ? "b + c = {$along}, a + b = {$across}, standing, length {$length}, width {$width}" + : "a + c = {$along}, b + c = {$across}, flat size {$length} x {$width}"; + return $sums . (Exact::sign($spec->sideGusset) === 0 ? '' : ", side gusset {$spec->sideGusset}") + . (Exact::sign($spec->bottomGusset) === 0 ? '' : ", bottom gusset {$spec->bottomGusset}"); + } + /** @param list|null $stated @param list $expected */ private static function matches(?array $stated, array $expected): bool { diff --git a/src/Support/ResultValidation/ContainerSpec.php b/src/Support/ResultValidation/ContainerSpec.php index 949f8cb..cbc1403 100644 --- a/src/Support/ResultValidation/ContainerSpec.php +++ b/src/Support/ResultValidation/ContainerSpec.php @@ -46,6 +46,20 @@ final class ContainerSpec * @var int|string */ public $sideGusset = 0; + /** + * 1.11: a gusseted bag's bottom gusset depth K in ticks, which lengthens the + * length girth to 2(a + c) <= 2L + K; 0 where none is declared. + * + * @var int|string + */ + public $bottomGusset = 0; + /** + * A bag standing on its bottom gusset, whose `$inner` is then the W x H x L frame + * it is packed in. + * + * @var bool + */ + public $standing = false; /** @var bool */ public $reportsAchievedExtent; /** @var MachineSpec|null */ diff --git a/src/Support/ResultValidation/ObjectiveCheck.php b/src/Support/ResultValidation/ObjectiveCheck.php index de7885a..a4123bf 100644 --- a/src/Support/ResultValidation/ObjectiveCheck.php +++ b/src/Support/ResultValidation/ObjectiveCheck.php @@ -147,7 +147,7 @@ private static function objective($result, Context $context, Ordered $fabricated } /** `floor(volume * weight ticks per unit / (length ticks per unit ^ 3 * divisor))`. @param array $size @return int|string */ - private static function dimensionalWeight(array $size, int $divisor, string $lengthUnit, string $weightUnit) + public static function dimensionalWeight(array $size, int $divisor, string $lengthUnit, string $weightUnit) { $length = Units::perUnit(Units::LENGTH, $lengthUnit); $weight = Units::perUnit(Units::WEIGHT, $weightUnit); diff --git a/src/Support/ResultValidation/Spec.php b/src/Support/ResultValidation/Spec.php index 44891c0..55f6161 100644 --- a/src/Support/ResultValidation/Spec.php +++ b/src/Support/ResultValidation/Spec.php @@ -90,7 +90,13 @@ 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, $spec->deck] = self::frameAndDeck(Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit), Json::get($raw, 'pallet_overhang_limit'), $unit); + $boundary = Json::get($raw, 'deformable_boundary'); + $standing = $boundary !== null && Json::get($boundary, 'orientation') === 'standing'; + $declared = Units::dimensions(Json::at($raw, 'inner_dimensions'), $unit); + if ($standing) { + $declared = [$declared[1], $declared[2], $declared[0]]; + } + [$spec->inner, $spec->deck] = self::frameAndDeck($declared, 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); @@ -106,8 +112,10 @@ public static function containers($request, string $unit): Ordered $spec->axles = self::axles($raw, $unit); $spec->maxStackDensity = self::measured($raw, 'max_stack_density', 'g', Units::WEIGHT); $spec->rateTable = Json::get($raw, 'rate_table'); - $spec->flatBag = Json::get($raw, 'deformable_boundary') !== null; - $spec->sideGusset = self::sideGusset(Json::get($raw, 'deformable_boundary'), $unit); + $spec->flatBag = $boundary !== null; + $spec->sideGusset = self::gusset($boundary, 'side_gusset_depth', $unit); + $spec->bottomGusset = self::gusset($boundary, 'bottom_gusset_depth', $unit); + $spec->standing = $standing; $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); @@ -117,13 +125,13 @@ public static function containers($request, string $unit): Ordered } /** - * A gusseted bag's side gusset depth in ticks, else 0. + * A gusseted bag's side or bottom gusset depth in ticks, else 0. * * @param mixed $boundary @return int|string */ - private static function sideGusset($boundary, string $unit) + private static function gusset($boundary, string $name, string $unit) { - $depth = $boundary === null ? null : Json::get($boundary, 'side_gusset_depth'); + $depth = $boundary === null ? null : Json::get($boundary, $name); return $depth === null ? 0 : Units::toTicks($depth, $unit, Units::LENGTH); } diff --git a/src/Support/StableSorter.php b/src/Support/StableSorter.php index 94237cf..533b87f 100644 --- a/src/Support/StableSorter.php +++ b/src/Support/StableSorter.php @@ -3,6 +3,17 @@ namespace Packvium\Support; final class StableSorter { + /** + * A user-supplied id as a sort-key element that compares by bytes. PHP's `<=>` reads two + * numeric-looking strings as numbers ("9" < "10", "1e1" == "10"); the other engines order + * ids by code point. The shared non-numeric prefix forces string comparison and leaves + * the order of the ids themselves untouched. + */ + public static function textKey(string $id): string + { + return 'id:'.$id; + } + /** @template T @param list $values @param callable(T,T):int $compare @return list */ public static function sort(array $values, callable $compare): array { diff --git a/src/Validation/IndependentSolutionValidator.php b/src/Validation/IndependentSolutionValidator.php index 8b103e9..0dae341 100644 --- a/src/Validation/IndependentSolutionValidator.php +++ b/src/Validation/IndependentSolutionValidator.php @@ -99,11 +99,12 @@ 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()){ + $girth=$packed->container->girth(); + if($girth!==null){ // 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,$packed->container->sideGussetTicks()))$issues[]=new ValidationIssue('bag_girth_exceeded',$packed->id()); + // (1.10) and lengthened by a bottom one, flat or standing; the frame + // is checked above. + if(!$girth->admits(FlatBag::extentOf($packed->placements)))$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){ @@ -124,12 +125,12 @@ public function validate(PackingRequest $request,array $containers,float $minimu } $missing=[]; foreach($expected as $id=>$_)if(!isset($seen[$id]))$missing[]=$id; - sort($missing); + sort($missing,SORT_STRING); foreach($missing as $id)$issues[]=new ValidationIssue('missing_item',$id); } $unknown=[]; foreach($seen as $id=>$_)if(!isset($expected[$id]))$unknown[]=$id; - sort($unknown); + sort($unknown,SORT_STRING); foreach($unknown as $id)$issues[]=new ValidationIssue('unknown_item',$id); foreach(self::splitGroups($containers) as $detail)$issues[]=new ValidationIssue('group_split',$detail); array_push($issues,...self::madeToMeasureIssues($request,$containers)); @@ -253,7 +254,7 @@ private static function unloadingOrderViolation(PackedContainer $packed):?Valida UnloadingDependencyGraph::safeRouteRemovalOrder($boxes,$stops,$packed->container->innerDimensions); }catch(RouteSequenceError $error){ $stuckIds=array_map(static fn(int $i)=>$placements[$i]->instance->id(),$error->stuck); - sort($stuckIds); + sort($stuckIds,SORT_STRING); return new ValidationIssue( 'unloading_order_violation', $packed->id().': stop '.$error->stop.' cannot be fully unloaded ('.implode(', ',$stuckIds).' still blocked)', @@ -319,7 +320,8 @@ private static function sortedKeys(array $keys):array $list=array_map('strval',array_keys($keys)); usort($list,static function(string $left,string $right):int{ $a=explode("\0",$left);$b=explode("\0",$right); - return [$a[0],$a[1],(int)$a[2],(int)$a[3],(int)$a[4],$a[5]]<=>[$b[0],$b[1],(int)$b[2],(int)$b[3],(int)$b[4],$b[5]]; + // strcmp on the ids: `<=>` compares numeric strings as numbers ("9" < "10"), Python as text. + return strcmp($a[0],$b[0])?:strcmp($a[1],$b[1])?:[(int)$a[2],(int)$a[3],(int)$a[4],$a[5]]<=>[(int)$b[2],(int)$b[3],(int)$b[4],$b[5]]; }); return $list; } @@ -339,11 +341,11 @@ private static function splitGroups(array $containers):array if($group===null)continue; $located[$group][$packed->id()]=true; } - ksort($located); + ksort($located,SORT_STRING); $out=[]; foreach($located as $group=>$where){ if(count($where)<=1)continue; - $ids=array_keys($where);sort($ids); + $ids=array_keys($where);sort($ids,SORT_STRING); $out[]=$group.': '.implode(', ',$ids); } return $out; @@ -362,7 +364,7 @@ private static function partialGroups(PackingRequest $request,array $containers) $group=$placement->instance->item->group; if($group!==null)$placed[$group][$placement->instance->id()]=true; } - ksort($expected);$out=[]; + ksort($expected,SORT_STRING);$out=[]; foreach($expected as $group=>$members){ $count=count($placed[$group]??[]); if($count>0&&$count Arithmetic::mulDivCeil(1, 1, 0)); self::assertThrows(InvalidArgumentException::class, static fn() => Arithmetic::mulDivCeil(1, 1, -1)); } + + public static function testCeilRefusesAQuotientBeyondTheIntegerRange(): void + { + // A product whose ceiling quotient passes PHP_INT_MAX used to reach `(int)` and fail + // with a TypeError further out; it is a typed refusal instead. + try { + Arithmetic::mulDivCeil(9007199254740991, 9007199254740991, 1); + self::assertTrue(false, 'a quotient past PHP_INT_MAX must be refused'); + } catch (ObjectRefusal $refusal) { + self::assertSame('above_maximum', $refusal->reason()); + } + self::assertThrows(ObjectRefusal::class, static fn() => Arithmetic::mulDivCeil(PHP_INT_MAX, 2, 1)); + self::assertSame(PHP_INT_MAX, Arithmetic::mulDivCeil(PHP_INT_MAX, 2, 2)); + } + + public static function testExactCeilKeepsAQuotientBeyondTheIntegerRangeAsADecimalString(): void + { + self::assertSame(7, Arithmetic::mulDivCeilExact(20, 2, 6)); + self::assertSame(PHP_INT_MAX, Arithmetic::mulDivCeilExact(PHP_INT_MAX, 2, 2)); + self::assertSame('81129638414606663681390495662081', Arithmetic::mulDivCeilExact(9007199254740991, 9007199254740991, 1)); + self::assertSame('18446744073709551614', Arithmetic::mulDivCeilExact(PHP_INT_MAX, 2, 1)); + self::assertThrows(InvalidArgumentException::class, static fn() => Arithmetic::mulDivCeilExact(1, 1, 0)); + } + + public static function testANonNegativeSumBeyondTheIntegerRangeIsRefusedNotFloated(): void + { + self::assertSame(PHP_INT_MAX, Arithmetic::addNonNegative(PHP_INT_MAX - 1, 1)); + self::assertThrows(ObjectRefusal::class, static fn() => Arithmetic::addNonNegative(PHP_INT_MAX, 1)); + } } diff --git a/tests/BottomGussetTest.php b/tests/BottomGussetTest.php new file mode 100644 index 0000000..b270164 --- /dev/null +++ b/tests/BottomGussetTest.php @@ -0,0 +1,173 @@ + 'rod', 'allowed_rotations' => ['LWH'], 'dimensions' => ['length' => '300', 'width' => '100', 'height' => '20']]; + private const BOTTLE = ['id' => 'bottle', 'allowed_rotations' => ['LWH'], 'dimensions' => ['length' => '50', 'width' => '50', 'height' => '150']]; + + public static function testTheLoopsAreTheRuleOfEitherFrame(): void + { + // A fixed linear walk, not a random one: determinism is the suite's own rule too. + for ($seed = 0; $seed < 60; ++$seed) { + $length = 2 + ($seed * 7) % 39; + $width = 2 + ($seed * 11) % 39; + $side = ($seed * 5) % ($width + 1); + $bottom = 1 + ($seed * 13) % (2 * $length); + $standing = $seed % 2 === 1; + $girth = FlatBag::girthFor($length, $width, $side, $bottom, $standing); + for ($step = 0; $step < 80; ++$step) { + $extent = [($seed + $step * 3) % 41, ($seed * 2 + $step * 5) % 41, ($seed * 3 + $step * 7) % 41]; + [$a, $b, $c] = $extent; + $expected = $standing + ? $a + $b <= $width + $side && 2 * ($b + $c) <= 2 * $length + $bottom + : 2 * ($a + $c) <= 2 * $length + $bottom && $b + $c <= $width + $side; + self::assertSame($expected, $girth->admits($extent), "seed {$seed}, extent " . implode(',', $extent)); + } + } + } + + public static function testABottomGussetAdmitsARodTheFlatLengthRefuses(): void + { + // A 300 mm rod 20 mm thick fills the flat length, so a + c = 320 > 300 lying flat; a + // 40 mm bottom gusset makes the loop 2L + K = 640 = 2(a + c), and equality fits. + $flat = ArrayCodec::pack(self::request(['kind' => 'gusseted_bag', 'side_gusset_depth' => '10'], self::ROD, 1)); + self::assertSame('no_compatible_container_dimensions', $flat['unpacked_items'][0]['reason']); + $block = ArrayCodec::pack(self::request(['kind' => 'gusseted_bag', 'bottom_gusset_depth' => '40'], self::ROD, 1)); + self::assertSame([], $block['unpacked_items']); + $past = ArrayCodec::pack(self::request(['kind' => 'gusseted_bag', 'bottom_gusset_depth' => ['value' => (string) (self::ticks(40) - 1), 'unit' => 'ticks']], self::ROD, 1)); + self::assertSame('no_compatible_container_dimensions', $past['unpacked_items'][0]['reason']); + } + + public static function testAStandingPouchPacksInItsTurnedFrameAndTheValidatorAgrees(): void + { + // Standing, the 300 x 150 x 100 pouch is a 150 x 100 x 300 frame. Two 50 x 50 x 150 + // bottles stand side by side, here front to back (a + b = 150 = W + G, b <= H); a third + // beside them breaks the loop round the section and one on top breaks the loop down the + // bag, 2(b + c) = 700 > 660. + $standing = self::request(['kind' => 'gusseted_bag', 'bottom_gusset_depth' => '60', 'orientation' => 'standing'], self::BOTTLE, 3); + $result = ArrayCodec::pack($standing); + $packed = $result['containers'][0]; + self::assertCount(2, $packed['placements']); + self::assertCount(1, $result['unpacked_items']); + self::assertSame(['50', '100', '150'], self::values($packed['achieved_dimensions'])); + self::assertSame(['300', '150', '100'], self::values($packed['inner_dimensions'])); + self::assertSame([], validate($standing, $result)); + } + + public static function testTheValidatorRefusesAStandingPackagePastItsLoop(): void + { + // The same two bottles against a pouch 1 mm narrower: a + b = 150 > W = 149. + $standing = self::request(['kind' => 'gusseted_bag', 'bottom_gusset_depth' => '60', 'orientation' => 'standing'], self::BOTTLE, 2); + $result = ArrayCodec::pack($standing); + $narrower = $standing; + $narrower['containers'][0]['inner_dimensions']['width'] = '149'; + $girth = array_values(array_filter(validate($narrower, $result), static fn($issue): bool => $issue->code === 'bag_girth_exceeded')); + self::assertCount(1, $girth); + self::assertSame('pouch#1: b + c = 4000000, a + b = 2400000, standing, length 4800000, width 2384000, bottom gusset 960000', $girth[0]->detail); + } + + public static function testAStandingFixedSetPastItsLoopCannotHold(): void + { + $narrower = self::request(['kind' => 'gusseted_bag', 'bottom_gusset_depth' => '60', 'orientation' => 'standing'], self::BOTTLE, 2); + $narrower['containers'][0]['inner_dimensions']['width'] = '149'; + $narrower['fixed_placements'] = []; + foreach (['0', '50'] as $y) { + $narrower['fixed_placements'][] = ['item_type' => 'bottle', 'container_type' => 'pouch', 'orientation' => 'LWH', 'position' => ['x' => '0', 'y' => $y, 'z' => '0']]; + } + try { + ArrayCodec::pack($narrower); + throw new \RuntimeException('the fixed set was admitted'); + } catch (FixedPlacementException $error) { + self::assertSame('invalid_fixed_placement: bag_girth_exceeded: pouch#1', $error->getMessage()); + } + } + + public static function testTheStandingFrameTurnsOnceAndDeclaresTheBagAsGiven(): void + { + $declared = Dimensions::mm(300, 150, 100); + $bag = new Container('pouch', $declared, deformableBoundary: 'gusseted_bag', bottomGussetDepth: Length::mm(60), bagOrientation: 'standing'); + $frame = PalletOverhang::solvingFrame($bag); + self::assertEquals(Dimensions::mm(150, 100, 300), $frame->innerDimensions); + self::assertEquals($declared, $frame->declaredInner()); + self::assertSame($frame, PalletOverhang::solvingFrame($frame)); + self::assertEquals(FlatBag::girthFor(self::ticks(300), self::ticks(150), 0, self::ticks(60), true), $frame->girth()); + self::assertEquals(new Girth([0, 2], 2 * self::ticks(300) + self::ticks(60), [1, 2], self::ticks(150)), $bag->girth()); + } + + public static function testTheObjectApiRefusesWhatTheJsonPathRefuses(): void + { + $cases = [ + [[], 'missing_field', 'a gusseted_bag requires side_gusset_depth'], + [['bottomGussetDepth' => new Length(self::ticks(600) + 1)], 'invalid_value', 'bottom_gusset_depth exceeds twice inner_dimensions length'], + [['bottomGussetDepth' => new Length(0)], 'invalid_value', 'bottom_gusset_depth must be positive'], + [['sideGussetDepth' => Length::mm(10), 'bagOrientation' => 'standing'], 'missing_field', 'bottom_gusset_depth is required when orientation is standing'], + [['bottomGussetDepth' => Length::mm(10), 'bagOrientation' => 'upright'], 'not_allowed', "orientation must be one of ['flat', 'standing']"], + ]; + foreach ($cases as [$fields, $reason, $detail]) { + $error = self::caught(static fn() => new Container('pouch', Dimensions::mm(300, 150, 100), ...(['deformableBoundary' => 'gusseted_bag'] + $fields))); + self::assertSame([$reason, $detail], [$error->reason(), $error->detail()]); + } + } + + public static function testARigidBoxOrFlatBagRefusesTheGussetedFields(): void + { + foreach ([['bottomGussetDepth' => Length::mm(10)], ['bagOrientation' => 'standing']] as $fields) { + foreach ([null, 'flat_bag'] as $boundary) { + $error = self::caught(static fn() => new Container('box', Dimensions::mm(300, 150, 100), ...(['deformableBoundary' => $boundary] + $fields))); + self::assertSame('not_allowed', $error->reason()); + } + } + } + + public static function testTheJsonPathRefusesAStandingBagWithoutABottomGusset(): void + { + $error = self::caught(static fn() => ArrayCodec::pack(self::request(['kind' => 'gusseted_bag', 'side_gusset_depth' => '10', 'orientation' => 'standing'], self::BOTTLE, 1))); + self::assertSame(['missing_field', '/containers/0/deformable_boundary/bottom_gusset_depth'], [$error->reason(), $error->field()]); + } + + private static function ticks(int $millimetres): int + { + return Length::mm($millimetres)->ticks; + } + + /** @param array $dimensions @return list */ + private static function values(array $dimensions): array + { + return array_map(static fn(string $side): string => $dimensions[$side]['value'], ['length', 'width', 'height']); + } + + /** @param array $boundary @param array $item @return array */ + private static function request(array $boundary, array $item, int $quantity): array + { + return ['items' => [['quantity' => $quantity, 'weight' => '300 g'] + $item], + '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/BoundLoadingTest.php b/tests/BoundLoadingTest.php index 3cfdfdb..dc000b9 100644 --- a/tests/BoundLoadingTest.php +++ b/tests/BoundLoadingTest.php @@ -17,7 +17,7 @@ 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 = $case === 'unsupported' +$config = $case === 'billed' ? new Packvium\Config\PackingConfig(objective: 'shipping_cost', dimensionalWeightDivisor: 5000) : new Packvium\Config\PackingConfig(objective: 'default'); $scorer = $case === 'custom' ? new Packvium\Objective\DefaultSolutionScorer() : null; @@ -38,9 +38,10 @@ private static function probe(string $case): array return json_decode($out, true, flags: JSON_THROW_ON_ERROR); } - public static function testAnUnsupportedObjectiveDoesNotLoadTheBound(): void + /** Every built-in objective is covered since, so a billed one loads its bound. */ + public static function testABilledObjectiveLoadsAndStatesItsBound(): void { - self::assertSame(['loaded' => false, 'bound' => null], self::probe('unsupported')); + self::assertSame(['loaded' => true, 'bound' => [0]], self::probe('billed')); } public static function testAMachineDoesNotLoadTheBound(): void diff --git a/tests/CommerceGuardsTest.php b/tests/CommerceGuardsTest.php index 72f689a..db41523 100644 --- a/tests/CommerceGuardsTest.php +++ b/tests/CommerceGuardsTest.php @@ -383,4 +383,23 @@ public static function testCatalogPinnedLookupKeepsBoundariesAndRollback(): void self::assertSame(63, $registry->resolve(100, asOf: 0)->number); } + + public static function testTariffZonesAreValidatedInCodePointOrderOfTheirKeys(): void + { + // PHP turns the numeric-looking key "2" into an int; "2" still sorts before "b" as a string. + foreach ([['b' => 'x', '2' => 'x'], ['2' => 'x', 'b' => 'x']] as $zones) { + $document = self::document(); + $document['tariffs'][0]['versions'][0]['cost_per_dimensional_kg_minor'] = $zones; + try { + quote($document, ['carrier_id' => 'acme', 'service_id' => 'ground', 'tariff_version' => 1, + 'zone' => 'b', 'actual_weight_g' => 1, 'volume_mm3' => 1]); + self::assertTrue(false, 'a non-integer zone cost must be refused'); + } catch (CommerceInputException $error) { + self::assertTrue( + str_contains($error->getMessage(), 'cost_per_dimensional_kg_minor[2]'), + 'the first error names zone "2": ' . $error->getMessage(), + ); + } + } + } } diff --git a/tests/CommerceTest.php b/tests/CommerceTest.php index b49128d..b8345ff 100644 --- a/tests/CommerceTest.php +++ b/tests/CommerceTest.php @@ -114,6 +114,100 @@ public static function testAnUnsupportedPolicyOperatorFailsAdmission(): void ); } + public static function testAQuoteBeyondTheIntegerRangeIsRefusedNotWrapped(): void + { + // weight = rate = 2^53 - 1 at divisor 1: the base charge is about 8e28 minor units. + $document = self::minimalDocument(); + $version = &$document['tariffs'][0]['versions'][0]; + $version['dimensional_weight_divisor'] = 1; + $version['cost_per_dimensional_kg_minor'] = ['zone-a' => 9007199254740991]; + self::assertThrows( + CommerceInputException::class, + static fn() => quote($document, self::shipment(['actual_weight_g' => 9007199254740991])), + 'an unrepresentable quote must be a typed refusal, not a TypeError or a float', + ); + self::assertQuoteRefusedWith( + 'quote amount 81129638414606663681390495663 is above 9007199254740991 and cannot be represented exactly', + $document, + self::shipment(['actual_weight_g' => 9007199254740991]), + ); + } + + public static function testAnAmountAtTheCeilingIsQuotedExactly(): void + { + $document = self::tariffDocument(minimumCharge: 9007199254740991); + $quote = quote($document, self::shipment(['actual_weight_g' => 1, 'volume_mm3' => 1]))['quote']; + self::assertSame(9007199254740991, $quote['base_charge_minor']); + self::assertSame(9007199254740991, $quote['total_minor']); + } + + public static function testABaseChargeAboveTheCeilingIsRefused(): void + { + // Past 2^53 - 1 but inside PHP_INT_MAX: PHP used to answer it. + self::assertQuoteRefusedWith( + 'quote amount 9007199254740992 is above 9007199254740991 and cannot be represented exactly', + self::tariffDocument(minimumCharge: 9007199254740992), + self::shipment(['actual_weight_g' => 1, 'volume_mm3' => 1]), + ); + } + + public static function testAFuelSurchargeAboveTheCeilingIsRefusedWhileTheBaseIsInside(): void + { + self::assertQuoteRefusedWith( + 'quote amount 12000000000000000 is above 9007199254740991 and cannot be represented exactly', + self::tariffDocument(minimumCharge: 6000000000000000, fuelPermille: 2000), + self::shipment(['actual_weight_g' => 1, 'volume_mm3' => 1]), + ); + } + + public static function testAnAccessorialAboveTheCeilingIsRefusedWhileTheBaseIsInside(): void + { + self::assertQuoteRefusedWith( + 'quote amount 12000000000000000 is above 9007199254740991 and cannot be represented exactly', + self::tariffDocument(minimumCharge: 6000000000000000, accessorialPermille: 2000), + self::shipment(['actual_weight_g' => 1, 'volume_mm3' => 1, 'requested_accessorials' => ['liftgate']]), + ); + } + + public static function testATotalAboveTheCeilingIsRefusedWhileEveryComponentIsInside(): void + { + self::assertQuoteRefusedWith( + 'quote amount 9600000000000000 is above 9007199254740991 and cannot be represented exactly', + self::tariffDocument(minimumCharge: 4800000000000000, fuelPermille: 1000), + self::shipment(['actual_weight_g' => 1, 'volume_mm3' => 1]), + ); + } + + /** + * @param array $document + * @param array $request + */ + private static function assertQuoteRefusedWith(string $message, array $document, array $request): void + { + try { + quote($document, $request); + } catch (CommerceInputException $error) { + self::assertSame($message, $error->getMessage()); + return; + } + self::assertTrue(false, 'the quote must be refused'); + } + + /** @return array */ + private static function tariffDocument(int $minimumCharge, int $fuelPermille = 0, ?int $accessorialPermille = null): array + { + $accessorial = $accessorialPermille === null + ? ['flat_charge_minor' => 0] : ['permille_of_base' => $accessorialPermille]; + return ['tariffs' => [['carrier_id' => 'acme', 'service_id' => 'ground', 'versions' => [[ + 'effective_at' => 0, + 'dimensional_weight_divisor' => 5000, + 'cost_per_dimensional_kg_minor' => ['zone-a' => 1], + 'minimum_charge_minor' => $minimumCharge, + 'fuel_surcharge_permille' => $fuelPermille, + 'accessorials' => [['accessorial_id' => 'liftgate'] + $accessorial], + ]]]]]; + } + public static function testAnUnpriceableZoneIsAnAnswerNotAnException(): void { $result = quote(self::minimalDocument(), self::shipment(['zone' => 'zone-nowhere'])); diff --git a/tests/DomainTest.php b/tests/DomainTest.php index 3501d9e..2c845b6 100644 --- a/tests/DomainTest.php +++ b/tests/DomainTest.php @@ -302,4 +302,14 @@ public static function testAPriceBandMayDipBecauseAPromotionalRateCardIsReal(): self::assertSame(900, $table->chargeMinor(50)); self::assertSame(500, $table->chargeMinor(150)); } + + public static function testALandedCostBeyondTheIntegerRangeIsRefusedNotFloated(): void + { + // The surcharge product and the sum used to pass PHP_INT_MAX and become a float. + $surcharged = new RateTable([100], [PHP_INT_MAX], fuelSurchargePermille: 1000); + self::assertThrows(InvalidArgumentException::class, static fn() => $surcharged->chargeMinorOrNull(50)); + $wide = new RateTable([100], [PHP_INT_MAX - 1], fuelSurchargePermille: 1); + self::assertThrows(InvalidArgumentException::class, static fn() => $wide->chargeMinor(50)); + self::assertSame(1_001, (new RateTable([100], [1_000], fuelSurchargePermille: 1))->chargeMinor(50)); + } } diff --git a/tests/FixedPlacementTest.php b/tests/FixedPlacementTest.php index df6946a..14aa1f2 100644 --- a/tests/FixedPlacementTest.php +++ b/tests/FixedPlacementTest.php @@ -225,6 +225,20 @@ public static function testSeveralMovedFixedItemsAreReportedInOneOrder(): void ], array_values(array_filter($details, static fn(string $d): bool => str_contains($d, 'fixed')))); } + public static function testMovedFixedItemsWithNumericLookingIdsAreReportedInCodePointOrder(): void + { + // `<=>` would order "9" before "10" as numbers; Python orders the ids as text. + $items = [Item::create('9', Dimensions::mm(100, 100, 100), '1000g', 1), Item::create('10', Dimensions::mm(100, 100, 100), '1000g', 1)]; + $containers = [Container::create('box', Dimensions::mm(200, 100, 200), 0, null, null, 0, 1)]; + $fixedAt = static fn(string $type, int $x, int $z): FixedPlacement => new FixedPlacement($type, 'box', new Point(Length::mm($x)->ticks, 0, Length::mm($z)->ticks), Rotation::LWH, 1); + $packed = (new Packer(new PackingConfig()))->pack($items, $containers, [$fixedAt('9', 0, 0), $fixedAt('10', 100, 0)]); + $moved = new PackingRequest($items, $containers, [$fixedAt('9', 0, 100), $fixedAt('10', 100, 100)]); + $report = (new IndependentSolutionValidator())->validate($moved, $packed->containers, 0.0, null, $packed->unpacked); + $movedIds = array_values(array_map(static fn($issue): string => explode(' ', $issue->detail)[0], + array_filter($report->issues, static fn($issue): bool => $issue->code === 'fixed_placement_moved'))); + self::assertSame(['10', '9'], $movedIds); + } + public static function testTheValidatorCatchesAMissingFixedContainer(): void { [$items, $containers] = self::domain(); diff --git a/tests/IrregularItemsTest.php b/tests/IrregularItemsTest.php index eb80ec2..a58f56d 100644 --- a/tests/IrregularItemsTest.php +++ b/tests/IrregularItemsTest.php @@ -7,6 +7,7 @@ use Packvium\Domain\{AxisAlignedBox, Compression, Container, Dimensions, HullShape, Item, Nesting, Placement, Point, Rotation, ShapeType}; use ReflectionMethod; use Packvium\Serialization\ArrayCodec; +use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\{Length, Weight}; use Packvium\Support\SignedBigInt; @@ -116,6 +117,30 @@ public static function testTheRotatedShapeMemoIsBoundedAndAnswersTheSameAfterCle self::assertSame($before->edgeDirections, $after->edgeDirections); } + public static function testAMemoisedPairCollidesLikeUnmemoisedShapesThroughPairMemoChurn(): void + { + // Shapes from `of` opt out of the pair memo, so they are the reference answer. The churn + // pushes far more axes than the pair memo holds, so it is cleared and refilled mid-test. + $wedge = self::lowerWedge(); + $pairs = []; + foreach ([Rotation::LWH, Rotation::HWL, Rotation::WLH] as $rotation) { + $pairs[] = [HullShape::shapeFor($wedge, $rotation), HullShape::of(HullShape::rotate($wedge, $rotation)), HullShape::box(7, 5, 3)]; + } + for ($round = 0; $round < 3; $round++) { + foreach ($pairs as [$memoised, $reference, $box]) { + foreach ([[0, 0, 0], [3, 2, 1], [6, 0, 0], [-4, 1, 2], [100, 0, 0]] as $offset) { + self::assertSame(HullShape::collide($reference, [0, 0, 0], $reference, $offset), HullShape::collide($memoised, [0, 0, 0], $memoised, $offset)); + self::assertSame(HullShape::collide($reference, [0, 0, 0], $box, $offset), HullShape::collide($memoised, [0, 0, 0], $box, $offset)); + self::assertSame(HullShape::collide($box, $offset, $reference, [0, 0, 0]), HullShape::collide($box, $offset, $memoised, [0, 0, 0])); + } + } + for ($stretch = 1; $stretch <= 900; $stretch++) { + $left = HullShape::shapeFor([[0, 0, 0], [$stretch + $round * 1000, 0, 0], [0, 3, 0], [0, 0, 5], [1, 1, 1]], Rotation::LWH); + HullShape::collide($left, [0, 0, 0], $left, [1, 0, 0]); + } + } + } + public static function testTheCrushBoundaryIsInclusive(): void { self::assertFalse(Compression::exceeds(['100', '1'], 100), 'the limit itself is admissible'); @@ -664,4 +689,67 @@ public static function testTheFaceWalkStartsFromACornerNotFromASmallString(): vo self::assertSame($case['edge_directions'], $shape->edgeDirections); } } + + public static function testAHullOfThirtyTwoVerticesIsAdmittedAndThirtyThreeIsRefusedBeforeAnyHullWork(): void + { + $prism = self::sixteenGonPrism(); + self::assertSame(32, count($prism)); + // A long fuse: building a 32-vertex shape is the slowest admitted case, and the default + // one-second limit would let a loaded machine decide whether the prism is packed. + $request = static function (array $vertices): array { + $wire = self::wireRequest([self::wireItem('big', 'convex_hull', $vertices)]); + $wire['configuration']['time_limit_ms'] = 60000; + return $wire; + }; + $result = ArrayCodec::pack($request($prism)); + self::assertSame([], $result['unpacked_items'] ?? []); + + // The 33rd vertex repeats one: were the cap not first, the uniqueness rule would answer. + $over = $request(array_merge($prism, [$prism[0]])); + try { + ArrayCodec::pack($over); + self::assertTrue(false, 'a 33-vertex hull must be refused'); + } catch (InvalidRequestException $error) { + self::assertSame('above_maximum', $error->reason()); + self::assertSame('/items/0/hull_vertices', $error->field()); + self::assertSame('must have at most 32 vertices', $error->detail()); + } + + $objectPrism = array_map(static fn(array $v): array => [$v[0] * 16000, $v[1] * 16000, $v[2] * 16000], self::sixteenGonPrismPoints()); + self::assertSame(32, count(self::item(ShapeType::CONVEX_HULL, $objectPrism)->hullVertices ?? [])); + self::assertRefused('hull_vertices must have at most 32 vertices', + fn() => self::item(ShapeType::CONVEX_HULL, array_merge($objectPrism, [$objectPrism[0]]))); + } + + /** @return list */ + private static function sixteenGonPrism(): array + { + return self::wireVertices(array_map( + static fn(array $v): array => [$v[0] * 16000, $v[1] * 16000, $v[2] * 16000], + self::sixteenGonPrismPoints(), + )); + } + + /** @return list sixteen convex-position points at two heights; 32 vertices in all */ + private static function sixteenGonPrismPoints(): array + { + // Every primitive edge vector with its opposite, in angle order, closes into a convex polygon. + $edges = [[1, 0], [2, 1], [1, 1], [1, 2], [0, 1], [-1, 2], [-1, 1], [-2, 1], + [-1, 0], [-2, -1], [-1, -1], [-1, -2], [0, -1], [1, -2], [1, -1], [2, -1]]; + $points = []; + $x = 0; + $y = 0; + foreach ($edges as [$dx, $dy]) { + $points[] = [$x + 5, $y + 5]; + $x += $dx; + $y += $dy; + } + $prism = []; + foreach ([0, 10] as $z) { + foreach ($points as [$px, $py]) { + $prism[] = [$px, $py, $z]; + } + } + return $prism; + } } diff --git a/tests/LayerDirectionTest.php b/tests/LayerDirectionTest.php new file mode 100644 index 0000000..d612e38 --- /dev/null +++ b/tests/LayerDirectionTest.php @@ -0,0 +1,245 @@ + 0, + 'Support' => 0, + 'Domain' => 1, + 'Constraint' => 2, + 'Config' => 2, + 'Explain' => 2, + 'Execution' => 2, + 'Sequence' => 3, + 'Policy' => 3, + 'Result' => 3, + 'Extension' => 3, + 'Objective' => 3, + 'Artifacts' => 3, + 'Validation' => 4, + 'Revisions' => 4, + 'Algorithm' => 5, + 'Support\\ResultValidation' => 5, + 'Packer' => 6, + 'Serialization' => 7, + 'Nested' => 7, + 'Support\\ExactGeometry' => 1, + 'Support\\UnsupportedPlacements' => 1, + 'Support\\FixedPlacementShape' => 4, + 'Support\\RequestObjects' => 6, + 'Support\\RequestRules' => 6, + 'Support\\Internal' => 6, + ]; + + private const COMMERCE = 'Commerce'; + + /** + * Upward imports that exist today: reason => file below `src/` => imported classes below `Packvium\`. + * + * @var array>> + */ + private const ALLOWED = [ + 'Commerce is a leaf by design but reuses Support helpers (R-01)' => [ + 'Commerce/Rating/AccessorialCharge.php' => ['Support\\Arithmetic'], + 'Commerce/Rating/CarrierRegistry.php' => ['Support\\Arithmetic', 'Support\\CanonicalJson', 'Support\\ExactInteger'], + ], + 'The refusal types hang off Serialization\\InvalidRequestException, so Support and Validation import up to it (R-01)' => [ + 'Support/ObjectRefusal.php' => ['Serialization\\InvalidRequestException'], + 'Support/RequestObjects.php' => ['Serialization\\InvalidRequestException'], + 'Support/RequestRules.php' => ['Serialization\\InvalidRequestException'], + 'Validation/FixedPlacementException.php' => ['Serialization\\InvalidRequestException'], + ], + 'Config and Revisions call the request-admission rules and Config names its budget in Algorithm (R-01)' => [ + 'Config/PackingConfig.php' => ['Algorithm\\EffortBudget', 'Support\\RequestRules'], + 'Revisions/PlanRevision.php' => ['Support\\RequestRules'], + ], + 'Extension signatures are typed on Algorithm state (R-01)' => [ + 'Extension/CandidateScorer.php' => ['Algorithm\\ContainerState'], + 'Extension/ContainerSelector.php' => ['Algorithm\\SingleContainerSolution'], + 'Extension/DefaultCandidateScorer.php' => ['Algorithm\\CandidateFinder', 'Algorithm\\ContainerState'], + 'Extension/DefaultContainerSelector.php' => ['Algorithm\\SingleContainerSolution'], + 'Extension/ExtensionRegistry.php' => ['Algorithm\\SingleContainerSolver'], + ], + 'Objective scorers take Algorithm\\RawSolution (R-01)' => [ + 'Objective/DefaultSolutionScorer.php' => ['Algorithm\\RawSolution'], + 'Objective/LandedCostSolutionScorer.php' => ['Algorithm\\RawSolution'], + 'Objective/LowestCostSolutionScorer.php' => ['Algorithm\\RawSolution'], + 'Objective/MaximumValueSolutionScorer.php' => ['Algorithm\\RawSolution'], + 'Objective/MaximumVolumeSolutionScorer.php' => ['Algorithm\\RawSolution'], + 'Objective/OpenDimensionSolutionScorer.php' => ['Algorithm\\RawSolution'], + 'Objective/ShippingCostSolutionScorer.php' => ['Algorithm\\RawSolution'], + 'Objective/SolutionScorer.php' => ['Algorithm\\RawSolution'], + ], + 'Facades that delegate to a higher module which imports them back (R-01)' => [ + 'Support/MeasureReading.php' => ['Support\\Internal\\MeasureOverflow'], + 'Validation/functions.php' => ['Support\\ResultValidation\\Validator'], + ], + ]; + + public static function testNoImportPointsUpTheLayersExceptTheListedOnes(): void + { + $found = self::violations(); + $allowed = self::allowedPairs(); + self::assertSame([], array_values(array_diff($found, $allowed)), 'new upward imports (file => class); fix the import or list it with a reason'); + self::assertSame([], array_values(array_diff($allowed, $found)), 'allow-listed imports that are gone; remove them from ALLOWED'); + } + + /** Every file's namespace is placed, so a new one cannot slip past the table unnoticed. */ + public static function testEveryNamespaceIsPlaced(): void + { + foreach (array_keys(self::imports()) as $file) { + $class = self::classOf($file); + self::assertTrue(self::isCommerce($class) || self::tierOf($class) !== null, "{$file} is in no tier of LayerDirectionTest::TIERS"); + } + } + + /** @return list sorted `file => class` pairs */ + public static function violations(): array + { + $found = []; + foreach (self::imports() as $file => $classes) { + foreach ($classes as $class) { + if (self::isUpward(self::classOf($file), $class)) { + $found[] = "{$file} => {$class}"; + } + } + } + sort($found); + return $found; + } + + /** @return list */ + private static function allowedPairs(): array + { + $pairs = []; + foreach (self::ALLOWED as $files) { + foreach ($files as $file => $classes) { + foreach ($classes as $class) { + $pairs[] = "{$file} => {$class}"; + } + } + } + sort($pairs); + return $pairs; + } + + private static function isUpward(string $from, string $to): bool + { + $fromCommerce = self::isCommerce($from); + if ($fromCommerce || self::isCommerce($to)) { + return $fromCommerce !== self::isCommerce($to); + } + $fromTier = self::tierOf($from); + $toTier = self::tierOf($to); + return $fromTier !== null && $toTier !== null && $toTier > $fromTier; + } + + private static function isCommerce(string $class): bool + { + return $class === self::COMMERCE || str_starts_with($class, self::COMMERCE . '\\'); + } + + private static function tierOf(string $class): ?int + { + $best = null; + $bestLength = -1; + foreach (self::TIERS as $prefix => $tier) { + $matches = $class === $prefix || str_starts_with($class, $prefix . '\\'); + if ($matches && strlen($prefix) > $bestLength) { + $best = $tier; + $bestLength = strlen($prefix); + } + } + return $best; + } + + /** `Domain/Item.php` => `Domain\Item`. */ + private static function classOf(string $file): string + { + return str_replace('/', '\\', substr($file, 0, -strlen('.php'))); + } + + /** @return array> file below `src/` => Packvium classes it imports, below `Packvium\` */ + private static function imports(): array + { + $root = dirname(__DIR__) . '/src'; + $files = []; + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS)) as $entry) { + if ($entry->getExtension() === 'php') { + $files[] = substr($entry->getPathname(), strlen($root) + 1); + } + } + sort($files); + $imports = []; + foreach ($files as $file) { + $imports[$file] = self::usedClasses((string) file_get_contents($root . '/' . $file)); + } + return $imports; + } + + /** @return list */ + private static function usedClasses(string $source): array + { + preg_match_all('/^use\s+(?!function\s|const\s)([^;]+);/m', $source, $statements); + $classes = []; + foreach ($statements[1] as $statement) { + foreach (self::expand($statement) as $class) { + if (str_starts_with($class, 'Packvium\\')) { + $classes[] = substr($class, strlen('Packvium\\')); + } + } + } + $classes = array_values(array_unique($classes)); + sort($classes); + return $classes; + } + + /** @return list `A\B\{C, D as E}` => `A\B\C`, `A\B\D` */ + private static function expand(string $statement): array + { + $names = []; + if (preg_match('/^([^{]*)\{([^}]*)\}$/s', trim($statement), $group) === 1) { + foreach (explode(',', $group[2]) as $member) { + $names[] = trim($group[1]) . self::withoutAlias($member); + } + return $names; + } + foreach (explode(',', $statement) as $name) { + $names[] = self::withoutAlias($name); + } + return $names; + } + + private static function withoutAlias(string $name): string + { + return trim(preg_split('/\s+as\s+/i', trim($name))[0]); + } +} diff --git a/tests/MeasureReadingTest.php b/tests/MeasureReadingTest.php index 25a8a44..d306851 100644 --- a/tests/MeasureReadingTest.php +++ b/tests/MeasureReadingTest.php @@ -58,4 +58,23 @@ public static function testAWholeNumberPastTheLargestExactIntegerIsWholeHoweverI self::assertFalse(MeasureReading::isWholeBeyondExact(1.5)); self::assertFalse(MeasureReading::isWholeBeyondExact(\INF)); } + + public static function testTheMeasureGrammarIsTheReferences(): void + { + // K1: optional sign, ASCII digits, a point only with digits on both sides, a fraction or + // a mixed fraction, at most 18 fractional digits, and a unit in any case. + $readable = ['100', '100.0', '0.5', '+5', '1/2', '1 1/2', '1.' . \str_repeat('1', 18), '1.5 MM', '1.5 Cm', '5 ']; + foreach ($readable as $text) { + self::assertSame(MeasureReading::READABLE, MeasureReading::verdict($text, Length::class, 'mm'), $text); + } + $unreadable = ['100.', '.5', '0x64', '1e2', '1_0', '1/0', '- 5', '1.5/2', '1 -1/2', '1.' . \str_repeat('1', 19)]; + foreach ($unreadable as $text) { + self::assertSame(MeasureReading::UNREADABLE, MeasureReading::verdict($text, Length::class, 'mm'), $text); + } + self::assertSame(MeasureReading::NEGATIVE, MeasureReading::verdict('-5', Length::class, 'mm')); + foreach (['1 g', '1 G', '1 kg', '1 KG', '1 lb', '1 LB'] as $text) { + self::assertSame(MeasureReading::READABLE, MeasureReading::verdict($text, Weight::class, 'g'), $text); + } + self::assertSame(MeasureReading::UNREADABLE, MeasureReading::verdict('1 gg', Weight::class, 'g')); + } } diff --git a/tests/ObjectiveBoundsTest.php b/tests/ObjectiveBoundsTest.php index e6371fe..370d22a 100644 --- a/tests/ObjectiveBoundsTest.php +++ b/tests/ObjectiveBoundsTest.php @@ -2,15 +2,18 @@ declare(strict_types=1); namespace Packvium\Tests; -use Packvium\Domain\{Container, Dimensions, FixedPlacement, Item, ItemInstance, MadeToMeasure, PackingRequest, Point, Rotation, ShapeType}; -use Packvium\Algorithm\{BoundOverflowException, ObjectiveBounds}; +use Packvium\Domain\{Container, Dimensions, FixedPlacement, Item, ItemInstance, MadeToMeasure, PackingRequest, Point, RateTable, Rotation, ShapeType}; +use Packvium\Algorithm\{BoundOverflowException, BoundWithheldException, ObjectiveBounds}; use Packvium\Config\PackingConfig; use Packvium\Objective\DefaultSolutionScorer; use Packvium\Packer; use Packvium\Result\PackingStatus; -use Packvium\Support\BigInt; +use Packvium\Serialization\ArrayCodec; +use Packvium\Support\{BigInt, ExactInteger}; use Packvium\Unit\{Length, Weight}; +use function Packvium\Validation\validate; + /** * This engine's lower bounds against Python's, on the shared corpus. * @@ -45,7 +48,8 @@ private static function scene(): array /** * Every covered objective's vector for one normalised input, null where a ceiling - * withholds it -- the shape the scene's `objectives` records. + * withholds it -- the shape the scene's `objectives` records. The billed objectives read + * a configuration these inputs do not carry; the scene's `billed` cases hold them. * * @param list> $instances * @param list> $containers @@ -55,6 +59,9 @@ private static function objectives(array $instances, array $containers): array { $vectors = []; foreach (ObjectiveBounds::OBJECTIVE_ORDERS as $objective => $order) { + if (in_array($objective, ObjectiveBounds::BILLED_OBJECTIVES, true)) { + continue; + } try { $vectors[$objective] = ObjectiveBounds::objectiveVector($instances, $containers, $order); } catch (BoundOverflowException $refused) { @@ -86,6 +93,47 @@ public static function testEveryCorpusCaseMatchesPythonExactly(): void } } + /** + * A billed objective's vector, or null where it is withheld -- for want of a priceable + * answer or past a ceiling. + * + * @param list> $instances + * @param list> $containers + * @return ?list + */ + private static function billedVector(array $instances, array $containers, string $objective): ?array + { + try { + return ObjectiveBounds::objectiveVector($instances, $containers, + ObjectiveBounds::OBJECTIVE_ORDERS[$objective]); + } catch (BoundOverflowException | BoundWithheldException $withheld) { + return null; + } + } + + /** + * The scene's billed cases, from the corpus and the oracle's hand-checked + * examples. Each container carries what a carrier bills -- `tare`, `dimensional` as a + * decimal string and `brackets` as `[bound ticks as a string, charge]` -- so the check is + * about the arithmetic over those numbers; deriving them from a request is asserted below. + */ + public static function testEveryBilledCaseMatchesPythonExactly(): void + { + $billed = self::scene()['billed'] ?? []; + self::assertGreaterThan(14, count($billed), 'the scene carries too few billed cases'); + foreach ($billed as $case) { + $containers = array_map(static fn(array $raw): array => [ + 'dimensional' => ExactInteger::normalize($raw['dimensional']), + 'brackets' => array_map(static fn(array $bracket): array + => [ExactInteger::normalize((string)$bracket[0]), $bracket[1]], $raw['brackets']), + ] + $raw, $case['containers']); + self::assertSame($case['bounds'], ObjectiveBounds::fromNormalised($case['instances'], $containers), + "bounds diverge from Python on {$case['fixture']}"); + self::assertSame($case['vector'], self::billedVector($case['instances'], $containers, $case['objective']), + "{$case['objective']} diverges from Python on {$case['fixture']}"); + } + } + /** * The five cases docs/OPTIMALITY-CERTIFICATES.md works by hand. * @@ -331,7 +379,7 @@ public static function testEverySceneEdgeIsAnsweredOrRefusedAsTheOraclePredicate /** * `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. + *; the two shipping objectives one each for what a carrier bills. */ public static function testTheRequestBoundIsStatedOnlyForTheCoveredObjectives(): void { @@ -354,9 +402,11 @@ public static function testTheRequestBoundIsStatedOnlyForTheCoveredObjectives(): 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); - } + // A 100 mm cube is 1 kg dimensional at 1000 cm/kg, above two weightless boxes in it. + $billing = new PackingConfig(objective: 'shipping_cost', dimensionalWeightDivisor: 1000, + dimensionalWeightLengthUnit: 'cm', dimensionalWeightWeightUnit: 'kg'); + self::assertSame([$unpacked, 1000 * Weight::TICKS_PER_G, $count, $unused, $height], + ObjectiveBounds::forRequest($items, $crate, 'shipping_cost', $billing)); // D13: a box cut to measure has no declared size until it is cut. $ticks = static fn(int $mm): array => [$mm * Length::TICKS_PER_MM, $mm * Length::TICKS_PER_MM, $mm * Length::TICKS_PER_MM]; @@ -365,6 +415,216 @@ public static function testTheRequestBoundIsStatedOnlyForTheCoveredObjectives(): self::assertNull(ObjectiveBounds::forRequest($items, $machine, 'default')); } + /** + * The billed key needs the configuration's divisor; without one there is no number to + * bound, and the packer refuses such a request before it gets here. + */ + public static function testABilledObjectiveWithoutItsDivisorGetsNone(): void + { + $items = self::instancesOf(Item::create('i', Dimensions::mm(10, 10, 10)), 2); + $box = [Container::create('box', Dimensions::mm(30, 30, 30))]; + foreach (ObjectiveBounds::BILLED_OBJECTIVES as $objective) { + self::assertNull(ObjectiveBounds::forRequest($items, $box, $objective), $objective); + self::assertNull(ObjectiveBounds::forRequest($items, $box, $objective, + new PackingConfig(objective: $objective)), $objective); + } + } + + /** + * One billed request, packed by the exhaustive profile at 5000 cm/kg. + * + * @param list> $containers + * @param list> $items + * @return array + */ + private static function billed(string $objective, array $containers, array $items): array + { + return ArrayCodec::pack(['items' => $items, 'containers' => $containers, 'configuration' => [ + 'objective' => $objective, 'dimensional_weight_divisor' => 5000, + 'dimensional_weight_length_unit' => 'cm', 'dimensional_weight_weight_unit' => 'kg', + 'solver_profile' => 'exact_small']]); + } + + /** @return array */ + private static function brick(int $quantity, int $grams): array + { + return ['id' => 'brick', 'quantity' => $quantity, 'weight' => "{$grams} g", + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]; + } + + /** + * A 200 x 100 x 100 mm box at 5000 cm/kg is 0.4 kg dimensional; two 1 kg bricks + * and a 300 g tare bill 2.3 kg actual, so the bound is the actual weight, and attained. + */ + public static function testShippingCostBillsAtLeastTheFloorAndAtLeastTarePlusPayload(): void + { + $result = self::billed('shipping_cost', [['id' => 'box', 'tare_weight' => '300 g', + 'inner_dimensions' => ['length' => '200', 'width' => '100', 'height' => '100']]], [self::brick(2, 1000)]); + self::assertSame([0, 2300 * Weight::TICKS_PER_G], array_slice($result['optimality']['lower_bound'], 0, 2)); + self::assertSame('optimal', $result['status']); + } + + /** A 400 mm cube is 12.8 kg dimensional at 5000 cm/kg, above one light brick and its tare. */ + public static function testShippingCostTakesTheDimensionalFloorWhenTheBoxIsBulky(): void + { + $result = self::billed('shipping_cost', [['id' => 'bulky', + 'inner_dimensions' => ['length' => '400', 'width' => '400', 'height' => '400']]], [self::brick(1, 100)]); + self::assertSame(12800 * Weight::TICKS_PER_G, $result['optimality']['lower_bound'][1]); + } + + /** + * Two 1000 g bricks cannot share a 1500 g bracket, so two containers pay it twice: the + * item cover says 200, which the weight cover alone (134) and the count term (100) miss. + */ + public static function testLandedCostSeesThatTwoBricksCannotShareABracket(): void + { + $result = self::billed('lowest_landed_cost', [ + ['id' => 'snug-dear', 'inner_dimensions' => ['length' => '200', 'width' => '100', 'height' => '100'], + 'rate_table' => ['weight_brackets_g' => [20000], 'prices_minor' => [5000]]], + ['id' => 'unit-cheap', 'inner_dimensions' => ['length' => '100', 'width' => '100', 'height' => '100'], + 'rate_table' => ['weight_brackets_g' => [1500], 'prices_minor' => [100]]], + ], [self::brick(2, 1000)]); + self::assertSame([0, 200], array_slice($result['optimality']['lower_bound'], 0, 2)); + self::assertSame(200, $result['score'][1]); + } + + /** + * One normalised billed container: unlimited, no limits, room for anything. + * + * @param list $brackets + * @return array + */ + private static function billedType(int $tare, int $dimensional, array $brackets, ?int $quantity = null): array + { + return ['usable' => '10', 'inner' => '10', 'base_area' => 10, 'height' => 1, 'payload' => null, + 'max_items' => null, 'quantity' => $quantity, 'cost_minor' => 0, + 'tare' => $tare, 'dimensional' => $dimensional, 'brackets' => $brackets]; + } + + /** + * A promotional dip: the 2 kg bracket is dearer than the 5 kg one. A load that could be + * billed in either is bounded by the cheaper, since prices need not rise with weight. + */ + public static function testLandedCostReadsTheCheapestBracketAFloorCanReachNotTheFloorsOwn(): void + { + $landed = new \ReflectionMethod(ObjectiveBounds::class, 'landedChargeBound'); + $type = self::billedType(0, 0, [[2000 * Weight::TICKS_PER_G, 700], [5000 * Weight::TICKS_PER_G, 400]]); + self::assertSame(400, $landed->invoke(null, [1000 * Weight::TICKS_PER_G], ['1'], false, [$type], 0, 1)); + } + + /** `max(price, minimum)` then the ceiling surcharge, the rate table's own order. */ + public static function testLandedCostAppliesTheMinimumChargeAndTheSurchargeToEveryBracket(): void + { + $container = Container::create('c', Dimensions::mm(100, 100, 100), + rateTable: new RateTable([1000, 2000], [100, 900], minimumChargeMinor: 300, fuelSurchargePermille: 85)); + $brackets = new \ReflectionMethod(ObjectiveBounds::class, 'brackets'); + self::assertSame([[1000 * Weight::TICKS_PER_G, 326], [2000 * Weight::TICKS_PER_G, 977]], + $brackets->invoke(null, $container)); + } + + /** + * A floor above every bracket cannot be priced, and a packing that opens it is refused + * rather than returned, so with nothing else to open no statement is made. + */ + public static function testATypeNoBracketCanPriceIsLeftOutAndNoneLeftWithholdsTheBound(): void + { + $landed = new \ReflectionMethod(ObjectiveBounds::class, 'landedChargeBound'); + self::assertThrows(BoundWithheldException::class, static fn() => $landed->invoke( + null, [1], ['1'], false, [self::billedType(0, 10, [[5, 100]])], 0, 1)); + } + + /** Greedy by cost per unit is exact for one covering constraint; inventory caps an offer. */ + public static function testTheFractionalCoverTakesCostPerUnitOrderAndRoundsOnlyOnce(): void + { + $cover = new \ReflectionMethod(ObjectiveBounds::class, 'cover'); + self::assertSame(24, $cover->invoke(null, [[10, 3, null], [4, 1, null]], 7), '7 x 10/3, rounded up'); + self::assertSame(10 + 16, $cover->invoke(null, [[10, 3, 1], [4, 1, null]], 7), 'one 3-unit, then 4 x 4'); + self::assertNull($cover->invoke(null, [[10, 3, 1]], 7), 'cannot cover'); + self::assertSame(0, $cover->invoke(null, [[0, 5, null]], 7)); + } + + public static function testTheShippingBoundIsWithheldWithoutEnoughInventoryToOpen(): void + { + $billedWeight = new \ReflectionMethod(ObjectiveBounds::class, 'billedWeightBound'); + self::assertThrows(BoundWithheldException::class, static fn() => $billedWeight->invoke( + null, [1, 1], [self::billedType(0, 5, [], 1)], 0, 2)); + } + + /** + * One `lowest_landed_cost` request at 5000 cm/kg, packed by the fast profile. + * + * @param list> $containers + * @param list> $items + * @return array + */ + private static function landedRequest(array $containers, array $items): array + { + return ['items' => $items, 'containers' => $containers, 'configuration' => [ + 'objective' => 'lowest_landed_cost', 'dimensional_weight_divisor' => 5000, + 'dimensional_weight_length_unit' => 'cm', 'dimensional_weight_weight_unit' => 'kg', + 'solver_profile' => 'fast', 'time_limit_ms' => 20000]]; + } + + /** + * A type whose floor no bracket reaches offers nothing; a payload cap and a slot limit + * bound what a bracket carries; a nesting item drops the volume count. The engine's + * stated bound and the validator's recomputed one agree. + */ + public static function testTheLandedBoundReadsPayloadSlotAndShrinkingLimitsAlikeInEngineAndValidator(): void + { + $request = self::landedRequest([ + ['id' => 'bulky', 'inner_dimensions' => ['length' => '500', 'width' => '500', 'height' => '500'], + 'rate_table' => ['weight_brackets_g' => [1000], 'prices_minor' => [10]]], + ['id' => 'capped', 'max_payload' => '1500 g', 'max_items' => 1, + 'inner_dimensions' => ['length' => '200', 'width' => '200', 'height' => '200'], + 'rate_table' => ['weight_brackets_g' => [3000, 9000], 'prices_minor' => [300, 200]]], + ], [['id' => 'cup', 'quantity' => 2, 'weight' => '1000 g', 'nesting_height' => '10', + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '50']]]); + $result = ArrayCodec::pack($request); + self::assertSame(400, $result['optimality']['lower_bound'][1]); + self::assertSame([], validate($request, $result)); + } + + /** A payload no instance fits places nothing, opens nothing and bills nothing. */ + public static function testNothingPlaceableBoundsTheBilledKeysAtZero(): void + { + $request = self::landedRequest([['id' => 'tiny', 'quantity' => 1, 'max_payload' => '1 g', + 'inner_dimensions' => ['length' => '200', 'width' => '200', 'height' => '200'], + 'rate_table' => ['weight_brackets_g' => [3000], 'prices_minor' => [300]]]], + [['id' => 'brick', 'weight' => '1000 g', 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]]); + foreach (ObjectiveBounds::BILLED_OBJECTIVES as $objective) { + $request['configuration']['objective'] = $objective; + $result = ArrayCodec::pack($request); + self::assertSame([1, 0], array_slice($result['optimality']['lower_bound'], 0, 2), $objective); + self::assertSame([], validate($request, $result), $objective); + } + $billedWeight = new \ReflectionMethod(ObjectiveBounds::class, 'billedWeightBound'); + self::assertSame(0, $billedWeight->invoke(null, [1], [self::billedType(0, 5, [])], 1, 0)); + $landed = new \ReflectionMethod(ObjectiveBounds::class, 'landedChargeBound'); + self::assertSame(0, $landed->invoke(null, [1], ['1'], false, [], 1, 0)); + } + + /** A container without a rate table prices nothing, and nothing to cover costs nothing. */ + public static function testTheBillingHelpersCoverTheirEdges(): void + { + $brackets = new \ReflectionMethod(ObjectiveBounds::class, 'brackets'); + self::assertSame([], $brackets->invoke(null, Container::create('bare', Dimensions::mm(10, 10, 10)))); + $cover = new \ReflectionMethod(ObjectiveBounds::class, 'cover'); + self::assertSame(0, $cover->invoke(null, [[1, 1, null]], 0)); + } + + /** + * § 1.5: absence is "no statement", never "attained". Every built-in objective is covered + * since, so the withheld case is a made-to-measure container (D13). + */ + public static function testAWithheldBoundStatesNothing(): void + { + // A copy of the conformance fixture, so the test also runs in the published package. + $path = __DIR__ . '/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json'; + $result = ArrayCodec::pack(json_decode((string)file_get_contents($path), true)); + self::assertSame(['code'], array_keys($result['optimality'])); + } + /** * 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. diff --git a/tests/PolicyTest.php b/tests/PolicyTest.php index 59e3b96..8584ab2 100644 --- a/tests/PolicyTest.php +++ b/tests/PolicyTest.php @@ -161,6 +161,17 @@ public static function testResolutionOrdersRulesByPriorityThenIdNeverByDeclarati self::assertSame(['c', 'a', 'b'], $ids(array_reverse($rules))); } + public static function testNumericLookingRuleIdsTieBreakByCodePointNotByNumericValue(): void + { + $rule = static fn(string $id): array => ['id' => $id, 'version' => 1, 'effective_at' => 0, 'priority' => 5, + 'separate_tags' => ['tag' => 'x', 'from_tag' => 'y']]; + $ids = array_map( + static fn($resolved): string => $resolved->id, + PolicyRuleSet::fromArray(['as_of' => 0, 'rules' => [$rule('9'), $rule('10'), $rule('1e1')]])->rules, + ); + self::assertSame(['10', '1e1', '9'], $ids); + } + public static function testAnUndeclaredShipmentFactIsAbsentRatherThanMatchingAnything(): void { self::assertTrue((new ShipmentContext(facility: 'SEA1'))->satisfiedBy(new ShipmentContext(facility: 'SEA1'))); diff --git a/tests/RebalanceTest.php b/tests/RebalanceTest.php index e55aba8..415e6fb 100644 --- a/tests/RebalanceTest.php +++ b/tests/RebalanceTest.php @@ -15,6 +15,7 @@ use Packvium\Domain\Rotation; use Packvium\Domain\UnpackedItem; use Packvium\Domain\UnratedWeightException; +use Packvium\Config\SolverProfile; use Packvium\Objective\UnknownObjectiveException; use Packvium\Validation\IndependentSolutionValidator; @@ -465,4 +466,25 @@ public static function testRebalanceNeverWidensThePayloadSpread(): void } } } + + public static function testACompactLatticeResultIsRebalancedNotFataled(): void + { + // A compact lattice container carries no per-item placements; indexing them + // as if present used to fatal on `range(0, -1)`. + $cube = Support::item('cube', 100, 100, 100, ['quantity' => 25, 'weight' => '100 g']); + $boxType = Support::box('box', 300, 200, 100, ['quantity' => 10]); + $config = new PackingConfig(profile: SolverProfile::Fast, requirePlacementCoordinates: false); + $result = Support::pack([$cube], [$boxType], $config); + self::assertTrue( + array_filter($result->containers, static fn(PackedContainer $c): bool => $c->latticeSummary !== null) !== [], + 'the fixture must produce a compact lattice container', + ); + + $outcome = WeightRebalancer::rebalance(new PackingRequest([$cube], [$boxType]), $result->containers, $result->unpacked, $config); + + foreach ($outcome->containers as $container) { + self::assertNull($container->latticeSummary); + } + self::assertAccountingHolds(new PackingRequest([$cube], [$boxType]), $outcome->containers, $result->unpacked); + } } diff --git a/tests/RequestErrorTest.php b/tests/RequestErrorTest.php index 48825a0..4eb5677 100644 --- a/tests/RequestErrorTest.php +++ b/tests/RequestErrorTest.php @@ -19,6 +19,8 @@ */ final class RequestErrorTest extends TestCase { + private const TOP_BRACKET_MESSAGE = 'must price its top bracket at most 9007199254740991 minor units with the fuel surcharge'; + public static function testTheErrorCarriesItsCodeReasonFieldAndDetail(): void { $error = new InvalidRequestException('below_minimum', '/items/0/quantity', 'must be at least 1'); @@ -119,6 +121,16 @@ public static function testEachRuleNamesTheValueItBroke(): void 'wrong_type', '/containers/0/rate_table/weight_brackets_g', 'must be a list'], 'negative surcharge' => [static function (array &$r): void { $r['containers'][0]['rate_table'] = ['fuel_surcharge_permille' => -1]; }, 'below_minimum', '/containers/0/rate_table/fuel_surcharge_permille', 'must be at least 0'], + 'top bracket with surcharge one above 2^53 - 1' => [static function (array &$r): void { $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000], 'prices_minor' => [4503599627370496], 'fuel_surcharge_permille' => 1000]; }, + 'above_maximum', '/containers/0/rate_table', self::TOP_BRACKET_MESSAGE], + 'top bracket far past 2^64' => [static function (array &$r): void { $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000], 'prices_minor' => [9007199254740991], 'fuel_surcharge_permille' => 9007199254740991]; }, + 'above_maximum', '/containers/0/rate_table', self::TOP_BRACKET_MESSAGE], + 'minimum charge lifts a cheap table past the ceiling' => [static function (array &$r): void { $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000], 'prices_minor' => [1], 'minimum_charge_minor' => 9007199254740991, 'fuel_surcharge_permille' => 1]; }, + 'above_maximum', '/containers/0/rate_table', self::TOP_BRACKET_MESSAGE], + 'dearest bracket is not the last' => [static function (array &$r): void { $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000, 5000], 'prices_minor' => [4503599627370496, 1], 'fuel_surcharge_permille' => 1000]; }, + 'above_maximum', '/containers/0/rate_table', self::TOP_BRACKET_MESSAGE], + 'a wrong-typed price reports its own error first' => [static function (array &$r): void { $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000], 'prices_minor' => ['9'], 'fuel_surcharge_permille' => 9007199254740991]; }, + 'wrong_type', '/containers/0/rate_table/prices_minor/0', 'must be an integer'], 'catalog reference not an object' => [static function (array &$r): void { $r['catalog_versions_used'] = [5]; }, 'invalid_value', '', 'catalog_versions_used[0] must be an object'], 'catalog reference missing a field' => [static function (array &$r): void { $r['catalog_versions_used'] = [['catalog_id' => 'cartons', 'version' => 1]]; }, @@ -179,6 +191,17 @@ public static function testAWellFormedRateTablePassesTheRules(): void self::assertContains(ArrayCodec::pack($request)['status'], ['feasible', 'optimal']); } + public static function testALandedCostExactlyAtTheCeilingIsAdmitted(): void + { + foreach ([[9007199254740991, 0, 0], [4503599627370495, 0, 1000], [1, 9007199254740991, 0]] as [$price, $minimum, $permille]) { + $request = self::request(); + $request['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000], 'prices_minor' => [$price], + 'minimum_charge_minor' => $minimum, 'fuel_surcharge_permille' => $permille]; + RequestRules::check($request); + } + self::assertTrue(true); + } + public static function testWhatTheRulesDoNotNameIsStillARequestError(): void { $request = self::request(); diff --git a/tests/RequestJsonTest.php b/tests/RequestJsonTest.php new file mode 100644 index 0000000..3827838 --- /dev/null +++ b/tests/RequestJsonTest.php @@ -0,0 +1,56 @@ + 1, '{"0":1,"1":2}' => 1, '{"1":1,"0":2}' => 2] as $limits => $placed) { + $result = ArrayCodec::pack(RequestJson::decode(self::request((string)$limits))); + self::assertSame($placed, count($result['containers'][0]['placements']), (string)$limits); + } + } + + public static function testAJsonArrayIsStillRefusedAsNotAnObject(): void + { + try { + ArrayCodec::pack(RequestJson::decode(self::request('[1]'))); + self::assertTrue(false, 'a list is not a tag_limits object'); + } catch (InvalidRequestException $error) { + self::assertSame('wrong_type', $error->reason()); + self::assertSame('/containers/0/tag_limits', $error->field()); + } + } + + public static function testARequestWithoutTagLimitsDecodesAsBefore(): void + { + $json = self::request('{}'); + self::assertSame(\json_decode($json, true), RequestJson::decode($json)); + } + + public static function testContainersThatAreNotAListAreLeftForTheCodecToRefuse(): void + { + foreach (['{"containers":{"box":{"tag_limits":{"0":1}}}}', '{"containers":7}', '[]', '7'] as $json) { + self::assertSame(\json_decode($json, true), RequestJson::decode($json), $json); + } + } + + private static function request(string $tagLimits): string + { + return '{"items":[{"id":"cube","quantity":3,"weight":"10","tags":["0"],' + . '"dimensions":{"length":"100","width":"100","height":"100"}}],' + . '"containers":[{"id":"box","quantity":1,"tag_limits":' . $tagLimits . ',' + . '"inner_dimensions":{"length":"300","width":"100","height":"100"}}],' + . '"configuration":{"solver_profile":"fast"}}'; + } +} diff --git a/tests/RequestObjectsCorpusTest.php b/tests/RequestObjectsCorpusTest.php index 61336a6..59cb964 100644 --- a/tests/RequestObjectsCorpusTest.php +++ b/tests/RequestObjectsCorpusTest.php @@ -66,6 +66,7 @@ final class RequestObjectsCorpusTest extends TestCase 'container-made-to-measure-not-object' => 'a machine that is not an object is not a MadeToMeasure', 'container-deformable-boundary-not-object' => 'the object holds the bag\'s kind, not a block', 'container-deformable-boundary-kind-missing' => 'the object holds the bag\'s kind, not a block', + 'item-hull-vertices-not-list' => 'ArrayCodec::hullVertices takes a list, not a number', 'item-id-missing' => 'Item requires an id', 'item-dimensions-missing' => 'Item requires dimensions', 'item-side-missing' => 'Dimensions requires all three sides', @@ -98,6 +99,9 @@ final class RequestObjectsCorpusTest extends TestCase 'item-accepts-stacking-groups-not-list' => self::TYPED, 'item-side-boolean' => self::TYPED, 'container-gusseted-bag-side-gusset-depth-boolean' => self::TYPED, + 'container-gusseted-bag-bottom-gusset-depth-boolean' => self::TYPED, + 'container-flat-bag-orientation' => '`bagOrientation` defaults to flat, so a flat bag that names it ' + . 'cannot be told apart from one that does not', 'item-side-fraction' => self::TYPED, 'item-stacking-group-number' => self::TYPED, 'fixed-position-unparsable' => 'a Point holds integer ticks, not text', @@ -108,6 +112,8 @@ final class RequestObjectsCorpusTest extends TestCase 'item-side-beyond-native-integers' => self::TYPED, 'item-side-vast-mixed-fraction' => self::TYPED, 'item-side-vast-with-a-unit-suffix' => self::TYPED, + 'item-side-5000-digits' => self::TYPED, + 'item-side-5000-digit-numerator' => self::TYPED, 'obstacle-additional-boxes-not-list' => 'an Obstacle holds its additional boxes as a list', 'fixed_placements.position.x="-1"' => self::NEGATIVE_POSITION, 'fixed_placements.position.x=-1' => self::NEGATIVE_POSITION, @@ -203,7 +209,7 @@ final class RequestObjectsCorpusTest extends TestCase ]; /** Pinned, so the skip set cannot grow without this line changing too. */ - private const SKIPPED = 148; + private const SKIPPED = 153; public static function testTheSkipSetIsPinnedAndNamesOnlyCorpusCases(): void { diff --git a/tests/RequestObjectsTest.php b/tests/RequestObjectsTest.php index 1f929f7..be648ac 100644 --- a/tests/RequestObjectsTest.php +++ b/tests/RequestObjectsTest.php @@ -54,6 +54,8 @@ static function (array &$r): void { $r['containers'][0]['cost_minor'] = self::TO static function (array &$r): void { $r['containers'][0]['tag_limits'] = ['fragile' => self::TOO_LARGE]; }], 'rate table price past 2^53 - 1' => [self::packed(null, [self::box(rateTable: new RateTable([1000], [self::TOO_LARGE]))]), static function (array &$r): void { $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000], 'prices_minor' => [self::TOO_LARGE]]; }], + 'rate table landed cost past 2^53 - 1' => [self::packed(null, [self::box(rateTable: new RateTable([1000], [9007199254740991], fuelSurchargePermille: 2000))]), + static function (array &$r): void { $r['containers'][0]['rate_table'] = ['weight_brackets_g' => [1000], 'prices_minor' => [9007199254740991], 'fuel_surcharge_permille' => 2000]; }], 'time limit past 2^53 - 1' => [self::packed(null, null, PackingConfig::fast(self::TOO_LARGE)), static function (array &$r): void { $r['configuration']['time_limit_ms'] = self::TOO_LARGE; }], 'effort limit past 2^53 - 1' => [self::packed(null, null, new PackingConfig(SolverProfile::Fast, effortBudget: new EffortBudget(maxRestarts: self::TOO_LARGE))), @@ -74,6 +76,15 @@ static function (array &$r): void { $r['containers'][0]['made_to_measure'] = sel } } + public static function testARateTableLandedCostIsRefusedOnTheObjectPathWithTheContractMessage(): void + { + $table = new RateTable([1000], [9007199254740991], fuelSurchargePermille: 2000); + $error = self::refusal(self::packed(null, [self::box(rateTable: $table)]), 'surcharged table'); + self::assertSame(['above_maximum', '/containers/0/rate_table', + 'invalid_request: /containers/0/rate_table: must price its top bracket at most 9007199254740991 minor units with the fuel surcharge'], + [$error->reason(), $error->field(), $error->getMessage()]); + } + public static function testAnObjectRefusesWithTheJsonReasonAndNoField(): void { $cases = [ diff --git a/tests/ResultValidationBoundTest.php b/tests/ResultValidationBoundTest.php index 501c621..0636506 100644 --- a/tests/ResultValidationBoundTest.php +++ b/tests/ResultValidationBoundTest.php @@ -6,6 +6,8 @@ use Packvium\Serialization\ArrayCodec; use Packvium\Support\ResultValidation\Bound; use Packvium\Support\ResultValidation\Exact; +use Packvium\Support\ResultValidation\Spec; +use Packvium\Support\ResultValidation\Units; use Packvium\Validation\ResultIssue; use function Packvium\Validation\validate; @@ -84,6 +86,109 @@ public static function testTheBoundMatchesEveryCaseAndEdgeOfTheSharedScene(): vo self::assertGreaterThan(400, $compared); } + /** + * The scene's billed cases, each container's `tare`, `dimensional` and priced + * `brackets` read as this copy's billing records. + */ + public static function testTheBilledKeyMatchesEveryBilledCaseOfTheSharedScene(): void + { + $path = \dirname(__DIR__, 2) . '/conformance/scene/objective-bounds.json'; + if (!\is_file($path)) { + self::skip('the shared cross-language scene fixture is not part of this package'); + } + $scene = \json_decode((string)\file_get_contents($path), true); + self::assertGreaterThan(14, \count($scene['billed'])); + foreach ($scene['billed'] as $case) { + $containers = \array_map(static function (array $container): array { + return [ + 'inner_volume' => self::integer($container['inner']), + 'base_area' => self::integer($container['base_area']), + 'height' => self::integer($container['height']), + 'usable' => self::integer($container['usable']), + 'cost_minor' => self::integer($container['cost_minor']), + 'payload' => $container['payload'], + 'max_items' => $container['max_items'], + 'quantity' => $container['quantity'], + ]; + }, $case['containers']); + $billing = \array_map(static function (array $container): array { + return [ + 'floor' => Exact::max(self::integer($container['tare']), self::integer($container['dimensional'])), + 'tare' => self::integer($container['tare']), + 'brackets' => \array_map(static function (array $bracket): array { + return [self::integer($bracket[0]), $bracket[1]]; + }, $container['brackets']), + ]; + }, $case['containers']); + $shrinks = \in_array(true, \array_column($case['instances'], 'shrinks'), true); + [$stated] = Bound::objectiveBound(self::runs($case['instances'], 'volume'), self::runs($case['instances'], 'weight'), + self::runs($case['instances'], 'value'), $shrinks, $containers, $case['objective'], $billing); + self::assertSame($case['vector'], $stated, "{$case['objective']} diverges from the oracle on {$case['fixture']}"); + } + } + + /** + * The reason `stated` gives for one request read as a feasible result would be. + * + * @param array $request + */ + private static function withheldReason(array $request): string + { + $unit = Units::lengthUnit($request); + $stated = new \ReflectionMethod(Bound::class, 'stated'); + return $stated->invoke(null, $request, 'feasible', Spec::items($request, $unit), Spec::containers($request, $unit))[1]; + } + + /**: nothing can price the one type, a billed request with no divisor, an unknown objective. */ + public static function testALandedRequestNothingCanPriceStatesNoBoundInTheValidator(): void + { + $request = [ + 'items' => [['id' => 'brick', 'weight' => '100 g', 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]], + 'containers' => [['id' => 'bulky', 'inner_dimensions' => ['length' => '500', 'width' => '500', 'height' => '500'], + 'rate_table' => ['weight_brackets_g' => [1000], 'prices_minor' => [10]]]], + 'configuration' => ['objective' => 'lowest_landed_cost', 'dimensional_weight_divisor' => 5000, + 'dimensional_weight_length_unit' => 'cm', 'dimensional_weight_weight_unit' => 'kg'], + ]; + $unpriced = 'no priceable inventory carries a packing that attains the count bound'; + self::assertSame($unpriced, self::withheldReason($request)); + self::assertSame($unpriced, self::withheldReason(['configuration' => ['objective' => 'shipping_cost']] + $request)); + self::assertSame("objective 'custom' has no bound", self::withheldReason(['configuration' => ['objective' => 'custom']] + $request)); + } + + /** The billing helpers' edges: nothing to cover, an uncoverable need, a short inventory, a ragged table. */ + public static function testTheValidatorBillingHelpersCoverTheirEdges(): void + { + $method = static function (string $name): \ReflectionMethod { return new \ReflectionMethod(Bound::class, $name); }; + $cover = $method('fractionalCover'); + self::assertSame(0, $cover->invoke(null, [], 0)); + self::assertNull($cover->invoke(null, [[10, 3, 1]], 7)); + self::assertSame(10 + 16, $cover->invoke(null, [[10, 3, 1], [4, 1, null]], 7)); + self::assertNull($method('leastOfInventory')->invoke(null, [5], [1], 2)); + $type = ['usable' => 10, 'payload' => null, 'max_items' => null, 'quantity' => 1]; + $billing = [['floor' => 5, 'tare' => 0, 'brackets' => []]]; + self::assertNull($method('billedTerm')->invoke(null, 'shipping_cost', $billing, [[1, 2]], [[1, 2]], false, [$type], [0, 2, 0, 0, 0])); + self::assertSame([[1000 * Units::TICKS_PER_GRAM, 5]], + $method('brackets')->invoke(null, ['weight_brackets_g' => [1000, 2000], 'prices_minor' => [5]])); + } + + /** + * The validator's own billed term agrees with what the engine states, and a bound + * moved by one is caught. + */ + public static function testABilledObjectiveStatesTheBoundTheValidatorRecomputes(): void + { + $request = self::REQUEST + ['configuration' => [ + 'objective' => 'shipping_cost', 'dimensional_weight_divisor' => 5000, + 'dimensional_weight_length_unit' => 'cm', 'dimensional_weight_weight_unit' => 'kg', + ]]; + $result = ArrayCodec::pack($request); + self::assertSame([], validate($request, $result)); + --$result['optimality']['lower_bound'][1]; + self::assertSame(['optimality_bound_mismatch'], \array_map(static function (ResultIssue $issue): string { + return $issue->code; + }, validate($request, $result))); + } + public static function testANegativeOrUnlimitedCapacityAndZeroVolumesAreReadAsTheReferenceReadsThem(): void { $container = [ diff --git a/tests/SolverTest.php b/tests/SolverTest.php index 2d32025..74d3468 100644 --- a/tests/SolverTest.php +++ b/tests/SolverTest.php @@ -42,6 +42,7 @@ use Packvium\Domain\Point; use Packvium\Domain\Rotation; use Packvium\Domain\ShapeType; +use Packvium\Extension\CandidateScorer; use Packvium\Extension\DefaultCandidateScorer; use Packvium\Support\BigInt; use Packvium\Unit\Length; @@ -2029,4 +2030,47 @@ public static function testDirectPlacementsBuildSignatureOnlyWhenRequested(): vo self::assertSame($expected, $state->placementSignature()); self::assertSame($expected, $state->copy()->placementSignature()); } + + public static function testNumericLookingContainerIdsTieBreakByCodePointNotByNumericValue(): void + { + // Two identical containers differ only by id; "10" precedes "9" by code point, + // as in the other engines, though 9 < 10 as numbers. + $items = [Support::item('9', 100, 100, 100), Support::item('10', 100, 100, 100)]; + $containers = [ + Support::box('9', 100, 100, 100, ['quantity' => 1]), + Support::box('10', 100, 100, 100, ['quantity' => 1]), + ]; + foreach ([PackingConfig::balanced(), PackingConfig::quality()] as $config) { + $result = Support::pack($items, $containers, $config); + self::assertSame( + ['10', '9'], + array_map(static fn($c): string => $c->container->id, $result->containers), + ); + } + } + + public static function testASupportDiagnosticThatRunsOutOfBudgetGivesNoVerdictInsteadOfThrowing(): void + { + // The post-solve "was support the blocker?" replay has its own budget; when a + // search inside it is cut, the diagnostic must stay silent, not escape `pack()`. + $scorer = new class implements CandidateScorer { + public function score(ContainerState $state, Point $point, Dimensions $envelope): array + { + throw new TimeLimitReached(); + } + }; + $box = Support::box('box', 200, 200, 200); + $item = Support::item('cube', 50, 50, 50); + $method = new ReflectionMethod(SolverOrchestrator::class, 'supportIsTheBlocker'); + $method->setAccessible(true); + + $verdict = $method->invoke( + new SolverOrchestrator(candidateScorer: $scorer), + $item->instances()[0], + [new PackedContainer($box, 1, [])], + new PackingConfig(minimumSupportRatio: 0.5), + ); + + self::assertFalse($verdict); + } } diff --git a/tests/StockCutIndexTest.php b/tests/StockCutIndexTest.php index dee42f5..0131920 100644 --- a/tests/StockCutIndexTest.php +++ b/tests/StockCutIndexTest.php @@ -54,6 +54,30 @@ public static function testReplacementAndLockRefuseUnreadableStockFields(): void } } + public static function testCutBoxPricedPastTheExactIntegerCeilingIsRefused(): void + { + $sides = ['length' => '10', 'width' => '10', 'height' => '10']; + $request = ['items' => [['id' => 'cube', 'dimensions' => $sides]], 'containers' => [ + ['id' => 'machine', 'inner_dimensions' => $sides, 'made_to_measure' => ['minimum' => $sides, 'increment' => $sides, 'cost_per_square_metre_minor' => 9007199254740991]], + ]]; + $artifact = OperationalArtifact::build($request, ArrayCodec::pack($request)); + $request['fixed_placements'] = [['container_type' => 'machine']]; + // 600 mm^2 of surface is far below a square metre, so the price stays inside the ceiling. + self::assertTrue(PlanRevision::stockCutBoxes($request, $artifact, 1)->containers[1]->cost_minor <= 9007199254740991); + // The same rate on a cut box of 2000 mm per side is 24 m^2 and passes it. + $cut = $artifact; + foreach (['length', 'width', 'height'] as $axis) { + $cut['geometry']['containers'][0]['inner_dimensions'][$axis] = (string) (2000 * 16000); + } + try { + PlanRevision::stockCutBoxes($request, $cut, 1); + self::assertTrue(false, 'a cut box priced past 2^53 - 1 was accepted'); + } catch (PlanRevisionException $error) { + self::assertSame('invalid_revision', $error->errorCode()); + self::assertSame("a made-to-measure container's cost_per_square_metre_minor prices the largest box above 9007199254740991", $error->getMessage()); + } + } + public static function testStockingKeepsFirstLockOrder(): void { $fixed = $orders = $shapes = []; diff --git a/tests/ValidationTest.php b/tests/ValidationTest.php index f218b7e..ee86ae6 100644 --- a/tests/ValidationTest.php +++ b/tests/ValidationTest.php @@ -390,6 +390,26 @@ public static function testAGroupSpreadAcrossContainersIsCaught(): void self::assertContains('group_split', $codes); } + public static function testNumericLookingGroupNamesAreReportedInCodePointOrder(): void + { + // "9" and "10" become integer array keys; the report must still order them as + // strings, as the other engines do. + $nine = self::item('a', options: ['quantity' => 2, 'group' => '9']); + $ten = self::item('b', options: ['quantity' => 2, 'group' => '10']); + $box = self::shelf(options: ['quantity' => 2]); + [$nineFirst, $nineSecond] = $nine->instances(); + [$tenFirst, $tenSecond] = $ten->instances(); + $report = (new IndependentSolutionValidator())->validate(new PackingRequest([$nine, $ten], [$box]), [ + new PackedContainer($box, 1, [self::place($nineFirst), self::place($tenFirst, 100 * self::MM)]), + new PackedContainer($box, 2, [self::place($nineSecond), self::place($tenSecond, 100 * self::MM)]), + ], 0.0, null, []); + $splits = array_values(array_map( + static fn($issue): string => $issue->detail, + array_filter($report->issues, static fn($issue): bool => $issue->code === 'group_split'), + )); + self::assertSame(['10: shelf#1, shelf#2', '9: shelf#1, shelf#2'], $splits); + } + // ------------------------------------------------------------- reported geometry public static function testARotationTheItemForbidsIsCaught(): void diff --git a/tests/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json b/tests/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json new file mode 100644 index 0000000..8a42fc7 --- /dev/null +++ b/tests/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json @@ -0,0 +1,60 @@ +{ + "units": { + "length": "mm" + }, + "configuration": { + "solver_profile": "balanced", + "time_limit_ms": 300000, + "minimum_support_ratio": 1, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + }, + "objective": "shipping_cost", + "dimensional_weight_divisor": 5000, + "dimensional_weight_length_unit": "cm", + "dimensional_weight_weight_unit": "kg" + }, + "items": [ + { + "id": "cube", + "quantity": 8, + "weight": "1", + "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" + }, + "cost_per_square_metre_minor": 1000, + "outer_allowance": { + "length": "3", + "width": "3", + "height": "3" + } + } + } + ] +}