diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml index ebec750..0bb59bc 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.8.0 (PHP)" + placeholder: "packvium/packvium 1.9.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 ba6ac16..e91fe0b 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.8.0 (PHP)" + placeholder: "packvium/packvium 1.9.0 (PHP)" validations: required: false - type: textarea diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 4991b7c..0014acf 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.8.0. - placeholder: "1.8.0" + description: The exact version installed, for example 1.9.0. + placeholder: "1.9.0" validations: required: true - type: input diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 1e0ae8c..9310929 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.8.0" + placeholder: "1.9.0" validations: required: true - type: textarea diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a59678..479b4c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: matrix: php: ["8.2", "8.3", "8.4", "8.5"] steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 with: php-version: ${{ matrix.php }} @@ -56,7 +56,7 @@ jobs: matrix: php: ["7.3", "7.4", "8.0", "8.1"] steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 with: path: package - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 @@ -111,7 +111,7 @@ jobs: # Prove the package installs from a clean checkout the way a consumer gets it. runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 with: path: package - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 @@ -139,7 +139,7 @@ jobs: contents: read pull-requests: write steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 with: fail-on-severity: low diff --git a/.github/workflows/rc.yml b/.github/workflows/rc.yml index 6f36b1a..acb2d1c 100644 --- a/.github/workflows/rc.yml +++ b/.github/workflows/rc.yml @@ -20,7 +20,7 @@ jobs: verify-tag: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 with: php-version: "8.3" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 18ca855..3cf745d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,7 +22,7 @@ jobs: verify-tag: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 with: php-version: "8.3" @@ -58,7 +58,7 @@ jobs: permissions: contents: write # the Release is the only thing this workflow writes to the repository steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Create the GitHub Release from the tag env: GH_TOKEN: ${{ github.token }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 30af470..a95713e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,43 @@ 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.9.0] + +No API change, but admission is stricter: some requests 1.8 accepted are now refused (see the +weight and length limits below). More requests now agree with the reference, kilometre-scale +requests included. + +### Changed + +- **Under a clearance a compressible item bears its load on its own footprint**, so its crush + check is stricter and `validate` measures its own compressed volume. +- **A weight is at most `2^63 - 1` ticks, and so is every item's weight times its quantity plus + the heaviest tare**: past it, `invalid_request` / `above_maximum`; a weight written as a JSON + number past `2^53 - 1` is `invalid_value` and must be a string. +- **Agrees with the other engines where 1.8 did not:** nesting under a clearance shares the + items' own overlap and a deep nesting column nests in pairs; a length past `2^53 - 1` ticks or + a box past `10^30` cubic ticks is `invalid_request` / `above_maximum`; a side that reads as zero + ticks is `invalid_value` / `must be positive`; an obstacle box outside its container is + `invalid_value` / `lies outside inner_dimensions`, each at its own pointer. +- **`validate` checks the centroid (`centre_of_gravity_unsupported`) and the whole stack's load + (`top_load_exceeded`)**, an item on several bearers shared by contact area. It no longer + holds that item's whole weight against every bearer, so it accepts some results 1.8 rejected + and names the overloaded bearer. +- **A plan beam wider than 1 compares every container type**, whatever the node limit. +- **A request whose areas pass a 64-bit integer is answered exactly**, where it + threw a `TypeError`; `support_ratio` and `volume_utilization` are the correctly rounded + quotient, which can differ in the sixth decimal. +- **`quality` runs the full staged portfolio:** its answer and its `alternatives` now agree + with the reference, at about 0.9x the time on the measured quality fixtures. +- **`fast` is back to 1.7's peak memory on most requests** (the space-subtraction helper and the + fixed-placement and landed-cost checks load only when used). + +### Fixed + +- **A narrow nesting item under a clearance threw `BigInt::subtract would be negative`**, and a + deep nesting column on the lattice returned `invalid_result`. +- **Greedy `quality` starts dropped `PackingConfig::accessDirections`.** + ## [1.8.0] Results now say how far they can be from the best possible answer, `optimal` means a proof, diff --git a/CITATION.cff b/CITATION.cff index 922d5ab..7c2cac4 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,7 +5,7 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.8.0" +version: "1.9.0" license: MIT url: "https://packvium.com" repository-code: "https://github.com/toxakara/packvium-php" diff --git a/README.md b/README.md index 44826ec..0df626b 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ coordinates and rotations for each item, with a reason for anything that did not Full documentation, the constraint reference and benchmarks live at [packvium.com](https://packvium.com). -> **Version 1.8.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.9.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) @@ -367,7 +367,7 @@ Documentation, the constraint reference and the benchmarks are at | --- | --- | --- | | Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/toxakara/packvium-python) | | PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/toxakara/packvium-php) | -| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.8"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.9"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | | Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/toxakara/packvium-node) | | Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/toxakara/packvium-wasm) | | PHP FFI bridge — [`packvium/native-bridge`](https://packagist.org/packages/packvium/native-bridge) | `composer require packvium/native-bridge` | [packvium-php-bridge](https://github.com/toxakara/packvium-php-bridge) | @@ -391,7 +391,7 @@ CodeMeta form. @software{packvium_php, author = {{Packvium contributors}}, title = {Packvium for PHP}, - version = {1.8.0}, + version = {1.9.0}, license = {MIT}, url = {https://packvium.com} } diff --git a/codemeta.json b/codemeta.json index ca3ec69..12fec4a 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.8.0", + "version": "1.9.0", "license": "https://spdx.org/licenses/MIT", "author": [ { diff --git a/docs/COMMERCE-API.md b/docs/COMMERCE-API.md index 7fcc53d..6f4e4b7 100644 --- a/docs/COMMERCE-API.md +++ b/docs/COMMERCE-API.md @@ -150,6 +150,10 @@ history with a hole or a duplicated version number. All three top-level keys are optional; a document that only needs to price a shipment may carry only `tariffs`. Field-level rules: +- A tariff history is identified by the ordered pair `(carrier_id, service_id)`. + Separators inside either string are ordinary identifier characters: for example, + `("a/b", "c")` and `("a", "b/c")` name different histories. Duplicate detection and + both pinned and effective-dated lookup use the complete pair. - `accessorials` is an ordered **list**, not an object, so no language has to agree about key order; each entry sets exactly one of `flat_charge_minor` or `permille_of_base`. Duplicate `accessorial_id` values are an input error. @@ -165,6 +169,9 @@ may carry only `tariffs`. Field-level rules: `published_at`, `cost_minor`, `minimum_charge_minor`, `fuel_surcharge_permille`, `flat_charge_minor`, `permille_of_base` and each zone rate in `cost_per_dimensional_kg_minor` may be zero but not negative. + Rollback versions follow the same date bounds as snapshot versions, and a catalog + request's `resolved_at` must also be non-negative, including when its catalog or + version does not exist. These are input errors rather than lookup rejections. ### Input errors versus rejections @@ -244,6 +251,16 @@ Success: `false` `allowed` always carries a citation — the model refuses to construct a citation-free rejection. +`equals` and `not_equals` compare JSON values recursively: list order matters, +object key order does not, and different key sets remain different even when values +are `null`. Boolean/integer equality follows the reference model (`true == 1`, +`false == 0`), including inside lists and objects. `in` and `not_in` test list +elements, string substrings, or object keys; object values are not members. A +non-string context value cannot be a substring or an object key. A missing context +field matches neither binary operator, including its negated form. Rust's rule priority +comparison handles the entire signed 64-bit range without negating its minimum; +portable JavaScript inputs remain limited by exact `Number` representation. + ### `catalog_version_info` Request: @@ -368,6 +385,16 @@ The `e log e` term is sorting the three id lists; every other bound is a linear the relevant history. These are the bounds of the underlying models; the wrapper adds parsing and serialization, both linear in the payload, and nothing else. +The policy rows treat predicate values as bounded. For structured values, multiply +their predicate work by the comparison/membership cost: recursive equality visits +the compared values, with an additional logarithmic key lookup per object entry in +Rust's default ordered maps. PHP and JavaScript use expected constant-time object-key +lookup; JavaScript also allocates key arrays during object comparison. Python's +effective-dated model evaluation streams version resolution and winner selection in +constant auxiliary space, excluding value-comparison recursion and the loaded +document. Each matching rule's predicates run once; the other ports retain their +existing rule-pool storage. + ## Limitations - The document is supplied by the caller. Nothing here fetches, scrapes or embeds any @@ -380,6 +407,11 @@ parsing and serialization, both linear in the payload, and nothing else. - Policy evaluation covers the closed `PolicyScope` / `PolicyOperator` vocabulary. An unrecognised scope or operator fails document admission rather than being silently ignored — the guarantee `domain/policy/model.py` already makes. +- PHP's array boundary cannot recover the object/list distinction erased by an + associative JSON decoder: `{}` and `[]`, or an object with consecutive numeric + keys, can become the same PHP array. Portable object-valued predicates should use + nonempty objects with nonnumeric string keys. This limitation does not affect + list ordering or ordinary string-key object comparisons. - A JSON number must be written without a fractional part. `1` is an integer; `1.0` and `1e3` are not, and Python, PHP and Rust refuse them. JavaScript cannot tell the difference — `JSON.parse` gives the same `Number` for `1` and `1.0` — so this is the diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 8cdcba6..0d40bf9 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.8.0` freezes the public API. Field names, status codes, the objective +Version `1.9.0` freezes the public API. Field names, status codes, the objective vector, the numeric policy and the validation rules do not change without a major version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde constraint on `1.0` is enough; an exact pin is no longer required. diff --git a/docs/PUBLIC-API.md b/docs/PUBLIC-API.md index d737e88..7eb418e 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -239,6 +239,9 @@ All counters are non-negative integers. A zero means the selected solver did not that phase; it does not mean the metric is unsupported. Compatibility fields `algorithm.placements_attempted` and `algorithm.candidates_evaluated` remain and must equal `metrics.orientations_considered` and `metrics.feasible_candidates`. +For a multi-start portfolio these counters belong to the selected start; the complete +list of starts is recorded separately in `termination.starts`. Counters are not summed +across starts. Metrics are diagnostics: they never participate in feasibility, ranking or the objective vector. @@ -469,9 +472,9 @@ bounds its work by counting must get the same answer on any machine, and a start own share of the clock would lose quietly, with no flag saying the answer depended on the machine's speed. When the clock does fire, the portfolio-wide deadline is reached and `time_limit_reached` is true. Rust and the JavaScript fallback always run their starts against -the one portfolio deadline. Each start keeps its own counters against the whole budget in -Python, PHP and Rust; the JavaScript fallback hands each later start what the earlier ones -left of one budget, so the same number buys less search there. +the one portfolio deadline. Each start keeps its own counters against the whole budget, in all +four engines; until 1.9.0 the JavaScript fallback handed each later start what the earlier ones +left of one budget, so the same number bought less search there. **Read `any_start_truncated` when the answer must not depend on the budget.** The selected start can finish while another start, one that might have won, was stopped by the budget; the diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index fd1e6e6..c09c8e8 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -59,6 +59,42 @@ a caller would get a number from one and a refusal from another for the same inp carries the guarded sums in a representation that holds `10^30` exactly: Python's `int`, PHP's `BigInt` decimal strings, JavaScript's `BigInt`, Rust's `i128`. +Areas follow the same rule in the search itself (1.9.0). Two lengths below +`PHP_INT_MAX` ticks multiply past a native `int` -- a 10 mm wide item longer than about +3,600 km already does -- and Python and Rust hold that product exactly. PHP forms every such +product (base and contact areas, their sums and the load shared by them, the centre-of-gravity +hull, lattice slot counts, the candidate score's room-left term) through +`Packvium\Support\ExactInteger` and `ExactGeometry`: the native `int` while it fits, an exact +decimal string past it, so an ordinary request pays one `is_int` check. The public +`Dimensions::baseAreaTicks()` and `AxisAlignedBox::overlapAreaXY()` keep their `int` contract. +`support_ratio` and `volume_utilization` are Python's correctly rounded `int / int`, not a +quotient of two doubles. + +**The admission ceiling (1.9.0).** Every engine refuses, before any model is built, a +JSON request with a length past `2^53 - 1` ticks (about 563,000 km) or a box -- an item, a +container's inner or outer dimensions, an obstacle, a made-to-measure step -- enclosing more than +`10^30` cubic ticks (about 244 million cubic metres). Both are `invalid_request` with reason +`above_maximum` at the offending pointer (ERRORS.md). The first is the largest tick +count JavaScript's `Number` holds exactly; the second is the bound path's own ceiling, which keeps +`volume x 10^6` inside Rust's `i128`. Until 1.9.0 each engine failed past its own native limit: Rust +and PHP refused a length past `2^63 - 1` ticks with different errors, Python and JavaScript answered, +Python died with `decimal.InvalidOperation` at `10^20` mm, and Rust overflowed `i128` on a container +past about `1.7 x 10^32` cubic ticks. A whole JSON number past `2^53 - 1` is refused the +same way however a parser stored it, and a value past a native integer is read exactly to tell +which way it is out of range. + +**Weights (1.9.0).** A weight is at most `2^63 - 1` ticks (about 1.15 million +tonnes), and so is every item's weight times its quantity plus the heaviest container tare, so +no container's payload or gross weight can pass a signed 64-bit integer, which is how Rust and +PHP add them. Past either, the request is `invalid_request` / `above_maximum`, at the weight or at +`/items`. A weight written as a JSON number past `2^53 - 1` is `invalid_value`: JavaScript has +rounded such a number before any engine code reads it, so a weight that large is written as a +string. Inside the ceiling every engine is exact: Python's `int`, PHP's `int` and `BigInt`, +Rust's `i64` with `i128` products, and in JavaScript a `BigInt` for every weight sum. A +JavaScript result carries a weight's `ticks`, and a `shipping_cost` score position, as a `Number` +while it is exact and as a `BigInt` past `2^53 - 1`; `stringifyExact` and `parseExact` move such +a result through JSON text without rounding it, and `pack` uses them on both backends. + That intermediate ceiling is deliberately not the result ceiling. The five bound keys can cross JSON and are returned as JavaScript `Number` values, so every engine also refuses a final key above **`2^53 - 1` (`9,007,199,254,740,991`)**. This is the largest integer all four diff --git a/src-legacy/Algorithm/CandidateFinder.php b/src-legacy/Algorithm/CandidateFinder.php index 9d85977..0a88c58 100644 --- a/src-legacy/Algorithm/CandidateFinder.php +++ b/src-legacy/Algorithm/CandidateFinder.php @@ -4,7 +4,7 @@ use Packvium\Config\PackingConfig; use Packvium\Constraint\{AxleLoad,ConstraintContext,LoadCalculator,PlacementConstraint,SupportConstraint}; use Packvium\Constraint\Internal\ConstraintActivity; -use Packvium\Support\{BigInt,StableSorter}; +use Packvium\Support\{BigInt,ExactInteger,StableSorter}; use Packvium\Domain\{HullShape,ItemInstance,Nesting,Placement,Point,ShapeType}; use Packvium\Extension\CandidateScorer; final class CandidateFinder @@ -147,12 +147,12 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf if($inertChain){ $stats->supportChecks+=$inertSupportChecks; }else{ - $ctx=new ConstraintContext($container,$placed,$item,$point,$rotation,$physical,$envelope,$stackSensitive,$routeSensitive); + $ctx=null; foreach($active as $link=>[$constraint,$countsSupport,$positionIndependent]){ if($countsSupport)$stats->supportChecks++; $allowed=$positionIndependent - ?($fixedVerdicts[$link] = $fixedVerdicts[$link] ?? $constraint->evaluate($ctx)->allowed) - :$constraint->evaluate($ctx)->allowed; + ?($fixedVerdicts[$link] = $fixedVerdicts[$link] ?? $constraint->evaluate($ctx = $ctx ?? new ConstraintContext($container,$placed,$item,$point,$rotation,$physical,$envelope,$stackSensitive,$routeSensitive))->allowed) + :$constraint->evaluate($ctx = $ctx ?? new ConstraintContext($container,$placed,$item,$point,$rotation,$physical,$envelope,$stackSensitive,$routeSensitive))->allowed; if(!$allowed){$blocked=true;break;} } if($blocked)continue; @@ -163,14 +163,14 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf if($defaultScorer){ if($max===1&&$best!==null&&$z1>$best->score[0])continue; if($retained!==null&&$retained->count()===$max&&$z1>$retained->top()->score[0])continue; - $score=[$z1,$z2>$bagZ?$z2:$bagZ,($limitX-$x2)*($limitY-$y2)+($limitZ-$z2),$y1,$x1]; + $score=[$z1,$z2>$bagZ?$z2:$bagZ,self::roomLeftKey($limitX-$x2,$limitY-$y2,$limitZ-$z2),$y1,$x1]; }else{ $score=$scorer->score($state,$point,$envelope); } $position=($nullsafeVariable1 = $tentative) ? $nullsafeVariable1->position : null; }else{ $score=$defaultScorer - ?[$z1,$z2>$bagZ?$z2:$bagZ,($limitX-$x2)*($limitY-$y2)+($limitZ-$z2),$y1,$x1] + ?[$z1,$z2>$bagZ?$z2:$bagZ,self::roomLeftKey($limitX-$x2,$limitY-$y2,$limitZ-$z2),$y1,$x1] :$scorer->score($state,$point,$envelope); $position=(($nullsafeVariable2 = $tentative) ? $nullsafeVariable2->position : null)??new Point($x1+$clearance,$y1+$clearance,$z1+$clearance); $reservePlacement=$tentative??new Placement( @@ -219,6 +219,23 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf return $max===null?$out:array_slice($out,0,$max); } + /** + * `rx * ry + rz`, the score's room-left term, as an order-preserving key: the native + * value while it fits an int, its exact chunks past that. Any chunked key + * outranks every int, as its value does. + * + * @return int|list + */ + public static function roomLeftKey(int $rx,int $ry,int $rz) + { + $area=$rx*$ry; + if(is_int($area)){ + $residual=$area+$rz; + if(is_int($residual))return $residual; + } + return ExactInteger::sortKey(ExactInteger::add(ExactInteger::mul($rx,$ry),$rz)); + } + /** @return list */ private static function nestingPoints(ContainerState $state,ItemInstance $item):array { diff --git a/src-legacy/Algorithm/Deadline.php b/src-legacy/Algorithm/Deadline.php index a5e3629..73e110b 100644 --- a/src-legacy/Algorithm/Deadline.php +++ b/src-legacy/Algorithm/Deadline.php @@ -163,10 +163,16 @@ public function effortRoom(SearchStats $counted,int $candidates,int $placements, public function expired():bool{return $this->effortStops() || $this->remainingNs()<=0;} public function slice(int $parts):self + { + return $this->share(1,$parts); + } + + /** `$weight / $total` of what is left, never below the minimum slice; all of it when this is the last share. */ + public function share(int $weight,int $total):self { $remaining=$this->remainingNs(); - if($parts<=1)return new self($remaining,$this->clock,$this->effortBudget,$this->stats); - return new self(max(intdiv($remaining,$parts),min($remaining,self::MINIMUM_SLICE_NS)),$this->clock,$this->effortBudget,$this->stats); + if($total<=$weight)return new self($remaining,$this->clock,$this->effortBudget,$this->stats); + return new self(max(intdiv($remaining*$weight,$total),min($remaining,self::MINIMUM_SLICE_NS)),$this->clock,$this->effortBudget,$this->stats); } /** Bind an effort budget to this start's own stats, keeping the same time bound. */ diff --git a/src-legacy/Algorithm/FixedPlacementAdmission.php b/src-legacy/Algorithm/FixedPlacementAdmission.php index 0167946..adabc3e 100644 --- a/src-legacy/Algorithm/FixedPlacementAdmission.php +++ b/src-legacy/Algorithm/FixedPlacementAdmission.php @@ -3,7 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,FixedPlacement,Item,ItemInstance,PackedContainer,PackingRequest,Placement,Point}; -use Packvium\Support\CanonicalJson; +use Packvium\Support\{CanonicalJson,ExactGeometry,ExactInteger}; use Packvium\Unit\{Length,Weight}; use Packvium\Validation\{FixedPlacementException,IndependentSolutionValidator}; /** @@ -165,7 +165,7 @@ private static function supportRatio(array $others,Placement $placement):float if($placement->envelopeOrigin->z===0)return 1.0; $box=new AxisAlignedBox($placement->envelopeOrigin,$placement->envelopeDimensions); $support=LoadSupportGraph::candidateView($others,$placement->instance,$box); - return $support->supportingArea/$placement->envelopeDimensions->baseAreaTicks(); + return ExactInteger::ratio($support->supportingArea,ExactGeometry::baseArea($placement->envelopeDimensions)); } /** @param list $packed */ diff --git a/src-legacy/Algorithm/GridSolver.php b/src-legacy/Algorithm/GridSolver.php index 16b2b5b..787284d 100644 --- a/src-legacy/Algorithm/GridSolver.php +++ b/src-legacy/Algorithm/GridSolver.php @@ -3,6 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container,LatticeSummary,Placement,Point,ShapeType}; +use Packvium\Support\ExactInteger; /** * Regular lattice for a single item type. * @@ -121,7 +122,7 @@ public function packOne(Container $container,int $sequence,array $items,PackingC $ny=intdiv($container->innerDimensions->width->ticks,$envelope->width->ticks); $layerStep=$envelope->height->ticks-$nestingTicks; $innerHeight=$container->innerDimensions->height->ticks; - $nz=$innerHeight<$envelope->height->ticks?0:intdiv($innerHeight-$envelope->height->ticks,$layerStep)+1; + $nz=self::columnLayers($innerHeight,$envelope->height->ticks,$nestingTicks); if($singleLayer)$nz=min($nz,1); // Every item in a uniform column has the same weight. Its bottom item // therefore bears `(nz - 1) * weight`, so the exact greatest safe layer @@ -137,15 +138,16 @@ public function packOne(Container $container,int $sequence,array $items,PackingC // bottom one, which is exactly the count maxStackedItems bounds. The lattice // can express this in its layer count, so it caps rather than falling back. if($prototype->maxStackedItems!==null)$nz=min($nz,$prototype->maxStackedItems+1); - $capacity=$nx*$ny*$nz; - if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems); - if($container->maxPayload!==null&&$prototype->weight->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks,$prototype->weight->ticks)); - foreach(array_intersect($prototype->tags,array_keys($container->tagLimits)) as $tag)$capacity=min($capacity,$container->tagLimits[$tag]); - $score=array_merge([-$capacity],$envelope->volumeKey(),[$rotation]); + // Exact: tiny items in a vast container have more lattice slots than an int holds. + $capacity=ExactInteger::mul(ExactInteger::mul($nx,$ny),$nz); + if($container->maxItems!==null)$capacity=self::atMost($capacity,$container->maxItems); + if($container->maxPayload!==null&&$prototype->weight->ticks>0)$capacity=self::atMost($capacity,intdiv($container->maxPayload->ticks,$prototype->weight->ticks)); + foreach(array_intersect($prototype->tags,array_keys($container->tagLimits)) as $tag)$capacity=self::atMost($capacity,$container->tagLimits[$tag]); + $score=array_merge(ExactInteger::descendingKey($capacity),$envelope->volumeKey(),[$rotation]); if($best===null||$score<$best[0])$best=[$score,$rotation,$physical,$envelope,$nx,$ny,$layerStep,$capacity]; } [,$rotation,$physical,$envelope,$nx,$ny,$layerStep,$capacity]=$best; - $total=min($capacity,count($items)); + $total=(int)self::atMost($capacity,count($items)); // A group is all-or-nothing: a lattice that cannot hold every member holds none. if($prototype->group!==null&&$totalclearance->ticks; @@ -175,13 +177,13 @@ public function packOne(Container $container,int $sequence,array $items,PackingC return new SingleContainerSolution($state,array_slice($items,$total)); } $targetFootprint=[$physical->length->ticks,$physical->width->ticks,$physical->height->ticks]; - $placed=0; + $placed=0;$perLayer=ExactInteger::mul($nx,$ny); for($index=0;$index<$total;$index++){ if($deadline->expired())break; $stats->searchNodesExpanded++; $stats->candidatePointsConsidered++; - $x=$index%$nx;$y=intdiv($index,$nx)%$ny;$z=intdiv($index,$nx*$ny); - $point=new Point($x*$envelope->length->ticks,$y*$envelope->width->ticks,$z*$layerStep); + $x=$index%$nx;$y=intdiv($index,$nx)%$ny;$z=(int)ExactInteger::floorDiv($index,$perLayer); + $point=new Point($x*$envelope->length->ticks,$y*$envelope->width->ticks,self::columnLayerZ($z,$envelope->height->ticks,$nestingTicks)); $position=new Point($point->x+$clearance,$point->y+$clearance,$point->z+$clearance); // A mixed-declared-type lattice group is only reached when every // item shares the same achievable footprint set, not necessarily the same @@ -202,4 +204,35 @@ public function packOne(Container $container,int $sequence,array $items,PackingC if($prototype->group!==null&&$placedexpired(),true); return new SingleContainerSolution($state,array_slice($items,$placed),false,$placed<$total&&$deadline->expired(),true); } + + /** `min($capacity, $cap)`, exact while the capacity may exceed a native int. + * @param int|string $capacity + * @return int|string */ + private static function atMost($capacity,int $cap) + { + return ExactInteger::compare($capacity,$cap)>0?$cap:$capacity; + } + + /** + * The bottom of layer `$layer` in a column of identical envelopes `$height` tall that each + * sink `$nesting` into the one beneath. + * + * Only a directly adjacent pair may overlap. Once `2 x nesting > height` a third + * copy sunk into the second would reach into the first, so the column nests in pairs: the + * second sinks into the first and the third rests on the pair. O(1). + */ + private static function columnLayerZ(int $layer, int $height, int $nesting): int + { + if (2 * $nesting <= $height) { return $layer * ($height - $nesting); } + return intdiv($layer, 2) * (2 * $height - $nesting) + ($layer % 2) * ($height - $nesting); + } + + /** How many layers `columnLayerZ` fits under `$room`. O(1). */ + private static function columnLayers(int $room, int $height, int $nesting): int + { + if ($room < $height) { return 0; } + if (2 * $nesting <= $height) { return intdiv($room - $height, $height - $nesting) + 1; } + $pair = 2 * $height - $nesting; + return 2 * intdiv($room, $pair) + ($room % $pair >= $height ? 1 : 0); + } } diff --git a/src-legacy/Algorithm/HomogeneousBlockSolver.php b/src-legacy/Algorithm/HomogeneousBlockSolver.php index 8c881e3..35ff7de 100644 --- a/src-legacy/Algorithm/HomogeneousBlockSolver.php +++ b/src-legacy/Algorithm/HomogeneousBlockSolver.php @@ -4,11 +4,10 @@ use Packvium\Config\PackingConfig; use Packvium\Config\SolverProfile; -use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Constraint\PlacementConstraint; use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Placement,Point,ShapeType}; use Packvium\Extension\CandidateScorer; -use Packvium\Support\BigInt; +use Packvium\Support\{BigInt,ExactGeometry,ExactInteger}; use Packvium\Unit\Length; /** @@ -114,14 +113,6 @@ public function supports(Container $container,array $items,PackingConfig $config return true; } - /** The share of a member's base that rests on the floor or on a box beneath it. */ - private static function memberSupport(ContainerState $state,ItemInstance $instance,Point $point,Dimensions $envelope):float - { - if($point->z===0)return 1.0; - $support=LoadSupportGraph::candidateView($state->placements,$instance,new AxisAlignedBox($point,$envelope)); - return $support->supportingArea/$envelope->baseAreaTicks(); - } - private function solutionKey(SingleContainerSolution $solution,bool $byVolume=false):array { $signature=[]; @@ -298,7 +289,8 @@ private static function leadingBlocks(array $spaces,array $capacities,array $rot if($envelopeLength>$spaceLength||$envelopeWidth>$spaceWidth)continue; $maximumX=intdiv($spaceLength,$envelopeLength); $maximumY=intdiv($spaceWidth,$envelopeWidth); - $groupNodes=$maximumX*$maximumY<=$capacity?$maximumX*$maximumY:self::latticeNodes($maximumX,$maximumY,$capacity); + $footprintSlots=ExactInteger::mul($maximumX,$maximumY); + $groupNodes=ExactInteger::compare($footprintSlots,$capacity)<=0?(int)$footprintSlots:self::latticeNodes($maximumX,$maximumY,$capacity); // Only a group that reaches a counted limit or a clock read needs the slow path. if($nodes+$groupNodes>$stopAt||(($nodes+$groupNodes-1)>>self::CLOCK_SHIFT)!==(($nodes-1)>>self::CLOCK_SHIFT)){ $expanded=self::expandable($nodes,$groupNodes,$stopAt,$deadline); @@ -307,11 +299,13 @@ private static function leadingBlocks(array $spaces,array $capacities,array $rot }else{$nodes+=$groupNodes;$stats->searchNodesExpanded+=$groupNodes;} if($envelopeHeight>$spaceHeight)continue; $maximumZ=intdiv($spaceHeight,$envelopeHeight); - $whole=$maximumX*$maximumY*$maximumZ; + // Exact: a tiny item in a vast space has more slots than an int holds. + $whole=ExactInteger::mul($footprintSlots,$maximumZ); $volume=$lattice['approximateVolume']; - $largest=$capacity<$whole?$capacity:$whole; + $fitsWhole=ExactInteger::compare($capacity,$whole)>=0; + $largest=$fitsWhole?(int)$whole:$capacity; if($byCount?$largest<$leadCount:$largest*$volume<$leadFloor)continue; - [$count,$nx,$ny,$nz]=$capacity>=$whole?[$whole,$maximumX,$maximumY,$maximumZ]:self::largestBlock($maximumX,$maximumY,$maximumZ,$capacity); + [$count,$nx,$ny,$nz]=$fitsWhole?[$largest,$maximumX,$maximumY,$maximumZ]:self::largestBlock($maximumX,$maximumY,$maximumZ,$capacity); $approximateUsed=$count*$volume; if($byCount?$count<$leadCount:$approximateUsed<$leadFloor)continue; $candidate=['space'=>$space,'itemId'=>$itemId,'rotation'=>$lattice['rotation'],'rotationName'=>$lattice['rotationName'],'physical'=>$lattice['physical'],'envelope'=>$lattice['envelope'],'volume'=>$lattice['volume'],'approximateUsed'=>$approximateUsed,'nx'=>$nx,'ny'=>$ny,'nz'=>$nz,'count'=>$count]; @@ -480,7 +474,7 @@ private static function commit(ContainerState $state,array $spaces,array &$remai return null; } $blockDimensions=new Dimensions(new Length($best['nx']*$best['envelope']->length->ticks),new Length($best['ny']*$best['envelope']->width->ticks),new Length($best['nz']*$best['envelope']->height->ticks)); - return MaximalSpaceSolver::subtractAll($spaces,[new AxisAlignedBox($best['space']->origin,$blockDimensions)],$stats); + return SpaceSubtraction::subtractAll($spaces,[new AxisAlignedBox($best['space']->origin,$blockDimensions)],$stats); } /** @@ -494,14 +488,42 @@ private static function placeMembers(ContainerState $state,array &$remaining,arr { $chosen=array_slice($remaining[$best['itemId']],0,$members); $remaining[$best['itemId']]=array_slice($remaining[$best['itemId']],$members); - $clearance=$config->clearance->ticks;$perLayer=$best['nx']*$best['ny']; + $clearance=$config->clearance->ticks;$perLayer=ExactInteger::mul($best['nx'],$best['ny']); + $dx=$best['envelope']->length->ticks;$dy=$best['envelope']->width->ticks;$dz=$best['envelope']->height->ticks; + $baseZ=$best['space']->origin->z;$baseArea=ExactGeometry::baseArea($best['envelope']); + $supporters=[]; + if($baseZ>0&&$members>0){ + $bx1=$best['space']->origin->x;$by1=$best['space']->origin->y; + $bx2=$bx1+$best['nx']*$dx;$by2=$by1+$best['ny']*$dy; + foreach($state->placements as $existing){ + $eOrigin=$existing->envelopeOrigin;$eDims=$existing->envelopeDimensions; + if($eOrigin->z+$eDims->height->ticks!==$baseZ)continue; + $ox1=$eOrigin->x;$ox2=$ox1+$eDims->length->ticks; + if($ox2<=$bx1||$ox1>=$bx2)continue; + $oy1=$eOrigin->y;$oy2=$oy1+$eDims->width->ticks; + if($oy2<=$by1||$oy1>=$by2)continue; + $supporters[]=[$ox1,$oy1,$ox2,$oy2]; + } + } for($index=0;$index<$members;$index++){ - $x=$index%$best['nx'];$y=intdiv($index,$best['nx'])%$best['ny'];$z=intdiv($index,$perLayer); - $point=new Point($best['space']->origin->x+$x*$best['envelope']->length->ticks,$best['space']->origin->y+$y*$best['envelope']->width->ticks,$best['space']->origin->z+$z*$best['envelope']->height->ticks); - $position=new Point($point->x+$clearance,$point->y+$clearance,$point->z+$clearance); + $x=$index%$best['nx'];$y=intdiv($index,$best['nx'])%$best['ny'];$z=(int)ExactInteger::floorDiv($index,$perLayer); + $px1=$best['space']->origin->x+$x*$dx;$py1=$best['space']->origin->y+$y*$dy;$pz1=$baseZ+$z*$dz; + $point=new Point($px1,$py1,$pz1); + $position=new Point($px1+$clearance,$py1+$clearance,$pz1+$clearance); // Above its bottom layer a member rests on an identical footprint; the // bottom layer rests on whatever is there. - $support=$z===0?self::memberSupport($state,$chosen[$index],$point,$best['envelope']):1.0; + if($z===0&&$baseZ>0){ + $px2=$px1+$dx;$py2=$py1+$dy;$area=0; + foreach($supporters as [$ox1,$oy1,$ox2,$oy2]){ + $ix=($px2<$ox2?$px2:$ox2)-($px1>$ox1?$px1:$ox1); + if($ix<=0)continue; + $iy=($py2<$oy2?$py2:$oy2)-($py1>$oy1?$py1:$oy1); + if($iy>0)$area=ExactInteger::add($area,ExactInteger::mul($ix,$iy)); + } + $support=ExactInteger::ratio($area,$baseArea); + }else{ + $support=1.0; + } $state->addDirect(new Placement($chosen[$index],$position,$best['rotation'],$best['physical'],$point,$best['envelope'],$support)); $stats->candidatesEvaluated++;$stats->placementsAttempted++; } diff --git a/src-legacy/Algorithm/Internal/ConcurrentStarts.php b/src-legacy/Algorithm/Internal/ConcurrentStarts.php new file mode 100644 index 0000000..56fd6e6 --- /dev/null +++ b/src-legacy/Algorithm/Internal/ConcurrentStarts.php @@ -0,0 +1,146 @@ +name().':'.$start[1],false,false,false); + }, + $starts, + ); + $results=array_fill(0,count($starts),null); + + [$solver0,$orderName0,$order0]=$starts[0]; + $stats0=new SearchStats(); + $budget0=$call('startBudget',$deadline,$effortBudget,$stats0,count($starts)); + [$packed0,$unpacked0,$exhaustive0,$reached0,$dominantLattice0]=$call('acrossContainers',$solver0,$order0,$containers,$config,$stats0,$budget0,$preloaded); + [$wallReached0,$effortReached0]=$call('limitsReached',$reached0,$budget0->effortStopped(),$budget0->remainingNs()); + $unpacked0=$call('effortLimited',$unpacked0,$effortReached0); + $id0=$solver0->name().':'.$orderName0; + $results[0]=new RawSolution($id0,$packed0,$unpacked0,$stats0,$wallReached0,$effortReached0,$exhaustive0); + $records[0]=new StartRecord($id0,true,!$reached0,$reached0); + + // Same correction as the sequential path: only a genuine lattice + // construction is provably no worse than what remains, never a GridSolver + // delegate result -- see `solveSequential`'s identical check for the full + // rationale. + $shortCircuit=$dominantLattice0&&$unpacked0===[]&&$candidateScorer===null; + $remaining=array_slice($starts,1,null,true); + + if($remaining!==[]&&!$shortCircuit&&!$deadline->expired()){ + $absoluteDeadlineNs=hrtime(true)+$deadline->remainingNs(); + $workerCount=max(1,min($config->parallelStarts,count($remaining))); + foreach(array_chunk($remaining,$workerCount,true) as $batch){ + $sockets=[];$pids=[]; + foreach($batch as $position=>[$solver,$orderName,$order]){ + $pair=stream_socket_pair(STREAM_PF_UNIX,STREAM_SOCK_STREAM,STREAM_IPPROTO_IP); + $pid=pcntl_fork(); + if($pid===-1){ + fclose($pair[0]);fclose($pair[1]); + [$results[$position],$records[$position]]=self::runOneStartInProcess($call, + $solver,$orderName,$order,$containers,$config,$effortBudget,$absoluteDeadlineNs,$preloaded, + ); + continue; + } + if($pid===0){ + fclose($pair[0]); + $stats=new SearchStats(); + $budget=Deadline::until($absoluteDeadlineNs); + if($effortBudget!==null)$budget=$budget->withEffort($effortBudget,$stats); + [$packed,$unpacked,$exhaustive,$reached]=$call('acrossContainers',$solver,$order,$containers,$config,$stats,$budget,$preloaded); + // Trusted internal IPC: this payload only ever comes from this + // process's own fork running the exact same code, never from + // external/attacker-controlled input, so the default (allow + // every class) `unserialize()` on the parent's side is safe. + fwrite($pair[1],serialize([$packed,$unpacked,$exhaustive,$reached,$stats,$budget->effortStopped()])); + fclose($pair[1]); + exit(0); + } + fclose($pair[1]); + $sockets[$position]=$pair[0]; + $pids[$position]=$pid; + } + foreach($sockets as $position=>$socket){ + [$solver,$orderName]=$batch[$position]; + $data=stream_get_contents($socket); + fclose($socket); + pcntl_waitpid($pids[$position],$status); + [$packed,$unpacked,$exhaustive,$reached,$stats,$effortStopped]=unserialize($data); + [$wallReached,$effortReached]=$call('limitsReached',$reached,$effortStopped,$absoluteDeadlineNs-hrtime(true)); + $unpacked=$call('effortLimited',$unpacked,$effortReached); + $id=$solver->name().':'.$orderName; + $results[$position]=new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive); + $records[$position]=new StartRecord($id,true,!$reached,$reached); + } + } + } + + $results=array_values(array_filter($results,static function ($result): bool { + return $result!==null; + })); + return $call('finishPortfolio',$items,$containers,$deadline,$results,$records,$preloaded); + } + + /** Fallback body for one start when `pcntl_fork()` itself fails -- runs synchronously, in the parent. */ + public static function runOneStartInProcess(\Closure $call,SingleContainerSolver $solver,string $orderName,array $order,array $containers,PackingConfig $config,?EffortBudget $effortBudget,int $absoluteDeadlineNs,array $preloaded):array + { + $stats=new SearchStats(); + $budget=Deadline::until($absoluteDeadlineNs); + if($effortBudget!==null)$budget=$budget->withEffort($effortBudget,$stats); + [$packed,$unpacked,$exhaustive,$reached,]=$call('acrossContainers',$solver,$order,$containers,$config,$stats,$budget,$preloaded); + [$wallReached,$effortReached]=$call('limitsReached',$reached,$budget->effortStopped(),$budget->remainingNs()); + $unpacked=$call('effortLimited',$unpacked,$effortReached); + $id=$solver->name().':'.$orderName; + return [ + new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive), + new StartRecord($id,true,!$reached,$reached), + ]; + } +} diff --git a/src-legacy/Algorithm/Internal/ContainerPlanBeam.php b/src-legacy/Algorithm/Internal/ContainerPlanBeam.php new file mode 100644 index 0000000..211b2c7 --- /dev/null +++ b/src-legacy/Algorithm/Internal/ContainerPlanBeam.php @@ -0,0 +1,141 @@ +,remaining:list,inventory:array,sequences:array,exhaustive:bool,dominant:bool} $initial + * @return array{0:list,1:list,2:bool,3:bool,4:bool} + */ + public static function acrossContainerPlans(\Closure $call,SingleContainerSolver $solver,array $items,array $containers,PackingConfig $config,SearchStats $stats,Deadline $deadline,array $initial,bool $reached):array + { + // Numbered per container type, as the greedy path and every other engine number + // them: a fixed placement names `#`, so the count must be the type's own. + $beam=$reached?[]:[$initial];$incumbent=$initial;$nodes=0; + $incumbentScore=self::planScore($incumbent,$incumbent['remaining'],$config); + $maximum=$config->maxContainers??array_sum(array_map(static function (Container $container) use ($items): int { + 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]); + }); + // 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. + $nodeLimit=max($config->containerPlanNodeLimit,$config->containerPlanBeamWidth*count($containers)); + while($beam!==[]&&$nodes<$nodeLimit){ + $expansions=[]; + foreach($beam as $plan){ + if($plan['remaining']===[]||count($plan['packed'])>=$maximum){ + $planScore=self::planScore($plan,$plan['remaining'],$config); + if($planScore<$incumbentScore){$incumbent=$plan;$incumbentScore=$planScore;} + continue; + } + foreach($ordered as $container){ + if($nodes>=$nodeLimit)break; + if($deadline->expired()){$reached=true;break;} + if($plan['inventory'][$container->id]!==null&&$plan['inventory'][$container->id]<=0)continue; + // Each rung is one single-container solve, so the node limit keeps bounding + // the work of a made-to-measure chain. + try{[$one,$trials]=$call('trial',$solver,$container,$plan['sequences'][$container->id]+1,$plan['remaining'],$config,$stats,$deadline);}catch(TimeLimitReached $exception){$nodes++;$reached=true;break;} + $nodes+=$trials; + $reached=$reached||$one->timeLimitReached;if($one->state->placementCount()===0)continue; + [$committed,$ids]=$call('commitState',$one->state);$child=$plan;$child['packed'][]=$committed;$child['remaining']=array_values(array_filter($plan['remaining'],static function (ItemInstance $item) use ($ids): bool { + return !isset($ids[$item->id()]); + }));$child['sequences'][$container->id]++; + if($child['inventory'][$container->id]!==null)$child['inventory'][$container->id]--; + $child['exhaustive']=$plan['exhaustive']&&$one->exhaustive;$child['dominant']=$plan['dominant']&&$one->dominantLattice;$expansions[]=$child; + $childScore=self::planScore($child,$child['remaining'],$config); + if($childScore<$incumbentScore){$incumbent=$child;$incumbentScore=$childScore;} + if($reached)break; + } + if($reached)break; + } + if($reached||$expansions===[])break; + $dominant=[]; + foreach($expansions as $plan){ + $signature=implode('|',array_map(static function (ItemInstance $item): string { + return $item->id(); + },$plan['remaining'])).'::'.json_encode($plan['inventory'],JSON_THROW_ON_ERROR); + $partialScore=self::planScore($plan,[],$config); + $previous=$dominant[$signature]??null; + if($previous===null||$partialScore<$previous[0])$dominant[$signature]=[$partialScore,$plan]; + } + // planBound re-derives the additive volume/payload relaxation with BigInt + // string math; one evaluation per plan instead of one per stable-usort + // comparison leaves the ordering untouched. + $survivors=array_map(static function (array $pair): array { + return $pair[1]; + },array_values($dominant)); + $beam=count($survivors)>1 + ?array_slice(StableSorter::sortBy($survivors,static function (array $plan) use ($containers, $config): array { + return self::planBound($plan,$containers,$config); + }),0,$config->containerPlanBeamWidth) + :$survivors; + } + $unpacked=[];$opened=$call('openedByType',$incumbent['packed']);foreach($incumbent['remaining'] as $item){[$reason,$details]=$call('unpackedReason',$item,$containers,$reached);if($reason==='no_feasible_placement'&&$call('supportIsTheBlocker',$item,$incumbent['packed'],$config))$reason='insufficient_support';if($reason==='no_feasible_placement')$reason=$call('limitReason',$item,$containers,$opened,$config)??$reason;$unpacked[]=new UnpackedItem($item,$reason,$details);} + $proven=$incumbent['exhaustive']&&!$reached&&$unpacked===[]&&count($incumbent['packed'])===1; + return [$incumbent['packed'],$unpacked,$proven,$reached,$incumbent['dominant']]; + } + public static function planScore(array $plan,array $remaining,PackingConfig $config):array + { + $unpacked=array_map(static function (ItemInstance $item): UnpackedItem { + return new UnpackedItem($item,'search_exhausted'); + },$remaining); + $raw=new RawSolution('container_plan',$plan['packed'],$unpacked,new SearchStats()); + return ObjectiveRegistry::resolve($config->objective,$config)->score($raw)->components; + } + + public static function planBound(array $plan,array $containers,PackingConfig $config):array + { + $score=self::planScore($plan,[],$config);$index=$config->objective==='default'?1:2; + $score[$index]+=self::additionalContainerLowerBound($plan,$containers); + $score[]=implode('|',array_map(static function (ItemInstance $item): string { + return $item->id(); + },$plan['remaining'])); + return $score; + } + + private static function additionalContainerLowerBound(array $plan,array $containers):int + { + $available=array_values(array_filter($containers,static function (Container $container) use ($plan): bool { + return $plan['inventory'][$container->id]===null||$plan['inventory'][$container->id]>0; + })); + if($plan['remaining']===[]||$available===[])return 0; + $lower=0; + if(!array_filter($plan['remaining'],static function (ItemInstance $item): bool { + return $item->item->nestingHeight!==null; + })){ + $capacity='0';foreach($available as $container)if(BigInt::compare($container->innerDimensions->volumeString(),$capacity)>0)$capacity=$container->innerDimensions->volumeString(); + if($capacity!=='0'){ + $required='0';foreach($plan['remaining'] as $item)$required=BigInt::add($required,Nesting::itemOccupiedVolume($item)); + $lower=max($lower,(int)BigInt::divide(BigInt::add($required,BigInt::subtract($capacity,'1')),$capacity)); + } + } + if(array_filter($available,static function (Container $container): bool { + return $container->maxPayload===null; + })===[]){ + $capacity=max(array_map(static function (Container $container): int { + return $container->maxPayload->ticks; + },$available)); + if($capacity>0){$required=array_sum(array_map(static function (ItemInstance $item): int { + return $item->weight()->ticks; + },$plan['remaining']));$lower=max($lower,intdiv($required+$capacity-1,$capacity));} + } + return $lower; + } +} diff --git a/src-legacy/Algorithm/Internal/MadeToMeasureTrial.php b/src-legacy/Algorithm/Internal/MadeToMeasureTrial.php new file mode 100644 index 0000000..d8844e2 --- /dev/null +++ b/src-legacy/Algorithm/Internal/MadeToMeasureTrial.php @@ -0,0 +1,55 @@ + $items + * @return array{0:SingleContainerSolution,1:int} + */ + public static function madeToMeasureTrial(\Closure $call,?ContainerSelector $containerSelector,SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array + { + $machine=$container->madeToMeasure; + $maximum=[$container->innerDimensions->length->ticks,$container->innerDimensions->width->ticks,$container->innerDimensions->height->ticks]; + $rungs=$machine->solvingEnvelopes($maximum,MadeToMeasure::instanceEdges($items,$config->clearance->ticks)); + $rungConfig=$config->requirePlacementCoordinates?$config:$call('withCoordinates',$config); + $selector=$containerSelector??new DefaultContainerSelector(); + $best=null;$bestKey=null;$last=null;$stopped=false;$trials=0; + foreach($rungs as $rung){ + try{$one=$solver->packOne($container->withEnvelope($rung),$sequence,$items,$rungConfig,$stats,$deadline);} + catch(TimeLimitReached $limit){if($best===null)throw $limit;$stopped=true;break;} + $trials++; + $stopped=$one->timeLimitReached; + $last=$one; + if($one->state->placementCount()>0){ + $trial=$call('fabricated',$container,$one); + if($one->state->placementCount()===count($items))return [$trial,$trials]; + $key=$call('roundScore',$trial,$items,$config,$selector); + if($best===null||($key<=>$bestKey)<0){$best=$trial;$bestKey=$key;} + } + if($stopped||$deadline->expired()){$stopped=true;break;} + } + $chosen=$best??$last; + return [new SingleContainerSolution($chosen->state,$chosen->unpacked,$chosen->exhaustive,$chosen->timeLimitReached||$stopped,$chosen->dominantLattice),$trials]; + } +} diff --git a/src-legacy/Algorithm/Internal/QualityStages.php b/src-legacy/Algorithm/Internal/QualityStages.php new file mode 100644 index 0000000..58f10f4 --- /dev/null +++ b/src-legacy/Algorithm/Internal/QualityStages.php @@ -0,0 +1,72 @@ + $results + * @param array}> $completed + * @return array{0:SingleContainerSolver,1:string,2:list}|null + */ + public static function stagedStart(string $orderName,array $results,array $completed,PackingConfig $config):?array + { + $neighborhood=strncmp($orderName, 'neighborhood:', strlen('neighborhood:')) === 0; + $eligible=array_values(array_filter( + $results, + static function (RawSolution $result) use ($completed, $neighborhood): bool { + return $completed[$result->solverName][0] instanceof ExtremePointSolver + &&(!$neighborhood||substr_compare($result->solverName, ':greedy', -strlen(':greedy')) === 0); + }, + )); + if($eligible===[])return null; + $scorer=ObjectiveRegistry::resolve($config->objective,$config); + $best=$eligible[0];$bestScore=$scorer->score($best); + foreach(array_slice($eligible,1) as $result){ + $score=$scorer->score($result); + $order=$score->compare($bestScore); + if($order<0||($order===0&&strcmp($result->solverName,$best->solverName)<0)){$best=$result;$bestScore=$score;} + } + [$solver,$baseName,$order]=$completed[$best->solverName]; + if(!$neighborhood)return [$solver,$baseName.':beam',$order]; + $type=(string) substr($orderName,strlen('neighborhood:')); + $late=array_merge( + array_filter($order,static function (ItemInstance $instance) use ($type): bool { + return $instance->item->id!==$type; + }), + array_filter($order,static function (ItemInstance $instance) use ($type): bool { + return $instance->item->id===$type; + }), + ); + return [$solver,$baseName.':late_'.$type,$late]; + } + + public static function searchWidth(PackingConfig $config,int $candidatesPerItem,int $beamWidth,int $nodeLimit):PackingConfig + { + return new PackingConfig( + $config->profile,$config->timeLimitMs,$config->topK,$config->seed,$config->maxContainers, + $config->clearance,$config->minimumSupportRatio,$config->exactItemLimit,$config->multiStartOrders, + $config->validateResult,$candidatesPerItem,$config->maxCandidatePoints,$config->solvers,$config->objective, + $config->effortBudget,$config->dimensionalWeightDivisor,$config->dimensionalWeightLengthUnit, + $config->dimensionalWeightWeightUnit,$config->requirePlacementCoordinates,1, + $beamWidth,$nodeLimit,$config->accessDirections, + ); + } +} diff --git a/src-legacy/Algorithm/LayerSolver.php b/src-legacy/Algorithm/LayerSolver.php index 4ebd2f6..faaa656 100644 --- a/src-legacy/Algorithm/LayerSolver.php +++ b/src-legacy/Algorithm/LayerSolver.php @@ -5,7 +5,7 @@ use Packvium\Constraint\{ConstraintSet,PlacementConstraint}; use Packvium\Domain\{Container,ItemInstance}; use Packvium\Extension\{CandidateScorer,DefaultCandidateScorer}; -use Packvium\Support\StableSorter; +use Packvium\Support\{ExactGeometry,ExactInteger,StableSorter}; final class LayerSolver implements SingleContainerSolver { /** @@ -29,7 +29,7 @@ public function orderInsensitive():bool{return true;} public function packOne(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):SingleContainerSolution { $ordered=StableSorter::sortBy($items,static function (ItemInstance $i) use ($config): array { - return array_merge(ItemOrdering::lead($i,$config), [-$i->dimensions()->baseAreaTicks()], $i->dimensions()->descendingVolumeKey(), [-$i->weight()->ticks, $i->id()]); + return array_merge(ItemOrdering::lead($i,$config), ExactInteger::descendingKey(ExactGeometry::baseArea($i->dimensions())), $i->dimensions()->descendingVolumeKey(), [-$i->weight()->ticks, $i->id()]); }); return BeamPacker::pack($container,$sequence,$ordered,$config,ConstraintSet::defaults($config->minimumSupportRatio,$this->constraints,$config->accessDirections),$stats,$deadline,$this->scorer??new DefaultCandidateScorer()); } diff --git a/src-legacy/Algorithm/MaximalSpaceSolver.php b/src-legacy/Algorithm/MaximalSpaceSolver.php index 4b72660..d1dcedb 100644 --- a/src-legacy/Algorithm/MaximalSpaceSolver.php +++ b/src-legacy/Algorithm/MaximalSpaceSolver.php @@ -3,10 +3,8 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; use Packvium\Constraint\{ConstraintSet,PlacementConstraint}; -use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Point}; +use Packvium\Domain\{AxisAlignedBox,Container,ItemInstance,Point}; use Packvium\Extension\{CandidateScorer,DefaultCandidateScorer}; -use Packvium\Support\StableSorter; -use Packvium\Unit\Length; /** * Maximal free spaces plus the common feasibility engine. * @@ -16,6 +14,7 @@ */ final class MaximalSpaceSolver implements SingleContainerSolver { + /** * @var list */ @@ -24,19 +23,6 @@ final class MaximalSpaceSolver implements SingleContainerSolver * @var \Packvium\Extension\CandidateScorer|null */ private $scorer; - /** - * Adversarial item mixes can carve far more surviving maximal spaces than any real - * request needs -- growth is roughly linear in placement count once size variety - * defeats the dominance filter below, and every extra space multiplies the - * per-item choose() scan, the carve and subtractAll's O(new * s) dominance check. - * Past this many surviving spaces, the smallest (least likely to fit a future - * item) are dropped first; well under any request this library's tests or - * fixtures exercise. - */ - public const MAX_MAXIMAL_SPACES = 256; - /** Stands in for the six-chunk volume key of a space whose origin no other space shares. */ - private const UNSHARED_ORIGIN_TAIL=[0,0,0,0,0,0]; - /** @param list $constraints */ public function __construct(array $constraints=[], ?CandidateScorer $scorer=null) { @@ -54,7 +40,7 @@ public function packOne(Container $container,int $sequence,array $items,PackingC return $o->boxes(); },$container->obstacles)); foreach($container->preloaded as $placement)$obstacleBoxes[]=$placement->envelopeBox(); - $spaces=self::subtractAll([new Space(new Point(0,0,0),$container->innerDimensions)],$obstacleBoxes,$stats); + $spaces=SpaceSubtraction::subtractAll([new Space(new Point(0,0,0),$container->innerDimensions)],$obstacleBoxes,$stats); $unplaced=[]; $batches=GroupBatcher::batches($items); foreach($batches as $position=>$batch){ @@ -68,7 +54,7 @@ public function packOne(Container $container,int $sequence,array $items,PackingC $chosen=self::choose($state,$spaces,$item,$config,$constraints,$stats,$deadline,$scorer); if($chosen===null){$placed=false;break;} $state=BeamPacker::extended($state,$item,$chosen); - $spaces=self::subtractAll($spaces,[new AxisAlignedBox($chosen->point,$chosen->envelopeDimensions)],$stats); + $spaces=SpaceSubtraction::subtractAll($spaces,[new AxisAlignedBox($chosen->point,$chosen->envelopeDimensions)],$stats); } }catch(TimeLimitReached $exception){ $state=$snapshot; @@ -90,140 +76,4 @@ private static function choose(ContainerState $state,array $spaces,ItemInstance } return null; } - - /** - * The six maximal slabs of an extent that survive carving a box extent out of it, as - * extents, empty ones dropped. - * - * @param array{int,int,int,int,int,int} $s @param array{int,int,int,int,int,int} $b - * @return list - */ - private static function slabs(array $s,array $b):array - { - [$x1,$y1,$z1,$x2,$y2,$z2]=$s; - $out=[]; - foreach([ - [$x1,$y1,$z1,min($x2,$b[0]),$y2,$z2], - [max($x1,$b[3]),$y1,$z1,$x2,$y2,$z2], - [$x1,$y1,$z1,$x2,min($y2,$b[1]),$z2], - [$x1,max($y1,$b[4]),$z1,$x2,$y2,$z2], - [$x1,$y1,$z1,$x2,$y2,min($z2,$b[2])], - [$x1,$y1,max($z1,$b[5]),$x2,$y2,$z2], - ] as $slab)if($slab[3]>$slab[0]&&$slab[4]>$slab[1]&&$slab[5]>$slab[2])$out[]=$slab; - return $out; - } - - /** - * Precondition: $spaces is containment-free -- every call site passes either a - * single whole space or this method's own output. A survivor untouched by every - * carve can therefore neither contain nor be contained by another survivor, and a - * new slab cannot contain it either (the slab's own parent could not), so only - * new slabs need the dominance check below: O(new * s) instead of O(s^2). - * - * Slabs stay integer extents until they survive: a `Space` is built only for a new - * slab that is kept, and the order is one native multi-column sort. - * - * @param list $spaces @param list $boxes @return list - */ - public static function subtractAll(array $spaces,array $boxes,?SearchStats $stats=null):array - { - // [extent, the untouched Space or null for a new slab] - $current=[]; - foreach($spaces as $space){$o=$space->origin;$d=$space->dimensions;$current[]=[[$o->x,$o->y,$o->z,$o->x+$d->length->ticks,$o->y+$d->width->ticks,$o->z+$d->height->ticks],$space];} - foreach($boxes as $box){ - if($stats!==null)$stats->spacePartitions+=count($current); - $b=$box->extent(); - $next=[]; - foreach($current as $entry){ - $e=$entry[0]; - if(!($e[0]<$b[3]&&$e[3]>$b[0]&&$e[1]<$b[4]&&$e[4]>$b[1]&&$e[2]<$b[5]&&$e[5]>$b[2])){$next[]=$entry;continue;} - foreach(self::slabs($e,$b) as $slab)$next[]=[$slab,null]; - } - $current=$next; - } - // A repeated extent keeps its first position and its last entry. - $unique=[]; - foreach($current as $entry)$unique[implode(':',$entry[0])]=$entry; - $unique=array_values($unique); - return self::survivors(self::sortedByOrigin($unique)); - } - - /** - * Ordered by origin z, y, x, then -- only between spaces sharing an origin -- largest - * volume first, then first seen. The volume key is decimal-string arithmetic, so every - * other space gets a same-length zero tail that no comparison reaches. - * - * @param list $entries - * @return list - */ - private static function sortedByOrigin(array $entries):array - { - if(count($entries)<2)return $entries; - $origins=[]; - foreach($entries as [$e])$origins["{$e[0]}:{$e[1]}:{$e[2]}"]=($origins["{$e[0]}:{$e[1]}:{$e[2]}"]??0)+1; - $columns=array_fill(0,10,[]); - foreach($entries as $index=>[$e]){ - $tail=$origins["{$e[0]}:{$e[1]}:{$e[2]}"]>1 - ?(new Dimensions(new Length($e[3]-$e[0]),new Length($e[4]-$e[1]),new Length($e[5]-$e[2])))->descendingVolumeKey() - :self::UNSHARED_ORIGIN_TAIL; - $columns[0][]=$e[2];$columns[1][]=$e[1];$columns[2][]=$e[0]; - foreach($tail as $chunk=>$value)$columns[3+$chunk][]=$value; - $columns[9][]=$index; - } - array_multisort($columns[0],$columns[1],$columns[2],$columns[3],$columns[4],$columns[5],$columns[6],$columns[7],$columns[8],$columns[9]); - return array_map(static function (int $index) use ($entries): array { - return $entries[$index]; - },$columns[9]); - } - - /** - * The sorted entries that no other contains, as spaces, capped at MAX_MAXIMAL_SPACES. - * - * @param list $kept - * @return list - */ - private static function survivors(array $kept):array - { - // Without this filter every placement multiplies the space list and the solver - // degenerates into an exponential scan of overlapping duplicates. - $extents=array_column($kept,0); - $result=[]; - foreach($kept as $index=>[$e,$space]){ - if($space!==null){$result[]=$space;continue;} - if(self::isContained($extents,$index))continue; - $result[]=new Space(new Point($e[0],$e[1],$e[2]),new Dimensions(new Length($e[3]-$e[0]),new Length($e[4]-$e[1]),new Length($e[5]-$e[2]))); - } - if(count($result)>self::MAX_MAXIMAL_SPACES){ - $byVolume=StableSorter::sortBy($result,static function (Space $space): array { - return $space->dimensions->descendingVolumeKey(); - }); - $result=StableSorter::sortBy( - array_slice($byVolume,0,self::MAX_MAXIMAL_SPACES), - static function (Space $space): array { - return [$space->origin->z,$space->origin->y,$space->origin->x]; - }, - ); - } - return $result; - } - - /** - * Whether another extent contains `$extents[$index]`, for extents ordered by - * `(z1, y1, x1, -volume)`. - * - * A containing extent starts at or before `$extents[$index]` on every axis and has strictly - * larger volume when origins match, so it always appears at a position `< $index` with - * `$extent[2] <= $z1` already guaranteed. - * - * @param list $extents - */ - private static function isContained(array $extents,int $index):bool - { - [$x1,$y1,,$x2,$y2,$z2]=$extents[$index]; - for($other=0;$other<$index;++$other){ - $extent=$extents[$other]; - if($extent[3]>=$x2&&$extent[4]>=$y2&&$extent[5]>=$z2&&$extent[0]<=$x1&&$extent[1]<=$y1)return true; - } - return false; - } } diff --git a/src-legacy/Algorithm/ObjectiveBounds.php b/src-legacy/Algorithm/ObjectiveBounds.php index 2f7a863..f89b92e 100644 --- a/src-legacy/Algorithm/ObjectiveBounds.php +++ b/src-legacy/Algorithm/ObjectiveBounds.php @@ -8,6 +8,8 @@ use Packvium\Domain\ItemInstance; use Packvium\Domain\ShapeType; use Packvium\Support\BigInt; +use Packvium\Support\ExactGeometry; +use Packvium\Support\ExactInteger; /** * Lower bounds on the objective vector, and the gap against an incumbent. @@ -205,7 +207,7 @@ public static function compute(array $instances, array $containers): array $normalisedContainers[] = [ 'usable' => VolumeReserve::usable($container), 'inner' => $container->innerDimensions->volumeString(), - 'base_area' => $container->innerDimensions->baseAreaTicks(), + 'base_area' => ExactGeometry::baseArea($container->innerDimensions), 'height' => $container->innerDimensions->height->ticks, 'payload' => ($nullsafeVariable1 = $container->maxPayload) ? $nullsafeVariable1->ticks : null, 'max_items' => $container->maxItems, @@ -226,7 +228,7 @@ public static function compute(array $instances, array $containers): array * so a port cannot pass the arithmetic check by copying a flag it never computes. * * @param list $instances - * @param list $containers + * @param list $containers * @return array{int,int,int,int,int} */ public static function fromNormalised(array $instances, array $containers): array @@ -249,8 +251,8 @@ public static function fromNormalised(array $instances, array $containers): arra $inner = array_map(static function (array $c): string { return $c['inner']; }, $containers); - $areas = array_map(static function (array $c): int { - return $c['base_area']; + $areas = array_map(static function (array $c) { + return ExactInteger::normalize($c['base_area']); }, $containers); $heights = array_map(static function (array $c): int { return $c['height']; @@ -472,7 +474,7 @@ private static function unusedVolumeBound(array $volumes, bool $shrinks, int $pl * before summing. * * @param list $volumes ascending - * @param list $areas + * @param list $areas square ticks, exact past a native int * @param list $heights */ private static function stackHeightBound(array $volumes, bool $shrinks, int $placed, @@ -481,9 +483,9 @@ private static function stackHeightBound(array $volumes, bool $shrinks, int $pla if ($shrinks || $opened <= 0 || $areas === []) { return 0; } - $widest = max($areas); + $widest = array_reduce($areas, \Closure::fromCallable([ExactInteger::class, 'max']), 0); $tallest = max($heights); - if ($widest <= 0 || $tallest <= 0) { + if (ExactInteger::sign($widest) <= 0 || $tallest <= 0) { return 0; } $required = '0'; diff --git a/src-legacy/Algorithm/SolverOrchestrator.php b/src-legacy/Algorithm/SolverOrchestrator.php index 97fe7c9..1cf644b 100644 --- a/src-legacy/Algorithm/SolverOrchestrator.php +++ b/src-legacy/Algorithm/SolverOrchestrator.php @@ -7,8 +7,9 @@ use Packvium\Domain\{Container,Dimensions,FlatBag,ItemInstance,MadeToMeasure,Nesting,PackedContainer,Rotation,UnpackedItem}; use Packvium\Extension\{CandidateScorer,ContainerSelector,DefaultCandidateScorer,DefaultContainerSelector,ItemOrderStrategy}; use Packvium\Result\StartRecord; -use Packvium\Support\{BigInt,StableSorter}; +use Packvium\Support\{BigInt,ExactGeometry,ExactInteger,StableSorter}; use Packvium\Objective\{LandedCostSolutionScorer,ObjectiveRegistry}; +use Packvium\Algorithm\Internal\{ConcurrentStarts,ContainerPlanBeam,MadeToMeasureTrial,QualityStages}; final class SolverOrchestrator { /** @@ -31,6 +32,11 @@ final class SolverOrchestrator * @var \Packvium\Extension\ContainerSelector|null */ private $containerSelector; + /** + * Beam width and candidates per item for the refinement of a winning late-type order + * (`...:late_:beam`), as Python's `LATE_TYPE_REFINEMENT_WIDTH`. + */ + private const LATE_TYPE_REFINEMENT_WIDTH=4; public function __construct(array $customConstraints=[], array $customOrders=[], array $customSolvers=[], ?CandidateScorer $candidateScorer=null, ?ContainerSelector $containerSelector=null) { $this->customConstraints = $customConstraints; @@ -61,7 +67,7 @@ public function solvePortfolio(array $items,array $containers,PackingConfig $con $effortBudget=$config->effortBudget; if($effortBudget!==null&&$effortBudget->maxRestarts!==null)$starts=array_slice($starts,0,$effortBudget->maxRestarts); $run=$this->eligibleForConcurrentExecution($deadline,$config)&&count($starts)>1 - ? $this->solveConcurrent($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded) + ? ConcurrentStarts::solveConcurrent($this->bridge(),$this->candidateScorer,$items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded) : $this->solveSequential($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded); return self::withoutABlockStartThatOnlyTies($run,$starts,$config); } @@ -134,16 +140,24 @@ static function (array $start): StartRecord { }, $starts, ); + $completed=[]; + $weights=self::sliceWeights($starts); foreach($starts as $position=>[$solver,$orderName,$order]){ if($deadline->expired())break; + if(strncmp($orderName, 'neighborhood:', strlen('neighborhood:')) === 0||substr_compare($orderName, ':beam', -strlen(':beam')) === 0){ + $staged=QualityStages::stagedStart($orderName,$results,$completed,$config); + if($staged===null)continue; + [$solver,$orderName,$order]=$staged; + } $stats=new SearchStats(); - $budget=self::startBudget($deadline,$effortBudget,$stats,count($starts)-$position); - $startConfig=substr_compare($orderName, ':greedy', -strlen(':greedy')) === 0?self::greedyConfig($config):$config; + $budget=self::startBudget($deadline,$effortBudget,$stats,\array_sum(\array_slice($weights,$position)),$weights[$position]); + $startConfig=self::startConfig($orderName,$config); [$packed,$unpacked,$exhaustive,$reached,$dominantLattice]=$this->acrossContainers($solver,$order,$containers,$startConfig,$stats,$budget,$preloaded); [$wallReached,$effortReached]=self::limitsReached($reached,$budget->effortStopped(),$budget->remainingNs()); $unpacked=self::effortLimited($unpacked,$effortReached); $id=$solver->name().':'.$orderName; $results[]=new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive); + $completed[$id]=[$solver,$orderName,$order]; $records[$position]=new StartRecord($id,true,!$reached,$reached); // A single item type's densest possible packing is the regular lattice grid // just tried: no *default-scored* solver in this portfolio can place it in @@ -174,134 +188,6 @@ static function (array $start): StartRecord { return $this->finishPortfolio($items,$containers,$deadline,$results,$records,$preloaded); } - /** - * Runs every start after the first one concurrently, each in its own forked - * process. - * - * The first start always runs in-process, exactly as `solveSequential` would - * run it: `starts()` always places the order-insensitive lattice first when it - * is eligible at all, so the grid short-circuit below can only ever - * fire on this one start, and running it in-process first keeps that - * short-circuit -- and every sequential-mode test that depends on it -- - * byte-for-byte unchanged. - * - * Every remaining start is forked, bound to one shared absolute deadline - * (`Deadline::until`) computed once, right here, from however much of the - * portfolio's own deadline is left; `hrtime(true)` is machine-wide rather than - * per-process, so every child can independently compare its own fresh reading - * against that same instant. Forks are batched in groups of `parallelStarts` so - * this never spawns more concurrent processes than the caller asked for. - * Results are placed into `$results`/`$records` by each start's fixed position, - * never by completion order, so the final list handed to `Packer::pack`'s - * (order-independent, full-key) ranking is identical no matter how the OS - * scheduled the forked processes. - * - * A child communicates its outcome back to the parent over an anonymous - * `stream_socket_pair` (no disk I/O, unlike a temp file) as one `serialize()`d - * payload, written after the child's own solve finishes and read by the parent - * via a blocking `stream_get_contents` that returns once the child closes its - * end. If `pcntl_fork()` itself fails for one start (a real but rare resource - * exhaustion case), that one start falls back to running synchronously in the - * parent instead of losing it -- correctness never depends on the fork - * succeeding, only on whether that start gets the speed-up. - */ - private function solveConcurrent(array $items,array $containers,PackingConfig $config,Deadline $deadline,array $starts,?EffortBudget $effortBudget,array $preloaded=[]):PortfolioRun - { - $records=array_map( - static function (array $start): StartRecord { - return new StartRecord($start[0]->name().':'.$start[1],false,false,false); - }, - $starts, - ); - $results=array_fill(0,count($starts),null); - - [$solver0,$orderName0,$order0]=$starts[0]; - $stats0=new SearchStats(); - $budget0=self::startBudget($deadline,$effortBudget,$stats0,count($starts)); - [$packed0,$unpacked0,$exhaustive0,$reached0,$dominantLattice0]=$this->acrossContainers($solver0,$order0,$containers,$config,$stats0,$budget0,$preloaded); - [$wallReached0,$effortReached0]=self::limitsReached($reached0,$budget0->effortStopped(),$budget0->remainingNs()); - $unpacked0=self::effortLimited($unpacked0,$effortReached0); - $id0=$solver0->name().':'.$orderName0; - $results[0]=new RawSolution($id0,$packed0,$unpacked0,$stats0,$wallReached0,$effortReached0,$exhaustive0); - $records[0]=new StartRecord($id0,true,!$reached0,$reached0); - - // Same correction as the sequential path: only a genuine lattice - // construction is provably no worse than what remains, never a GridSolver - // delegate result -- see `solveSequential`'s identical check for the full - // rationale. - $shortCircuit=$dominantLattice0&&$unpacked0===[]&&$this->candidateScorer===null; - $remaining=array_slice($starts,1,null,true); - - if($remaining!==[]&&!$shortCircuit&&!$deadline->expired()){ - $absoluteDeadlineNs=hrtime(true)+$deadline->remainingNs(); - $workerCount=max(1,min($config->parallelStarts,count($remaining))); - foreach(array_chunk($remaining,$workerCount,true) as $batch){ - $sockets=[];$pids=[]; - foreach($batch as $position=>[$solver,$orderName,$order]){ - $pair=stream_socket_pair(STREAM_PF_UNIX,STREAM_SOCK_STREAM,STREAM_IPPROTO_IP); - $pid=pcntl_fork(); - if($pid===-1){ - fclose($pair[0]);fclose($pair[1]); - [$results[$position],$records[$position]]=$this->runOneStartInProcess( - $solver,$orderName,$order,$containers,$config,$effortBudget,$absoluteDeadlineNs,$preloaded, - ); - continue; - } - if($pid===0){ - fclose($pair[0]); - $stats=new SearchStats(); - $budget=Deadline::until($absoluteDeadlineNs); - if($effortBudget!==null)$budget=$budget->withEffort($effortBudget,$stats); - [$packed,$unpacked,$exhaustive,$reached]=$this->acrossContainers($solver,$order,$containers,$config,$stats,$budget,$preloaded); - // Trusted internal IPC: this payload only ever comes from this - // process's own fork running the exact same code, never from - // external/attacker-controlled input, so the default (allow - // every class) `unserialize()` on the parent's side is safe. - fwrite($pair[1],serialize([$packed,$unpacked,$exhaustive,$reached,$stats,$budget->effortStopped()])); - fclose($pair[1]); - exit(0); - } - fclose($pair[1]); - $sockets[$position]=$pair[0]; - $pids[$position]=$pid; - } - foreach($sockets as $position=>$socket){ - [$solver,$orderName]=$batch[$position]; - $data=stream_get_contents($socket); - fclose($socket); - pcntl_waitpid($pids[$position],$status); - [$packed,$unpacked,$exhaustive,$reached,$stats,$effortStopped]=unserialize($data); - [$wallReached,$effortReached]=self::limitsReached($reached,$effortStopped,$absoluteDeadlineNs-hrtime(true)); - $unpacked=self::effortLimited($unpacked,$effortReached); - $id=$solver->name().':'.$orderName; - $results[$position]=new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive); - $records[$position]=new StartRecord($id,true,!$reached,$reached); - } - } - } - - $results=array_values(array_filter($results,static function ($result): bool { - return $result!==null; - })); - return $this->finishPortfolio($items,$containers,$deadline,$results,$records,$preloaded); - } - - /** Fallback body for one start when `pcntl_fork()` itself fails -- runs synchronously, in the parent. */ - private function runOneStartInProcess(SingleContainerSolver $solver,string $orderName,array $order,array $containers,PackingConfig $config,?EffortBudget $effortBudget,int $absoluteDeadlineNs,array $preloaded):array - { - $stats=new SearchStats(); - $budget=Deadline::until($absoluteDeadlineNs); - if($effortBudget!==null)$budget=$budget->withEffort($effortBudget,$stats); - [$packed,$unpacked,$exhaustive,$reached,]=$this->acrossContainers($solver,$order,$containers,$config,$stats,$budget,$preloaded); - [$wallReached,$effortReached]=self::limitsReached($reached,$budget->effortStopped(),$budget->remainingNs()); - $unpacked=self::effortLimited($unpacked,$effortReached); - $id=$solver->name().':'.$orderName; - return [ - new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive), - new StartRecord($id,true,!$reached,$reached), - ]; - } - /** * The deadline one start runs under. * @@ -311,9 +197,9 @@ private function runOneStartInProcess(SingleContainerSolver $solver,string $orde * deadline and `time_limit_reached` say it did. A slice would let a start the clock cut * lose quietly, making a budgeted answer depend on the machine's speed. */ - private static function startBudget(Deadline $deadline,?EffortBudget $effortBudget,SearchStats $stats,int $startsLeft):Deadline + private static function startBudget(Deadline $deadline,?EffortBudget $effortBudget,SearchStats $stats,int $startsLeft,int $weight=1):Deadline { - if($effortBudget===null)return $deadline->slice($startsLeft); + if($effortBudget===null)return $deadline->share($weight,$startsLeft); return $deadline->withEffort($effortBudget,$stats); } @@ -577,20 +463,63 @@ private function starts(array $items,PackingConfig $config,array $containers=[]) $greedy=array_map(static function (array $start): array { return $start[0]->name()==='homogeneous_blocks'?$start:[$start[0],$start[1].':greedy',$start[2]]; },$starts); - $refinements=[];foreach($starts as [$solver,$name,$order])if($solver->name()==='extreme_points'&&count($refinements)<2)$refinements[]=[$solver,$name.':beam',$order]; - return array_merge($greedy, $refinements); + $extreme=null;foreach($starts as $start)if($start[0]->name()==='extreme_points'){$extreme=$start;break;} + if($extreme===null)return $greedy; + // The same stages as Python -- every greedy order, then each item type moved + // last in the best greedy order, then one wide refinement of the best order found. + // The placeholder orders are replaced when the stage runs (`stagedStart`). + $types=array_values(array_unique(array_map(static function (ItemInstance $instance): string { + return $instance->item->id; + },$items))); + usort($types,'strcmp'); + $neighborhoods=array_map(static function (string $type) use ($extreme): array { + return [$extreme[0],'neighborhood:'.$type,$extreme[2]]; + },$types); + return array_merge($greedy,$neighborhoods,[[$extreme[0],'best:beam',$extreme[2]]]); } - private static function greedyConfig(PackingConfig $config):PackingConfig + /** + * Each start's weight in the time slicing, as Python's `_slice_weights`: the late-type + * neighbourhoods are greedy re-runs of one order, so together they weigh one start; with T + * of them each weighs 1 and every other start T. Without them every start weighs 1. + * + * @param list}> $starts + * @return list + */ + private static function sliceWeights(array $starts):array { - return new PackingConfig( - $config->profile,$config->timeLimitMs,$config->topK,$config->seed,$config->maxContainers, - $config->clearance,$config->minimumSupportRatio,$config->exactItemLimit,$config->multiStartOrders, - $config->validateResult,1,$config->maxCandidatePoints,$config->solvers,$config->objective, - $config->effortBudget,$config->dimensionalWeightDivisor,$config->dimensionalWeightLengthUnit, - $config->dimensionalWeightWeightUnit,$config->requirePlacementCoordinates,1, - 1,1, - ); + $neighbourhoods=0; + foreach($starts as [,$name])if(strncmp($name, 'neighborhood:', strlen('neighborhood:')) === 0)$neighbourhoods++; + if($neighbourhoods===0)return \array_fill(0,\count($starts),1); + return \array_map(static function (array $start) use ($neighbourhoods): int { + return strncmp($start[1], 'neighborhood:', strlen('neighborhood:')) === 0?1:$neighbourhoods; + },$starts); + } + + /** + * Whether a start keeps one candidate per item: the greedy orders and their late-type + * neighbourhoods. A `:beam` refinement of a winning neighbourhood still carries `:late_` + * in its name, yet it is the one start meant to search wide. + */ + private static function runsGreedy(string $orderName):bool + { + if(substr_compare($orderName, ':beam', -strlen(':beam')) === 0)return false; + return substr_compare($orderName, ':greedy', -strlen(':greedy')) === 0||strpos($orderName, ':late_') !== false; + } + + /** The configuration one portfolio start searches with, as Python's `_start_config`. */ + private static function startConfig(string $orderName,PackingConfig $config):PackingConfig + { + if(self::runsGreedy($orderName))return QualityStages::searchWidth($config,1,1,1); + if(substr_compare($orderName, ':beam', -strlen(':beam')) === 0&&strpos($orderName, ':late_') !== false){ + return QualityStages::searchWidth( + $config, + min($config->maxCandidatesPerItem,self::LATE_TYPE_REFINEMENT_WIDTH), + min($config->containerPlanBeamWidth,self::LATE_TYPE_REFINEMENT_WIDTH), + $config->containerPlanNodeLimit, + ); + } + return $config; } /** The same configuration with placement coordinates required: no compact lattice form (D12). */ @@ -664,7 +593,7 @@ private function orders(array $items,PackingConfig $config):array return array_merge(ItemOrdering::lead($i,$config), $i->dimensions()->descendingVolumeKey(), [-$i->dimensions()->maxEdge(), -$i->weight()->ticks, $i->id()]); }], ['base_area',static function (ItemInstance $i) use ($config): array { - return array_merge(ItemOrdering::lead($i,$config), [-$i->dimensions()->baseAreaTicks()], $i->dimensions()->descendingVolumeKey(), [$i->id()]); + return array_merge(ItemOrdering::lead($i,$config), ExactInteger::descendingKey(ExactGeometry::baseArea($i->dimensions())), $i->dimensions()->descendingVolumeKey(), [$i->id()]); }], ['weight',static function (ItemInstance $i) use ($config): array { return array_merge(ItemOrdering::lead($i,$config), [-$i->weight()->ticks], $i->dimensions()->descendingVolumeKey(), [$i->id()]); @@ -768,44 +697,7 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem private function trial(SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array { if($container->madeToMeasure===null)return [$solver->packOne($container,$sequence,$items,$config,$stats,$deadline),1]; - return $this->madeToMeasureTrial($solver,$container,$sequence,$items,$config,$stats,$deadline); - } - - /** - * Try each solving envelope in ascending order and keep the first that places every item; - * failing that, the trial this round's own key prefers, the smaller rung on a tie. - * - * At most four solves, two trial states alive. A compact lattice cannot describe a box cut - * to the achieved extent, so the rung solves always report coordinates (D12), and a rung - * choice is a heuristic, so the trial is never exhaustive (D13). - * - * @param list $items - * @return array{0:SingleContainerSolution,1:int} - */ - private function madeToMeasureTrial(SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array - { - $machine=$container->madeToMeasure; - $maximum=[$container->innerDimensions->length->ticks,$container->innerDimensions->width->ticks,$container->innerDimensions->height->ticks]; - $rungs=$machine->solvingEnvelopes($maximum,MadeToMeasure::instanceEdges($items,$config->clearance->ticks)); - $rungConfig=$config->requirePlacementCoordinates?$config:self::withCoordinates($config); - $selector=$this->containerSelector??new DefaultContainerSelector(); - $best=null;$bestKey=null;$last=null;$stopped=false;$trials=0; - foreach($rungs as $rung){ - try{$one=$solver->packOne($container->withEnvelope($rung),$sequence,$items,$rungConfig,$stats,$deadline);} - catch(TimeLimitReached $limit){if($best===null)throw $limit;$stopped=true;break;} - $trials++; - $stopped=$one->timeLimitReached; - $last=$one; - if($one->state->placementCount()>0){ - $trial=self::fabricated($container,$one); - if($one->state->placementCount()===count($items))return [$trial,$trials]; - $key=self::roundScore($trial,$items,$config,$selector); - if($best===null||($key<=>$bestKey)<0){$best=$trial;$bestKey=$key;} - } - if($stopped||$deadline->expired()){$stopped=true;break;} - } - $chosen=$best??$last; - return [new SingleContainerSolution($chosen->state,$chosen->unpacked,$chosen->exhaustive,$chosen->timeLimitReached||$stopped,$chosen->dominantLattice),$trials]; + return MadeToMeasureTrial::madeToMeasureTrial($this->bridge(),$this->containerSelector,$solver,$container,$sequence,$items,$config,$stats,$deadline); } /** A rung trial as the box cut for it: the achieved extent of its placements, envelope far faces with clearance, rounded up onto the machine grid (D14). O(p). */ @@ -821,7 +713,7 @@ private function acrossContainers(SingleContainerSolver $solver,array $items,arr $beam=$config->containerPlanBeamWidth>1&&($this->containerSelector===null||$this->containerSelector instanceof DefaultContainerSelector); [$opened,$reached]=$this->openPreloaded($solver,$preloaded,$items,$containers,$config,$stats,$deadline); if($beam){ - return $this->acrossContainerPlans($solver,$items,$containers,$config,$stats,$deadline,$opened,$reached); + return ContainerPlanBeam::acrossContainerPlans($this->bridge(),$solver,$items,$containers,$config,$stats,$deadline,$opened,$reached); } $remaining=$opened['remaining'];$packed=$opened['packed'];$exhaustive=$opened['exhaustive'];$dominantLattice=$opened['dominant']; $inventory=$opened['inventory'];$seq=$opened['sequences']; @@ -923,122 +815,11 @@ private static function commitState(ContainerState $state):array return [$packed,$ids]; } - private static function planScore(array $plan,array $remaining,PackingConfig $config):array + /** The orchestrator's own private methods, for the parts kept in `Internal` (see there). */ + private function bridge():\Closure { - $unpacked=array_map(static function (ItemInstance $item): UnpackedItem { - return new UnpackedItem($item,'search_exhausted'); - },$remaining); - $raw=new RawSolution('container_plan',$plan['packed'],$unpacked,new SearchStats()); - return ObjectiveRegistry::resolve($config->objective,$config)->score($raw)->components; - } - - private static function additionalContainerLowerBound(array $plan,array $containers):int - { - $available=array_values(array_filter($containers,static function (Container $container) use ($plan): bool { - return $plan['inventory'][$container->id]===null||$plan['inventory'][$container->id]>0; - })); - if($plan['remaining']===[]||$available===[])return 0; - $lower=0; - if(!array_filter($plan['remaining'],static function (ItemInstance $item): bool { - return $item->item->nestingHeight!==null; - })){ - $capacity='0';foreach($available as $container)if(BigInt::compare($container->innerDimensions->volumeString(),$capacity)>0)$capacity=$container->innerDimensions->volumeString(); - if($capacity!=='0'){ - $required='0';foreach($plan['remaining'] as $item)$required=BigInt::add($required,Nesting::itemOccupiedVolume($item)); - $lower=max($lower,(int)BigInt::divide(BigInt::add($required,BigInt::subtract($capacity,'1')),$capacity)); - } - } - if(array_filter($available,static function (Container $container): bool { - return $container->maxPayload===null; - })===[]){ - $capacity=max(array_map(static function (Container $container): int { - return $container->maxPayload->ticks; - },$available)); - if($capacity>0){$required=array_sum(array_map(static function (ItemInstance $item): int { - return $item->weight()->ticks; - },$plan['remaining']));$lower=max($lower,intdiv($required+$capacity-1,$capacity));} - } - return $lower; - } - - private static function planBound(array $plan,array $containers,PackingConfig $config):array - { - $score=self::planScore($plan,[],$config);$index=$config->objective==='default'?1:2; - $score[$index]+=self::additionalContainerLowerBound($plan,$containers); - $score[]=implode('|',array_map(static function (ItemInstance $item): string { - return $item->id(); - },$plan['remaining'])); - return $score; - } - - /** - * @param array{packed:list,remaining:list,inventory:array,sequences:array,exhaustive:bool,dominant:bool} $initial - * @return array{0:list,1:list,2:bool,3:bool,4:bool} - */ - private function acrossContainerPlans(SingleContainerSolver $solver,array $items,array $containers,PackingConfig $config,SearchStats $stats,Deadline $deadline,array $initial,bool $reached):array - { - // Numbered per container type, as the greedy path and every other engine number - // them: a fixed placement names `#`, so the count must be the type's own. - $beam=$reached?[]:[$initial];$incumbent=$initial;$nodes=0; - $incumbentScore=self::planScore($incumbent,$incumbent['remaining'],$config); - $maximum=$config->maxContainers??array_sum(array_map(static function (Container $container) use ($items): int { - 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]); - }); - while($beam!==[]&&$nodes<$config->containerPlanNodeLimit){ - $expansions=[]; - foreach($beam as $plan){ - if($plan['remaining']===[]||count($plan['packed'])>=$maximum){ - $planScore=self::planScore($plan,$plan['remaining'],$config); - if($planScore<$incumbentScore){$incumbent=$plan;$incumbentScore=$planScore;} - continue; - } - foreach($ordered as $container){ - if($nodes>=$config->containerPlanNodeLimit)break; - if($deadline->expired()){$reached=true;break;} - if($plan['inventory'][$container->id]!==null&&$plan['inventory'][$container->id]<=0)continue; - // Each rung is one single-container solve, so the node limit keeps bounding - // the work of a made-to-measure chain. - try{[$one,$trials]=$this->trial($solver,$container,$plan['sequences'][$container->id]+1,$plan['remaining'],$config,$stats,$deadline);}catch(TimeLimitReached $exception){$nodes++;$reached=true;break;} - $nodes+=$trials; - $reached=$reached||$one->timeLimitReached;if($one->state->placementCount()===0)continue; - [$committed,$ids]=self::commitState($one->state);$child=$plan;$child['packed'][]=$committed;$child['remaining']=array_values(array_filter($plan['remaining'],static function (ItemInstance $item) use ($ids): bool { - return !isset($ids[$item->id()]); - }));$child['sequences'][$container->id]++; - if($child['inventory'][$container->id]!==null)$child['inventory'][$container->id]--; - $child['exhaustive']=$plan['exhaustive']&&$one->exhaustive;$child['dominant']=$plan['dominant']&&$one->dominantLattice;$expansions[]=$child; - $childScore=self::planScore($child,$child['remaining'],$config); - if($childScore<$incumbentScore){$incumbent=$child;$incumbentScore=$childScore;} - if($reached)break; - } - if($reached)break; - } - if($reached||$expansions===[])break; - $dominant=[]; - foreach($expansions as $plan){ - $signature=implode('|',array_map(static function (ItemInstance $item): string { - return $item->id(); - },$plan['remaining'])).'::'.json_encode($plan['inventory'],JSON_THROW_ON_ERROR); - $partialScore=self::planScore($plan,[],$config); - $previous=$dominant[$signature]??null; - if($previous===null||$partialScore<$previous[0])$dominant[$signature]=[$partialScore,$plan]; - } - // planBound re-derives the additive volume/payload relaxation with BigInt - // string math; one evaluation per plan instead of one per stable-usort - // comparison leaves the ordering untouched. - $survivors=array_map(static function (array $pair): array { - return $pair[1]; - },array_values($dominant)); - $beam=count($survivors)>1 - ?array_slice(StableSorter::sortBy($survivors,static function (array $plan) use ($containers, $config): array { - return self::planBound($plan,$containers,$config); - }),0,$config->containerPlanBeamWidth) - :$survivors; - } - $unpacked=[];$opened=self::openedByType($incumbent['packed']);foreach($incumbent['remaining'] as $item){[$reason,$details]=$this->unpackedReason($item,$containers,$reached);if($reason==='no_feasible_placement'&&$this->supportIsTheBlocker($item,$incumbent['packed'],$config))$reason='insufficient_support';if($reason==='no_feasible_placement')$reason=self::limitReason($item,$containers,$opened,$config)??$reason;$unpacked[]=new UnpackedItem($item,$reason,$details);} - $proven=$incumbent['exhaustive']&&!$reached&&$unpacked===[]&&count($incumbent['packed'])===1; - return [$incumbent['packed'],$unpacked,$proven,$reached,$incumbent['dominant']]; + return function (string $method, ...$arguments) { + return $this->{$method}(...$arguments); + }; } } diff --git a/src-legacy/Algorithm/SpaceSubtraction.php b/src-legacy/Algorithm/SpaceSubtraction.php new file mode 100644 index 0000000..c8c967a --- /dev/null +++ b/src-legacy/Algorithm/SpaceSubtraction.php @@ -0,0 +1,164 @@ + + */ + private static function slabs(array $s,array $b):array + { + [$x1,$y1,$z1,$x2,$y2,$z2]=$s; + $out=[]; + foreach([ + [$x1,$y1,$z1,min($x2,$b[0]),$y2,$z2], + [max($x1,$b[3]),$y1,$z1,$x2,$y2,$z2], + [$x1,$y1,$z1,$x2,min($y2,$b[1]),$z2], + [$x1,max($y1,$b[4]),$z1,$x2,$y2,$z2], + [$x1,$y1,$z1,$x2,$y2,min($z2,$b[2])], + [$x1,$y1,max($z1,$b[5]),$x2,$y2,$z2], + ] as $slab)if($slab[3]>$slab[0]&&$slab[4]>$slab[1]&&$slab[5]>$slab[2])$out[]=$slab; + return $out; + } + + /** + * Precondition: $spaces is containment-free -- every call site passes either a + * single whole space or this method's own output. A survivor untouched by every + * carve can therefore neither contain nor be contained by another survivor, and a + * new slab cannot contain it either (the slab's own parent could not), so only + * new slabs need the dominance check below: O(new * s) instead of O(s^2). + * + * Slabs stay integer extents until they survive: a `Space` is built only for a new + * slab that is kept, and the order is one native multi-column sort. + * + * @param list $spaces @param list $boxes @return list + */ + public static function subtractAll(array $spaces,array $boxes,?SearchStats $stats=null):array + { + // [extent, the untouched Space or null for a new slab] + $current=[]; + foreach($spaces as $space){$o=$space->origin;$d=$space->dimensions;$current[]=[[$o->x,$o->y,$o->z,$o->x+$d->length->ticks,$o->y+$d->width->ticks,$o->z+$d->height->ticks],$space];} + foreach($boxes as $box){ + if($stats!==null)$stats->spacePartitions+=count($current); + $b=$box->extent(); + $next=[]; + foreach($current as $entry){ + $e=$entry[0]; + if(!($e[0]<$b[3]&&$e[3]>$b[0]&&$e[1]<$b[4]&&$e[4]>$b[1]&&$e[2]<$b[5]&&$e[5]>$b[2])){$next[]=$entry;continue;} + foreach(self::slabs($e,$b) as $slab)$next[]=[$slab,null]; + } + $current=$next; + } + // A repeated extent keeps its first position and its last entry. + $unique=[]; + foreach($current as $entry)$unique[implode(':',$entry[0])]=$entry; + $unique=array_values($unique); + return self::survivors(self::sortedByOrigin($unique)); + } + + /** + * Ordered by origin z, y, x, then -- only between spaces sharing an origin -- largest + * volume first, then first seen. The volume key is decimal-string arithmetic, so every + * other space gets a same-length zero tail that no comparison reaches. + * + * @param list $entries + * @return list + */ + private static function sortedByOrigin(array $entries):array + { + if(count($entries)<2)return $entries; + $origins=[]; + foreach($entries as [$e])$origins["{$e[0]}:{$e[1]}:{$e[2]}"]=($origins["{$e[0]}:{$e[1]}:{$e[2]}"]??0)+1; + $columns=array_fill(0,10,[]); + foreach($entries as $index=>[$e]){ + $tail=$origins["{$e[0]}:{$e[1]}:{$e[2]}"]>1 + ?(new Dimensions(new Length($e[3]-$e[0]),new Length($e[4]-$e[1]),new Length($e[5]-$e[2])))->descendingVolumeKey() + :self::UNSHARED_ORIGIN_TAIL; + $columns[0][]=$e[2];$columns[1][]=$e[1];$columns[2][]=$e[0]; + foreach($tail as $chunk=>$value)$columns[3+$chunk][]=$value; + $columns[9][]=$index; + } + array_multisort($columns[0],$columns[1],$columns[2],$columns[3],$columns[4],$columns[5],$columns[6],$columns[7],$columns[8],$columns[9]); + return array_map(static function (int $index) use ($entries): array { + return $entries[$index]; + },$columns[9]); + } + + /** + * The sorted entries that no other contains, as spaces, capped at MAX_MAXIMAL_SPACES. + * + * @param list $kept + * @return list + */ + private static function survivors(array $kept):array + { + // Without this filter every placement multiplies the space list and the solver + // degenerates into an exponential scan of overlapping duplicates. + $extents=array_column($kept,0); + $result=[]; + foreach($kept as $index=>[$e,$space]){ + if($space!==null){$result[]=$space;continue;} + if(self::isContained($extents,$index))continue; + $result[]=new Space(new Point($e[0],$e[1],$e[2]),new Dimensions(new Length($e[3]-$e[0]),new Length($e[4]-$e[1]),new Length($e[5]-$e[2]))); + } + if(count($result)>self::MAX_MAXIMAL_SPACES){ + $byVolume=StableSorter::sortBy($result,static function (Space $space): array { + return $space->dimensions->descendingVolumeKey(); + }); + $result=StableSorter::sortBy( + array_slice($byVolume,0,self::MAX_MAXIMAL_SPACES), + static function (Space $space): array { + return [$space->origin->z,$space->origin->y,$space->origin->x]; + }, + ); + } + return $result; + } + + /** + * Whether another extent contains `$extents[$index]`, for extents ordered by + * `(z1, y1, x1, -volume)`. + * + * A containing extent starts at or before `$extents[$index]` on every axis and has strictly + * larger volume when origins match, so it always appears at a position `< $index` with + * `$extent[2] <= $z1` already guaranteed. + * + * @param list $extents + */ + private static function isContained(array $extents,int $index):bool + { + [$x1,$y1,,$x2,$y2,$z2]=$extents[$index]; + for($other=0;$other<$index;++$other){ + $extent=$extents[$other]; + if($extent[3]>=$x2&&$extent[4]>=$y2&&$extent[5]>=$z2&&$extent[0]<=$x1&&$extent[1]<=$y1)return true; + } + return false; + } +} diff --git a/src-legacy/Algorithm/SpatialIndex.php b/src-legacy/Algorithm/SpatialIndex.php index 31165af..c0051bc 100644 --- a/src-legacy/Algorithm/SpatialIndex.php +++ b/src-legacy/Algorithm/SpatialIndex.php @@ -64,9 +64,10 @@ public function copy(): self return clone $this; } + /** Non-negative operands; `n + d - 1` would overflow for a coordinate near `PHP_INT_MAX`. */ private static function ceilDiv(int $numerator, int $denominator): int { - return intdiv($numerator + $denominator - 1, $denominator); + return intdiv($numerator, $denominator) + ($numerator % $denominator === 0 ? 0 : 1); } /** @return array{0:int,1:int,2:int,3:int,4:int,5:int} [ix1,ix2,iy1,iy2,iz1,iz2) */ diff --git a/src-legacy/Algorithm/SupportCalculator.php b/src-legacy/Algorithm/SupportCalculator.php index a310bf9..7d710f4 100644 --- a/src-legacy/Algorithm/SupportCalculator.php +++ b/src-legacy/Algorithm/SupportCalculator.php @@ -3,6 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Domain\{AxisAlignedBox,ItemInstance}; +use Packvium\Support\{ExactGeometry,ExactInteger}; final class SupportCalculator { /** Reported support fraction, from resting contact with other placements only. */ @@ -11,6 +12,6 @@ public static function ratio(ContainerState $state,ItemInstance $item,Candidate if($c->point->z===0)return 1.0; $box=new AxisAlignedBox($c->point,$c->envelopeDimensions); $support=LoadSupportGraph::candidateView($state->placements,$item,$box); - return $support->supportingArea/$c->envelopeDimensions->baseAreaTicks(); + return ExactInteger::ratio($support->supportingArea,ExactGeometry::baseArea($c->envelopeDimensions)); } } diff --git a/src-legacy/Artifacts/OperationalArtifact.php b/src-legacy/Artifacts/OperationalArtifact.php index 03def28..5c8b0f1 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.8.0'; + public const SUITE_VERSION = '1.9.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/Api.php b/src-legacy/Commerce/Api.php index 3f7dabc..2196c0f 100644 --- a/src-legacy/Commerce/Api.php +++ b/src-legacy/Commerce/Api.php @@ -126,6 +126,7 @@ public static function catalogVersionInfo(array $document, array $request): arra Shape::keys($request, 'request', ['catalog_id', 'resolved_at'], ['version', 'as_of']); $catalogId = Shape::text($request['catalog_id'], 'request.catalog_id'); $resolvedAt = Shape::integer($request['resolved_at'], 'request.resolved_at'); + if ($resolvedAt < 0) { Shape::fail('request.resolved_at', 'cannot be negative'); } $version = ($request['version'] ?? null) === null ? null : Shape::integer($request['version'], 'request.version'); $asOf = ($request['as_of'] ?? null) === null ? null : Shape::integer($request['as_of'], 'request.as_of'); if ($version !== null && $asOf !== null) { Shape::fail('request', "expected at most one of ['version', 'as_of']"); } diff --git a/src-legacy/Commerce/Document.php b/src-legacy/Commerce/Document.php index b5fbade..458c7e6 100644 --- a/src-legacy/Commerce/Document.php +++ b/src-legacy/Commerce/Document.php @@ -78,7 +78,7 @@ private static function loadTariffs($value): CarrierRegistry Shape::keys($fields, $path, ['carrier_id', 'service_id', 'versions']); $carrierId = Shape::text($fields['carrier_id'], "{$path}.carrier_id"); $serviceId = Shape::text($fields['service_id'], "{$path}.service_id"); - $key = $carrierId . "\0" . $serviceId; + $key = strlen($carrierId) . ':' . $carrierId . $serviceId; if (isset($seen[$key])) { Shape::fail($path, "duplicate tariff history for {$carrierId}/{$serviceId}"); } $seen[$key] = true; self::publishTariffVersions($registry, $carrierId, $serviceId, $fields['versions'], $path); diff --git a/src-legacy/Commerce/Policy/Predicate.php b/src-legacy/Commerce/Policy/Predicate.php index 554f6c7..5488a6e 100644 --- a/src-legacy/Commerce/Policy/Predicate.php +++ b/src-legacy/Commerce/Policy/Predicate.php @@ -72,7 +72,7 @@ public function matches(array $context): bool } /** - * Value equality over the JSON scalar types, matching the reference implementation's + * Structural equality over JSON values, matching the reference implementation's * semantics exactly -- including that a boolean equals the integer it stands for, * which is the one place a naive `===` would disagree and quietly change a decision. * @param mixed $left @@ -85,9 +85,25 @@ private static function equals($left, $right): bool return (is_int($left) || is_int($right)) && (int)$left === (int)$right; } if (is_array($left) && is_array($right)) { - if (count($left) !== count($right) || array_keys($left) !== array_keys($right)) { return false; } + $arrayIsListFunction = function (array $array): bool { + if (function_exists('array_is_list')) { + return array_is_list($array); + } + if ($array === []) { + return true; + } + $current_key = 0; + foreach ($array as $key => $noop) { + if ($key !== $current_key) { + return false; + } + ++$current_key; + } + return true; + }; + if (count($left) !== count($right) || $arrayIsListFunction($left) !== array_is_list($right)) { return false; } foreach ($left as $key => $entry) { - if (!self::equals($entry, $right[$key])) { return false; } + if (!array_key_exists($key, $right) || !self::equals($entry, $right[$key])) { return false; } } return true; } @@ -104,8 +120,25 @@ private static function contains($haystack, $needle): bool { if (is_string($haystack)) { return is_string($needle) && ($needle === '' || strpos($haystack, $needle) !== false); } if (!is_array($haystack)) { - throw new UnsupportedPredicateException('an in/not_in predicate needs a list or string value'); + throw new UnsupportedPredicateException('an in/not_in predicate needs a list, object or string value'); } + $arrayIsListFunction = function (array $array): bool { + if (function_exists('array_is_list')) { + return array_is_list($array); + } + if ($array === []) { + return true; + } + $current_key = 0; + foreach ($array as $key => $noop) { + if ($key !== $current_key) { + return false; + } + ++$current_key; + } + return true; + }; + if (!$arrayIsListFunction($haystack)) { return is_string($needle) && array_key_exists($needle, $haystack); } foreach ($haystack as $candidate) { if (self::equals($candidate, $needle)) { return true; } } diff --git a/src-legacy/Commerce/Rating/CarrierRegistry.php b/src-legacy/Commerce/Rating/CarrierRegistry.php index ca613cd..6a0e595 100644 --- a/src-legacy/Commerce/Rating/CarrierRegistry.php +++ b/src-legacy/Commerce/Rating/CarrierRegistry.php @@ -140,6 +140,6 @@ public static function rateTariff(Tariff $tariff, RatingRequest $request): RateB private static function key(string $carrierId, string $serviceId): string { - return $carrierId . "\0" . $serviceId; + return strlen($carrierId) . ':' . $carrierId . $serviceId; } } diff --git a/src-legacy/Constraint/AxleLoad.php b/src-legacy/Constraint/AxleLoad.php index 2002677..28dd62e 100644 --- a/src-legacy/Constraint/AxleLoad.php +++ b/src-legacy/Constraint/AxleLoad.php @@ -3,7 +3,7 @@ namespace Packvium\Constraint; use Packvium\Constraint\Internal\AxleTotals; use Packvium\Domain\Axle; -use Packvium\Support\BigInt; +use Packvium\Support\{BigInt,ExactGeometry}; /** * Two-axle weight distribution. @@ -90,7 +90,7 @@ public static function axleBalancedOrigins(array $axles, array $otherUnits, int } $otherDoubledX = BigInt::multiply((string)$tareWeightTicks, (string)$tareDoubledCenterX); foreach ($otherUnits as $unit) { - $doubledCenterX = (string)(2 * $unit->box->origin->x + $unit->box->dimensions->length->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($unit->box->origin->x, $unit->box->dimensions->length->ticks); $otherDoubledX = BigInt::add($otherDoubledX, BigInt::multiply((string)$unit->weightTicks, $doubledCenterX)); } $total = BigInt::add($otherTotal, (string)$itemWeightTicks); diff --git a/src-legacy/Constraint/ContactGraph.php b/src-legacy/Constraint/ContactGraph.php index 110e425..caaf463 100644 --- a/src-legacy/Constraint/ContactGraph.php +++ b/src-legacy/Constraint/ContactGraph.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Domain\AxisAlignedBox; +use Packvium\Support\ExactGeometry; final class ContactEdge { @@ -11,11 +12,12 @@ final class ContactEdge */ public $index; /** + * @var int|string * @readonly - * @var int */ public $area; - public function __construct(int $index, int $area) + /** @param int|string $area square ticks, exact past a native int */ + public function __construct(int $index, $area) { $this->index = $index; $this->area = $area; @@ -178,7 +180,7 @@ public function __construct(array $boxes, int $cellHint = 1) if ($otherIndex === $index) { continue; } - $matches[] = [$otherIndex, $other->overlapAreaXY($box)]; + $matches[] = [$otherIndex, ExactGeometry::overlapAreaXY($other, $box)]; } usort($matches, static function (array $a, array $b): int { return $a[0] <=> $b[0]; @@ -286,7 +288,7 @@ private function matches(array $buckets, array &$cache, int $plane, AxisAlignedB $level = ($cache[$plane] = $cache[$plane] ?? new ContactLevelIndex($this->cell, $buckets[$plane])); $matches = []; foreach ($level->near($box) as [$otherIndex, $other]) { - $area = $other->overlapAreaXY($box); + $area = ExactGeometry::overlapAreaXY($other, $box); if ($area > 0) { $matches[] = [$otherIndex, $area]; } diff --git a/src-legacy/Constraint/Internal/AxleTotals.php b/src-legacy/Constraint/Internal/AxleTotals.php index ec8eef3..8dc7549 100644 --- a/src-legacy/Constraint/Internal/AxleTotals.php +++ b/src-legacy/Constraint/Internal/AxleTotals.php @@ -3,7 +3,7 @@ namespace Packvium\Constraint\Internal; use Packvium\Constraint\LoadUnit; use Packvium\Domain\{AxisAlignedBox,Axle,Placement}; -use Packvium\Support\BigInt; +use Packvium\Support\{BigInt,ExactGeometry}; /** * The exact sums behind the two-axle check: gross weight and doubled @@ -29,7 +29,7 @@ public static function ofPlacements(array $placements, int $tareWeightTicks, int foreach ($placements as $placement) { $weight = (string)$placement->instance->weight()->ticks; $totalWeight = BigInt::add($totalWeight, $weight); - $doubledCenterX = (string)(2 * $placement->envelopeOrigin->x + $placement->envelopeDimensions->length->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($placement->envelopeOrigin->x, $placement->envelopeDimensions->length->ticks); $doubledWeightedX = BigInt::add($doubledWeightedX, BigInt::multiply($weight, $doubledCenterX)); } return [$totalWeight, $doubledWeightedX]; @@ -49,7 +49,7 @@ public static function ofUnits(array $units, int $tareWeightTicks, int $tareDoub } $doubledWeightedX = BigInt::multiply((string)$tareWeightTicks, (string)$tareDoubledCenterX); foreach ($units as $unit) { - $doubledCenterX = (string)(2 * $unit->box->origin->x + $unit->box->dimensions->length->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($unit->box->origin->x, $unit->box->dimensions->length->ticks); $doubledWeightedX = BigInt::add($doubledWeightedX, BigInt::multiply((string)$unit->weightTicks, $doubledCenterX)); } return [$totalWeight, $doubledWeightedX]; @@ -64,7 +64,7 @@ public static function ofUnits(array $units, int $tareWeightTicks, int $tareDoub public static function plus(array $totals, AxisAlignedBox $box, int $weightTicks): array { $weight = (string)$weightTicks; - $doubledCenterX = (string)(2 * $box->origin->x + $box->dimensions->length->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($box->origin->x, $box->dimensions->length->ticks); return [BigInt::add($totals[0], $weight), BigInt::add($totals[1], BigInt::multiply($weight, $doubledCenterX))]; } diff --git a/src-legacy/Constraint/Internal/DirectSupportView.php b/src-legacy/Constraint/Internal/DirectSupportView.php index 97ff3f4..a91a0ac 100644 --- a/src-legacy/Constraint/Internal/DirectSupportView.php +++ b/src-legacy/Constraint/Internal/DirectSupportView.php @@ -17,21 +17,22 @@ final class DirectSupportView */ public $supporterBoxes; /** - * @var list + * @var list * @readonly */ public $supporterAreas; /** * @readonly - * @var int + * @var int|string */ public $supportingArea; /** * @param list $supporterIndexes * @param list $supporterBoxes - * @param list $supporterAreas + * @param list $supporterAreas square ticks, exact past a native int + * @param int|string $supportingArea */ - public function __construct(array $supporterIndexes, array $supporterBoxes, array $supporterAreas, int $supportingArea) + public function __construct(array $supporterIndexes, array $supporterBoxes, array $supporterAreas, $supportingArea) { $this->supporterIndexes = $supporterIndexes; $this->supporterBoxes = $supporterBoxes; diff --git a/src-legacy/Constraint/Internal/LoadAnalysis.php b/src-legacy/Constraint/Internal/LoadAnalysis.php index 4fb6078..11233ac 100644 --- a/src-legacy/Constraint/Internal/LoadAnalysis.php +++ b/src-legacy/Constraint/Internal/LoadAnalysis.php @@ -4,7 +4,7 @@ use Packvium\Constraint\{ContactEdge,LoadCalculator,LoadUnit}; use Packvium\Domain\Compression; -use Packvium\Support\{Arithmetic,BigInt}; +use Packvium\Support\{BigInt,ExactGeometry,ExactInteger}; /** * Per-scene load analysis over an already constructed support graph. @@ -53,12 +53,12 @@ public function topLoads():array foreach($order as $upperIndex){ $supports=$graph->supporters($upperIndex); $totalArea=0; - foreach($supports as $edge)$totalArea+=$edge->area; + foreach($supports as $edge)$totalArea=ExactInteger::add($totalArea,$edge->area); if($totalArea===0)continue; $downward=$this->units[$upperIndex]->weightTicks+$loads[$upperIndex]; $assigned=0;$last=count($supports)-1; foreach($supports as $position=>$edge){ - $share=$position===$last?$downward-$assigned:Arithmetic::mulDiv($downward,$edge->area,$totalArea); + $share=$position===$last?$downward-$assigned:ExactInteger::mulDiv($downward,$edge->area,$totalArea); $assigned+=$share; $loads[$edge->index]+=$share; } @@ -96,7 +96,7 @@ public function crushed():?array $limit=$unit->maxCompressionPressureKpa; if($limit===null)continue; $box=$unit->box; - $footprint=($box->x2()-$box->origin->x)*($box->y2()-$box->origin->y); + $footprint=$unit->footprintTicks2??ExactInteger::mul($box->x2()-$box->origin->x,$box->y2()-$box->origin->y); if(Compression::exceeds(Compression::pressure($loads[$index],$footprint),$limit)) return ['crush_violation',$unit->label]; } @@ -206,7 +206,7 @@ public function stackDensityExceeded(?int $maxDensityTicks):?array foreach($this->units as $index=>$unit){ $total=$unit->weightTicks+$loads[$index]; $bearing=BigInt::multiply($total,LoadCalculator::SQUARE_METRE_TICKS); - $allowed=BigInt::multiply($maxDensityTicks,$unit->box->dimensions->baseAreaTicks()); + $allowed=BigInt::multiply($maxDensityTicks,ExactGeometry::baseArea($unit->box->dimensions)); if(BigInt::compare($bearing,$allowed)>0)return ['stack_density_exceeded',$unit->label]; } return null; diff --git a/src-legacy/Constraint/Internal/LoadSupportGraph.php b/src-legacy/Constraint/Internal/LoadSupportGraph.php index e04051e..57d5ef7 100644 --- a/src-legacy/Constraint/Internal/LoadSupportGraph.php +++ b/src-legacy/Constraint/Internal/LoadSupportGraph.php @@ -3,6 +3,7 @@ namespace Packvium\Constraint\Internal; use Packvium\Constraint\{ContactEdge,ContactGraph,LoadUnit}; use Packvium\Domain\{AxisAlignedBox,Item,ItemInstance,Placement}; +use Packvium\Support\{ExactGeometry,ExactInteger}; /** * Direct load support: ordinary face contact plus exact adjacent nesting contact. @@ -34,6 +35,10 @@ final class LoadSupportGraph private $descending; /** @var list|null */ private $priorDescending; + /** @var list|null */ + private static $cachedPlanePlacements; + /** @var array> */ + private static $cachedByTop=[]; /** @param list $units */ public function __construct(array $units, int $cellHint = 1) @@ -95,7 +100,7 @@ public function __construct(array $units, int $cellHint = 1) ]; if(!$sameColumn)$retained[]=$edge; } - $area=$units[$lowerIndex]->box->overlapAreaXY($units[$upperIndex]->box); + $area=ExactGeometry::overlapAreaXY($units[$lowerIndex]->box,$units[$upperIndex]->box); $insertAt=0;$retainedCount=count($retained); while($insertAt<$retainedCount&&$retained[$insertAt]->index<$lowerIndex)$insertAt++; array_splice($retained,$insertAt,0,[new ContactEdge($lowerIndex,$area)]); @@ -232,12 +237,40 @@ private static function sameNestingColumn(Placement $placement,ItemInstance $ite */ public static function candidateView(array $placements,ItemInstance $item,AxisAlignedBox $box):DirectSupportView { - $supporterEntries=[];$nearestLower=null; $nesting=$item->item->nestingHeight; + if($nesting===null){ + if(self::$cachedPlanePlacements!==$placements){ + $byTop=[]; + foreach($placements as $index=>$placement){ + $other=$placement->envelopeBox(); + $byTop[$other->z2()][]=[$index,$other,$other->origin->x,$other->origin->y,$other->x2(),$other->y2()]; + } + self::$cachedPlanePlacements=$placements; + self::$cachedByTop=$byTop; + } + $plane=self::$cachedByTop[$box->origin->z]??[]; + if($plane===[])return new DirectSupportView([],[],[],0); + $bx1=$box->origin->x;$by1=$box->origin->y;$bx2=$box->x2();$by2=$box->y2(); + $indexes=[];$boxes=[];$areas=[];$totalArea=0; + foreach($plane as [$index,$other,$ox1,$oy1,$ox2,$oy2]){ + $dx=($bx2<$ox2?$bx2:$ox2)-($bx1>$ox1?$bx1:$ox1); + if($dx<=0)continue; + $dy=($by2<$oy2?$by2:$oy2)-($by1>$oy1?$by1:$oy1); + if($dy<=0)continue; + // Native products and sums while they fit; past that the exact forms. + $area=$dx*$dy; + if(!is_int($area))$area=ExactInteger::mul($dx,$dy); + $sum=$totalArea+$area; + $totalArea=is_int($sum)?$sum:ExactInteger::add($totalArea,$area); + $indexes[]=$index;$boxes[]=$other;$areas[]=$area; + } + return new DirectSupportView($indexes,$boxes,$areas,$totalArea); + } + $supporterEntries=[];$nearestLower=null; foreach($placements as $index=>$placement){ $other=$placement->envelopeBox(); if($other->z2()===$box->origin->z){ - $area=$other->overlapAreaXY($box); + $area=ExactGeometry::overlapAreaXY($other,$box); if($area>0)$supporterEntries[]=['index'=>$index,'box'=>$other,'area'=>$area]; } $otherNesting=$placement->instance->item->nestingHeight; @@ -261,12 +294,12 @@ static function (array $entry) use ($placements, $item, $box): bool { while($supporterAt$predecessor['index'],'box'=>$predecessor['box'], - 'area'=>$predecessor['box']->overlapAreaXY($box), + 'area'=>ExactGeometry::overlapAreaXY($predecessor['box'],$box), ]]); } $indexes=[];$boxes=[];$areas=[];$totalArea=0; foreach($supporterEntries as $entry){ - $indexes[]=$entry['index'];$boxes[]=$entry['box'];$areas[]=$entry['area'];$totalArea+=$entry['area']; + $indexes[]=$entry['index'];$boxes[]=$entry['box'];$areas[]=$entry['area'];$totalArea=ExactInteger::add($totalArea,$entry['area']); } return new DirectSupportView($indexes,$boxes,$areas,$totalArea); } diff --git a/src-legacy/Constraint/LoadCalculator.php b/src-legacy/Constraint/LoadCalculator.php index 530198c..db6fd94 100644 --- a/src-legacy/Constraint/LoadCalculator.php +++ b/src-legacy/Constraint/LoadCalculator.php @@ -3,6 +3,7 @@ namespace Packvium\Constraint; use Packvium\Constraint\Internal\{LoadAnalysis,LoadSupportGraph}; use Packvium\Domain\Placement; +use Packvium\Support\ExactInteger; use Packvium\Unit\Length; final class LoadCalculator { @@ -23,6 +24,7 @@ public static function units(array $placements,?LoadUnit $extra=null):array $p->envelopeBox(),$p->instance->weight()->ticks,($nullsafeVariable1 = $item->maxTopLoad) ? $nullsafeVariable1->ticks : null,$item->maxStackedItems,$p->instance->id(), $nesting===null?null:$item->id,($nullsafeVariable2 = $nesting) ? $nullsafeVariable2->ticks : null, $item->compressionRatioPpm,$item->maxCompressionPressureKpa, + ExactInteger::mul($p->dimensions->length->ticks,$p->dimensions->width->ticks), ); } if($extra!==null)$units[]=$extra; diff --git a/src-legacy/Constraint/LoadUnit.php b/src-legacy/Constraint/LoadUnit.php index 6b593fa..c9267eb 100644 --- a/src-legacy/Constraint/LoadUnit.php +++ b/src-legacy/Constraint/LoadUnit.php @@ -50,7 +50,15 @@ final class LoadUnit * @var int|null */ public $maxCompressionPressureKpa; - public function __construct(AxisAlignedBox $box, int $weightTicks, ?int $maxTopLoadTicks, ?int $maxStackedItems, string $label, ?string $nestingItemId=null, ?int $nestingHeightTicks=null, ?int $compressionRatioPpm=null, ?int $maxCompressionPressureKpa=null) + /** + * @readonly + * @var int|string|null + */ + public $footprintTicks2 = null; + /** + * @param int|string|null $footprintTicks2 + */ + public function __construct(AxisAlignedBox $box, int $weightTicks, ?int $maxTopLoadTicks, ?int $maxStackedItems, string $label, ?string $nestingItemId=null, ?int $nestingHeightTicks=null, ?int $compressionRatioPpm=null, ?int $maxCompressionPressureKpa=null, $footprintTicks2=null) { $this->box = $box; $this->weightTicks = $weightTicks; @@ -64,5 +72,8 @@ public function __construct(AxisAlignedBox $box, int $weightTicks, ?int $maxTopL // needs, so the crush check rides the graph that is built anyway. $this->compressionRatioPpm = $compressionRatioPpm; $this->maxCompressionPressureKpa = $maxCompressionPressureKpa; + // The item's own footprint, which the load presses on; `box` is its envelope, grown by + // the clearance, and it carries the support graph. A decimal string past `int`. + $this->footprintTicks2 = $footprintTicks2; } } diff --git a/src-legacy/Constraint/SupportConstraint.php b/src-legacy/Constraint/SupportConstraint.php index 8e48f7d..a6bdcb2 100644 --- a/src-legacy/Constraint/SupportConstraint.php +++ b/src-legacy/Constraint/SupportConstraint.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Constraint\Internal\LoadSupportGraph; +use Packvium\Support\{ExactGeometry,ExactInteger}; /** * Support ratios arrive as floats from the public API but must never decide feasibility * in floating point. The ratio is converted once to a scaled integer and the comparison @@ -59,13 +60,13 @@ public function evaluate(ConstraintContext $c):ConstraintResult $required=max($this->globalMinimum,$c->item->item->minimumSupportRatio); if($required<=0)return ConstraintResult::allow(); $area=$support->supportingArea; - $baseArea=$c->envelopeDimensions->baseAreaTicks(); - if($areaenvelopeDimensions); + if(ExactInteger::compare($area,self::exactRequiredArea($baseArea,self::scaled($required)))<0) + return ConstraintResult::reject('insufficient_support',sprintf('%s/%s < %.6f',$area,$baseArea,$required)); // Over half of a rectangle cannot lie strictly to one side of a line through its // centre (central symmetry), so any support covering >50% of the base already // encloses the centroid and needs no hull check. - if($area*2>$baseArea)return ConstraintResult::allow(); + if(ExactInteger::compare(ExactInteger::mul($area,2),$baseArea)>0)return ConstraintResult::allow(); // Area alone is not stability: a candidate can clear the ratio // while overhanging its own centre of gravity, which the ratio check above // cannot see. Checked only once a minimum ratio is already being enforced, @@ -73,7 +74,7 @@ public function evaluate(ConstraintContext $c):ConstraintResult // code and no behaviour change. $hull=SupportPolygon::convexHull(SupportPolygon::contactHullPoints($box,$supporters)); if(!SupportPolygon::pointInHull(SupportPolygon::doubledCentroid($box),$hull)) - return ConstraintResult::reject('centre_of_gravity_unsupported',sprintf('%d/%d met but centroid outside the %d-point support hull',$area,$baseArea,count($hull))); + return ConstraintResult::reject('centre_of_gravity_unsupported',sprintf('%s/%s met but centroid outside the %d-point support hull',$area,$baseArea,count($hull))); return ConstraintResult::allow(); } @@ -110,4 +111,12 @@ public static function requiredArea(int $baseArea,int $scaled):int { return intdiv($baseArea,self::SCALE)*$scaled+intdiv(($baseArea%self::SCALE)*$scaled,self::SCALE); } + + /** `requiredArea` for a base area past a native int too. + * @param int|string $baseArea + * @return int|string */ + private static function exactRequiredArea($baseArea,int $scaled) + { + return is_int($baseArea)?self::requiredArea($baseArea,$scaled):ExactInteger::floorDiv(ExactInteger::mul($baseArea,$scaled),self::SCALE); + } } diff --git a/src-legacy/Constraint/SupportPolygon.php b/src-legacy/Constraint/SupportPolygon.php index 71d8f1d..3a856ef 100644 --- a/src-legacy/Constraint/SupportPolygon.php +++ b/src-legacy/Constraint/SupportPolygon.php @@ -2,25 +2,33 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Domain\AxisAlignedBox; +use Packvium\Support\ExactInteger as Exact; final class Point2D { /** * @readonly - * @var int + * @var int|string */ public $x; /** * @readonly - * @var int + * @var int|string */ public $y; - public function __construct(int $x, int $y) + /** Doubled ticks: native ints while they fit, exact decimal strings beyond. + * @param int|string $x + * @param int|string $y */ + public function __construct($x, $y) { $this->x = $x; $this->y = $y; } public function equals(Point2D $other): bool { return $this->x === $other->x && $this->y === $other->y; } + public function compare(Point2D $other): int + { + return Exact::compare($this->x, $other->x) ?: Exact::compare($this->y, $other->y); + } } /** @@ -28,13 +36,18 @@ public function equals(Point2D $other): bool { return $this->x === $other->x && * * Overlap area is not the same as stability: an item can be supported over enough * area and still overhang its own centre of gravity. Every function here is exact - * integer arithmetic, no trig or division. + * integer arithmetic, no trig or division, and stays exact past a native int: two doubled + * coordinates near `PHP_INT_MAX` ticks multiply to what Python and Rust's `i128` still hold. */ final class SupportPolygon { - private static function cross(Point2D $o, Point2D $a, Point2D $b): int + /** The sign of the cross product (a - o) x (b - o). */ + private static function turn(Point2D $o, Point2D $a, Point2D $b): int { - return ($a->x - $o->x) * ($b->y - $o->y) - ($a->y - $o->y) * ($b->x - $o->x); + return Exact::compare( + Exact::mul(Exact::sub($a->x, $o->x), Exact::sub($b->y, $o->y)), + Exact::mul(Exact::sub($a->y, $o->y), Exact::sub($b->x, $o->x)), + ); } /** @@ -51,20 +64,20 @@ public static function convexHull(array $points): array foreach ($points as $p) { $unique["{$p->x},{$p->y}"] = $p; } $pts = array_values($unique); usort($pts, static function (Point2D $a, Point2D $b): int { - return [$a->x, $a->y] <=> [$b->x, $b->y]; + return $a->compare($b); }); if (count($pts) <= 2) { return $pts; } $lower = []; foreach ($pts as $p) { - while (count($lower) >= 2 && self::cross($lower[count($lower) - 2], $lower[count($lower) - 1], $p) <= 0) { + while (count($lower) >= 2 && self::turn($lower[count($lower) - 2], $lower[count($lower) - 1], $p) <= 0) { array_pop($lower); } $lower[] = $p; } $upper = []; foreach (array_reverse($pts) as $p) { - while (count($upper) >= 2 && self::cross($upper[count($upper) - 2], $upper[count($upper) - 1], $p) <= 0) { + while (count($upper) >= 2 && self::turn($upper[count($upper) - 2], $upper[count($upper) - 1], $p) <= 0) { array_pop($upper); } $upper[] = $p; @@ -76,9 +89,19 @@ public static function convexHull(array $points): array private static function onSegment(Point2D $p, Point2D $a, Point2D $b): bool { - if (self::cross($a, $b, $p) !== 0) { return false; } - return min($a->x, $b->x) <= $p->x && $p->x <= max($a->x, $b->x) - && min($a->y, $b->y) <= $p->y && $p->y <= max($a->y, $b->y); + if (self::turn($a, $b, $p) !== 0) { return false; } + return self::between($p->x, $a->x, $b->x) && self::between($p->y, $a->y, $b->y); + } + + /** + * @param int|string $value + * @param int|string $end + * @param int|string $other + */ + private static function between($value, $end, $other): bool + { + [$low, $high] = Exact::compare($end, $other) <= 0 ? [$end, $other] : [$other, $end]; + return Exact::compare($low, $value) <= 0 && Exact::compare($value, $high) <= 0; } /** Whether `$point` lies inside or on the boundary of a hull from `convexHull`. @param list $hull */ @@ -89,7 +112,7 @@ public static function pointInHull(Point2D $point, array $hull): bool if ($n === 1) { return $point->equals($hull[0]); } if ($n === 2) { return self::onSegment($point, $hull[0], $hull[1]); } for ($i = 0; $i < $n; $i++) { - if (self::cross($hull[$i], $hull[($i + 1) % $n], $point) < 0) { return false; } + if (self::turn($hull[$i], $hull[($i + 1) % $n], $point) < 0) { return false; } } return true; } @@ -113,7 +136,7 @@ public static function contactHullPoints(AxisAlignedBox $candidate, array $suppo $ox2 = min($cx2, $box->x2()); $oy2 = min($cy2, $box->y2()); if ($ox2 > $ox1 && $oy2 > $oy1) { foreach ([$ox1, $ox2] as $x) { - foreach ([$oy1, $oy2] as $y) { $points[] = new Point2D(2 * $x, 2 * $y); } + foreach ([$oy1, $oy2] as $y) { $points[] = new Point2D(Exact::mul(2, $x), Exact::mul(2, $y)); } } } } @@ -123,6 +146,6 @@ public static function contactHullPoints(AxisAlignedBox $candidate, array $suppo /** Twice the box's own footprint centroid, exact for odd as well as even extents. */ public static function doubledCentroid(AxisAlignedBox $box): Point2D { - return new Point2D($box->origin->x + $box->x2(), $box->origin->y + $box->y2()); + return new Point2D(Exact::add($box->origin->x, $box->x2()), Exact::add($box->origin->y, $box->y2())); } } diff --git a/src-legacy/Constraint/TopLoadConstraint.php b/src-legacy/Constraint/TopLoadConstraint.php index 4e9deab..7493d9a 100644 --- a/src-legacy/Constraint/TopLoadConstraint.php +++ b/src-legacy/Constraint/TopLoadConstraint.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Constraint\Internal\{LoadAnalysis,PlacedSupportBase}; +use Packvium\Support\ExactInteger; /** * Rejects a placement that would rest on something unable to carry it. * @@ -26,6 +27,7 @@ public function evaluate(ConstraintContext $c):ConstraintResult $c->envelopeBox(),$c->item->weight()->ticks,($nullsafeVariable1 = $item->maxTopLoad) ? $nullsafeVariable1->ticks : null,$item->maxStackedItems,$c->item->id(), $item->nestingHeight===null?null:$item->id,($nullsafeVariable2 = $item->nestingHeight) ? $nullsafeVariable2->ticks : null, $item->compressionRatioPpm,$item->maxCompressionPressureKpa, + ExactInteger::mul($c->dimensions->length->ticks,$c->dimensions->width->ticks), ); [$units,$graph]=($this->support = $this->support ?? new PlacedSupportBase())->withCandidate($c->placements,$unit); $nonStackable=$graph->nonStackableFailure($c->placements,$c->item,count($units)-1); diff --git a/src-legacy/Domain/CentreOfMass.php b/src-legacy/Domain/CentreOfMass.php index 6df7dca..af2df31 100644 --- a/src-legacy/Domain/CentreOfMass.php +++ b/src-legacy/Domain/CentreOfMass.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; use Packvium\Support\BigInt; +use Packvium\Support\ExactGeometry; /** * How far the weighted centre of mass sits from the container's own centre. @@ -41,8 +42,8 @@ public static function offsetPpm(Dimensions $inner, array $placements): int $doubledWeightedY = '0'; foreach ($placements as $p) { $weight = (string)$p->instance->weight()->ticks; - $doubledCenterX = (string)(2 * $p->position->x + $p->dimensions->length->ticks); - $doubledCenterY = (string)(2 * $p->position->y + $p->dimensions->width->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($p->position->x, $p->dimensions->length->ticks); + $doubledCenterY = ExactGeometry::doubledCentre($p->position->y, $p->dimensions->width->ticks); $doubledWeightedX = BigInt::add($doubledWeightedX, BigInt::multiply($weight, $doubledCenterX)); $doubledWeightedY = BigInt::add($doubledWeightedY, BigInt::multiply($weight, $doubledCenterY)); } diff --git a/src-legacy/Domain/Compression.php b/src-legacy/Domain/Compression.php index ad69314..bee47ec 100644 --- a/src-legacy/Domain/Compression.php +++ b/src-legacy/Domain/Compression.php @@ -38,10 +38,11 @@ final class Compression * the uncompressed one, which compression never changes. * * @return array{string,string} numerator and denominator, both non-negative + * @param int|string $footprintAreaTicks */ - public static function pressure(int $topLoadTicks, int $footprintAreaTicks): array + public static function pressure(int $topLoadTicks, $footprintAreaTicks): array { - if ($footprintAreaTicks <= 0) { + if (\Packvium\Support\ExactInteger::sign($footprintAreaTicks) <= 0) { throw new InvalidArgumentException('footprint area must be positive'); } $metre = Length::TICKS_PER_MM * 1000; diff --git a/src-legacy/Domain/Container.php b/src-legacy/Domain/Container.php index 59bd207..da9cef4 100644 --- a/src-legacy/Domain/Container.php +++ b/src-legacy/Domain/Container.php @@ -158,7 +158,7 @@ public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $ 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=array_values(array_filter(SweptRegion::ALL_DIRECTIONS,static function (string $d) use ($accessDirections): bool { + $this->accessDirections=$accessDirections===[]?[]:array_values(array_filter(SweptRegion::ALL_DIRECTIONS,static function (string $d) use ($accessDirections): bool { return in_array($d,$accessDirections,true); }));} /** The same container holding `$placements` before search. @param list $placements */ diff --git a/src-legacy/Domain/LatticeSummary.php b/src-legacy/Domain/LatticeSummary.php index 81d0eb5..0422298 100644 --- a/src-legacy/Domain/LatticeSummary.php +++ b/src-legacy/Domain/LatticeSummary.php @@ -4,6 +4,7 @@ use InvalidArgumentException; use Packvium\Support\BigInt; +use Packvium\Support\ExactInteger; /** * Compact, O(1)-to-build description of one GridSolver regular-lattice run. @@ -105,9 +106,12 @@ public function __construct( if ($nx <= 0 || $ny <= 0) { throw new InvalidArgumentException('a lattice summary requires positive per-axis capacity'); } } - private function perLayer(): int { return $this->nx * $this->ny; } - public function fullLayers(): int { return intdiv($this->count, $this->perLayer()); } - public function remainder(): int { return $this->count % $this->perLayer(); } + /** Exact past a native int: a tiny item in a vast container has more slots per layer than an int holds. + * @return int|string */ + private function perLayer() { return ExactInteger::mul($this->nx, $this->ny); } + /** An int: `count` is one, and the quotient is no larger. */ + public function fullLayers(): int { return (int)ExactInteger::floorDiv($this->count, $this->perLayer()); } + public function remainder(): int { return (int)ExactInteger::mod($this->count, $this->perLayer()); } public function layersUsed(): int { return $this->fullLayers() + ($this->remainder() > 0 ? 1 : 0); } /** Plain `int`, matching `Weight::$ticks` and the existing per-placement summation this replaces. */ @@ -131,7 +135,21 @@ public function maxZTicks(): int return $topLayerIndex * $this->layerStep + $this->envelope->height->ticks; } - private function triangular(int $n): int { return intdiv($n * ($n - 1), 2); } + /** + * @return int|string + */ + private function triangular(int $n) { return ExactInteger::floorDiv(ExactInteger::mul($n, $n - 1), 2); } + + /** `2 * pitch * indexSum + count * (2 * clearance + side)`: the lattice's doubled centres summed along one axis. + * @param int|string $indexSum + * @return int|string */ + private function doubledCentreSum(int $pitch, $indexSum, int $clearance, int $side) + { + return ExactInteger::add( + ExactInteger::mul(ExactInteger::mul(2, $pitch), $indexSum), + ExactInteger::mul($this->count, 2 * $clearance + $side), + ); + } /** * Closed-form equivalent of CentreOfMass::offsetPpm for a uniform lattice of @@ -153,13 +171,23 @@ public function centreOfMassOffsetPpm(int $innerLengthTicks, int $innerWidthTick $rowsInPartial = intdiv($remainder, $nx); $extraCols = $remainder % $nx; - $sumX = $fullLayers * $ny * $this->triangular($nx) + $rowsInPartial * $this->triangular($nx) + $this->triangular($extraCols); - $sumY = $fullLayers * $nx * $this->triangular($ny) + $nx * $this->triangular($rowsInPartial) + $extraCols * $rowsInPartial; + // Exact throughout: a lattice index sum times a doubled pitch passes a native int + // long before the container does. + $sumX = ExactInteger::sum([ + ExactInteger::mul(ExactInteger::mul($fullLayers, $ny), $this->triangular($nx)), + ExactInteger::mul($rowsInPartial, $this->triangular($nx)), + $this->triangular($extraCols), + ]); + $sumY = ExactInteger::sum([ + ExactInteger::mul(ExactInteger::mul($fullLayers, $nx), $this->triangular($ny)), + ExactInteger::mul($nx, $this->triangular($rowsInPartial)), + ExactInteger::mul($extraCols, $rowsInPartial), + ]); $clearance = $this->clearanceTicks; $weight = (string)$this->weightTicks; - $doubledWeightedX = BigInt::multiply($weight, (string)(2 * $this->envelope->length->ticks * $sumX + $this->count * (2 * $clearance + $this->physical->length->ticks))); - $doubledWeightedY = BigInt::multiply($weight, (string)(2 * $this->envelope->width->ticks * $sumY + $this->count * (2 * $clearance + $this->physical->width->ticks))); + $doubledWeightedX = BigInt::multiply($weight, (string)$this->doubledCentreSum($this->envelope->length->ticks, $sumX, $clearance, $this->physical->length->ticks)); + $doubledWeightedY = BigInt::multiply($weight, (string)$this->doubledCentreSum($this->envelope->width->ticks, $sumY, $clearance, $this->physical->width->ticks)); $totalWeight = (string)$this->totalWeightTicks(); $offsetXPpm = $this->axisOffsetPpm($doubledWeightedX, $totalWeight, (string)$innerLengthTicks); @@ -188,7 +216,7 @@ public function expand(array $items): array $nx = $this->nx; $ny = $this->ny; $layerStep = $this->layerStep; $clearance = $this->clearanceTicks; $out = []; for ($index = 0; $index < $this->count; $index++) { - $x = $index % $nx; $y = intdiv($index, $nx) % $ny; $z = intdiv($index, $nx * $ny); + $x = $index % $nx; $y = intdiv($index, $nx) % $ny; $z = (int)ExactInteger::floorDiv($index, $this->perLayer()); $point = new Point($x * $this->envelope->length->ticks, $y * $this->envelope->width->ticks, $z * $layerStep); $position = new Point($point->x + $clearance, $point->y + $clearance, $point->z + $clearance); $out[] = new Placement($items[$index], $position, $this->rotation, $this->physical, $point, $this->envelope, 1.0); diff --git a/src-legacy/Domain/Nesting.php b/src-legacy/Domain/Nesting.php index 364f086..cfecf17 100644 --- a/src-legacy/Domain/Nesting.php +++ b/src-legacy/Domain/Nesting.php @@ -1,7 +1,7 @@ z2() - $high->origin->z === $nesting->ticks; } + /** + * The physical space a valid nesting pair shares, as a decimal string. + * + * The pair sinks by `nestingHeight` envelope to envelope, so under a clearance the items + * themselves overlap by twice the clearance less, over their own footprint rather than + * the envelope's. Equal to `nestingHeight x base area` with no clearance. O(1). + */ + private static function nestedOverlap(Placement $lower, Placement $upper): string + { + $a = $lower->box(); $b = $upper->box(); + $height = min($a->z2(), $b->z2()) - max($a->origin->z, $b->origin->z); + return $height > 0 ? BigInt::multiply((string)ExactGeometry::overlapAreaXY($a, $b), (string)$height) : '0'; + } + /** * Total double-counted volume between adjacent nested layers, as a decimal * string -- nesting depth times base area can overflow a 64-bit int for a @@ -60,8 +74,7 @@ private static function overlapVolume(array $placements): string for ($i = 0; $i < count($group) - 1; $i++) { $lower = $group[$i]; $upper = $group[$i + 1]; if (self::isValidNesting($lower, $upper)) { - $slice = BigInt::multiply((string)$lower->instance->item->nestingHeight->ticks, (string)$lower->envelopeDimensions->baseAreaTicks()); - $overlap = BigInt::add($overlap, $slice); + $overlap = BigInt::add($overlap, self::nestedOverlap($lower, $upper)); } } } @@ -86,7 +99,7 @@ public static function occupiedVolume(Placement $placement): string } if ($item->maxCompressionPressureKpa === null) { return $placement->dimensions->volumeString(); } $dimensions = $placement->dimensions; - $footprint = $dimensions->baseAreaTicks(); + $footprint = ExactGeometry::baseArea($dimensions); $pressure = Compression::pressure($placement->topLoad->ticks, $footprint); // A crushed item has no meaningful occupied volume, and the arrangement is already // invalid -- the crush check refuses it and the validator reports it. Reporting the @@ -148,8 +161,7 @@ public static function usedVolumeDelta(array $placements, Placement $placement): $overlap = '0'; foreach ($placements as $existing) { if (!self::isValidNesting($existing, $placement)) { continue; } - $slice = BigInt::multiply((string)$nesting->ticks, (string)$placement->envelopeDimensions->baseAreaTicks()); - $overlap = BigInt::add($overlap, $slice); + $overlap = BigInt::add($overlap, self::nestedOverlap($existing, $placement)); } return BigInt::subtract($placement->dimensions->volumeString(), $overlap); } diff --git a/src-legacy/Domain/PackedContainer.php b/src-legacy/Domain/PackedContainer.php index 4637070..2e06ef9 100644 --- a/src-legacy/Domain/PackedContainer.php +++ b/src-legacy/Domain/PackedContainer.php @@ -1,6 +1,7 @@ latticeSummary !== null ? $this->latticeSummary->usedVolumeString() : Nesting::usedVolume($this->placements); } - public function utilization():float{return (float)$this->usedVolumeString()/$this->container->innerDimensions->volumeScore();} + /** Python's `used / inner` exactly rounded: two doubles divided would round twice, and a volume in cubic ticks passes 2^53 at a few centimetres. */ + public function utilization():float{return ExactInteger::ratio($this->usedVolumeString(),$this->container->innerDimensions->volumeString());} public function maxZTicks(): int { diff --git a/src-legacy/Extension/CandidateScorer.php b/src-legacy/Extension/CandidateScorer.php index 018c3e2..5db559c 100644 --- a/src-legacy/Extension/CandidateScorer.php +++ b/src-legacy/Extension/CandidateScorer.php @@ -4,9 +4,10 @@ use Packvium\Algorithm\ContainerState; use Packvium\Domain\{Dimensions,Point}; /** - * Ranks feasible placements. Lower sorts first. + * Ranks feasible placements. Lower sorts first, by PHP array comparison: a component may be + * an exact chunk key (see `ExactInteger::sortKey`) where an int would overflow. * * Receives the origin and envelope rather than a Candidate so the finder does not have * to build a throwaway object for every point/rotation pair it scores. */ -interface CandidateScorer{/** @return list */public function score(ContainerState $state,Point $point,Dimensions $envelope):array;} +interface CandidateScorer{/** @return list> */public function score(ContainerState $state,Point $point,Dimensions $envelope):array;} diff --git a/src-legacy/Extension/DefaultCandidateScorer.php b/src-legacy/Extension/DefaultCandidateScorer.php index 061e5f8..eaf7644 100644 --- a/src-legacy/Extension/DefaultCandidateScorer.php +++ b/src-legacy/Extension/DefaultCandidateScorer.php @@ -1,9 +1,9 @@ length->ticks-($point->x+$envelope->length->ticks); $ry=$inner->width->ticks-($point->y+$envelope->width->ticks); $rz=$inner->height->ticks-($point->z+$envelope->height->ticks); - return [$point->z,$newHeight,$rx*$ry+$rz,$point->y,$point->x]; + return [$point->z,$newHeight,CandidateFinder::roomLeftKey($rx,$ry,$rz),$point->y,$point->x]; } } diff --git a/src-legacy/Objective/ObjectiveRegistry.php b/src-legacy/Objective/ObjectiveRegistry.php index 9fa4d8f..556617a 100644 --- a/src-legacy/Objective/ObjectiveRegistry.php +++ b/src-legacy/Objective/ObjectiveRegistry.php @@ -26,10 +26,16 @@ public static function resolve(string $name, ?PackingConfig $config = null): Sol 'lowest_cost' => static function (?PackingConfig $config) { return new LowestCostSolutionScorer(); }, - 'shipping_cost' => \Closure::fromCallable([ShippingCostSolutionScorer::class, 'fromConfig']), + // Arrow functions rather than first-class callables, which load their class at once: + // without opcache every request compiles what it loads (1.9.0 release frontier). + 'shipping_cost' => static function (?PackingConfig $config) { + return ShippingCostSolutionScorer::fromConfig($config); + }, // Inherits the divisor requirement: landed cost is priced off billed // weight, so it needs the same dimensional-weight inputs. - 'lowest_landed_cost' => \Closure::fromCallable([LandedCostSolutionScorer::class, 'fromConfig']), + 'lowest_landed_cost' => static function (?PackingConfig $config) { + return LandedCostSolutionScorer::fromConfig($config); + }, 'open_dimension_height' => static function (?PackingConfig $config) { return new OpenDimensionSolutionScorer(); }, diff --git a/src-legacy/Packer.php b/src-legacy/Packer.php index f1776d5..b302740 100644 --- a/src-legacy/Packer.php +++ b/src-legacy/Packer.php @@ -3,7 +3,7 @@ namespace Packvium; -use Packvium\Algorithm\{Deadline, FixedPlacementAdmission, ObjectiveBoundScope, ObjectiveBounds, SolverOrchestrator}; +use Packvium\Algorithm\{Deadline, FixedLoad, FixedPlacementAdmission, ObjectiveBoundScope, ObjectiveBounds, SolverOrchestrator}; use Packvium\Support\{RequestObjects, StableSorter, UnsupportedPlacements}; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, UnratedWeightException}; @@ -143,7 +143,9 @@ private function solve(array $items, array $containers, array $fixedPlacements): } } } - $fixed = FixedPlacementAdmission::admit( + // Without fixed placements every instance is free; answered here so a request that + // fixes nothing never compiles the admission it does not use. + $fixed = $request->fixedPlacements === [] ? new FixedLoad([], $request->instances()) : FixedPlacementAdmission::admit( $request, $this->config->minimumSupportRatio, $this->config->clearance, @@ -262,7 +264,8 @@ static function ($result): bool { // refused -- the same refusal the other three engines give, in the same words. The // refusal is deliberately here and not in the scorer: throwing while *comparing* // candidates would abort runs that have a perfectly shippable answer. - $unpriceable = LandedCostSolutionScorer::unpriceableContainer($best->containers, $this->config); + $landed = $this->config->objective === 'lowest_landed_cost'; + $unpriceable = $landed ? LandedCostSolutionScorer::unpriceableContainer($best->containers, $this->config) : null; if ($unpriceable !== null) { [$containerId, $grams, $bound] = $unpriceable; throw new UnratedWeightException( @@ -277,8 +280,9 @@ static function ($result): bool { $alternatives = array_slice( array_values(array_filter( array_slice($selected, 1), - function (PackingResult $result): bool { - return LandedCostSolutionScorer::unpriceableContainer($result->containers, $this->config) === null; + function (PackingResult $result) use ($landed): bool { + return !$landed + || LandedCostSolutionScorer::unpriceableContainer($result->containers, $this->config) === null; }, )), 0, diff --git a/src-legacy/Sequence/LoadingDependencyGraph.php b/src-legacy/Sequence/LoadingDependencyGraph.php index 4fa4824..bc7b108 100644 --- a/src-legacy/Sequence/LoadingDependencyGraph.php +++ b/src-legacy/Sequence/LoadingDependencyGraph.php @@ -218,39 +218,82 @@ public static function verifyLoadingPrefixBusinessRules(array $placements, array if ($sortedOrder !== $expected) { throw new SequenceReplayError(-1, -1, 'order is not a permutation of every placement index exactly once'); } + if ($placements === []) { + return; + } $maxDensityTicks = ($nullsafeVariable1 = $container->maxStackDensity) ? $nullsafeVariable1->ticks : null; // A caller may hand this any scene, validated or not, so the stacking-group rule is // re-checked here too -- only when some item declares a list, and only on the edges // of the step's own new placement, since every earlier edge was judged at its step. $grouped = false; + $hasNonStackable = false; + $hasLoadLimits = false; + $hasGroundRules = false; foreach ($placements as $placement) { - $grouped = $grouped || $placement->instance->item->acceptsStackingGroups !== []; + $item = $placement->instance->item; + $grouped = $grouped || $item->acceptsStackingGroups !== []; + $hasNonStackable = $hasNonStackable || !$item->stackable; + $hasLoadLimits = $hasLoadLimits || $item->maxTopLoad !== null || $item->maxStackedItems !== null; + $hasGroundRules = $hasGroundRules || ( + $item->groundContactRule !== null + && $item->groundContactRule !== 'free' + && $placement->envelopeBox()->origin->z !== 0 + ); + } + $hasLoadRules = $maxDensityTicks !== null || $grouped || $hasNonStackable || $hasLoadLimits; + if (!$hasLoadRules && !$hasGroundRules) { + return; } + $allUnits = LoadCalculator::units($placements); $present = []; + $units = []; + $elevatedBases = []; + $anyNesting = false; foreach ($order as $step => $index) { - $present[] = $placements[$index]; - $units = LoadCalculator::units($present); - $analysis = new \Packvium\Constraint\Internal\LoadAnalysis($units); - $problem = $analysis->overloaded() - ?? $analysis->stackLimitExceeded() - ?? $analysis->stackDensityExceeded($maxDensityTicks); - if ($problem === null) { - $counts = $analysis->stackedCounts(); - foreach ($units as $unitIndex => $unit) { - if (!$present[$unitIndex]->instance->item->stackable && $counts[$unitIndex] > 0) { - $problem = ['non_stackable_item_has_load', $unit->label]; - break; + $candidate = $placements[$index]; + $unit = $allUnits[$index]; + $present[] = $candidate; + $units[] = $unit; + $candidateBox = $candidate->envelopeBox(); + if ($candidateBox->origin->z !== 0) { + $elevatedBases[$candidateBox->origin->z] = true; + } + if ($unit->nestingItemId !== null) { + $anyNesting = true; + } + $problem = null; + $isolatedFloorStep = $candidateBox->origin->z === 0 + && !$anyNesting + && !isset($elevatedBases[$candidateBox->z2()]); + if ($isolatedFloorStep) { + if ($maxDensityTicks !== null) { + $bearing = \Packvium\Support\BigInt::multiply($unit->weightTicks, LoadCalculator::SQUARE_METRE_TICKS); + $allowed = \Packvium\Support\BigInt::multiply($maxDensityTicks, \Packvium\Support\ExactGeometry::baseArea($candidateBox->dimensions)); + if (\Packvium\Support\BigInt::compare($bearing, $allowed) > 0) { + $problem = ['stack_density_exceeded', $unit->label]; } } + } elseif ($hasLoadRules) { + $analysis = new \Packvium\Constraint\Internal\LoadAnalysis($units); + $problem = $analysis->overloaded() + ?? $analysis->stackLimitExceeded() + ?? $analysis->stackDensityExceeded($maxDensityTicks); + if ($problem === null && $hasNonStackable) { + $counts = $analysis->stackedCounts(); + foreach ($units as $unitIndex => $u) { + if (!$present[$unitIndex]->instance->item->stackable && $counts[$unitIndex] > 0) { + $problem = ['non_stackable_item_has_load', $u->label]; + break; + } + } + } + if ($problem === null && $grouped) { + $last = count($present) - 1; + $problem = $analysis->graph()->nonStackableFailure($present, $candidate->instance, $last); + } } - if ($problem === null && $grouped) { - $last = count($present) - 1; - $problem = $analysis->graph()->nonStackableFailure($present, $present[$last]->instance, $last); - } - if ($problem === null) { - $candidate = $present[count($present) - 1]; + if ($problem === null && $hasGroundRules) { $rule = $candidate->instance->item->groundContactRule; - $candidateBox = $candidate->envelopeBox(); if ($rule !== null && $rule !== 'free' && $candidateBox->origin->z !== 0) { $support = LoadSupportGraph::candidateView( array_slice($present, 0, -1), $candidate->instance, $candidateBox, diff --git a/src-legacy/Serialization/ArrayCodec.php b/src-legacy/Serialization/ArrayCodec.php index 26ec3f8..54fc733 100644 --- a/src-legacy/Serialization/ArrayCodec.php +++ b/src-legacy/Serialization/ArrayCodec.php @@ -223,7 +223,8 @@ private static function model(array $data):array // Rules compile into this engine's own constraint pipeline rather than post-filtering // a chosen answer: an illegal candidate is rejected during search, so the packing // that wins was never allowed to be illegal in the first place. - $extensions=new ExtensionRegistry(PolicyRuleSet::fromArray($data['policy']??null)->constraints()); + // No policy is no policy constraint, without compiling `PolicyRuleSet` to say so. + $extensions=new ExtensionRegistry(($data['policy']??null)===null?[]:PolicyRuleSet::fromArray($data['policy'])->constraints()); $items=array_map(function ($r) use ($unit) { return self::item($r,$unit); },$data['items']); diff --git a/src-legacy/Support/ExactGeometry.php b/src-legacy/Support/ExactGeometry.php new file mode 100644 index 0000000..1b966f4 --- /dev/null +++ b/src-legacy/Support/ExactGeometry.php @@ -0,0 +1,44 @@ +length->ticks * $dimensions->width->ticks; + return is_int($area) ? $area : ExactInteger::mul($dimensions->length->ticks, $dimensions->width->ticks); + } + + /** + * @return int|string + */ + public static function overlapAreaXY(AxisAlignedBox $a, AxisAlignedBox $b) + { + $x = max(0, min($a->x2(), $b->x2()) - max($a->origin->x, $b->origin->x)); + $y = max(0, min($a->y2(), $b->y2()) - max($a->origin->y, $b->origin->y)); + $area = $x * $y; + return is_int($area) ? $area : ExactInteger::mul($x, $y); + } + + /** `2 * origin + extent`, the doubled centre of one side, as a decimal string. */ + public static function doubledCentre(int $origin, int $extent): string + { + return (string)ExactInteger::add(ExactInteger::mul(2, $origin), $extent); + } +} diff --git a/src-legacy/Support/ExactInteger.php b/src-legacy/Support/ExactInteger.php new file mode 100644 index 0000000..cc03898 --- /dev/null +++ b/src-legacy/Support/ExactInteger.php @@ -0,0 +1,302 @@ + $b; + } + return SignedBigInt::compare($a, $b); + } + + /** + * @param int|string $value + */ + public static function sign($value): int + { + return self::compare($value, 0); + } + + /** + * @param int|string $value + * @return int|string + */ + public static function negate($value) + { + if (is_int($value) && $value !== PHP_INT_MIN) { + return -$value; + } + return self::normalize(SignedBigInt::negate($value)); + } + + /** + * @param int|string $value + * @return int|string + */ + public static function abs($value) + { + return self::sign($value) < 0 ? self::negate($value) : $value; + } + + /** + * @param int|string $a + * @param int|string $b + * @return int|string + */ + public static function max($a, $b) + { + return self::compare($a, $b) >= 0 ? $a : $b; + } + + /** Python's `a // b`. + * @param int|string $a + * @param int|string $b + * @return int|string*/ + public static function floorDiv($a, $b) + { + if (self::sign($b) === 0) { + throw new \DivisionByZeroError('Division by zero'); + } + if (is_int($a) && is_int($b) && !($a === PHP_INT_MIN && $b === -1)) { + $quotient = intdiv($a, $b); + return ($a % $b !== 0 && (($a < 0) !== ($b < 0))) ? $quotient - 1 : $quotient; + } + $magnitude = BigInt::divide((string)self::abs($a), (string)self::abs($b)); + $negative = (self::sign($a) < 0) !== (self::sign($b) < 0); + if (!$negative) { + return self::normalize($magnitude); + } + $exact = self::compare(self::mul($magnitude, self::abs($b)), self::abs($a)) === 0; + return self::negate($exact ? self::normalize($magnitude) : self::add($magnitude, 1)); + } + + /** Python's `a % b`, which takes the divisor's sign. + * @param int|string $a + * @param int|string $b + * @return int|string */ + public static function mod($a, $b) + { + return self::sub($a, self::mul(self::floorDiv($a, $b), $b)); + } + + /** @param iterable $values + * @return int|string */ + public static function sum(iterable $values) + { + $total = 0; + foreach ($values as $value) { + $total = self::add($total, $value); + } + return $total; + } + + /** `2 ** $power`, exactly. + * @return int|string */ + public static function powerOfTwo(int $power) + { + if ($power < 62) { + return 1 << $power; + } + $value = 1 << 61; + for ($i = 61; $i < $power; ++$i) { + $value = self::mul($value, 2); + } + return $value; + } + + /** + * Exact `floor(a * b / d)` for non-negative operands whose quotient fits an `int`: a + * weight shared out by contact area, where the area and its total may not. + * @param int|string $b + * @param int|string $d + */ + public static function mulDiv(int $a, $b, $d): int + { + if (is_int($b) && is_int($d)) { + return Arithmetic::mulDiv($a, $b, $d); + } + $quotient = self::floorDiv(self::mul($a, $b), $d); + if (!is_int($quotient)) { + throw new \OverflowException('quotient exceeds a native integer'); + } + return $quotient; + } + + /** + * Python's `numerator / denominator` for non-negative integers: the double nearest the + * exact quotient, ties to even. PHP converts each operand to a double first, which + * rounds twice once either passes 2^53. O(d^2) in the operands' digit count, and only + * then; below 2^53 it is one native division. + * @param int|string $numerator + * @param int|string $denominator + */ + public static function ratio($numerator, $denominator): float + { + if (is_int($numerator) && is_int($denominator) + && $numerator <= self::EXACT_FLOAT && $denominator <= self::EXACT_FLOAT) { + return $numerator / $denominator; + } + if (self::sign($numerator) === 0) { + return 0.0; + } + $shift = self::QUOTIENT_BITS - self::bitLength($numerator) + self::bitLength($denominator); + // The estimate is within a bit or two; each step doubles or halves the quotient, so + // exactly one shift lands it in [2^54, 2^55). + while (true) { + [$quotient, $inexact] = self::shiftedQuotient($numerator, $denominator, $shift); + if (!is_int($quotient) || $quotient >= 1 << self::QUOTIENT_BITS) { + --$shift; + } elseif ($quotient < 1 << (self::QUOTIENT_BITS - 1)) { + ++$shift; + } else { + break; + } + } + $mantissa = $quotient >> 2; + $dropped = $quotient & 3; + if ($dropped > 2 || ($dropped === 2 && ($inexact || ($mantissa & 1) === 1))) { + ++$mantissa; + } + return $mantissa * 2.0 ** (2 - $shift); + } + + /** + * An order-preserving stand-in for a non-negative value inside a PHP array key: the + * value itself while it is an `int`, and its fixed-width chunks beyond. PHP ranks any + * array above any `int`, and every value that needs chunks exceeds every `int`, so + * comparing keys that hold either form still follows the exact integer order. + * + * @return int|list + * @param int|string $value + */ + public static function sortKey($value) + { + return is_int($value) ? $value : BigInt::chunks($value, 3, 15); + } + + /** + * Fixed-width chunks of a non-negative value, negated so ascending array order is + * largest first: the same shape as `Dimensions::descendingVolumeKey`. + * + * @return list + * @param int|string $value + */ + public static function descendingKey($value): array + { + return array_map(static function (int $chunk): int { + return -$chunk; + }, BigInt::chunks((string)$value, 3, 15)); + } + + /** Approximate: within a bit or two of the exact length, which `ratio` corrects. + * @param int|string $value */ + private static function bitLength($value): int + { + $digits = ltrim((string)$value, '-'); + $lead = (float)substr($digits, 0, 15); + return $lead <= 0.0 ? 0 : (int)floor(log($lead, 2) + max(0, strlen($digits) - 15) * log(10, 2)) + 1; + } + + /** + * `floor(n * 2^shift / d)` and whether it dropped a remainder. + * + * @return array{0:int|string,1:bool} + * @param int|string $numerator + * @param int|string $denominator + */ + private static function shiftedQuotient($numerator, $denominator, int $shift): array + { + $scaledNumerator = $shift >= 0 ? self::mul($numerator, self::powerOfTwo($shift)) : $numerator; + $scaledDenominator = $shift < 0 ? self::mul($denominator, self::powerOfTwo(-$shift)) : $denominator; + $quotient = self::floorDiv($scaledNumerator, $scaledDenominator); + $inexact = self::sign(self::sub($scaledNumerator, self::mul($quotient, $scaledDenominator))) !== 0; + return [$quotient, $inexact]; + } +} diff --git a/src-legacy/Support/FixedPlacementShape.php b/src-legacy/Support/FixedPlacementShape.php index 021caee..837cd4c 100644 --- a/src-legacy/Support/FixedPlacementShape.php +++ b/src-legacy/Support/FixedPlacementShape.php @@ -123,7 +123,7 @@ private static function requireCoordinate($value, string $where, string $field, if ($verdict === MeasureReading::NEGATIVE) { throw self::malformed("{$where} cannot be negative", $field); } - if ($verdict === MeasureReading::UNREADABLE) { + if ($verdict !== MeasureReading::READABLE) { throw self::malformed("{$where} is a measure", $field); } } diff --git a/src-legacy/Support/Internal/MeasureOverflow.php b/src-legacy/Support/Internal/MeasureOverflow.php new file mode 100644 index 0000000..f3905bb --- /dev/null +++ b/src-legacy/Support/Internal/MeasureOverflow.php @@ -0,0 +1,92 @@ + '/^(.+?)\s*(mm|cm|m|in|inch|inches|ft|ticks?)$/i', + Weight::class => '/^(.+?)\s*(mg|kg|g|oz|lbs?|ticks?)$/i', + ]; + + /** + * The verdict on text the native parser overflowed on, read exactly: negative, past the + * tick ceiling of its kind, or -- a vanishing fraction with a vast denominator -- still + * unreadable here. + * Ticks round to nearest, so they pass `MAX` once `n x m / d >= MAX + 1/2`; `MAX` is odd, + * so the tie itself rounds up to even. O(digits^2). + * + * @param int|string|array{value:int|string,unit?:string} $normalised + * @param class-string|class-string $kind + */ + public static function beyondNativeInteger($normalised, string $kind, string $unit): string + { + $text = \is_array($normalised) ? (string) $normalised['value'] : (string) $normalised; + $unit = \is_array($normalised) ? ($normalised['unit'] ?? $unit) : $unit; + if (\is_string($normalised) && \preg_match(self::SUFFIXES[$kind], \trim($normalised), $m)) { + [$text, $unit] = [\trim($m[1]), $m[2]]; + } + $fraction = self::exactFraction(\trim(\str_replace("\u{00A0}", ' ', $text))); + if ($fraction === null || $fraction[1] === '0') { + return MeasureReading::UNREADABLE; + } + [$negative, $numerator, $denominator] = $fraction; + if ($negative) { + return MeasureReading::NEGATIVE; + } + $multiplier = $kind::multiplier($unit); + $doubled = BigInt::multiply(BigInt::multiply($numerator, $multiplier), 2); + $ceiling = $kind === Weight::class ? RequestRules::MAX_WEIGHT_TICKS : JsonValue::MAX_EXACT_MAGNITUDE; + $threshold = BigInt::multiply($denominator, BigInt::add(BigInt::multiply($ceiling, 2), '1')); + return BigInt::compare($doubled, $threshold) >= 0 ? MeasureReading::TOO_LARGE : MeasureReading::UNREADABLE; + } + + /** + * `RationalParser::parse` over decimal strings: an integer, decimal, fraction or mixed + * fraction as its sign, numerator and denominator, or null for any other text. + * + * @return array{0:bool,1:string,2:string}|null + */ + private static function exactFraction(string $text): ?array + { + $negative = strncmp($text, '-', strlen('-')) === 0; + if (\preg_match('/^[+-]?(\d+)\s+(\d+)\s*\/\s*(\d+)$/', $text, $m)) { + return self::signed($negative, BigInt::add(BigInt::multiply(self::digits($m[1]), self::digits($m[3])), self::digits($m[2])), $m[3]); + } + if (\preg_match('/^[+-]?(\d+)\s*\/\s*(\d+)$/', $text, $m)) { + return self::signed($negative, $m[1], $m[2]); + } + if (\preg_match('/^[+-]?(\d+)(?:\.(\d+))?$/', $text, $m)) { + $fraction = $m[2] ?? ''; + return self::signed($negative, $m[1] . $fraction, '1' . \str_repeat('0', \strlen($fraction))); + } + return null; + } + + /** @return array{0:bool,1:string,2:string}|null */ + private static function signed(bool $negative, string $numerator, string $denominator): ?array + { + $numerator = self::digits($numerator); + $denominator = self::digits($denominator); + if ($denominator === '0') { + return null; + } + return [$negative && $numerator !== '0', $numerator, $denominator]; + } + + private static function digits(string $digits): string + { + return \ltrim($digits, '0') ?: '0'; + } +} diff --git a/src-legacy/Support/Internal/RareRequestRules.php b/src-legacy/Support/Internal/RareRequestRules.php new file mode 100644 index 0000000..49a1627 --- /dev/null +++ b/src-legacy/Support/Internal/RareRequestRules.php @@ -0,0 +1,161 @@ + $container + * @param mixed $raw + */ + public static function madeToMeasure(\Closure $call, $container, $raw, string $where, string $unit): void + { + $field = "{$where}/made_to_measure"; + $machine = $call('objectAt', $raw, $field); + $call('knownFields', $machine, $field, self::MADE_TO_MEASURE_FIELDS); + foreach (['minimum', 'increment'] as $name) { + $call('required', $machine, $name, $field); + } + foreach (['minimum', 'increment', 'outer_allowance'] as $name) { + $sides = JsonValue::get($machine, $name); + if ($sides !== null) { + $call('dimensions', $sides, "{$field}/{$name}", $unit, false); + } + } + $call('optionalInteger', $machine, 'cost_per_square_metre_minor', $field, 0); + $call('optionalMeasure', $machine, 'tare_per_square_metre', $field, Weight::class, RequestRules::WEIGHT_UNIT); + if (JsonValue::get($container, 'outer_dimensions') !== null) { + throw $call('refuse', 'not_allowed', "{$where}/outer_dimensions", 'cannot be combined with made_to_measure'); + } + $inner = $call('sideTicks', JsonValue::get($container, 'inner_dimensions'), $unit); + $minimum = $call('sideTicks', JsonValue::get($machine, 'minimum'), $unit); + $increment = $call('sideTicks', JsonValue::get($machine, 'increment'), $unit); + foreach (RequestRules::SIDES as $axis => $side) { + if ($minimum[$axis] === 0) { + throw $call('refuse', 'invalid_value', "{$field}/minimum/{$side}", 'must be positive'); + } + if ($increment[$axis] === 0) { + throw $call('refuse', 'invalid_value', "{$field}/increment/{$side}", 'must be positive'); + } + if ($minimum[$axis] > $inner[$axis]) { + throw $call('refuse', 'invalid_value', "{$field}/minimum/{$side}", 'exceeds inner_dimensions'); + } + if (($inner[$axis] - $minimum[$axis]) % $increment[$axis] !== 0) { + throw $call('refuse', 'invalid_value', "{$field}/increment/{$side}", 'does not divide inner_dimensions minus minimum'); + } + } + $price = JsonValue::integer(JsonValue::get($machine, 'cost_per_square_metre_minor') ?? 0); + $fee = JsonValue::integer(JsonValue::get($container, 'cost_minor') ?? 0); + if (BigInt::compare(MadeToMeasure::boxCostFor((int) $price, (int) $fee, $inner), MadeToMeasure::MAX_EXACT_INTEGER) > 0) { + throw $call('refuse', 'invalid_value', "{$field}/cost_per_square_metre_minor", 'prices the largest box above ' . CanonicalJson::MAX_EXACT_MAGNITUDE); + } + } + + /** + * The bag's own shape, then every container field a flat bag refuses, in the + * order of `BAG_EXCLUSIONS`. + * + * @param stdClass|array $container + * @param mixed $raw + */ + public static function deformableBoundary(\Closure $call, $container, $raw, string $where): void + { + $field = "{$where}/deformable_boundary"; + $boundary = $call('objectAt', $raw, $field); + if (!\in_array($call('required', $boundary, 'kind', $field), FlatBag::KINDS, true)) { + throw $call('refuse', 'not_allowed', "{$field}/kind", 'must be one of ' . CanonicalJson::spelling(FlatBag::KINDS)); + } + $call('knownFields', $boundary, $field, ['kind']); + foreach (RequestRules::BAG_EXCLUSIONS as $name) { + if ($call('setBesideABag', $name, JsonValue::get($container, $name))) { + throw $call('refuse', 'not_allowed', "{$where}/{$name}", 'cannot be combined with deformable_boundary'); + } + } + } + + /** @param mixed $raw */ + public static function rateTable(\Closure $call, $raw, string $where): void + { + $table = $call('objectAt', $raw, $where); + foreach (['weight_brackets_g' => 1, 'prices_minor' => 0] as $name => $minimum) { + $values = JsonValue::get($table, $name); + if ($values === null) { + continue; + } + foreach ($call('listAt', $values, "{$where}/{$name}") as $index => $value) { + $call('integer', $value, "{$where}/{$name}/{$index}", $minimum); + } + } + $call('optionalInteger', $table, 'minimum_charge_minor', $where, 0); + $call('optionalInteger', $table, 'fuel_surcharge_permille', $where, 0); + } + + /** @param mixed $raw @param array{0:int,1:int,2:int} $inner */ + public static function obstacles(\Closure $call, $raw, string $where, string $unit, array $inner): void + { + foreach ($call('listAt', $raw, $where) as $index => $entry) { + $at = "{$where}/{$index}"; + $obstacle = $call('objectAt', $entry, $at); + self::placedBox($call, $obstacle, $at, $unit, $inner); + $extra = JsonValue::get($obstacle, 'additional_boxes'); + if ($extra !== null) { + foreach ($call('listAt', $extra, "{$at}/additional_boxes") as $position => $box) { + $part = "{$at}/additional_boxes/{$position}"; + self::placedBox($call, $call('objectAt', $box, $part), $part, $unit, $inner); + } + } + } + } + + /** + * An optional `origin` and required `dimensions`: an obstacle, or one more box of it + *, whose measures are read in the request's unit like every other length, and + * which lies inside the container. + * + * @param stdClass|array $box @param array{0:int,1:int,2:int} $inner + */ + public static function placedBox(\Closure $call, $box, string $at, string $unit, array $inner): void + { + $origin = JsonValue::get($box, 'origin'); + if ($origin !== null) { + $point = $call('objectAt', $origin, "{$at}/origin"); + foreach (['x', 'y', 'z'] as $axis) { + $call('optionalMeasure', $point, $axis, "{$at}/origin", Length::class, $unit); + } + } + $call('dimensions', $call('required', $box, 'dimensions', $at), "{$at}/dimensions", $unit); + $sides = $call('sideTicks', JsonValue::get($box, 'dimensions'), $unit); + foreach (['x', 'y', 'z'] as $index => $axis) { + $start = $origin === null ? null : JsonValue::get($origin, $axis); + $offset = $start === null ? 0 : MeasureReading::ticks($start, Length::class, $unit); + if ($offset + $sides[$index] > $inner[$index]) { + throw $call('refuse', 'invalid_value', $at, 'lies outside inner_dimensions'); + } + } + } + + // ------------------------------------------------------------------------- primitives +} diff --git a/src-legacy/Support/MeasureReading.php b/src-legacy/Support/MeasureReading.php index bc7fd50..d1fee4f 100644 --- a/src-legacy/Support/MeasureReading.php +++ b/src-legacy/Support/MeasureReading.php @@ -4,6 +4,7 @@ use ArithmeticError; use InvalidArgumentException; +use Packvium\Support\Internal\MeasureOverflow; use Packvium\Unit\Length; use Packvium\Unit\Weight; use TypeError; @@ -23,11 +24,13 @@ final class MeasureReading public const READABLE = 'readable'; public const NEGATIVE = 'negative'; public const UNREADABLE = 'unreadable'; + /** A measure the reference reads whose tick count is past every engine's integers. */ + public const TOO_LARGE = 'too_large'; /** * @param mixed $value * @param class-string|class-string $kind - * @return self::READABLE|self::NEGATIVE|self::UNREADABLE + * @return self::READABLE|self::NEGATIVE|self::UNREADABLE|self::TOO_LARGE */ public static function verdict($value, string $kind, string $unit): string { @@ -38,6 +41,9 @@ public static function verdict($value, string $kind, string $unit): string try { $kind::parse($normalised, $unit); } catch (InvalidArgumentException $error) { + if (strpos($error->getMessage(), 'exceeds integer range') !== false) { + return MeasureOverflow::beyondNativeInteger($normalised, $kind, $unit); + } return strpos($error->getMessage(), 'cannot be negative') !== false ? self::NEGATIVE : self::UNREADABLE; } catch (TypeError | ValueError | ArithmeticError $error) { return self::UNREADABLE; @@ -45,6 +51,19 @@ public static function verdict($value, string $kind, string $unit): string return self::READABLE; } + /** + * A JSON number past 2^53 - 1 is a whole number to the caller, whether `json_decode` kept it + * an `int` or made it a float, and its ticks are past the ceiling in every unit a bare + * number can carry. + * + * @param mixed $value + */ + public static function isWholeBeyondExact($value): bool + { + $whole = \is_int($value) || (\is_float($value) && \is_finite($value) && \floor($value) === $value); + return $whole && \abs($value) > JsonValue::MAX_EXACT_MAGNITUDE; + } + /** * The ticks of a value `verdict` already found readable, for a rule that compares measures. * An unreadable one reaches the parser as null and is refused there as a `TypeError`. diff --git a/src-legacy/Support/PrettyJsonStream.php b/src-legacy/Support/PrettyJsonStream.php index 1af591e..f2fc266 100644 --- a/src-legacy/Support/PrettyJsonStream.php +++ b/src-legacy/Support/PrettyJsonStream.php @@ -29,7 +29,11 @@ final class PrettyJsonStream { /** A placement counts 30 or so; a container with its placements counts thousands. */ private const WHOLE_ELEMENTS = 64; - private const FLUSH_BYTES = 65536; + /** + * Small enough to stay a few heap pages: `.=` reallocates the buffer as it grows, and a + * 64 KB run found no room in two fragmented chunks on br1 `fast` #3 in 1.9. + */ + private const FLUSH_BYTES = 8192; private const FLAGS = \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_THROW_ON_ERROR; private const INDENT = ' '; diff --git a/src-legacy/Support/RequestObjects.php b/src-legacy/Support/RequestObjects.php index 45af6e2..e8ae4aa 100644 --- a/src-legacy/Support/RequestObjects.php +++ b/src-legacy/Support/RequestObjects.php @@ -4,6 +4,7 @@ use Packvium\Config\PackingConfig; use Packvium\Domain\Container; +use Packvium\Domain\Dimensions; use Packvium\Domain\FixedPlacement; use Packvium\Domain\Item; use Packvium\Domain\MadeToMeasure; @@ -65,6 +66,14 @@ public static function check(array $items, array $containers, PackingConfig $con RequestRules::requireUniqueIds(\array_map(static function (Container $container): string { return $container->id; }, $containers), 'containers'); + RequestRules::totalWeight( + \array_map(static function (Item $item): array { + return [$item->weight->ticks, $item->quantity]; + }, $items), + \array_map(static function (Container $container): int { + return $container->tareWeight->ticks; + }, $containers), + ); foreach ($fixedPlacements as $index => $placement) { self::fixedPlacement($placement, "fixed_placements[{$index}]", "/fixed_placements/{$index}"); } @@ -99,6 +108,7 @@ private static function configuration(PackingConfig $config): void $property = self::CONFIGURATION_PROPERTIES[$name]; self::optionalInteger($config->{$property}, "{$where}/{$name}", $minimum); } + RequestRules::lengthTicks($config->clearance->ticks, "{$where}/clearance"); RequestRules::ratio($config->minimumSupportRatio, "{$where}/minimum_support_ratio", 1); $budget = $config->effortBudget; if ($budget === null) { @@ -113,6 +123,10 @@ private static function configuration(PackingConfig $config): void private static function item(Item $item, string $where): void { RequestRules::integer($item->quantity, "{$where}/quantity", 1); + RequestRules::box(self::sides($item->dimensions), "{$where}/dimensions"); + if ($item->nestingHeight !== null) { + RequestRules::lengthTicks($item->nestingHeight->ticks, "{$where}/nesting_height"); + } self::optionalInteger($item->maxStackedItems, "{$where}/max_stacked_items", 1); self::optionalInteger($item->stopIndex, "{$where}/stop_index", 0); self::optionalInteger($item->value, "{$where}/value", 0); @@ -129,6 +143,10 @@ private static function item(Item $item, string $where): void private static function container(Container $container, string $where): void { self::optionalInteger($container->quantity, "{$where}/quantity", 1); + RequestRules::box(self::sides($container->innerDimensions), "{$where}/inner_dimensions"); + if ($container->outerDimensions !== null) { + RequestRules::box(self::sides($container->outerDimensions), "{$where}/outer_dimensions"); + } self::optionalInteger($container->maxItems, "{$where}/max_items", 1); RequestRules::integer($container->costMinor, "{$where}/cost_minor", 0); RequestRules::ratio($container->voidFillReserveRatio, "{$where}/void_fill_reserve_ratio", 1); @@ -195,6 +213,9 @@ private static function flatBag(Container $container, string $where): void private static function madeToMeasure(Container $container, MadeToMeasure $machine, string $where): void { $price = "{$where}/made_to_measure/cost_per_square_metre_minor"; + foreach (['minimum' => $machine->minimum, 'increment' => $machine->increment, 'outer_allowance' => $machine->outerAllowance] as $name => $sides) { + RequestRules::box($sides, "{$where}/made_to_measure/{$name}"); + } RequestRules::integer($machine->costPerSquareMetreMinor, $price, 0); if ($container->outerDimensions !== null) { throw new InvalidRequestException('not_allowed', "{$where}/outer_dimensions", 'cannot be combined with made_to_measure'); @@ -207,6 +228,12 @@ private static function madeToMeasure(Container $container, MadeToMeasure $machi } } + /** @return array{0:int,1:int,2:int} */ + private static function sides(Dimensions $dimensions): array + { + return [$dimensions->length->ticks, $dimensions->width->ticks, $dimensions->height->ticks]; + } + private static function optionalInteger(?int $value, string $field, int $minimum): void { if ($value !== null) { diff --git a/src-legacy/Support/RequestRules.php b/src-legacy/Support/RequestRules.php index 3edb325..16ae75d 100644 --- a/src-legacy/Support/RequestRules.php +++ b/src-legacy/Support/RequestRules.php @@ -7,6 +7,7 @@ use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\Length; use Packvium\Unit\Weight; +use Packvium\Support\Internal\RareRequestRules; use stdClass; /** @@ -48,16 +49,25 @@ final class RequestRules 'minimum_support_ratio', 'multi_start_orders', 'objective', 'require_placement_coordinates', 'seed', 'solver_profile', 'solvers', 'time_limit_ms', ]; - private const SIDES = ['length', 'width', 'height']; + public const SIDES = ['length', 'width', 'height']; /** The item fields the request schema types `boolean`, in schema order. */ private const ITEM_BOOLEANS = ['keep_upright', 'stackable', 'must_be_on_floor']; /** Container fields a flat bag refuses, in reporting order (docs/DEFORMABLE-CONTAINERS.md). */ public const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure']; - /** Every key the request schema's `made_to_measure` declares; it sets `additionalProperties: false`. */ - private const MADE_TO_MEASURE_FIELDS = ['cost_per_square_metre_minor', 'increment', 'minimum', 'outer_allowance', - 'tare_per_square_metre']; - private const WEIGHT_UNIT = 'g'; + public const WEIGHT_UNIT = 'g'; + /** + * The admission ceiling every engine refuses past: a length is a tick count + * every engine holds exactly, JavaScript's `Number` included, and a box encloses no more than + * the bound path can sum, so `volume x 10^6` stays inside Rust's `i128`. + */ + public const MAX_LENGTH_TICKS = JsonValue::MAX_EXACT_MAGNITUDE; + public const MAX_VOLUME_TICKS3 = '1000000000000000000000000000000'; + /** + * A weight, and every item's weight times its quantity plus the heaviest tare, fit a signed + * 64-bit integer, which is how this engine and Rust add a container's payload (R19-01). + */ + public const MAX_WEIGHT_TICKS = \PHP_INT_MAX; /** * Refuse the request with its first violation, or return. @@ -81,6 +91,39 @@ public static function check($data): void self::container($raw, "/containers/{$index}", $unit); } self::requireUniqueIds(self::identifiers($containers), 'containers'); + self::totalWeight(\array_map( + static function ($item): array { + return [self::weightOf($item, 'weight'), (int) (JsonValue::get($item, 'quantity') ?? 1)]; + }, + $items, + ), \array_map(static function ($container): int { + return self::weightOf($container, 'tare_weight'); + }, $containers)); + } + + /** + * Every item's weight times its quantity, plus the heaviest tare, against `MAX_WEIGHT_TICKS`: + * no container's gross weight can pass it. Shared with `RequestObjects`. O(items + containers). + * + * @param list $itemWeights weight ticks and quantity + * @param list $tares + */ + public static function totalWeight(array $itemWeights, array $tares): void + { + $total = (string) ($tares === [] ? 0 : \max($tares)); + foreach ($itemWeights as [$weight, $quantity]) { + $total = BigInt::add($total, BigInt::multiply($weight, $quantity)); + } + if (BigInt::compare($total, self::MAX_WEIGHT_TICKS) > 0) { + throw self::refuse('above_maximum', '/items', 'must weigh at most ' . self::MAX_WEIGHT_TICKS . ' ticks in all, with the heaviest tare'); + } + } + + /** @param mixed $holder */ + private static function weightOf($holder, string $name): int + { + $value = JsonValue::get($holder, $name); + return $value === null ? 0 : MeasureReading::ticks($value, Weight::class, self::WEIGHT_UNIT); } /** The RFC 6901 pointer to one member, escaping `~` and `/` in its name. */ @@ -239,70 +282,19 @@ private static function container($raw, string $where, string $unit): void } $rateTable = JsonValue::get($container, 'rate_table'); if ($rateTable !== null) { - self::rateTable($rateTable, "{$where}/rate_table"); + RareRequestRules::rateTable(self::bridge(), $rateTable, "{$where}/rate_table"); } $obstacles = JsonValue::get($container, 'obstacles'); if ($obstacles !== null) { - self::obstacles($obstacles, "{$where}/obstacles", $unit); + RareRequestRules::obstacles(self::bridge(), $obstacles, "{$where}/obstacles", $unit, self::sideTicks(JsonValue::get($container, 'inner_dimensions'), $unit)); } $boundary = JsonValue::get($container, 'deformable_boundary'); if ($boundary !== null) { - self::deformableBoundary($container, $boundary, $where); + RareRequestRules::deformableBoundary(self::bridge(), $container, $boundary, $where); } $machine = JsonValue::get($container, 'made_to_measure'); if ($machine !== null) { - self::madeToMeasure($container, $machine, $where, $unit); - } - } - - /** - * The made-to-measure block's shape top to bottom, then each axis's four rules, - * then the price ceiling. Run after every other container field, so an existing error - * always wins. O(1). - * - * @param stdClass|array $container - * @param mixed $raw - */ - private static function madeToMeasure($container, $raw, string $where, string $unit): void - { - $field = "{$where}/made_to_measure"; - $machine = self::objectAt($raw, $field); - self::knownFields($machine, $field, self::MADE_TO_MEASURE_FIELDS); - foreach (['minimum', 'increment'] as $name) { - self::required($machine, $name, $field); - } - foreach (['minimum', 'increment', 'outer_allowance'] as $name) { - $sides = JsonValue::get($machine, $name); - if ($sides !== null) { - self::dimensions($sides, "{$field}/{$name}", $unit); - } - } - self::optionalInteger($machine, 'cost_per_square_metre_minor', $field, 0); - self::optionalMeasure($machine, 'tare_per_square_metre', $field, Weight::class, self::WEIGHT_UNIT); - if (JsonValue::get($container, 'outer_dimensions') !== null) { - throw self::refuse('not_allowed', "{$where}/outer_dimensions", 'cannot be combined with made_to_measure'); - } - $inner = self::sideTicks(JsonValue::get($container, 'inner_dimensions'), $unit); - $minimum = self::sideTicks(JsonValue::get($machine, 'minimum'), $unit); - $increment = self::sideTicks(JsonValue::get($machine, 'increment'), $unit); - foreach (self::SIDES as $axis => $side) { - if ($minimum[$axis] === 0) { - throw self::refuse('invalid_value', "{$field}/minimum/{$side}", 'must be positive'); - } - if ($increment[$axis] === 0) { - throw self::refuse('invalid_value', "{$field}/increment/{$side}", 'must be positive'); - } - if ($minimum[$axis] > $inner[$axis]) { - throw self::refuse('invalid_value', "{$field}/minimum/{$side}", 'exceeds inner_dimensions'); - } - if (($inner[$axis] - $minimum[$axis]) % $increment[$axis] !== 0) { - throw self::refuse('invalid_value', "{$field}/increment/{$side}", 'does not divide inner_dimensions minus minimum'); - } - } - $price = JsonValue::integer(JsonValue::get($machine, 'cost_per_square_metre_minor') ?? 0); - $fee = JsonValue::integer(JsonValue::get($container, 'cost_minor') ?? 0); - if (BigInt::compare(MadeToMeasure::boxCostFor((int) $price, (int) $fee, $inner), MadeToMeasure::MAX_EXACT_INTEGER) > 0) { - throw self::refuse('invalid_value', "{$field}/cost_per_square_metre_minor", 'prices the largest box above ' . CanonicalJson::MAX_EXACT_MAGNITUDE); + RareRequestRules::madeToMeasure(self::bridge(), $container, $machine, $where, $unit); } } @@ -319,28 +311,6 @@ private static function sideTicks($sides, string $unit): array return $ticks; } - /** - * The bag's own shape, then every container field a flat bag refuses, in the - * order of `BAG_EXCLUSIONS`. - * - * @param stdClass|array $container - * @param mixed $raw - */ - private static function deformableBoundary($container, $raw, string $where): void - { - $field = "{$where}/deformable_boundary"; - $boundary = self::objectAt($raw, $field); - if (!\in_array(self::required($boundary, 'kind', $field), FlatBag::KINDS, true)) { - throw self::refuse('not_allowed', "{$field}/kind", 'must be one of ' . CanonicalJson::spelling(FlatBag::KINDS)); - } - self::knownFields($boundary, $field, ['kind']); - foreach (self::BAG_EXCLUSIONS as $name) { - if (self::setBesideABag($name, JsonValue::get($container, $name))) { - throw self::refuse('not_allowed', "{$where}/{$name}", 'cannot be combined with deformable_boundary'); - } - } - } - /** * An empty obstacle list and a zero reserve change nothing, so only they are let through. * @@ -409,12 +379,53 @@ private static function oneOf($value, string $field, array $allowed): void } } - /** @param mixed $raw */ - private static function dimensions($raw, string $where, string $unit): void + /** + * A box's three sides, each a measure; a box that holds or is something has no empty side + *, while a made-to-measure step states its own rule for zero. + * + * @param mixed $raw + */ + private static function dimensions($raw, string $where, string $unit, bool $positive = true): void { $sides = self::objectAt($raw, $where); foreach (self::SIDES as $side) { - self::measure(self::required($sides, $side, $where), "{$where}/{$side}", Length::class, $unit); + $value = self::required($sides, $side, $where); + self::measure($value, "{$where}/{$side}", Length::class, $unit); + if ($positive && MeasureReading::ticks($value, Length::class, $unit) === 0) { + throw self::refuse('invalid_value', "{$where}/{$side}", 'must be positive'); + } + } + self::enclosure(self::sideTicks($sides, $unit), $where); + } + + /** + * A box's sides in ticks, held to the admission ceiling as the request spells them: each + * side, then what they enclose. Shared with `RequestObjects`. O(1). + * + * @param array{0:int,1:int,2:int} $sides + */ + public static function box(array $sides, string $where): void + { + foreach (self::SIDES as $index => $side) { + self::lengthTicks($sides[$index], "{$where}/{$side}"); + } + self::enclosure($sides, $where); + } + + /** A length the object path holds as ticks, against `MAX_LENGTH_TICKS`. */ + public static function lengthTicks(int $ticks, string $field): void + { + if ($ticks > self::MAX_LENGTH_TICKS) { + throw self::tooLong($field); + } + } + + /** @param array{0:int,1:int,2:int} $sides */ + private static function enclosure(array $sides, string $where): void + { + [$length, $width, $height] = $sides; + if (BigInt::compare(BigInt::multiply(BigInt::multiply($length, $width), $height), self::MAX_VOLUME_TICKS3) > 0) { + throw self::refuse('above_maximum', $where, 'must enclose at most 10^30 cubic ticks'); } } @@ -438,41 +449,6 @@ private static function tagLimits($raw, string $where): void } /** @param mixed $raw */ - private static function rateTable($raw, string $where): void - { - $table = self::objectAt($raw, $where); - foreach (['weight_brackets_g' => 1, 'prices_minor' => 0] as $name => $minimum) { - $values = JsonValue::get($table, $name); - if ($values === null) { - continue; - } - foreach (self::listAt($values, "{$where}/{$name}") as $index => $value) { - self::integer($value, "{$where}/{$name}/{$index}", $minimum); - } - } - self::optionalInteger($table, 'minimum_charge_minor', $where, 0); - self::optionalInteger($table, 'fuel_surcharge_permille', $where, 0); - } - - /** @param mixed $raw */ - private static function obstacles($raw, string $where, string $unit): void - { - foreach (self::listAt($raw, $where) as $index => $entry) { - $at = "{$where}/{$index}"; - $obstacle = self::objectAt($entry, $at); - $origin = JsonValue::get($obstacle, 'origin'); - if ($origin !== null) { - $point = self::objectAt($origin, "{$at}/origin"); - foreach (['x', 'y', 'z'] as $axis) { - self::optionalMeasure($point, $axis, "{$at}/origin", Length::class, $unit); - } - } - self::dimensions(self::required($obstacle, 'dimensions', $at), "{$at}/dimensions", $unit); - } - } - - // ------------------------------------------------------------------------- primitives - /** @param mixed $value */ public static function integer($value, string $field, int $minimum): void { @@ -527,7 +503,9 @@ public static function ratio($value, string $field, ?int $maximum): void */ private static function measure($value, string $field, string $kind, string $unit): void { - $scalar = \is_int($value) || \is_string($value) || (\is_float($value) && JsonValue::integer($value) !== null); + $length = $kind === Length::class; + $scalar = \is_int($value) || \is_string($value) + || (\is_float($value) && (JsonValue::integer($value) !== null || ($length && MeasureReading::isWholeBeyondExact($value)))); if (!$scalar && !self::isMeasureObject($value)) { throw self::refuse('wrong_type', $field, 'must be a measure'); } @@ -540,15 +518,36 @@ private static function measure($value, string $field, string $kind, string $uni throw self::refuse('invalid_unit', $field, 'has an unknown unit ' . CanonicalJson::spelling($stated)); } } + $amount = $scalar ? $value : JsonValue::get($value, 'value'); + if ($length && MeasureReading::isWholeBeyondExact($amount)) { + throw $amount < 0 ? self::refuse('negative_measure', $field, 'cannot be negative') : self::tooLong($field); + } + // Past 2^53 - 1 JavaScript has already rounded a JSON number before it reads it, so a + // weight that large is written as a string, which every engine reads exactly. + if (!$length && MeasureReading::isWholeBeyondExact($amount)) { + throw $amount < 0 ? self::refuse('negative_measure', $field, 'cannot be negative') : self::refuse('invalid_value', $field, 'must be written as a string past ' . JsonValue::MAX_EXACT_MAGNITUDE); + } $verdict = MeasureReading::verdict($value, $kind, $unit); if ($verdict === MeasureReading::NEGATIVE) { throw self::refuse('negative_measure', $field, 'cannot be negative'); } - if ($verdict === MeasureReading::UNREADABLE) { + if ($length && ($verdict === MeasureReading::TOO_LARGE + || ($verdict === MeasureReading::READABLE && MeasureReading::ticks($value, $kind, $unit) > self::MAX_LENGTH_TICKS))) { + throw self::tooLong($field); + } + if (!$length && $verdict === MeasureReading::TOO_LARGE) { + throw self::refuse('above_maximum', $field, 'must be at most ' . self::MAX_WEIGHT_TICKS . ' ticks'); + } + if ($verdict !== MeasureReading::READABLE) { throw self::refuse('wrong_type', $field, 'must be a measure'); } } + private static function tooLong(string $field): InvalidRequestException + { + return self::refuse('above_maximum', $field, 'must be at most ' . self::MAX_LENGTH_TICKS . ' ticks'); + } + /** * An object measure; the empty array is `{}` here, which has no `value` and is refused * as a measure either way. @@ -709,4 +708,12 @@ private static function refuse(string $reason, string $field, string $detail): I { return new InvalidRequestException($reason, $field, $detail); } + + /** `RequestRules`' own private helpers, for `Internal\RareRequestRules` (see there). */ + private static function bridge(): \Closure + { + return static function (string $method, ...$arguments) { + return self::{$method}(...$arguments); + }; + } } diff --git a/src-legacy/Support/ResultValidation/ContainerCheck.php b/src-legacy/Support/ResultValidation/ContainerCheck.php index c12aa7a..4f3658c 100644 --- a/src-legacy/Support/ResultValidation/ContainerCheck.php +++ b/src-legacy/Support/ResultValidation/ContainerCheck.php @@ -263,13 +263,14 @@ public static function check($packed, ContainerSpec $spec, Ordered $items, $clea [$supporters, $directAbove] = Stacking::supportGraph($entries); Stacking::checkSupportAndLoad($entries, $supporters, $directAbove, $globalSupport, $issues); $loads = Stacking::propagateLoad($entries, $supporters); + Stacking::checkStackTopLoad($entries, $loads, $issues); if ($spec->maxStackDensity !== null) { Stacking::checkStackDensity($packedId, $entries, $loads, $spec->maxStackDensity, $issues); } Stacking::checkCrush($packedId, $entries, $loads, $issues); Stacking::checkRouteRemovalOrder($packedId, $entries, $directAbove, $spec->inner, $spec->accessDirections, $issues); self::checkLimits($packed, $packedId, $placements, $spec, $items, $payload, $issues); - self::checkVolumes($packed, $packedId, $placements, $spec, $items, $byId, $loads, $issues); + self::checkVolumes($packed, $packedId, $placements, $spec, $items, $byId, $loads, $clearance, $issues); $totalWeight = self::payloadOf($packed, $items); self::checkCentreOfMass($packed, $packedId, $placements, $spec, $items, $totalWeight, $issues); self::checkAxles($packed, $packedId, $placements, $spec, $items, $totalWeight, $issues); @@ -351,7 +352,8 @@ private static function checkLimits($packed, Label $packedId, array $placements, * @param mixed $packed @param list $placements @param Ordered $items * @param Ordered $byId @param list $loads @param list $issues */ - private static function checkVolumes($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, Ordered $byId, array $loads, array &$issues): void + /** @param int|string $clearance */ + private static function checkVolumes($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, Ordered $byId, array $loads, $clearance, array &$issues): void { // Every placement counts, through the envelope its item id resolves to -- a repeated id // resolves to its last placement, as the reference's dict does. @@ -365,8 +367,15 @@ private static function checkVolumes($packed, Label $packedId, array $placements for ($first = 0, $count = \count($entries); $first < $count; ++$first) { for ($second = $first + 1; $second < $count; ++$second) { if (Stacking::validNesting($entries[$first], $entries[$second])) { + // The envelopes sink by the nesting height; the items themselves overlap by + // twice the clearance less, over their own footprint. $left = $entries[$first]; - $used = Exact::sub($used, Exact::mul(Exact::mul($left->spec->nestingHeight, $left->envelope->length), $left->envelope->width)); + $margin = Exact::mul(2, $clearance); + $overlap = Exact::sub($left->spec->nestingHeight, $margin); + if (Exact::sign($overlap) > 0) { + $footprint = Exact::mul(Exact::sub($left->envelope->length, $margin), Exact::sub($left->envelope->width, $margin)); + $used = Exact::sub($used, Exact::mul($overlap, $footprint)); + } } } } diff --git a/src-legacy/Support/ResultValidation/Stacking.php b/src-legacy/Support/ResultValidation/Stacking.php index ef43d03..3a41cb1 100644 --- a/src-legacy/Support/ResultValidation/Stacking.php +++ b/src-legacy/Support/ResultValidation/Stacking.php @@ -113,6 +113,9 @@ public static function checkSupportAndLoad(array $entries, array $supporters, ar if (Exact::compare($area, self::requiredSupportArea($entry->envelope->baseArea, ContainerCheck::ratioPpm($required))) < 0) { $ratio = Ratio::of($area, $entry->envelope->baseArea); $issues[] = new ResultIssue('insufficient_support', "{$itemId}: " . PyFormat::fixed6($ratio->toFloat()) . ' < ' . PyFormat::fixed6($required->toFloat())); + } elseif (Exact::compare(Exact::mul($area, 2), $entry->envelope->baseArea) <= 0 + && !self::centroidSupported($entry->envelope, \array_map(static function (array $edge) use ($entries) { return $entries[$edge[0]]->envelope; }, $supporting))) { + $issues[] = new ResultIssue('centre_of_gravity_unsupported', "{$itemId}: centroid outside its support hull"); } } foreach ($supporting as [$lower]) { @@ -126,9 +129,6 @@ public static function checkSupportAndLoad(array $entries, array $supporters, ar } elseif ($lowerSpec->acceptsStackingGroups !== [] && !Accounting::holds($lowerSpec->acceptsStackingGroups, $spec->stackingGroup)) { $issues[] = new ResultIssue('stacking_group_incompatible', "{$itemId} rests on {$lowerId}"); } - if ($lowerSpec->maxTopLoad !== null && Exact::compare($spec->weight, $lowerSpec->maxTopLoad) > 0) { - $issues[] = new ResultIssue('top_load_exceeded', "{$itemId} ({$spec->weight} ticks) on {$lowerId} (limit {$lowerSpec->maxTopLoad})"); - } } } foreach ($entries as $index => $entry) { @@ -154,6 +154,77 @@ public static function checkSupportAndLoad(array $entries, array $supporters, ar } /** Exact `floor(baseArea * ppm / 10^6)`, the least supported area the ratio allows. @param int|string $baseArea @return int|string */ + /** + * Whether the base centroid lies in the convex hull of the contact areas, the + * rule the searches apply once a support ratio is enforced; reached only at or below half + * the base, where it can refuse. Coordinates are doubled so the centroid is an + * integer for odd extents, and every product goes through Exact. The corners come four to + * a positive-area overlap, so the hull is empty or has at least three vertices. + * O(s log s) time and O(s) space for s supporters. + * + * @param list $surfaces + */ + private static function centroidSupported(Cuboid $envelope, array $surfaces): bool + { + $points = []; + foreach ($surfaces as $surface) { + foreach ([Exact::max($envelope->x, $surface->x), Exact::compare($envelope->x2, $surface->x2) <= 0 ? $envelope->x2 : $surface->x2] as $x) { + foreach ([Exact::max($envelope->y, $surface->y), Exact::compare($envelope->y2, $surface->y2) <= 0 ? $envelope->y2 : $surface->y2] as $y) { + $points[Exact::mul($x, 2) . ',' . Exact::mul($y, 2)] = [Exact::mul($x, 2), Exact::mul($y, 2)]; + } + } + } + $points = \array_values($points); + \usort($points, static function (array $a, array $b): int { + return Exact::compare($a[0], $b[0]) ?: Exact::compare($a[1], $b[1]); + }); + $hull = \array_merge(self::halfHull($points), self::halfHull(\array_reverse($points))); + $centroid = [Exact::add($envelope->x, $envelope->x2), Exact::add($envelope->y, $envelope->y2)]; + $count = \count($hull); + if ($count === 0) { + return false; + } + for ($index = 0; $index < $count; $index++) { + if (Exact::sign(self::cross($hull[$index], $hull[($index + 1) % $count], $centroid)) < 0) { + return false; + } + } + return true; + } + + /** + * One half of Andrew's monotone chain, its last point dropped for the other half to close. + * + * @param list $points + * @return list + */ + private static function halfHull(array $points): array + { + $chain = []; + foreach ($points as $point) { + while (\count($chain) >= 2 && Exact::sign(self::cross($chain[\count($chain) - 2], $chain[\count($chain) - 1], $point)) <= 0) { + \array_pop($chain); + } + $chain[] = $point; + } + \array_pop($chain); + return $chain; + } + + /** + * @param array{0: int|string, 1: int|string} $o + * @param array{0: int|string, 1: int|string} $a + * @param array{0: int|string, 1: int|string} $b + * @return int|string + */ + private static function cross(array $o, array $a, array $b) + { + return Exact::sub( + Exact::mul(Exact::sub($a[0], $o[0]), Exact::sub($b[1], $o[1])), + Exact::mul(Exact::sub($a[1], $o[1]), Exact::sub($b[0], $o[0])) + ); + } + private static function requiredSupportArea($baseArea, int $ppm) { return Exact::floorDiv(Exact::mul($baseArea, $ppm), ContainerCheck::SCORE_SCALE); @@ -242,6 +313,24 @@ private static function pressure($load, $baseArea): Ratio ); } + /** + * `max_top_load` against the whole stack an item bears, as every engine checks it. + * The only top-load rule since 1.9.0: an item resting on several bearers shares its + * weight among them by contact area. O(n) over the loads `propagateLoad` built. + * + * @param list $entries @param list $loads @param list $issues + */ + public static function checkStackTopLoad(array $entries, array $loads, array &$issues): void + { + foreach ($entries as $index => $entry) { + $limit = $entry->spec === null ? null : $entry->spec->maxTopLoad; + if ($limit === null || Exact::compare($loads[$index], $limit) <= 0) { + continue; + } + $issues[] = new ResultIssue('top_load_exceeded', PyFormat::str($entry->id) . " bears {$loads[$index]} ticks (limit {$limit})"); + } + } + /**: no `compressible` item may carry more pressure than it declared. @param list $entries @param list $loads @param list $issues */ public static function checkCrush(Label $packedId, array $entries, array $loads, array &$issues): void { @@ -250,7 +339,8 @@ public static function checkCrush(Label $packedId, array $entries, array $loads, if ($limit === null) { continue; } - $pressure = self::pressure($loads[$index], $entry->envelope->baseArea); + [$length, $width] = self::physicalSides($entry->placement); + $pressure = self::pressure($loads[$index], Exact::mul($length, $width)); if ($pressure->compareInt($limit) > 0) { $issues[] = new ResultIssue('crush_violation', PyFormat::str($entry->id) . " in {$packedId}: " . PyFormat::fixed6($pressure->toFloat()) . " kPa exceeds {$limit} kPa"); } @@ -259,27 +349,38 @@ public static function checkCrush(Label $packedId, array $entries, array $loads, /** * Occupied height under load, rounded up, never below one tick. A crushed item keeps its - * height: `checkCrush` already reports it. + * height: `checkCrush` already reports it. The load presses on the item itself, so the + * footprint and the height are its own, not its envelope's. * - * @param int|string $load @return int|string + * @param int $height @param int|string $footprint @param int|string $load @return int|string */ - public static function compressedHeight(Cuboid $envelope, ItemSpec $spec, $load) + public static function compressedHeight(int $height, $footprint, ItemSpec $spec, $load) { $limit = $spec->maxCompressionPressureKpa; if ($limit === null) { - return $envelope->height; + return $height; } if ($spec->compressionRatioPpm === null) { // The reference asserts the pair: a pressure limit without a ratio is not a request it reads. throw MalformedResult::shape("{$spec->id}: max_compression_pressure_kpa without compression_ratio"); } - $pressure = self::pressure($load, $envelope->baseArea); + $pressure = self::pressure($load, $footprint); if ($pressure->compareInt($limit) > 0 || $limit === 0) { - return $envelope->height; + return $height; } $divisor = Exact::mul(Exact::mul($limit, 1000000), $pressure->denominator); $retained = Exact::sub($divisor, Exact::mul($spec->compressionRatioPpm, $pressure->numerator)); - return Exact::max(1, Exact::ceilDiv(Exact::mul($envelope->height, $retained), $divisor)); + return Exact::max(1, Exact::ceilDiv(Exact::mul($height, $retained), $divisor)); + } + + /** The placed item's own sides, without the clearance its envelope adds. @param mixed $placement @return array{0:int,1:int,2:int} */ + private static function physicalSides($placement): array + { + $dimensions = Json::at($placement, 'dimensions'); + $side = static function (string $name) use ($dimensions): int { + return Json::int(Json::at(Json::at($dimensions, $name), 'ticks'), 'a placement dimension'); + }; + return [$side('length'), $side('width'), $side('height')]; } /**: weight per square metre of an item's own base, at every level of the stack. @param list $entries @param list $loads @param int|string $maxDensity @param list $issues */ @@ -415,18 +516,17 @@ public static function validNesting(Entry $left, Entry $right): bool public static function occupiedVolume(Cuboid $envelope, $placement, ?ItemSpec $spec, $load) { if ($spec !== null && $spec->maxCompressionPressureKpa !== null) { - return Exact::mul($envelope->baseArea, self::compressedHeight($envelope, $spec, $load)); + [$length, $width, $height] = self::physicalSides($placement); + $footprint = Exact::mul($length, $width); + return Exact::mul($footprint, self::compressedHeight($height, $footprint, $spec, $load)); } if ($spec !== null && $spec->isConvexHull() && $spec->hullVertices !== null) { return Geometry::hullVolume(Geometry::rotateHull($spec->hullVertices, Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')))); } $solid = self::placedHull($envelope, $placement, $spec); if ($solid === $envelope->vertices()) { - $dimensions = Json::at($placement, 'dimensions'); - $side = static function (string $name) use ($dimensions): int { - return Json::int(Json::at(Json::at($dimensions, $name), 'ticks'), 'a placement dimension'); - }; - return Exact::mul(Exact::mul($side('length'), $side('width')), $side('height')); + [$length, $width, $height] = self::physicalSides($placement); + return Exact::mul(Exact::mul($length, $width), $height); } return Geometry::hullVolume($solid); } diff --git a/src/Algorithm/CandidateFinder.php b/src/Algorithm/CandidateFinder.php index 27e544a..2228eb9 100644 --- a/src/Algorithm/CandidateFinder.php +++ b/src/Algorithm/CandidateFinder.php @@ -4,7 +4,7 @@ use Packvium\Config\PackingConfig; use Packvium\Constraint\{AxleLoad,ConstraintContext,LoadCalculator,PlacementConstraint,SupportConstraint}; use Packvium\Constraint\Internal\ConstraintActivity; -use Packvium\Support\{BigInt,StableSorter}; +use Packvium\Support\{BigInt,ExactInteger,StableSorter}; use Packvium\Domain\{HullShape,ItemInstance,Nesting,Placement,Point,ShapeType}; use Packvium\Extension\CandidateScorer; final class CandidateFinder @@ -143,12 +143,12 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf if($inertChain){ $stats->supportChecks+=$inertSupportChecks; }else{ - $ctx=new ConstraintContext($container,$placed,$item,$point,$rotation,$physical,$envelope,$stackSensitive,$routeSensitive); + $ctx=null; foreach($active as $link=>[$constraint,$countsSupport,$positionIndependent]){ if($countsSupport)$stats->supportChecks++; $allowed=$positionIndependent - ?($fixedVerdicts[$link]??=$constraint->evaluate($ctx)->allowed) - :$constraint->evaluate($ctx)->allowed; + ?($fixedVerdicts[$link]??=$constraint->evaluate($ctx??=new ConstraintContext($container,$placed,$item,$point,$rotation,$physical,$envelope,$stackSensitive,$routeSensitive))->allowed) + :$constraint->evaluate($ctx??=new ConstraintContext($container,$placed,$item,$point,$rotation,$physical,$envelope,$stackSensitive,$routeSensitive))->allowed; if(!$allowed){$blocked=true;break;} } if($blocked)continue; @@ -159,14 +159,14 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf if($defaultScorer){ if($max===1&&$best!==null&&$z1>$best->score[0])continue; if($retained!==null&&$retained->count()===$max&&$z1>$retained->top()->score[0])continue; - $score=[$z1,$z2>$bagZ?$z2:$bagZ,($limitX-$x2)*($limitY-$y2)+($limitZ-$z2),$y1,$x1]; + $score=[$z1,$z2>$bagZ?$z2:$bagZ,self::roomLeftKey($limitX-$x2,$limitY-$y2,$limitZ-$z2),$y1,$x1]; }else{ $score=$scorer->score($state,$point,$envelope); } $position=$tentative?->position; }else{ $score=$defaultScorer - ?[$z1,$z2>$bagZ?$z2:$bagZ,($limitX-$x2)*($limitY-$y2)+($limitZ-$z2),$y1,$x1] + ?[$z1,$z2>$bagZ?$z2:$bagZ,self::roomLeftKey($limitX-$x2,$limitY-$y2,$limitZ-$z2),$y1,$x1] :$scorer->score($state,$point,$envelope); $position=$tentative?->position??new Point($x1+$clearance,$y1+$clearance,$z1+$clearance); $reservePlacement=$tentative??new Placement( @@ -213,6 +213,23 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf return $max===null?$out:array_slice($out,0,$max); } + /** + * `rx * ry + rz`, the score's room-left term, as an order-preserving key: the native + * value while it fits an int, its exact chunks past that. Any chunked key + * outranks every int, as its value does. + * + * @return int|list + */ + public static function roomLeftKey(int $rx,int $ry,int $rz):int|array + { + $area=$rx*$ry; + if(is_int($area)){ + $residual=$area+$rz; + if(is_int($residual))return $residual; + } + return ExactInteger::sortKey(ExactInteger::add(ExactInteger::mul($rx,$ry),$rz)); + } + /** @return list */ private static function nestingPoints(ContainerState $state,ItemInstance $item):array { diff --git a/src/Algorithm/Deadline.php b/src/Algorithm/Deadline.php index 818a4f0..6b44f91 100644 --- a/src/Algorithm/Deadline.php +++ b/src/Algorithm/Deadline.php @@ -131,10 +131,16 @@ public function effortRoom(SearchStats $counted,int $candidates,int $placements, public function expired():bool{return $this->effortStops() || $this->remainingNs()<=0;} public function slice(int $parts):self + { + return $this->share(1,$parts); + } + + /** `$weight / $total` of what is left, never below the minimum slice; all of it when this is the last share. */ + public function share(int $weight,int $total):self { $remaining=$this->remainingNs(); - if($parts<=1)return new self($remaining,$this->clock,$this->effortBudget,$this->stats); - return new self(max(intdiv($remaining,$parts),min($remaining,self::MINIMUM_SLICE_NS)),$this->clock,$this->effortBudget,$this->stats); + if($total<=$weight)return new self($remaining,$this->clock,$this->effortBudget,$this->stats); + return new self(max(intdiv($remaining*$weight,$total),min($remaining,self::MINIMUM_SLICE_NS)),$this->clock,$this->effortBudget,$this->stats); } /** Bind an effort budget to this start's own stats, keeping the same time bound. */ diff --git a/src/Algorithm/FixedPlacementAdmission.php b/src/Algorithm/FixedPlacementAdmission.php index 014f1f8..da6ea65 100644 --- a/src/Algorithm/FixedPlacementAdmission.php +++ b/src/Algorithm/FixedPlacementAdmission.php @@ -3,7 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,FixedPlacement,Item,ItemInstance,PackedContainer,PackingRequest,Placement,Point}; -use Packvium\Support\CanonicalJson; +use Packvium\Support\{CanonicalJson,ExactGeometry,ExactInteger}; use Packvium\Unit\{Length,Weight}; use Packvium\Validation\{FixedPlacementException,IndependentSolutionValidator}; /** @@ -161,7 +161,7 @@ private static function supportRatio(array $others,Placement $placement):float if($placement->envelopeOrigin->z===0)return 1.0; $box=new AxisAlignedBox($placement->envelopeOrigin,$placement->envelopeDimensions); $support=LoadSupportGraph::candidateView($others,$placement->instance,$box); - return $support->supportingArea/$placement->envelopeDimensions->baseAreaTicks(); + return ExactInteger::ratio($support->supportingArea,ExactGeometry::baseArea($placement->envelopeDimensions)); } /** @param list $packed */ diff --git a/src/Algorithm/GridSolver.php b/src/Algorithm/GridSolver.php index 56522f3..eb454cc 100644 --- a/src/Algorithm/GridSolver.php +++ b/src/Algorithm/GridSolver.php @@ -3,6 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container,LatticeSummary,Placement,Point,ShapeType}; +use Packvium\Support\ExactInteger; /** * Regular lattice for a single item type. * @@ -121,7 +122,7 @@ public function packOne(Container $container,int $sequence,array $items,PackingC $ny=intdiv($container->innerDimensions->width->ticks,$envelope->width->ticks); $layerStep=$envelope->height->ticks-$nestingTicks; $innerHeight=$container->innerDimensions->height->ticks; - $nz=$innerHeight<$envelope->height->ticks?0:intdiv($innerHeight-$envelope->height->ticks,$layerStep)+1; + $nz=self::columnLayers($innerHeight,$envelope->height->ticks,$nestingTicks); if($singleLayer)$nz=min($nz,1); // Every item in a uniform column has the same weight. Its bottom item // therefore bears `(nz - 1) * weight`, so the exact greatest safe layer @@ -137,15 +138,16 @@ public function packOne(Container $container,int $sequence,array $items,PackingC // bottom one, which is exactly the count maxStackedItems bounds. The lattice // can express this in its layer count, so it caps rather than falling back. if($prototype->maxStackedItems!==null)$nz=min($nz,$prototype->maxStackedItems+1); - $capacity=$nx*$ny*$nz; - if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems); - if($container->maxPayload!==null&&$prototype->weight->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks,$prototype->weight->ticks)); - foreach(array_intersect($prototype->tags,array_keys($container->tagLimits)) as $tag)$capacity=min($capacity,$container->tagLimits[$tag]); - $score=array_merge([-$capacity],$envelope->volumeKey(),[$rotation->value]); + // Exact: tiny items in a vast container have more lattice slots than an int holds. + $capacity=ExactInteger::mul(ExactInteger::mul($nx,$ny),$nz); + if($container->maxItems!==null)$capacity=self::atMost($capacity,$container->maxItems); + if($container->maxPayload!==null&&$prototype->weight->ticks>0)$capacity=self::atMost($capacity,intdiv($container->maxPayload->ticks,$prototype->weight->ticks)); + foreach(array_intersect($prototype->tags,array_keys($container->tagLimits)) as $tag)$capacity=self::atMost($capacity,$container->tagLimits[$tag]); + $score=array_merge(ExactInteger::descendingKey($capacity),$envelope->volumeKey(),[$rotation->value]); if($best===null||$score<$best[0])$best=[$score,$rotation,$physical,$envelope,$nx,$ny,$layerStep,$capacity]; } [,$rotation,$physical,$envelope,$nx,$ny,$layerStep,$capacity]=$best; - $total=min($capacity,count($items)); + $total=(int)self::atMost($capacity,count($items)); // A group is all-or-nothing: a lattice that cannot hold every member holds none. if($prototype->group!==null&&$totalclearance->ticks; @@ -173,13 +175,13 @@ public function packOne(Container $container,int $sequence,array $items,PackingC return new SingleContainerSolution($state,array_slice($items,$total)); } $targetFootprint=[$physical->length->ticks,$physical->width->ticks,$physical->height->ticks]; - $placed=0; + $placed=0;$perLayer=ExactInteger::mul($nx,$ny); for($index=0;$index<$total;$index++){ if($deadline->expired())break; $stats->searchNodesExpanded++; $stats->candidatePointsConsidered++; - $x=$index%$nx;$y=intdiv($index,$nx)%$ny;$z=intdiv($index,$nx*$ny); - $point=new Point($x*$envelope->length->ticks,$y*$envelope->width->ticks,$z*$layerStep); + $x=$index%$nx;$y=intdiv($index,$nx)%$ny;$z=(int)ExactInteger::floorDiv($index,$perLayer); + $point=new Point($x*$envelope->length->ticks,$y*$envelope->width->ticks,self::columnLayerZ($z,$envelope->height->ticks,$nestingTicks)); $position=new Point($point->x+$clearance,$point->y+$clearance,$point->z+$clearance); // A mixed-declared-type lattice group is only reached when every // item shares the same achievable footprint set, not necessarily the same @@ -200,4 +202,33 @@ public function packOne(Container $container,int $sequence,array $items,PackingC if($prototype->group!==null&&$placedexpired(),true); return new SingleContainerSolution($state,array_slice($items,$placed),false,$placed<$total&&$deadline->expired(),true); } + + /** `min($capacity, $cap)`, exact while the capacity may exceed a native int. */ + private static function atMost(int|string $capacity,int $cap):int|string + { + return ExactInteger::compare($capacity,$cap)>0?$cap:$capacity; + } + + /** + * The bottom of layer `$layer` in a column of identical envelopes `$height` tall that each + * sink `$nesting` into the one beneath. + * + * Only a directly adjacent pair may overlap. Once `2 x nesting > height` a third + * copy sunk into the second would reach into the first, so the column nests in pairs: the + * second sinks into the first and the third rests on the pair. O(1). + */ + private static function columnLayerZ(int $layer, int $height, int $nesting): int + { + if (2 * $nesting <= $height) { return $layer * ($height - $nesting); } + return intdiv($layer, 2) * (2 * $height - $nesting) + ($layer % 2) * ($height - $nesting); + } + + /** How many layers `columnLayerZ` fits under `$room`. O(1). */ + private static function columnLayers(int $room, int $height, int $nesting): int + { + if ($room < $height) { return 0; } + if (2 * $nesting <= $height) { return intdiv($room - $height, $height - $nesting) + 1; } + $pair = 2 * $height - $nesting; + return 2 * intdiv($room, $pair) + ($room % $pair >= $height ? 1 : 0); + } } diff --git a/src/Algorithm/HomogeneousBlockSolver.php b/src/Algorithm/HomogeneousBlockSolver.php index 0bcc11e..697614e 100644 --- a/src/Algorithm/HomogeneousBlockSolver.php +++ b/src/Algorithm/HomogeneousBlockSolver.php @@ -4,11 +4,10 @@ use Packvium\Config\PackingConfig; use Packvium\Config\SolverProfile; -use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Constraint\PlacementConstraint; use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Placement,Point,ShapeType}; use Packvium\Extension\CandidateScorer; -use Packvium\Support\BigInt; +use Packvium\Support\{BigInt,ExactGeometry,ExactInteger}; use Packvium\Unit\Length; /** @@ -95,14 +94,6 @@ public function supports(Container $container,array $items,PackingConfig $config return true; } - /** The share of a member's base that rests on the floor or on a box beneath it. */ - private static function memberSupport(ContainerState $state,ItemInstance $instance,Point $point,Dimensions $envelope):float - { - if($point->z===0)return 1.0; - $support=LoadSupportGraph::candidateView($state->placements,$instance,new AxisAlignedBox($point,$envelope)); - return $support->supportingArea/$envelope->baseAreaTicks(); - } - private function solutionKey(SingleContainerSolution $solution,bool $byVolume=false):array { $signature=[]; @@ -277,7 +268,8 @@ private static function leadingBlocks(array $spaces,array $capacities,array $rot if($envelopeLength>$spaceLength||$envelopeWidth>$spaceWidth)continue; $maximumX=intdiv($spaceLength,$envelopeLength); $maximumY=intdiv($spaceWidth,$envelopeWidth); - $groupNodes=$maximumX*$maximumY<=$capacity?$maximumX*$maximumY:self::latticeNodes($maximumX,$maximumY,$capacity); + $footprintSlots=ExactInteger::mul($maximumX,$maximumY); + $groupNodes=ExactInteger::compare($footprintSlots,$capacity)<=0?(int)$footprintSlots:self::latticeNodes($maximumX,$maximumY,$capacity); // Only a group that reaches a counted limit or a clock read needs the slow path. if($nodes+$groupNodes>$stopAt||(($nodes+$groupNodes-1)>>self::CLOCK_SHIFT)!==(($nodes-1)>>self::CLOCK_SHIFT)){ $expanded=self::expandable($nodes,$groupNodes,$stopAt,$deadline); @@ -286,11 +278,13 @@ private static function leadingBlocks(array $spaces,array $capacities,array $rot }else{$nodes+=$groupNodes;$stats->searchNodesExpanded+=$groupNodes;} if($envelopeHeight>$spaceHeight)continue; $maximumZ=intdiv($spaceHeight,$envelopeHeight); - $whole=$maximumX*$maximumY*$maximumZ; + // Exact: a tiny item in a vast space has more slots than an int holds. + $whole=ExactInteger::mul($footprintSlots,$maximumZ); $volume=$lattice['approximateVolume']; - $largest=$capacity<$whole?$capacity:$whole; + $fitsWhole=ExactInteger::compare($capacity,$whole)>=0; + $largest=$fitsWhole?(int)$whole:$capacity; if($byCount?$largest<$leadCount:$largest*$volume<$leadFloor)continue; - [$count,$nx,$ny,$nz]=$capacity>=$whole?[$whole,$maximumX,$maximumY,$maximumZ]:self::largestBlock($maximumX,$maximumY,$maximumZ,$capacity); + [$count,$nx,$ny,$nz]=$fitsWhole?[$largest,$maximumX,$maximumY,$maximumZ]:self::largestBlock($maximumX,$maximumY,$maximumZ,$capacity); $approximateUsed=$count*$volume; if($byCount?$count<$leadCount:$approximateUsed<$leadFloor)continue; $candidate=['space'=>$space,'itemId'=>$itemId,'rotation'=>$lattice['rotation'],'rotationName'=>$lattice['rotationName'],'physical'=>$lattice['physical'],'envelope'=>$lattice['envelope'],'volume'=>$lattice['volume'],'approximateUsed'=>$approximateUsed,'nx'=>$nx,'ny'=>$ny,'nz'=>$nz,'count'=>$count]; @@ -459,7 +453,7 @@ private static function commit(ContainerState $state,array $spaces,array &$remai return null; } $blockDimensions=new Dimensions(new Length($best['nx']*$best['envelope']->length->ticks),new Length($best['ny']*$best['envelope']->width->ticks),new Length($best['nz']*$best['envelope']->height->ticks)); - return MaximalSpaceSolver::subtractAll($spaces,[new AxisAlignedBox($best['space']->origin,$blockDimensions)],$stats); + return SpaceSubtraction::subtractAll($spaces,[new AxisAlignedBox($best['space']->origin,$blockDimensions)],$stats); } /** @@ -473,14 +467,42 @@ private static function placeMembers(ContainerState $state,array &$remaining,arr { $chosen=array_slice($remaining[$best['itemId']],0,$members); $remaining[$best['itemId']]=array_slice($remaining[$best['itemId']],$members); - $clearance=$config->clearance->ticks;$perLayer=$best['nx']*$best['ny']; + $clearance=$config->clearance->ticks;$perLayer=ExactInteger::mul($best['nx'],$best['ny']); + $dx=$best['envelope']->length->ticks;$dy=$best['envelope']->width->ticks;$dz=$best['envelope']->height->ticks; + $baseZ=$best['space']->origin->z;$baseArea=ExactGeometry::baseArea($best['envelope']); + $supporters=[]; + if($baseZ>0&&$members>0){ + $bx1=$best['space']->origin->x;$by1=$best['space']->origin->y; + $bx2=$bx1+$best['nx']*$dx;$by2=$by1+$best['ny']*$dy; + foreach($state->placements as $existing){ + $eOrigin=$existing->envelopeOrigin;$eDims=$existing->envelopeDimensions; + if($eOrigin->z+$eDims->height->ticks!==$baseZ)continue; + $ox1=$eOrigin->x;$ox2=$ox1+$eDims->length->ticks; + if($ox2<=$bx1||$ox1>=$bx2)continue; + $oy1=$eOrigin->y;$oy2=$oy1+$eDims->width->ticks; + if($oy2<=$by1||$oy1>=$by2)continue; + $supporters[]=[$ox1,$oy1,$ox2,$oy2]; + } + } for($index=0;$index<$members;$index++){ - $x=$index%$best['nx'];$y=intdiv($index,$best['nx'])%$best['ny'];$z=intdiv($index,$perLayer); - $point=new Point($best['space']->origin->x+$x*$best['envelope']->length->ticks,$best['space']->origin->y+$y*$best['envelope']->width->ticks,$best['space']->origin->z+$z*$best['envelope']->height->ticks); - $position=new Point($point->x+$clearance,$point->y+$clearance,$point->z+$clearance); + $x=$index%$best['nx'];$y=intdiv($index,$best['nx'])%$best['ny'];$z=(int)ExactInteger::floorDiv($index,$perLayer); + $px1=$best['space']->origin->x+$x*$dx;$py1=$best['space']->origin->y+$y*$dy;$pz1=$baseZ+$z*$dz; + $point=new Point($px1,$py1,$pz1); + $position=new Point($px1+$clearance,$py1+$clearance,$pz1+$clearance); // Above its bottom layer a member rests on an identical footprint; the // bottom layer rests on whatever is there. - $support=$z===0?self::memberSupport($state,$chosen[$index],$point,$best['envelope']):1.0; + if($z===0&&$baseZ>0){ + $px2=$px1+$dx;$py2=$py1+$dy;$area=0; + foreach($supporters as [$ox1,$oy1,$ox2,$oy2]){ + $ix=($px2<$ox2?$px2:$ox2)-($px1>$ox1?$px1:$ox1); + if($ix<=0)continue; + $iy=($py2<$oy2?$py2:$oy2)-($py1>$oy1?$py1:$oy1); + if($iy>0)$area=ExactInteger::add($area,ExactInteger::mul($ix,$iy)); + } + $support=ExactInteger::ratio($area,$baseArea); + }else{ + $support=1.0; + } $state->addDirect(new Placement($chosen[$index],$position,$best['rotation'],$best['physical'],$point,$best['envelope'],$support)); $stats->candidatesEvaluated++;$stats->placementsAttempted++; } diff --git a/src/Algorithm/Internal/ConcurrentStarts.php b/src/Algorithm/Internal/ConcurrentStarts.php new file mode 100644 index 0000000..21651c6 --- /dev/null +++ b/src/Algorithm/Internal/ConcurrentStarts.php @@ -0,0 +1,142 @@ +new StartRecord($start[0]->name().':'.$start[1],false,false,false), + $starts, + ); + $results=array_fill(0,count($starts),null); + + [$solver0,$orderName0,$order0]=$starts[0]; + $stats0=new SearchStats(); + $budget0=$call('startBudget',$deadline,$effortBudget,$stats0,count($starts)); + [$packed0,$unpacked0,$exhaustive0,$reached0,$dominantLattice0]=$call('acrossContainers',$solver0,$order0,$containers,$config,$stats0,$budget0,$preloaded); + [$wallReached0,$effortReached0]=$call('limitsReached',$reached0,$budget0->effortStopped(),$budget0->remainingNs()); + $unpacked0=$call('effortLimited',$unpacked0,$effortReached0); + $id0=$solver0->name().':'.$orderName0; + $results[0]=new RawSolution($id0,$packed0,$unpacked0,$stats0,$wallReached0,$effortReached0,$exhaustive0); + $records[0]=new StartRecord($id0,true,!$reached0,$reached0); + + // Same correction as the sequential path: only a genuine lattice + // construction is provably no worse than what remains, never a GridSolver + // delegate result -- see `solveSequential`'s identical check for the full + // rationale. + $shortCircuit=$dominantLattice0&&$unpacked0===[]&&$candidateScorer===null; + $remaining=array_slice($starts,1,null,true); + + if($remaining!==[]&&!$shortCircuit&&!$deadline->expired()){ + $absoluteDeadlineNs=hrtime(true)+$deadline->remainingNs(); + $workerCount=max(1,min($config->parallelStarts,count($remaining))); + foreach(array_chunk($remaining,$workerCount,true) as $batch){ + $sockets=[];$pids=[]; + foreach($batch as $position=>[$solver,$orderName,$order]){ + $pair=stream_socket_pair(STREAM_PF_UNIX,STREAM_SOCK_STREAM,STREAM_IPPROTO_IP); + $pid=pcntl_fork(); + if($pid===-1){ + fclose($pair[0]);fclose($pair[1]); + [$results[$position],$records[$position]]=self::runOneStartInProcess($call, + $solver,$orderName,$order,$containers,$config,$effortBudget,$absoluteDeadlineNs,$preloaded, + ); + continue; + } + if($pid===0){ + fclose($pair[0]); + $stats=new SearchStats(); + $budget=Deadline::until($absoluteDeadlineNs); + if($effortBudget!==null)$budget=$budget->withEffort($effortBudget,$stats); + [$packed,$unpacked,$exhaustive,$reached]=$call('acrossContainers',$solver,$order,$containers,$config,$stats,$budget,$preloaded); + // Trusted internal IPC: this payload only ever comes from this + // process's own fork running the exact same code, never from + // external/attacker-controlled input, so the default (allow + // every class) `unserialize()` on the parent's side is safe. + fwrite($pair[1],serialize([$packed,$unpacked,$exhaustive,$reached,$stats,$budget->effortStopped()])); + fclose($pair[1]); + exit(0); + } + fclose($pair[1]); + $sockets[$position]=$pair[0]; + $pids[$position]=$pid; + } + foreach($sockets as $position=>$socket){ + [$solver,$orderName]=$batch[$position]; + $data=stream_get_contents($socket); + fclose($socket); + pcntl_waitpid($pids[$position],$status); + [$packed,$unpacked,$exhaustive,$reached,$stats,$effortStopped]=unserialize($data); + [$wallReached,$effortReached]=$call('limitsReached',$reached,$effortStopped,$absoluteDeadlineNs-hrtime(true)); + $unpacked=$call('effortLimited',$unpacked,$effortReached); + $id=$solver->name().':'.$orderName; + $results[$position]=new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive); + $records[$position]=new StartRecord($id,true,!$reached,$reached); + } + } + } + + $results=array_values(array_filter($results,static fn($result):bool=>$result!==null)); + return $call('finishPortfolio',$items,$containers,$deadline,$results,$records,$preloaded); + } + + /** Fallback body for one start when `pcntl_fork()` itself fails -- runs synchronously, in the parent. */ + public static function runOneStartInProcess(\Closure $call,SingleContainerSolver $solver,string $orderName,array $order,array $containers,PackingConfig $config,?EffortBudget $effortBudget,int $absoluteDeadlineNs,array $preloaded):array + { + $stats=new SearchStats(); + $budget=Deadline::until($absoluteDeadlineNs); + if($effortBudget!==null)$budget=$budget->withEffort($effortBudget,$stats); + [$packed,$unpacked,$exhaustive,$reached,]=$call('acrossContainers',$solver,$order,$containers,$config,$stats,$budget,$preloaded); + [$wallReached,$effortReached]=$call('limitsReached',$reached,$budget->effortStopped(),$budget->remainingNs()); + $unpacked=$call('effortLimited',$unpacked,$effortReached); + $id=$solver->name().':'.$orderName; + return [ + new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive), + new StartRecord($id,true,!$reached,$reached), + ]; + } +} diff --git a/src/Algorithm/Internal/ContainerPlanBeam.php b/src/Algorithm/Internal/ContainerPlanBeam.php new file mode 100644 index 0000000..097116f --- /dev/null +++ b/src/Algorithm/Internal/ContainerPlanBeam.php @@ -0,0 +1,115 @@ +,remaining:list,inventory:array,sequences:array,exhaustive:bool,dominant:bool} $initial + * @return array{0:list,1:list,2:bool,3:bool,4:bool} + */ + public static function acrossContainerPlans(\Closure $call,SingleContainerSolver $solver,array $items,array $containers,PackingConfig $config,SearchStats $stats,Deadline $deadline,array $initial,bool $reached):array + { + // Numbered per container type, as the greedy path and every other engine number + // them: a fixed placement names `#`, so the count must be the type's own. + $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]); + // 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. + $nodeLimit=max($config->containerPlanNodeLimit,$config->containerPlanBeamWidth*count($containers)); + while($beam!==[]&&$nodes<$nodeLimit){ + $expansions=[]; + foreach($beam as $plan){ + if($plan['remaining']===[]||count($plan['packed'])>=$maximum){ + $planScore=self::planScore($plan,$plan['remaining'],$config); + if($planScore<$incumbentScore){$incumbent=$plan;$incumbentScore=$planScore;} + continue; + } + foreach($ordered as $container){ + if($nodes>=$nodeLimit)break; + if($deadline->expired()){$reached=true;break;} + if($plan['inventory'][$container->id]!==null&&$plan['inventory'][$container->id]<=0)continue; + // Each rung is one single-container solve, so the node limit keeps bounding + // the work of a made-to-measure chain. + try{[$one,$trials]=$call('trial',$solver,$container,$plan['sequences'][$container->id]+1,$plan['remaining'],$config,$stats,$deadline);}catch(TimeLimitReached){$nodes++;$reached=true;break;} + $nodes+=$trials; + $reached=$reached||$one->timeLimitReached;if($one->state->placementCount()===0)continue; + [$committed,$ids]=$call('commitState',$one->state);$child=$plan;$child['packed'][]=$committed;$child['remaining']=array_values(array_filter($plan['remaining'],static fn(ItemInstance $item):bool=>!isset($ids[$item->id()])));$child['sequences'][$container->id]++; + if($child['inventory'][$container->id]!==null)$child['inventory'][$container->id]--; + $child['exhaustive']=$plan['exhaustive']&&$one->exhaustive;$child['dominant']=$plan['dominant']&&$one->dominantLattice;$expansions[]=$child; + $childScore=self::planScore($child,$child['remaining'],$config); + if($childScore<$incumbentScore){$incumbent=$child;$incumbentScore=$childScore;} + if($reached)break; + } + if($reached)break; + } + if($reached||$expansions===[])break; + $dominant=[]; + foreach($expansions as $plan){ + $signature=implode('|',array_map(static fn(ItemInstance $item):string=>$item->id(),$plan['remaining'])).'::'.json_encode($plan['inventory'],JSON_THROW_ON_ERROR); + $partialScore=self::planScore($plan,[],$config); + $previous=$dominant[$signature]??null; + if($previous===null||$partialScore<$previous[0])$dominant[$signature]=[$partialScore,$plan]; + } + // planBound re-derives the additive volume/payload relaxation with BigInt + // string math; one evaluation per plan instead of one per stable-usort + // comparison leaves the ordering untouched. + $survivors=array_map(static fn(array $pair):array=>$pair[1],array_values($dominant)); + $beam=count($survivors)>1 + ?array_slice(StableSorter::sortBy($survivors,static fn(array $plan):array=>self::planBound($plan,$containers,$config)),0,$config->containerPlanBeamWidth) + :$survivors; + } + $unpacked=[];$opened=$call('openedByType',$incumbent['packed']);foreach($incumbent['remaining'] as $item){[$reason,$details]=$call('unpackedReason',$item,$containers,$reached);if($reason==='no_feasible_placement'&&$call('supportIsTheBlocker',$item,$incumbent['packed'],$config))$reason='insufficient_support';if($reason==='no_feasible_placement')$reason=$call('limitReason',$item,$containers,$opened,$config)??$reason;$unpacked[]=new UnpackedItem($item,$reason,$details);} + $proven=$incumbent['exhaustive']&&!$reached&&$unpacked===[]&&count($incumbent['packed'])===1; + return [$incumbent['packed'],$unpacked,$proven,$reached,$incumbent['dominant']]; + } + public static function planScore(array $plan,array $remaining,PackingConfig $config):array + { + $unpacked=array_map(static fn(ItemInstance $item):UnpackedItem=>new UnpackedItem($item,'search_exhausted'),$remaining); + $raw=new RawSolution('container_plan',$plan['packed'],$unpacked,new SearchStats()); + return ObjectiveRegistry::resolve($config->objective,$config)->score($raw)->components; + } + + public static function planBound(array $plan,array $containers,PackingConfig $config):array + { + $score=self::planScore($plan,[],$config);$index=$config->objective==='default'?1:2; + $score[$index]+=self::additionalContainerLowerBound($plan,$containers); + $score[]=implode('|',array_map(static fn(ItemInstance $item):string=>$item->id(),$plan['remaining'])); + return $score; + } + + private static function additionalContainerLowerBound(array $plan,array $containers):int + { + $available=array_values(array_filter($containers,static fn(Container $container):bool=>$plan['inventory'][$container->id]===null||$plan['inventory'][$container->id]>0)); + if($plan['remaining']===[]||$available===[])return 0; + $lower=0; + if(!array_filter($plan['remaining'],static fn(ItemInstance $item):bool=>$item->item->nestingHeight!==null)){ + $capacity='0';foreach($available as $container)if(BigInt::compare($container->innerDimensions->volumeString(),$capacity)>0)$capacity=$container->innerDimensions->volumeString(); + if($capacity!=='0'){ + $required='0';foreach($plan['remaining'] as $item)$required=BigInt::add($required,Nesting::itemOccupiedVolume($item)); + $lower=max($lower,(int)BigInt::divide(BigInt::add($required,BigInt::subtract($capacity,'1')),$capacity)); + } + } + if(array_filter($available,static fn(Container $container):bool=>$container->maxPayload===null)===[]){ + $capacity=max(array_map(static fn(Container $container):int=>$container->maxPayload->ticks,$available)); + if($capacity>0){$required=array_sum(array_map(static fn(ItemInstance $item):int=>$item->weight()->ticks,$plan['remaining']));$lower=max($lower,intdiv($required+$capacity-1,$capacity));} + } + return $lower; + } +} diff --git a/src/Algorithm/Internal/MadeToMeasureTrial.php b/src/Algorithm/Internal/MadeToMeasureTrial.php new file mode 100644 index 0000000..d8844e2 --- /dev/null +++ b/src/Algorithm/Internal/MadeToMeasureTrial.php @@ -0,0 +1,55 @@ + $items + * @return array{0:SingleContainerSolution,1:int} + */ + public static function madeToMeasureTrial(\Closure $call,?ContainerSelector $containerSelector,SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array + { + $machine=$container->madeToMeasure; + $maximum=[$container->innerDimensions->length->ticks,$container->innerDimensions->width->ticks,$container->innerDimensions->height->ticks]; + $rungs=$machine->solvingEnvelopes($maximum,MadeToMeasure::instanceEdges($items,$config->clearance->ticks)); + $rungConfig=$config->requirePlacementCoordinates?$config:$call('withCoordinates',$config); + $selector=$containerSelector??new DefaultContainerSelector(); + $best=null;$bestKey=null;$last=null;$stopped=false;$trials=0; + foreach($rungs as $rung){ + try{$one=$solver->packOne($container->withEnvelope($rung),$sequence,$items,$rungConfig,$stats,$deadline);} + catch(TimeLimitReached $limit){if($best===null)throw $limit;$stopped=true;break;} + $trials++; + $stopped=$one->timeLimitReached; + $last=$one; + if($one->state->placementCount()>0){ + $trial=$call('fabricated',$container,$one); + if($one->state->placementCount()===count($items))return [$trial,$trials]; + $key=$call('roundScore',$trial,$items,$config,$selector); + if($best===null||($key<=>$bestKey)<0){$best=$trial;$bestKey=$key;} + } + if($stopped||$deadline->expired()){$stopped=true;break;} + } + $chosen=$best??$last; + return [new SingleContainerSolution($chosen->state,$chosen->unpacked,$chosen->exhaustive,$chosen->timeLimitReached||$stopped,$chosen->dominantLattice),$trials]; + } +} diff --git a/src/Algorithm/Internal/QualityStages.php b/src/Algorithm/Internal/QualityStages.php new file mode 100644 index 0000000..dc24095 --- /dev/null +++ b/src/Algorithm/Internal/QualityStages.php @@ -0,0 +1,66 @@ + $results + * @param array}> $completed + * @return array{0:SingleContainerSolver,1:string,2:list}|null + */ + public static function stagedStart(string $orderName,array $results,array $completed,PackingConfig $config):?array + { + $neighborhood=str_starts_with($orderName,'neighborhood:'); + $eligible=array_values(array_filter( + $results, + static fn(RawSolution $result):bool=>$completed[$result->solverName][0] instanceof ExtremePointSolver + &&(!$neighborhood||str_ends_with($result->solverName,':greedy')), + )); + if($eligible===[])return null; + $scorer=ObjectiveRegistry::resolve($config->objective,$config); + $best=$eligible[0];$bestScore=$scorer->score($best); + foreach(array_slice($eligible,1) as $result){ + $score=$scorer->score($result); + $order=$score->compare($bestScore); + if($order<0||($order===0&&strcmp($result->solverName,$best->solverName)<0)){$best=$result;$bestScore=$score;} + } + [$solver,$baseName,$order]=$completed[$best->solverName]; + if(!$neighborhood)return [$solver,$baseName.':beam',$order]; + $type=substr($orderName,strlen('neighborhood:')); + $late=array_merge( + array_filter($order,static fn(ItemInstance $instance):bool=>$instance->item->id!==$type), + array_filter($order,static fn(ItemInstance $instance):bool=>$instance->item->id===$type), + ); + return [$solver,$baseName.':late_'.$type,$late]; + } + + public static function searchWidth(PackingConfig $config,int $candidatesPerItem,int $beamWidth,int $nodeLimit):PackingConfig + { + return new PackingConfig( + profile:$config->profile,timeLimitMs:$config->timeLimitMs,topK:$config->topK,seed:$config->seed,maxContainers:$config->maxContainers, + clearance:$config->clearance,minimumSupportRatio:$config->minimumSupportRatio,exactItemLimit:$config->exactItemLimit,multiStartOrders:$config->multiStartOrders, + validateResult:$config->validateResult,maxCandidatesPerItem:$candidatesPerItem,maxCandidatePoints:$config->maxCandidatePoints,solvers:$config->solvers,objective:$config->objective, + effortBudget:$config->effortBudget,dimensionalWeightDivisor:$config->dimensionalWeightDivisor,dimensionalWeightLengthUnit:$config->dimensionalWeightLengthUnit, + dimensionalWeightWeightUnit:$config->dimensionalWeightWeightUnit,requirePlacementCoordinates:$config->requirePlacementCoordinates,parallelStarts:1, + containerPlanBeamWidth:$beamWidth,containerPlanNodeLimit:$nodeLimit,accessDirections:$config->accessDirections, + ); + } +} diff --git a/src/Algorithm/LayerSolver.php b/src/Algorithm/LayerSolver.php index 62568ea..88795b0 100644 --- a/src/Algorithm/LayerSolver.php +++ b/src/Algorithm/LayerSolver.php @@ -5,7 +5,7 @@ use Packvium\Constraint\{ConstraintSet,PlacementConstraint}; use Packvium\Domain\{Container,ItemInstance}; use Packvium\Extension\{CandidateScorer,DefaultCandidateScorer}; -use Packvium\Support\StableSorter; +use Packvium\Support\{ExactGeometry,ExactInteger,StableSorter}; final class LayerSolver implements SingleContainerSolver { /** @param list $constraints */ @@ -17,7 +17,7 @@ public function orderInsensitive():bool{return true;} public function packOne(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):SingleContainerSolution { $ordered=StableSorter::sortBy($items,static fn(ItemInstance $i):array=>[ - ...ItemOrdering::lead($i,$config),-$i->dimensions()->baseAreaTicks(),...$i->dimensions()->descendingVolumeKey(),-$i->weight()->ticks,$i->id(), + ...ItemOrdering::lead($i,$config),...ExactInteger::descendingKey(ExactGeometry::baseArea($i->dimensions())),...$i->dimensions()->descendingVolumeKey(),-$i->weight()->ticks,$i->id(), ]); return BeamPacker::pack($container,$sequence,$ordered,$config,ConstraintSet::defaults($config->minimumSupportRatio,$this->constraints,$config->accessDirections),$stats,$deadline,$this->scorer??new DefaultCandidateScorer()); } diff --git a/src/Algorithm/MaximalSpaceSolver.php b/src/Algorithm/MaximalSpaceSolver.php index 069af46..110680b 100644 --- a/src/Algorithm/MaximalSpaceSolver.php +++ b/src/Algorithm/MaximalSpaceSolver.php @@ -3,10 +3,8 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; use Packvium\Constraint\{ConstraintSet,PlacementConstraint}; -use Packvium\Domain\{AxisAlignedBox,Container,Dimensions,ItemInstance,Point}; +use Packvium\Domain\{AxisAlignedBox,Container,ItemInstance,Point}; use Packvium\Extension\{CandidateScorer,DefaultCandidateScorer}; -use Packvium\Support\StableSorter; -use Packvium\Unit\Length; /** * Maximal free spaces plus the common feasibility engine. * @@ -16,18 +14,6 @@ */ final class MaximalSpaceSolver implements SingleContainerSolver { - /** - * Adversarial item mixes can carve far more surviving maximal spaces than any real - * request needs -- growth is roughly linear in placement count once size variety - * defeats the dominance filter below, and every extra space multiplies the - * per-item choose() scan, the carve and subtractAll's O(new * s) dominance check. - * Past this many surviving spaces, the smallest (least likely to fit a future - * item) are dropped first; well under any request this library's tests or - * fixtures exercise. - */ - public const MAX_MAXIMAL_SPACES = 256; - /** Stands in for the six-chunk volume key of a space whose origin no other space shares. */ - private const UNSHARED_ORIGIN_TAIL=[0,0,0,0,0,0]; /** @param list $constraints */ public function __construct(private array $constraints=[],private ?CandidateScorer $scorer=null){} @@ -40,7 +26,7 @@ public function packOne(Container $container,int $sequence,array $items,PackingC $state=new ContainerState($container,$sequence); $obstacleBoxes=array_merge([],...array_map(static fn($o)=>$o->boxes(),$container->obstacles)); foreach($container->preloaded as $placement)$obstacleBoxes[]=$placement->envelopeBox(); - $spaces=self::subtractAll([new Space(new Point(0,0,0),$container->innerDimensions)],$obstacleBoxes,$stats); + $spaces=SpaceSubtraction::subtractAll([new Space(new Point(0,0,0),$container->innerDimensions)],$obstacleBoxes,$stats); $unplaced=[]; $batches=GroupBatcher::batches($items); foreach($batches as $position=>$batch){ @@ -54,7 +40,7 @@ public function packOne(Container $container,int $sequence,array $items,PackingC $chosen=self::choose($state,$spaces,$item,$config,$constraints,$stats,$deadline,$scorer); if($chosen===null){$placed=false;break;} $state=BeamPacker::extended($state,$item,$chosen); - $spaces=self::subtractAll($spaces,[new AxisAlignedBox($chosen->point,$chosen->envelopeDimensions)],$stats); + $spaces=SpaceSubtraction::subtractAll($spaces,[new AxisAlignedBox($chosen->point,$chosen->envelopeDimensions)],$stats); } }catch(TimeLimitReached){ $state=$snapshot; @@ -76,134 +62,4 @@ private static function choose(ContainerState $state,array $spaces,ItemInstance } return null; } - - /** - * The six maximal slabs of an extent that survive carving a box extent out of it, as - * extents, empty ones dropped. - * - * @param array{int,int,int,int,int,int} $s @param array{int,int,int,int,int,int} $b - * @return list - */ - private static function slabs(array $s,array $b):array - { - [$x1,$y1,$z1,$x2,$y2,$z2]=$s; - $out=[]; - foreach([ - [$x1,$y1,$z1,min($x2,$b[0]),$y2,$z2], - [max($x1,$b[3]),$y1,$z1,$x2,$y2,$z2], - [$x1,$y1,$z1,$x2,min($y2,$b[1]),$z2], - [$x1,max($y1,$b[4]),$z1,$x2,$y2,$z2], - [$x1,$y1,$z1,$x2,$y2,min($z2,$b[2])], - [$x1,$y1,max($z1,$b[5]),$x2,$y2,$z2], - ] as $slab)if($slab[3]>$slab[0]&&$slab[4]>$slab[1]&&$slab[5]>$slab[2])$out[]=$slab; - return $out; - } - - /** - * Precondition: $spaces is containment-free -- every call site passes either a - * single whole space or this method's own output. A survivor untouched by every - * carve can therefore neither contain nor be contained by another survivor, and a - * new slab cannot contain it either (the slab's own parent could not), so only - * new slabs need the dominance check below: O(new * s) instead of O(s^2). - * - * Slabs stay integer extents until they survive: a `Space` is built only for a new - * slab that is kept, and the order is one native multi-column sort. - * - * @param list $spaces @param list $boxes @return list - */ - public static function subtractAll(array $spaces,array $boxes,?SearchStats $stats=null):array - { - // [extent, the untouched Space or null for a new slab] - $current=[]; - foreach($spaces as $space){$o=$space->origin;$d=$space->dimensions;$current[]=[[$o->x,$o->y,$o->z,$o->x+$d->length->ticks,$o->y+$d->width->ticks,$o->z+$d->height->ticks],$space];} - foreach($boxes as $box){ - if($stats!==null)$stats->spacePartitions+=count($current); - $b=$box->extent(); - $next=[]; - foreach($current as $entry){ - $e=$entry[0]; - if(!($e[0]<$b[3]&&$e[3]>$b[0]&&$e[1]<$b[4]&&$e[4]>$b[1]&&$e[2]<$b[5]&&$e[5]>$b[2])){$next[]=$entry;continue;} - foreach(self::slabs($e,$b) as $slab)$next[]=[$slab,null]; - } - $current=$next; - } - // A repeated extent keeps its first position and its last entry. - $unique=[]; - foreach($current as $entry)$unique[implode(':',$entry[0])]=$entry; - $unique=array_values($unique); - return self::survivors(self::sortedByOrigin($unique)); - } - - /** - * Ordered by origin z, y, x, then -- only between spaces sharing an origin -- largest - * volume first, then first seen. The volume key is decimal-string arithmetic, so every - * other space gets a same-length zero tail that no comparison reaches. - * - * @param list $entries - * @return list - */ - private static function sortedByOrigin(array $entries):array - { - if(count($entries)<2)return $entries; - $origins=[]; - foreach($entries as [$e])$origins["{$e[0]}:{$e[1]}:{$e[2]}"]=($origins["{$e[0]}:{$e[1]}:{$e[2]}"]??0)+1; - $columns=array_fill(0,10,[]); - foreach($entries as $index=>[$e]){ - $tail=$origins["{$e[0]}:{$e[1]}:{$e[2]}"]>1 - ?(new Dimensions(new Length($e[3]-$e[0]),new Length($e[4]-$e[1]),new Length($e[5]-$e[2])))->descendingVolumeKey() - :self::UNSHARED_ORIGIN_TAIL; - $columns[0][]=$e[2];$columns[1][]=$e[1];$columns[2][]=$e[0]; - foreach($tail as $chunk=>$value)$columns[3+$chunk][]=$value; - $columns[9][]=$index; - } - array_multisort($columns[0],$columns[1],$columns[2],$columns[3],$columns[4],$columns[5],$columns[6],$columns[7],$columns[8],$columns[9]); - return array_map(static fn(int $index):array=>$entries[$index],$columns[9]); - } - - /** - * The sorted entries that no other contains, as spaces, capped at MAX_MAXIMAL_SPACES. - * - * @param list $kept - * @return list - */ - private static function survivors(array $kept):array - { - // Without this filter every placement multiplies the space list and the solver - // degenerates into an exponential scan of overlapping duplicates. - $extents=array_column($kept,0); - $result=[]; - foreach($kept as $index=>[$e,$space]){ - if($space!==null){$result[]=$space;continue;} - if(self::isContained($extents,$index))continue; - $result[]=new Space(new Point($e[0],$e[1],$e[2]),new Dimensions(new Length($e[3]-$e[0]),new Length($e[4]-$e[1]),new Length($e[5]-$e[2]))); - } - if(count($result)>self::MAX_MAXIMAL_SPACES){ - $byVolume=StableSorter::sortBy($result,static fn(Space $space):array=>$space->dimensions->descendingVolumeKey()); - $result=StableSorter::sortBy( - array_slice($byVolume,0,self::MAX_MAXIMAL_SPACES), - static fn(Space $space):array=>[$space->origin->z,$space->origin->y,$space->origin->x], - ); - } - return $result; - } - - /** - * Whether another extent contains `$extents[$index]`, for extents ordered by - * `(z1, y1, x1, -volume)`. - * - * A containing extent starts at or before `$extents[$index]` on every axis and has strictly - * larger volume when origins match, so it always appears at a position `< $index` with - * `$extent[2] <= $z1` already guaranteed. - * - * @param list $extents - */ - private static function isContained(array $extents,int $index):bool - { - [$x1,$y1,,$x2,$y2,$z2]=$extents[$index]; - for($other=0;$other<$index;++$other){ - $extent=$extents[$other]; - if($extent[3]>=$x2&&$extent[4]>=$y2&&$extent[5]>=$z2&&$extent[0]<=$x1&&$extent[1]<=$y1)return true; - } - return false; - } } diff --git a/src/Algorithm/ObjectiveBounds.php b/src/Algorithm/ObjectiveBounds.php index b7d4646..d9bdbca 100644 --- a/src/Algorithm/ObjectiveBounds.php +++ b/src/Algorithm/ObjectiveBounds.php @@ -8,6 +8,8 @@ use Packvium\Domain\ItemInstance; use Packvium\Domain\ShapeType; use Packvium\Support\BigInt; +use Packvium\Support\ExactGeometry; +use Packvium\Support\ExactInteger; /** * Lower bounds on the objective vector, and the gap against an incumbent. @@ -203,7 +205,7 @@ public static function compute(array $instances, array $containers): array $normalisedContainers[] = [ 'usable' => VolumeReserve::usable($container), 'inner' => $container->innerDimensions->volumeString(), - 'base_area' => $container->innerDimensions->baseAreaTicks(), + 'base_area' => ExactGeometry::baseArea($container->innerDimensions), 'height' => $container->innerDimensions->height->ticks, 'payload' => $container->maxPayload?->ticks, 'max_items' => $container->maxItems, @@ -224,7 +226,7 @@ public static function compute(array $instances, array $containers): array * so a port cannot pass the arithmetic check by copying a flag it never computes. * * @param list $instances - * @param list $containers + * @param list $containers * @return array{int,int,int,int,int} */ public static function fromNormalised(array $instances, array $containers): array @@ -243,7 +245,7 @@ public static function fromNormalised(array $instances, array $containers): arra $usable = array_map(static fn(array $c): string => $c['usable'], $containers); $inner = array_map(static fn(array $c): string => $c['inner'], $containers); - $areas = array_map(static fn(array $c): int => $c['base_area'], $containers); + $areas = array_map(static fn(array $c): int|string => ExactInteger::normalize($c['base_area']), $containers); $heights = array_map(static fn(array $c): int => $c['height'], $containers); $payloads = array_map(static fn(array $c): ?int => $c['payload'], $containers); $slots = array_map(static fn(array $c): ?int => $c['max_items'], $containers); @@ -452,7 +454,7 @@ private static function unusedVolumeBound(array $volumes, bool $shrinks, int $pl * before summing. * * @param list $volumes ascending - * @param list $areas + * @param list $areas square ticks, exact past a native int * @param list $heights */ private static function stackHeightBound(array $volumes, bool $shrinks, int $placed, @@ -461,9 +463,9 @@ private static function stackHeightBound(array $volumes, bool $shrinks, int $pla if ($shrinks || $opened <= 0 || $areas === []) { return 0; } - $widest = max($areas); + $widest = array_reduce($areas, ExactInteger::max(...), 0); $tallest = max($heights); - if ($widest <= 0 || $tallest <= 0) { + if (ExactInteger::sign($widest) <= 0 || $tallest <= 0) { return 0; } $required = '0'; diff --git a/src/Algorithm/SolverOrchestrator.php b/src/Algorithm/SolverOrchestrator.php index b0a2351..5c4e851 100644 --- a/src/Algorithm/SolverOrchestrator.php +++ b/src/Algorithm/SolverOrchestrator.php @@ -7,10 +7,16 @@ use Packvium\Domain\{Container,Dimensions,FlatBag,ItemInstance,MadeToMeasure,Nesting,PackedContainer,Rotation,UnpackedItem}; use Packvium\Extension\{CandidateScorer,ContainerSelector,DefaultCandidateScorer,DefaultContainerSelector,ItemOrderStrategy}; use Packvium\Result\StartRecord; -use Packvium\Support\{BigInt,StableSorter}; +use Packvium\Support\{BigInt,ExactGeometry,ExactInteger,StableSorter}; use Packvium\Objective\{LandedCostSolutionScorer,ObjectiveRegistry}; +use Packvium\Algorithm\Internal\{ConcurrentStarts,ContainerPlanBeam,MadeToMeasureTrial,QualityStages}; final class SolverOrchestrator { + /** + * Beam width and candidates per item for the refinement of a winning late-type order + * (`...:late_:beam`), as Python's `LATE_TYPE_REFINEMENT_WIDTH`. + */ + private const LATE_TYPE_REFINEMENT_WIDTH=4; public function __construct(private array $customConstraints=[],private array $customOrders=[],private array $customSolvers=[],private ?CandidateScorer $candidateScorer=null,private ?ContainerSelector $containerSelector=null){} /** @return list */ @@ -34,7 +40,7 @@ public function solvePortfolio(array $items,array $containers,PackingConfig $con $effortBudget=$config->effortBudget; if($effortBudget!==null&&$effortBudget->maxRestarts!==null)$starts=array_slice($starts,0,$effortBudget->maxRestarts); $run=$this->eligibleForConcurrentExecution($deadline,$config)&&count($starts)>1 - ? $this->solveConcurrent($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded) + ? ConcurrentStarts::solveConcurrent($this->bridge(),$this->candidateScorer,$items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded) : $this->solveSequential($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded); return self::withoutABlockStartThatOnlyTies($run,$starts,$config); } @@ -103,16 +109,24 @@ private function solveSequential(array $items,array $containers,PackingConfig $c static fn(array $start):StartRecord=>new StartRecord($start[0]->name().':'.$start[1],false,false,false), $starts, ); + $completed=[]; + $weights=self::sliceWeights($starts); foreach($starts as $position=>[$solver,$orderName,$order]){ if($deadline->expired())break; + if(str_starts_with($orderName,'neighborhood:')||str_ends_with($orderName,':beam')){ + $staged=QualityStages::stagedStart($orderName,$results,$completed,$config); + if($staged===null)continue; + [$solver,$orderName,$order]=$staged; + } $stats=new SearchStats(); - $budget=self::startBudget($deadline,$effortBudget,$stats,count($starts)-$position); - $startConfig=str_ends_with($orderName,':greedy')?self::greedyConfig($config):$config; + $budget=self::startBudget($deadline,$effortBudget,$stats,\array_sum(\array_slice($weights,$position)),$weights[$position]); + $startConfig=self::startConfig($orderName,$config); [$packed,$unpacked,$exhaustive,$reached,$dominantLattice]=$this->acrossContainers($solver,$order,$containers,$startConfig,$stats,$budget,$preloaded); [$wallReached,$effortReached]=self::limitsReached($reached,$budget->effortStopped(),$budget->remainingNs()); $unpacked=self::effortLimited($unpacked,$effortReached); $id=$solver->name().':'.$orderName; $results[]=new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive); + $completed[$id]=[$solver,$orderName,$order]; $records[$position]=new StartRecord($id,true,!$reached,$reached); // A single item type's densest possible packing is the regular lattice grid // just tried: no *default-scored* solver in this portfolio can place it in @@ -143,130 +157,6 @@ private function solveSequential(array $items,array $containers,PackingConfig $c return $this->finishPortfolio($items,$containers,$deadline,$results,$records,$preloaded); } - /** - * Runs every start after the first one concurrently, each in its own forked - * process. - * - * The first start always runs in-process, exactly as `solveSequential` would - * run it: `starts()` always places the order-insensitive lattice first when it - * is eligible at all, so the grid short-circuit below can only ever - * fire on this one start, and running it in-process first keeps that - * short-circuit -- and every sequential-mode test that depends on it -- - * byte-for-byte unchanged. - * - * Every remaining start is forked, bound to one shared absolute deadline - * (`Deadline::until`) computed once, right here, from however much of the - * portfolio's own deadline is left; `hrtime(true)` is machine-wide rather than - * per-process, so every child can independently compare its own fresh reading - * against that same instant. Forks are batched in groups of `parallelStarts` so - * this never spawns more concurrent processes than the caller asked for. - * Results are placed into `$results`/`$records` by each start's fixed position, - * never by completion order, so the final list handed to `Packer::pack`'s - * (order-independent, full-key) ranking is identical no matter how the OS - * scheduled the forked processes. - * - * A child communicates its outcome back to the parent over an anonymous - * `stream_socket_pair` (no disk I/O, unlike a temp file) as one `serialize()`d - * payload, written after the child's own solve finishes and read by the parent - * via a blocking `stream_get_contents` that returns once the child closes its - * end. If `pcntl_fork()` itself fails for one start (a real but rare resource - * exhaustion case), that one start falls back to running synchronously in the - * parent instead of losing it -- correctness never depends on the fork - * succeeding, only on whether that start gets the speed-up. - */ - private function solveConcurrent(array $items,array $containers,PackingConfig $config,Deadline $deadline,array $starts,?EffortBudget $effortBudget,array $preloaded=[]):PortfolioRun - { - $records=array_map( - static fn(array $start):StartRecord=>new StartRecord($start[0]->name().':'.$start[1],false,false,false), - $starts, - ); - $results=array_fill(0,count($starts),null); - - [$solver0,$orderName0,$order0]=$starts[0]; - $stats0=new SearchStats(); - $budget0=self::startBudget($deadline,$effortBudget,$stats0,count($starts)); - [$packed0,$unpacked0,$exhaustive0,$reached0,$dominantLattice0]=$this->acrossContainers($solver0,$order0,$containers,$config,$stats0,$budget0,$preloaded); - [$wallReached0,$effortReached0]=self::limitsReached($reached0,$budget0->effortStopped(),$budget0->remainingNs()); - $unpacked0=self::effortLimited($unpacked0,$effortReached0); - $id0=$solver0->name().':'.$orderName0; - $results[0]=new RawSolution($id0,$packed0,$unpacked0,$stats0,$wallReached0,$effortReached0,$exhaustive0); - $records[0]=new StartRecord($id0,true,!$reached0,$reached0); - - // Same correction as the sequential path: only a genuine lattice - // construction is provably no worse than what remains, never a GridSolver - // delegate result -- see `solveSequential`'s identical check for the full - // rationale. - $shortCircuit=$dominantLattice0&&$unpacked0===[]&&$this->candidateScorer===null; - $remaining=array_slice($starts,1,null,true); - - if($remaining!==[]&&!$shortCircuit&&!$deadline->expired()){ - $absoluteDeadlineNs=hrtime(true)+$deadline->remainingNs(); - $workerCount=max(1,min($config->parallelStarts,count($remaining))); - foreach(array_chunk($remaining,$workerCount,true) as $batch){ - $sockets=[];$pids=[]; - foreach($batch as $position=>[$solver,$orderName,$order]){ - $pair=stream_socket_pair(STREAM_PF_UNIX,STREAM_SOCK_STREAM,STREAM_IPPROTO_IP); - $pid=pcntl_fork(); - if($pid===-1){ - fclose($pair[0]);fclose($pair[1]); - [$results[$position],$records[$position]]=$this->runOneStartInProcess( - $solver,$orderName,$order,$containers,$config,$effortBudget,$absoluteDeadlineNs,$preloaded, - ); - continue; - } - if($pid===0){ - fclose($pair[0]); - $stats=new SearchStats(); - $budget=Deadline::until($absoluteDeadlineNs); - if($effortBudget!==null)$budget=$budget->withEffort($effortBudget,$stats); - [$packed,$unpacked,$exhaustive,$reached]=$this->acrossContainers($solver,$order,$containers,$config,$stats,$budget,$preloaded); - // Trusted internal IPC: this payload only ever comes from this - // process's own fork running the exact same code, never from - // external/attacker-controlled input, so the default (allow - // every class) `unserialize()` on the parent's side is safe. - fwrite($pair[1],serialize([$packed,$unpacked,$exhaustive,$reached,$stats,$budget->effortStopped()])); - fclose($pair[1]); - exit(0); - } - fclose($pair[1]); - $sockets[$position]=$pair[0]; - $pids[$position]=$pid; - } - foreach($sockets as $position=>$socket){ - [$solver,$orderName]=$batch[$position]; - $data=stream_get_contents($socket); - fclose($socket); - pcntl_waitpid($pids[$position],$status); - [$packed,$unpacked,$exhaustive,$reached,$stats,$effortStopped]=unserialize($data); - [$wallReached,$effortReached]=self::limitsReached($reached,$effortStopped,$absoluteDeadlineNs-hrtime(true)); - $unpacked=self::effortLimited($unpacked,$effortReached); - $id=$solver->name().':'.$orderName; - $results[$position]=new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive); - $records[$position]=new StartRecord($id,true,!$reached,$reached); - } - } - } - - $results=array_values(array_filter($results,static fn($result):bool=>$result!==null)); - return $this->finishPortfolio($items,$containers,$deadline,$results,$records,$preloaded); - } - - /** Fallback body for one start when `pcntl_fork()` itself fails -- runs synchronously, in the parent. */ - private function runOneStartInProcess(SingleContainerSolver $solver,string $orderName,array $order,array $containers,PackingConfig $config,?EffortBudget $effortBudget,int $absoluteDeadlineNs,array $preloaded):array - { - $stats=new SearchStats(); - $budget=Deadline::until($absoluteDeadlineNs); - if($effortBudget!==null)$budget=$budget->withEffort($effortBudget,$stats); - [$packed,$unpacked,$exhaustive,$reached,]=$this->acrossContainers($solver,$order,$containers,$config,$stats,$budget,$preloaded); - [$wallReached,$effortReached]=self::limitsReached($reached,$budget->effortStopped(),$budget->remainingNs()); - $unpacked=self::effortLimited($unpacked,$effortReached); - $id=$solver->name().':'.$orderName; - return [ - new RawSolution($id,$packed,$unpacked,$stats,$wallReached,$effortReached,$exhaustive), - new StartRecord($id,true,!$reached,$reached), - ]; - } - /** * The deadline one start runs under. * @@ -276,9 +166,9 @@ private function runOneStartInProcess(SingleContainerSolver $solver,string $orde * deadline and `time_limit_reached` say it did. A slice would let a start the clock cut * lose quietly, making a budgeted answer depend on the machine's speed. */ - private static function startBudget(Deadline $deadline,?EffortBudget $effortBudget,SearchStats $stats,int $startsLeft):Deadline + private static function startBudget(Deadline $deadline,?EffortBudget $effortBudget,SearchStats $stats,int $startsLeft,int $weight=1):Deadline { - if($effortBudget===null)return $deadline->slice($startsLeft); + if($effortBudget===null)return $deadline->share($weight,$startsLeft); return $deadline->withEffort($effortBudget,$stats); } @@ -530,20 +420,57 @@ private function starts(array $items,PackingConfig $config,array $containers=[]) if($orders!==[]&&($blocks=$this->blockStart($items,$config,$containers))!==null)$starts[]=[$blocks,...$orders[0]]; if($config->containerPlanBeamWidth<=1||$config->profile!==SolverProfile::Quality)return $starts; $greedy=array_map(static fn(array $start):array=>$start[0]->name()==='homogeneous_blocks'?$start:[$start[0],$start[1].':greedy',$start[2]],$starts); - $refinements=[];foreach($starts as [$solver,$name,$order])if($solver->name()==='extreme_points'&&count($refinements)<2)$refinements[]=[$solver,$name.':beam',$order]; - return [...$greedy,...$refinements]; + $extreme=null;foreach($starts as $start)if($start[0]->name()==='extreme_points'){$extreme=$start;break;} + if($extreme===null)return $greedy; + // The same stages as Python -- every greedy order, then each item type moved + // last in the best greedy order, then one wide refinement of the best order found. + // The placeholder orders are replaced when the stage runs (`stagedStart`). + $types=array_values(array_unique(array_map(static fn(ItemInstance $instance):string=>$instance->item->id,$items))); + usort($types,'strcmp'); + $neighborhoods=array_map(static fn(string $type):array=>[$extreme[0],'neighborhood:'.$type,$extreme[2]],$types); + return array_merge($greedy,$neighborhoods,[[$extreme[0],'best:beam',$extreme[2]]]); } - private static function greedyConfig(PackingConfig $config):PackingConfig + /** + * Each start's weight in the time slicing, as Python's `_slice_weights`: the late-type + * neighbourhoods are greedy re-runs of one order, so together they weigh one start; with T + * of them each weighs 1 and every other start T. Without them every start weighs 1. + * + * @param list}> $starts + * @return list + */ + private static function sliceWeights(array $starts):array { - return new PackingConfig( - profile:$config->profile,timeLimitMs:$config->timeLimitMs,topK:$config->topK,seed:$config->seed,maxContainers:$config->maxContainers, - clearance:$config->clearance,minimumSupportRatio:$config->minimumSupportRatio,exactItemLimit:$config->exactItemLimit,multiStartOrders:$config->multiStartOrders, - validateResult:$config->validateResult,maxCandidatesPerItem:1,maxCandidatePoints:$config->maxCandidatePoints,solvers:$config->solvers,objective:$config->objective, - effortBudget:$config->effortBudget,dimensionalWeightDivisor:$config->dimensionalWeightDivisor,dimensionalWeightLengthUnit:$config->dimensionalWeightLengthUnit, - dimensionalWeightWeightUnit:$config->dimensionalWeightWeightUnit,requirePlacementCoordinates:$config->requirePlacementCoordinates,parallelStarts:1, - containerPlanBeamWidth:1,containerPlanNodeLimit:1, - ); + $neighbourhoods=0; + foreach($starts as [,$name])if(str_starts_with($name,'neighborhood:'))$neighbourhoods++; + if($neighbourhoods===0)return \array_fill(0,\count($starts),1); + return \array_map(static fn(array $start):int=>str_starts_with($start[1],'neighborhood:')?1:$neighbourhoods,$starts); + } + + /** + * Whether a start keeps one candidate per item: the greedy orders and their late-type + * neighbourhoods. A `:beam` refinement of a winning neighbourhood still carries `:late_` + * in its name, yet it is the one start meant to search wide. + */ + private static function runsGreedy(string $orderName):bool + { + if(str_ends_with($orderName,':beam'))return false; + return str_ends_with($orderName,':greedy')||str_contains($orderName,':late_'); + } + + /** The configuration one portfolio start searches with, as Python's `_start_config`. */ + private static function startConfig(string $orderName,PackingConfig $config):PackingConfig + { + if(self::runsGreedy($orderName))return QualityStages::searchWidth($config,1,1,1); + if(str_ends_with($orderName,':beam')&&str_contains($orderName,':late_')){ + return QualityStages::searchWidth( + $config, + min($config->maxCandidatesPerItem,self::LATE_TYPE_REFINEMENT_WIDTH), + min($config->containerPlanBeamWidth,self::LATE_TYPE_REFINEMENT_WIDTH), + $config->containerPlanNodeLimit, + ); + } + return $config; } /** The same configuration with placement coordinates required: no compact lattice form (D12). */ @@ -610,7 +537,7 @@ private function orders(array $items,PackingConfig $config):array ]; $largeFirst=[ ['volume',static fn(ItemInstance $i):array=>[...ItemOrdering::lead($i,$config),...$i->dimensions()->descendingVolumeKey(),-$i->dimensions()->maxEdge(),-$i->weight()->ticks,$i->id()]], - ['base_area',static fn(ItemInstance $i):array=>[...ItemOrdering::lead($i,$config),-$i->dimensions()->baseAreaTicks(),...$i->dimensions()->descendingVolumeKey(),$i->id()]], + ['base_area',static fn(ItemInstance $i):array=>[...ItemOrdering::lead($i,$config),...ExactInteger::descendingKey(ExactGeometry::baseArea($i->dimensions())),...$i->dimensions()->descendingVolumeKey(),$i->id()]], ['weight',static fn(ItemInstance $i):array=>[...ItemOrdering::lead($i,$config),-$i->weight()->ticks,...$i->dimensions()->descendingVolumeKey(),$i->id()]], ['constrained',static fn(ItemInstance $i):array=>[...ItemOrdering::lead($i,$config),count($i->item->allowedRotations),-$i->item->minimumSupportRatio,...$i->dimensions()->descendingVolumeKey(),$i->id()]], ]; @@ -701,44 +628,7 @@ private static function roundScore(SingleContainerSolution $one,array $roundItem private function trial(SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array { if($container->madeToMeasure===null)return [$solver->packOne($container,$sequence,$items,$config,$stats,$deadline),1]; - return $this->madeToMeasureTrial($solver,$container,$sequence,$items,$config,$stats,$deadline); - } - - /** - * Try each solving envelope in ascending order and keep the first that places every item; - * failing that, the trial this round's own key prefers, the smaller rung on a tie. - * - * At most four solves, two trial states alive. A compact lattice cannot describe a box cut - * to the achieved extent, so the rung solves always report coordinates (D12), and a rung - * choice is a heuristic, so the trial is never exhaustive (D13). - * - * @param list $items - * @return array{0:SingleContainerSolution,1:int} - */ - private function madeToMeasureTrial(SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array - { - $machine=$container->madeToMeasure; - $maximum=[$container->innerDimensions->length->ticks,$container->innerDimensions->width->ticks,$container->innerDimensions->height->ticks]; - $rungs=$machine->solvingEnvelopes($maximum,MadeToMeasure::instanceEdges($items,$config->clearance->ticks)); - $rungConfig=$config->requirePlacementCoordinates?$config:self::withCoordinates($config); - $selector=$this->containerSelector??new DefaultContainerSelector(); - $best=null;$bestKey=null;$last=null;$stopped=false;$trials=0; - foreach($rungs as $rung){ - try{$one=$solver->packOne($container->withEnvelope($rung),$sequence,$items,$rungConfig,$stats,$deadline);} - catch(TimeLimitReached $limit){if($best===null)throw $limit;$stopped=true;break;} - $trials++; - $stopped=$one->timeLimitReached; - $last=$one; - if($one->state->placementCount()>0){ - $trial=self::fabricated($container,$one); - if($one->state->placementCount()===count($items))return [$trial,$trials]; - $key=self::roundScore($trial,$items,$config,$selector); - if($best===null||($key<=>$bestKey)<0){$best=$trial;$bestKey=$key;} - } - if($stopped||$deadline->expired()){$stopped=true;break;} - } - $chosen=$best??$last; - return [new SingleContainerSolution($chosen->state,$chosen->unpacked,$chosen->exhaustive,$chosen->timeLimitReached||$stopped,$chosen->dominantLattice),$trials]; + return MadeToMeasureTrial::madeToMeasureTrial($this->bridge(),$this->containerSelector,$solver,$container,$sequence,$items,$config,$stats,$deadline); } /** A rung trial as the box cut for it: the achieved extent of its placements, envelope far faces with clearance, rounded up onto the machine grid (D14). O(p). */ @@ -754,7 +644,7 @@ private function acrossContainers(SingleContainerSolver $solver,array $items,arr $beam=$config->containerPlanBeamWidth>1&&($this->containerSelector===null||$this->containerSelector instanceof DefaultContainerSelector); [$opened,$reached]=$this->openPreloaded($solver,$preloaded,$items,$containers,$config,$stats,$deadline); if($beam){ - return $this->acrossContainerPlans($solver,$items,$containers,$config,$stats,$deadline,$opened,$reached); + return ContainerPlanBeam::acrossContainerPlans($this->bridge(),$solver,$items,$containers,$config,$stats,$deadline,$opened,$reached); } $remaining=$opened['remaining'];$packed=$opened['packed'];$exhaustive=$opened['exhaustive'];$dominantLattice=$opened['dominant']; $inventory=$opened['inventory'];$seq=$opened['sequences']; @@ -848,96 +738,9 @@ private static function commitState(ContainerState $state):array return [$packed,$ids]; } - private static function planScore(array $plan,array $remaining,PackingConfig $config):array + /** The orchestrator's own private methods, for the parts kept in `Internal` (see there). */ + private function bridge():\Closure { - $unpacked=array_map(static fn(ItemInstance $item):UnpackedItem=>new UnpackedItem($item,'search_exhausted'),$remaining); - $raw=new RawSolution('container_plan',$plan['packed'],$unpacked,new SearchStats()); - return ObjectiveRegistry::resolve($config->objective,$config)->score($raw)->components; - } - - private static function additionalContainerLowerBound(array $plan,array $containers):int - { - $available=array_values(array_filter($containers,static fn(Container $container):bool=>$plan['inventory'][$container->id]===null||$plan['inventory'][$container->id]>0)); - if($plan['remaining']===[]||$available===[])return 0; - $lower=0; - if(!array_filter($plan['remaining'],static fn(ItemInstance $item):bool=>$item->item->nestingHeight!==null)){ - $capacity='0';foreach($available as $container)if(BigInt::compare($container->innerDimensions->volumeString(),$capacity)>0)$capacity=$container->innerDimensions->volumeString(); - if($capacity!=='0'){ - $required='0';foreach($plan['remaining'] as $item)$required=BigInt::add($required,Nesting::itemOccupiedVolume($item)); - $lower=max($lower,(int)BigInt::divide(BigInt::add($required,BigInt::subtract($capacity,'1')),$capacity)); - } - } - if(array_filter($available,static fn(Container $container):bool=>$container->maxPayload===null)===[]){ - $capacity=max(array_map(static fn(Container $container):int=>$container->maxPayload->ticks,$available)); - if($capacity>0){$required=array_sum(array_map(static fn(ItemInstance $item):int=>$item->weight()->ticks,$plan['remaining']));$lower=max($lower,intdiv($required+$capacity-1,$capacity));} - } - return $lower; - } - - private static function planBound(array $plan,array $containers,PackingConfig $config):array - { - $score=self::planScore($plan,[],$config);$index=$config->objective==='default'?1:2; - $score[$index]+=self::additionalContainerLowerBound($plan,$containers); - $score[]=implode('|',array_map(static fn(ItemInstance $item):string=>$item->id(),$plan['remaining'])); - return $score; - } - - /** - * @param array{packed:list,remaining:list,inventory:array,sequences:array,exhaustive:bool,dominant:bool} $initial - * @return array{0:list,1:list,2:bool,3:bool,4:bool} - */ - private function acrossContainerPlans(SingleContainerSolver $solver,array $items,array $containers,PackingConfig $config,SearchStats $stats,Deadline $deadline,array $initial,bool $reached):array - { - // Numbered per container type, as the greedy path and every other engine number - // them: a fixed placement names `#`, so the count must be the type's own. - $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]); - while($beam!==[]&&$nodes<$config->containerPlanNodeLimit){ - $expansions=[]; - foreach($beam as $plan){ - if($plan['remaining']===[]||count($plan['packed'])>=$maximum){ - $planScore=self::planScore($plan,$plan['remaining'],$config); - if($planScore<$incumbentScore){$incumbent=$plan;$incumbentScore=$planScore;} - continue; - } - foreach($ordered as $container){ - if($nodes>=$config->containerPlanNodeLimit)break; - if($deadline->expired()){$reached=true;break;} - if($plan['inventory'][$container->id]!==null&&$plan['inventory'][$container->id]<=0)continue; - // Each rung is one single-container solve, so the node limit keeps bounding - // the work of a made-to-measure chain. - try{[$one,$trials]=$this->trial($solver,$container,$plan['sequences'][$container->id]+1,$plan['remaining'],$config,$stats,$deadline);}catch(TimeLimitReached){$nodes++;$reached=true;break;} - $nodes+=$trials; - $reached=$reached||$one->timeLimitReached;if($one->state->placementCount()===0)continue; - [$committed,$ids]=self::commitState($one->state);$child=$plan;$child['packed'][]=$committed;$child['remaining']=array_values(array_filter($plan['remaining'],static fn(ItemInstance $item):bool=>!isset($ids[$item->id()])));$child['sequences'][$container->id]++; - if($child['inventory'][$container->id]!==null)$child['inventory'][$container->id]--; - $child['exhaustive']=$plan['exhaustive']&&$one->exhaustive;$child['dominant']=$plan['dominant']&&$one->dominantLattice;$expansions[]=$child; - $childScore=self::planScore($child,$child['remaining'],$config); - if($childScore<$incumbentScore){$incumbent=$child;$incumbentScore=$childScore;} - if($reached)break; - } - if($reached)break; - } - if($reached||$expansions===[])break; - $dominant=[]; - foreach($expansions as $plan){ - $signature=implode('|',array_map(static fn(ItemInstance $item):string=>$item->id(),$plan['remaining'])).'::'.json_encode($plan['inventory'],JSON_THROW_ON_ERROR); - $partialScore=self::planScore($plan,[],$config); - $previous=$dominant[$signature]??null; - if($previous===null||$partialScore<$previous[0])$dominant[$signature]=[$partialScore,$plan]; - } - // planBound re-derives the additive volume/payload relaxation with BigInt - // string math; one evaluation per plan instead of one per stable-usort - // comparison leaves the ordering untouched. - $survivors=array_map(static fn(array $pair):array=>$pair[1],array_values($dominant)); - $beam=count($survivors)>1 - ?array_slice(StableSorter::sortBy($survivors,static fn(array $plan):array=>self::planBound($plan,$containers,$config)),0,$config->containerPlanBeamWidth) - :$survivors; - } - $unpacked=[];$opened=self::openedByType($incumbent['packed']);foreach($incumbent['remaining'] as $item){[$reason,$details]=$this->unpackedReason($item,$containers,$reached);if($reason==='no_feasible_placement'&&$this->supportIsTheBlocker($item,$incumbent['packed'],$config))$reason='insufficient_support';if($reason==='no_feasible_placement')$reason=self::limitReason($item,$containers,$opened,$config)??$reason;$unpacked[]=new UnpackedItem($item,$reason,$details);} - $proven=$incumbent['exhaustive']&&!$reached&&$unpacked===[]&&count($incumbent['packed'])===1; - return [$incumbent['packed'],$unpacked,$proven,$reached,$incumbent['dominant']]; + return fn(string $method,...$arguments)=>$this->{$method}(...$arguments); } } diff --git a/src/Algorithm/SpaceSubtraction.php b/src/Algorithm/SpaceSubtraction.php new file mode 100644 index 0000000..66d0129 --- /dev/null +++ b/src/Algorithm/SpaceSubtraction.php @@ -0,0 +1,158 @@ + + */ + private static function slabs(array $s,array $b):array + { + [$x1,$y1,$z1,$x2,$y2,$z2]=$s; + $out=[]; + foreach([ + [$x1,$y1,$z1,min($x2,$b[0]),$y2,$z2], + [max($x1,$b[3]),$y1,$z1,$x2,$y2,$z2], + [$x1,$y1,$z1,$x2,min($y2,$b[1]),$z2], + [$x1,max($y1,$b[4]),$z1,$x2,$y2,$z2], + [$x1,$y1,$z1,$x2,$y2,min($z2,$b[2])], + [$x1,$y1,max($z1,$b[5]),$x2,$y2,$z2], + ] as $slab)if($slab[3]>$slab[0]&&$slab[4]>$slab[1]&&$slab[5]>$slab[2])$out[]=$slab; + return $out; + } + + /** + * Precondition: $spaces is containment-free -- every call site passes either a + * single whole space or this method's own output. A survivor untouched by every + * carve can therefore neither contain nor be contained by another survivor, and a + * new slab cannot contain it either (the slab's own parent could not), so only + * new slabs need the dominance check below: O(new * s) instead of O(s^2). + * + * Slabs stay integer extents until they survive: a `Space` is built only for a new + * slab that is kept, and the order is one native multi-column sort. + * + * @param list $spaces @param list $boxes @return list + */ + public static function subtractAll(array $spaces,array $boxes,?SearchStats $stats=null):array + { + // [extent, the untouched Space or null for a new slab] + $current=[]; + foreach($spaces as $space){$o=$space->origin;$d=$space->dimensions;$current[]=[[$o->x,$o->y,$o->z,$o->x+$d->length->ticks,$o->y+$d->width->ticks,$o->z+$d->height->ticks],$space];} + foreach($boxes as $box){ + if($stats!==null)$stats->spacePartitions+=count($current); + $b=$box->extent(); + $next=[]; + foreach($current as $entry){ + $e=$entry[0]; + if(!($e[0]<$b[3]&&$e[3]>$b[0]&&$e[1]<$b[4]&&$e[4]>$b[1]&&$e[2]<$b[5]&&$e[5]>$b[2])){$next[]=$entry;continue;} + foreach(self::slabs($e,$b) as $slab)$next[]=[$slab,null]; + } + $current=$next; + } + // A repeated extent keeps its first position and its last entry. + $unique=[]; + foreach($current as $entry)$unique[implode(':',$entry[0])]=$entry; + $unique=array_values($unique); + return self::survivors(self::sortedByOrigin($unique)); + } + + /** + * Ordered by origin z, y, x, then -- only between spaces sharing an origin -- largest + * volume first, then first seen. The volume key is decimal-string arithmetic, so every + * other space gets a same-length zero tail that no comparison reaches. + * + * @param list $entries + * @return list + */ + private static function sortedByOrigin(array $entries):array + { + if(count($entries)<2)return $entries; + $origins=[]; + foreach($entries as [$e])$origins["{$e[0]}:{$e[1]}:{$e[2]}"]=($origins["{$e[0]}:{$e[1]}:{$e[2]}"]??0)+1; + $columns=array_fill(0,10,[]); + foreach($entries as $index=>[$e]){ + $tail=$origins["{$e[0]}:{$e[1]}:{$e[2]}"]>1 + ?(new Dimensions(new Length($e[3]-$e[0]),new Length($e[4]-$e[1]),new Length($e[5]-$e[2])))->descendingVolumeKey() + :self::UNSHARED_ORIGIN_TAIL; + $columns[0][]=$e[2];$columns[1][]=$e[1];$columns[2][]=$e[0]; + foreach($tail as $chunk=>$value)$columns[3+$chunk][]=$value; + $columns[9][]=$index; + } + array_multisort($columns[0],$columns[1],$columns[2],$columns[3],$columns[4],$columns[5],$columns[6],$columns[7],$columns[8],$columns[9]); + return array_map(static fn(int $index):array=>$entries[$index],$columns[9]); + } + + /** + * The sorted entries that no other contains, as spaces, capped at MAX_MAXIMAL_SPACES. + * + * @param list $kept + * @return list + */ + private static function survivors(array $kept):array + { + // Without this filter every placement multiplies the space list and the solver + // degenerates into an exponential scan of overlapping duplicates. + $extents=array_column($kept,0); + $result=[]; + foreach($kept as $index=>[$e,$space]){ + if($space!==null){$result[]=$space;continue;} + if(self::isContained($extents,$index))continue; + $result[]=new Space(new Point($e[0],$e[1],$e[2]),new Dimensions(new Length($e[3]-$e[0]),new Length($e[4]-$e[1]),new Length($e[5]-$e[2]))); + } + if(count($result)>self::MAX_MAXIMAL_SPACES){ + $byVolume=StableSorter::sortBy($result,static fn(Space $space):array=>$space->dimensions->descendingVolumeKey()); + $result=StableSorter::sortBy( + array_slice($byVolume,0,self::MAX_MAXIMAL_SPACES), + static fn(Space $space):array=>[$space->origin->z,$space->origin->y,$space->origin->x], + ); + } + return $result; + } + + /** + * Whether another extent contains `$extents[$index]`, for extents ordered by + * `(z1, y1, x1, -volume)`. + * + * A containing extent starts at or before `$extents[$index]` on every axis and has strictly + * larger volume when origins match, so it always appears at a position `< $index` with + * `$extent[2] <= $z1` already guaranteed. + * + * @param list $extents + */ + private static function isContained(array $extents,int $index):bool + { + [$x1,$y1,,$x2,$y2,$z2]=$extents[$index]; + for($other=0;$other<$index;++$other){ + $extent=$extents[$other]; + if($extent[3]>=$x2&&$extent[4]>=$y2&&$extent[5]>=$z2&&$extent[0]<=$x1&&$extent[1]<=$y1)return true; + } + return false; + } +} diff --git a/src/Algorithm/SpatialIndex.php b/src/Algorithm/SpatialIndex.php index 3ea7ead..07d4b62 100644 --- a/src/Algorithm/SpatialIndex.php +++ b/src/Algorithm/SpatialIndex.php @@ -52,9 +52,10 @@ public function copy(): self return clone $this; } + /** Non-negative operands; `n + d - 1` would overflow for a coordinate near `PHP_INT_MAX`. */ private static function ceilDiv(int $numerator, int $denominator): int { - return intdiv($numerator + $denominator - 1, $denominator); + return intdiv($numerator, $denominator) + ($numerator % $denominator === 0 ? 0 : 1); } /** @return array{0:int,1:int,2:int,3:int,4:int,5:int} [ix1,ix2,iy1,iy2,iz1,iz2) */ diff --git a/src/Algorithm/SupportCalculator.php b/src/Algorithm/SupportCalculator.php index a310bf9..7d710f4 100644 --- a/src/Algorithm/SupportCalculator.php +++ b/src/Algorithm/SupportCalculator.php @@ -3,6 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Constraint\Internal\LoadSupportGraph; use Packvium\Domain\{AxisAlignedBox,ItemInstance}; +use Packvium\Support\{ExactGeometry,ExactInteger}; final class SupportCalculator { /** Reported support fraction, from resting contact with other placements only. */ @@ -11,6 +12,6 @@ public static function ratio(ContainerState $state,ItemInstance $item,Candidate if($c->point->z===0)return 1.0; $box=new AxisAlignedBox($c->point,$c->envelopeDimensions); $support=LoadSupportGraph::candidateView($state->placements,$item,$box); - return $support->supportingArea/$c->envelopeDimensions->baseAreaTicks(); + return ExactInteger::ratio($support->supportingArea,ExactGeometry::baseArea($c->envelopeDimensions)); } } diff --git a/src/Artifacts/OperationalArtifact.php b/src/Artifacts/OperationalArtifact.php index 03def28..5c8b0f1 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.8.0'; + public const SUITE_VERSION = '1.9.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/Api.php b/src/Commerce/Api.php index 31ba779..423ee59 100644 --- a/src/Commerce/Api.php +++ b/src/Commerce/Api.php @@ -124,6 +124,7 @@ public static function catalogVersionInfo(array $document, array $request): arra Shape::keys($request, 'request', ['catalog_id', 'resolved_at'], ['version', 'as_of']); $catalogId = Shape::text($request['catalog_id'], 'request.catalog_id'); $resolvedAt = Shape::integer($request['resolved_at'], 'request.resolved_at'); + if ($resolvedAt < 0) { Shape::fail('request.resolved_at', 'cannot be negative'); } $version = ($request['version'] ?? null) === null ? null : Shape::integer($request['version'], 'request.version'); $asOf = ($request['as_of'] ?? null) === null ? null : Shape::integer($request['as_of'], 'request.as_of'); if ($version !== null && $asOf !== null) { Shape::fail('request', "expected at most one of ['version', 'as_of']"); } diff --git a/src/Commerce/Document.php b/src/Commerce/Document.php index d6f010e..f554d74 100644 --- a/src/Commerce/Document.php +++ b/src/Commerce/Document.php @@ -59,7 +59,7 @@ private static function loadTariffs(mixed $value): CarrierRegistry Shape::keys($fields, $path, ['carrier_id', 'service_id', 'versions']); $carrierId = Shape::text($fields['carrier_id'], "{$path}.carrier_id"); $serviceId = Shape::text($fields['service_id'], "{$path}.service_id"); - $key = $carrierId . "\0" . $serviceId; + $key = strlen($carrierId) . ':' . $carrierId . $serviceId; if (isset($seen[$key])) { Shape::fail($path, "duplicate tariff history for {$carrierId}/{$serviceId}"); } $seen[$key] = true; self::publishTariffVersions($registry, $carrierId, $serviceId, $fields['versions'], $path); diff --git a/src/Commerce/Policy/Predicate.php b/src/Commerce/Policy/Predicate.php index aea96b1..b525d82 100644 --- a/src/Commerce/Policy/Predicate.php +++ b/src/Commerce/Policy/Predicate.php @@ -38,7 +38,7 @@ public function matches(array $context): bool } /** - * Value equality over the JSON scalar types, matching the reference implementation's + * Structural equality over JSON values, matching the reference implementation's * semantics exactly -- including that a boolean equals the integer it stands for, * which is the one place a naive `===` would disagree and quietly change a decision. */ @@ -49,9 +49,9 @@ private static function equals(mixed $left, mixed $right): bool return (is_int($left) || is_int($right)) && (int)$left === (int)$right; } if (is_array($left) && is_array($right)) { - if (count($left) !== count($right) || array_keys($left) !== array_keys($right)) { return false; } + if (count($left) !== count($right) || array_is_list($left) !== array_is_list($right)) { return false; } foreach ($left as $key => $entry) { - if (!self::equals($entry, $right[$key])) { return false; } + if (!array_key_exists($key, $right) || !self::equals($entry, $right[$key])) { return false; } } return true; } @@ -64,8 +64,9 @@ private static function contains(mixed $haystack, mixed $needle): bool { if (is_string($haystack)) { return is_string($needle) && ($needle === '' || str_contains($haystack, $needle)); } if (!is_array($haystack)) { - throw new UnsupportedPredicateException('an in/not_in predicate needs a list or string value'); + throw new UnsupportedPredicateException('an in/not_in predicate needs a list, object or string value'); } + if (!array_is_list($haystack)) { return is_string($needle) && array_key_exists($needle, $haystack); } foreach ($haystack as $candidate) { if (self::equals($candidate, $needle)) { return true; } } diff --git a/src/Commerce/Rating/CarrierRegistry.php b/src/Commerce/Rating/CarrierRegistry.php index 49029a4..de1bafc 100644 --- a/src/Commerce/Rating/CarrierRegistry.php +++ b/src/Commerce/Rating/CarrierRegistry.php @@ -143,6 +143,6 @@ public static function rateTariff(Tariff $tariff, RatingRequest $request): RateB private static function key(string $carrierId, string $serviceId): string { - return $carrierId . "\0" . $serviceId; + return strlen($carrierId) . ':' . $carrierId . $serviceId; } } diff --git a/src/Constraint/AxleLoad.php b/src/Constraint/AxleLoad.php index 31c19ce..52a004e 100644 --- a/src/Constraint/AxleLoad.php +++ b/src/Constraint/AxleLoad.php @@ -3,7 +3,7 @@ namespace Packvium\Constraint; use Packvium\Constraint\Internal\AxleTotals; use Packvium\Domain\Axle; -use Packvium\Support\BigInt; +use Packvium\Support\{BigInt,ExactGeometry}; /** * Two-axle weight distribution. @@ -90,7 +90,7 @@ public static function axleBalancedOrigins(array $axles, array $otherUnits, int } $otherDoubledX = BigInt::multiply((string)$tareWeightTicks, (string)$tareDoubledCenterX); foreach ($otherUnits as $unit) { - $doubledCenterX = (string)(2 * $unit->box->origin->x + $unit->box->dimensions->length->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($unit->box->origin->x, $unit->box->dimensions->length->ticks); $otherDoubledX = BigInt::add($otherDoubledX, BigInt::multiply((string)$unit->weightTicks, $doubledCenterX)); } $total = BigInt::add($otherTotal, (string)$itemWeightTicks); diff --git a/src/Constraint/ContactGraph.php b/src/Constraint/ContactGraph.php index ac2a410..1b5dd82 100644 --- a/src/Constraint/ContactGraph.php +++ b/src/Constraint/ContactGraph.php @@ -2,10 +2,12 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Domain\AxisAlignedBox; +use Packvium\Support\ExactGeometry; final readonly class ContactEdge { - public function __construct(public int $index, public int $area) {} + /** @param int|string $area square ticks, exact past a native int */ + public function __construct(public int $index, public int|string $area) {} } /** @@ -155,7 +157,7 @@ public function __construct(array $boxes, int $cellHint = 1) if ($otherIndex === $index) { continue; } - $matches[] = [$otherIndex, $other->overlapAreaXY($box)]; + $matches[] = [$otherIndex, ExactGeometry::overlapAreaXY($other, $box)]; } usort($matches, static fn(array $a, array $b): int => $a[0] <=> $b[0]); foreach ($matches as [$otherIndex, $area]) { @@ -261,7 +263,7 @@ private function matches(array $buckets, array &$cache, int $plane, AxisAlignedB $level = $cache[$plane] ??= new ContactLevelIndex($this->cell, $buckets[$plane]); $matches = []; foreach ($level->near($box) as [$otherIndex, $other]) { - $area = $other->overlapAreaXY($box); + $area = ExactGeometry::overlapAreaXY($other, $box); if ($area > 0) { $matches[] = [$otherIndex, $area]; } diff --git a/src/Constraint/Internal/AxleTotals.php b/src/Constraint/Internal/AxleTotals.php index 68088e1..55ed48c 100644 --- a/src/Constraint/Internal/AxleTotals.php +++ b/src/Constraint/Internal/AxleTotals.php @@ -3,7 +3,7 @@ namespace Packvium\Constraint\Internal; use Packvium\Constraint\LoadUnit; use Packvium\Domain\{AxisAlignedBox,Axle,Placement}; -use Packvium\Support\BigInt; +use Packvium\Support\{BigInt,ExactGeometry}; /** * The exact sums behind the two-axle check: gross weight and doubled @@ -29,7 +29,7 @@ public static function ofPlacements(array $placements, int $tareWeightTicks, int foreach ($placements as $placement) { $weight = (string)$placement->instance->weight()->ticks; $totalWeight = BigInt::add($totalWeight, $weight); - $doubledCenterX = (string)(2 * $placement->envelopeOrigin->x + $placement->envelopeDimensions->length->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($placement->envelopeOrigin->x, $placement->envelopeDimensions->length->ticks); $doubledWeightedX = BigInt::add($doubledWeightedX, BigInt::multiply($weight, $doubledCenterX)); } return [$totalWeight, $doubledWeightedX]; @@ -49,7 +49,7 @@ public static function ofUnits(array $units, int $tareWeightTicks, int $tareDoub } $doubledWeightedX = BigInt::multiply((string)$tareWeightTicks, (string)$tareDoubledCenterX); foreach ($units as $unit) { - $doubledCenterX = (string)(2 * $unit->box->origin->x + $unit->box->dimensions->length->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($unit->box->origin->x, $unit->box->dimensions->length->ticks); $doubledWeightedX = BigInt::add($doubledWeightedX, BigInt::multiply((string)$unit->weightTicks, $doubledCenterX)); } return [$totalWeight, $doubledWeightedX]; @@ -64,7 +64,7 @@ public static function ofUnits(array $units, int $tareWeightTicks, int $tareDoub public static function plus(array $totals, AxisAlignedBox $box, int $weightTicks): array { $weight = (string)$weightTicks; - $doubledCenterX = (string)(2 * $box->origin->x + $box->dimensions->length->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($box->origin->x, $box->dimensions->length->ticks); return [BigInt::add($totals[0], $weight), BigInt::add($totals[1], BigInt::multiply($weight, $doubledCenterX))]; } diff --git a/src/Constraint/Internal/DirectSupportView.php b/src/Constraint/Internal/DirectSupportView.php index 557a7d8..f574d12 100644 --- a/src/Constraint/Internal/DirectSupportView.php +++ b/src/Constraint/Internal/DirectSupportView.php @@ -9,12 +9,12 @@ /** * @param list $supporterIndexes * @param list $supporterBoxes - * @param list $supporterAreas + * @param list $supporterAreas square ticks, exact past a native int */ public function __construct( public array $supporterIndexes, public array $supporterBoxes, public array $supporterAreas, - public int $supportingArea, + public int|string $supportingArea, ){} } diff --git a/src/Constraint/Internal/LoadAnalysis.php b/src/Constraint/Internal/LoadAnalysis.php index 76a796e..8fdba30 100644 --- a/src/Constraint/Internal/LoadAnalysis.php +++ b/src/Constraint/Internal/LoadAnalysis.php @@ -4,7 +4,7 @@ use Packvium\Constraint\{ContactEdge,LoadCalculator,LoadUnit}; use Packvium\Domain\Compression; -use Packvium\Support\{Arithmetic,BigInt}; +use Packvium\Support\{BigInt,ExactGeometry,ExactInteger}; /** * Per-scene load analysis over an already constructed support graph. @@ -50,12 +50,12 @@ public function topLoads():array foreach($order as $upperIndex){ $supports=$graph->supporters($upperIndex); $totalArea=0; - foreach($supports as $edge)$totalArea+=$edge->area; + foreach($supports as $edge)$totalArea=ExactInteger::add($totalArea,$edge->area); if($totalArea===0)continue; $downward=$this->units[$upperIndex]->weightTicks+$loads[$upperIndex]; $assigned=0;$last=count($supports)-1; foreach($supports as $position=>$edge){ - $share=$position===$last?$downward-$assigned:Arithmetic::mulDiv($downward,$edge->area,$totalArea); + $share=$position===$last?$downward-$assigned:ExactInteger::mulDiv($downward,$edge->area,$totalArea); $assigned+=$share; $loads[$edge->index]+=$share; } @@ -93,7 +93,7 @@ public function crushed():?array $limit=$unit->maxCompressionPressureKpa; if($limit===null)continue; $box=$unit->box; - $footprint=($box->x2()-$box->origin->x)*($box->y2()-$box->origin->y); + $footprint=$unit->footprintTicks2??ExactInteger::mul($box->x2()-$box->origin->x,$box->y2()-$box->origin->y); if(Compression::exceeds(Compression::pressure($loads[$index],$footprint),$limit)) return ['crush_violation',$unit->label]; } @@ -201,7 +201,7 @@ public function stackDensityExceeded(?int $maxDensityTicks):?array foreach($this->units as $index=>$unit){ $total=$unit->weightTicks+$loads[$index]; $bearing=BigInt::multiply($total,LoadCalculator::SQUARE_METRE_TICKS); - $allowed=BigInt::multiply($maxDensityTicks,$unit->box->dimensions->baseAreaTicks()); + $allowed=BigInt::multiply($maxDensityTicks,ExactGeometry::baseArea($unit->box->dimensions)); if(BigInt::compare($bearing,$allowed)>0)return ['stack_density_exceeded',$unit->label]; } return null; diff --git a/src/Constraint/Internal/LoadSupportGraph.php b/src/Constraint/Internal/LoadSupportGraph.php index 3b5b520..2a209dd 100644 --- a/src/Constraint/Internal/LoadSupportGraph.php +++ b/src/Constraint/Internal/LoadSupportGraph.php @@ -3,6 +3,7 @@ namespace Packvium\Constraint\Internal; use Packvium\Constraint\{ContactEdge,ContactGraph,LoadUnit}; use Packvium\Domain\{AxisAlignedBox,Item,ItemInstance,Placement}; +use Packvium\Support\{ExactGeometry,ExactInteger}; /** * Direct load support: ordinary face contact plus exact adjacent nesting contact. @@ -28,6 +29,10 @@ final class LoadSupportGraph private ?array $descending=null; /** @var list|null */ private ?array $priorDescending=null; + /** @var list|null */ + private static ?array $cachedPlanePlacements=null; + /** @var array> */ + private static array $cachedByTop=[]; /** @param list $units */ public function __construct(array $units, int $cellHint = 1) @@ -87,7 +92,7 @@ public function __construct(array $units, int $cellHint = 1) ]; if(!$sameColumn)$retained[]=$edge; } - $area=$units[$lowerIndex]->box->overlapAreaXY($units[$upperIndex]->box); + $area=ExactGeometry::overlapAreaXY($units[$lowerIndex]->box,$units[$upperIndex]->box); $insertAt=0;$retainedCount=count($retained); while($insertAt<$retainedCount&&$retained[$insertAt]->index<$lowerIndex)$insertAt++; array_splice($retained,$insertAt,0,[new ContactEdge($lowerIndex,$area)]); @@ -222,12 +227,40 @@ private static function sameNestingColumn(Placement $placement,ItemInstance $ite */ public static function candidateView(array $placements,ItemInstance $item,AxisAlignedBox $box):DirectSupportView { - $supporterEntries=[];$nearestLower=null; $nesting=$item->item->nestingHeight; + if($nesting===null){ + if(self::$cachedPlanePlacements!==$placements){ + $byTop=[]; + foreach($placements as $index=>$placement){ + $other=$placement->envelopeBox(); + $byTop[$other->z2()][]=[$index,$other,$other->origin->x,$other->origin->y,$other->x2(),$other->y2()]; + } + self::$cachedPlanePlacements=$placements; + self::$cachedByTop=$byTop; + } + $plane=self::$cachedByTop[$box->origin->z]??[]; + if($plane===[])return new DirectSupportView([],[],[],0); + $bx1=$box->origin->x;$by1=$box->origin->y;$bx2=$box->x2();$by2=$box->y2(); + $indexes=[];$boxes=[];$areas=[];$totalArea=0; + foreach($plane as [$index,$other,$ox1,$oy1,$ox2,$oy2]){ + $dx=($bx2<$ox2?$bx2:$ox2)-($bx1>$ox1?$bx1:$ox1); + if($dx<=0)continue; + $dy=($by2<$oy2?$by2:$oy2)-($by1>$oy1?$by1:$oy1); + if($dy<=0)continue; + // Native products and sums while they fit; past that the exact forms. + $area=$dx*$dy; + if(!is_int($area))$area=ExactInteger::mul($dx,$dy); + $sum=$totalArea+$area; + $totalArea=is_int($sum)?$sum:ExactInteger::add($totalArea,$area); + $indexes[]=$index;$boxes[]=$other;$areas[]=$area; + } + return new DirectSupportView($indexes,$boxes,$areas,$totalArea); + } + $supporterEntries=[];$nearestLower=null; foreach($placements as $index=>$placement){ $other=$placement->envelopeBox(); if($other->z2()===$box->origin->z){ - $area=$other->overlapAreaXY($box); + $area=ExactGeometry::overlapAreaXY($other,$box); if($area>0)$supporterEntries[]=['index'=>$index,'box'=>$other,'area'=>$area]; } $otherNesting=$placement->instance->item->nestingHeight; @@ -249,12 +282,12 @@ public static function candidateView(array $placements,ItemInstance $item,AxisAl while($supporterAt$predecessor['index'],'box'=>$predecessor['box'], - 'area'=>$predecessor['box']->overlapAreaXY($box), + 'area'=>ExactGeometry::overlapAreaXY($predecessor['box'],$box), ]]); } $indexes=[];$boxes=[];$areas=[];$totalArea=0; foreach($supporterEntries as $entry){ - $indexes[]=$entry['index'];$boxes[]=$entry['box'];$areas[]=$entry['area'];$totalArea+=$entry['area']; + $indexes[]=$entry['index'];$boxes[]=$entry['box'];$areas[]=$entry['area'];$totalArea=ExactInteger::add($totalArea,$entry['area']); } return new DirectSupportView($indexes,$boxes,$areas,$totalArea); } diff --git a/src/Constraint/LoadCalculator.php b/src/Constraint/LoadCalculator.php index bc5160d..b70e6f8 100644 --- a/src/Constraint/LoadCalculator.php +++ b/src/Constraint/LoadCalculator.php @@ -3,6 +3,7 @@ namespace Packvium\Constraint; use Packvium\Constraint\Internal\{LoadAnalysis,LoadSupportGraph}; use Packvium\Domain\Placement; +use Packvium\Support\ExactInteger; use Packvium\Unit\Length; final class LoadCalculator { @@ -23,6 +24,7 @@ public static function units(array $placements,?LoadUnit $extra=null):array $p->envelopeBox(),$p->instance->weight()->ticks,$item->maxTopLoad?->ticks,$item->maxStackedItems,$p->instance->id(), $nesting===null?null:$item->id,$nesting?->ticks, $item->compressionRatioPpm,$item->maxCompressionPressureKpa, + ExactInteger::mul($p->dimensions->length->ticks,$p->dimensions->width->ticks), ); } if($extra!==null)$units[]=$extra; diff --git a/src/Constraint/LoadUnit.php b/src/Constraint/LoadUnit.php index ed4c7d8..51c47d3 100644 --- a/src/Constraint/LoadUnit.php +++ b/src/Constraint/LoadUnit.php @@ -18,5 +18,8 @@ public function __construct( // needs, so the crush check rides the graph that is built anyway. public ?int $compressionRatioPpm=null, public ?int $maxCompressionPressureKpa=null, + // The item's own footprint, which the load presses on; `box` is its envelope, grown by + // the clearance, and it carries the support graph. A decimal string past `int`. + public int|string|null $footprintTicks2=null, ){} } diff --git a/src/Constraint/SupportConstraint.php b/src/Constraint/SupportConstraint.php index 0f2bddb..0910cd2 100644 --- a/src/Constraint/SupportConstraint.php +++ b/src/Constraint/SupportConstraint.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Constraint\Internal\LoadSupportGraph; +use Packvium\Support\{ExactGeometry,ExactInteger}; /** * Support ratios arrive as floats from the public API but must never decide feasibility * in floating point. The ratio is converted once to a scaled integer and the comparison @@ -51,13 +52,13 @@ public function evaluate(ConstraintContext $c):ConstraintResult $required=max($this->globalMinimum,$c->item->item->minimumSupportRatio); if($required<=0)return ConstraintResult::allow(); $area=$support->supportingArea; - $baseArea=$c->envelopeDimensions->baseAreaTicks(); - if($areaenvelopeDimensions); + if(ExactInteger::compare($area,self::exactRequiredArea($baseArea,self::scaled($required)))<0) + return ConstraintResult::reject('insufficient_support',sprintf('%s/%s < %.6f',$area,$baseArea,$required)); // Over half of a rectangle cannot lie strictly to one side of a line through its // centre (central symmetry), so any support covering >50% of the base already // encloses the centroid and needs no hull check. - if($area*2>$baseArea)return ConstraintResult::allow(); + if(ExactInteger::compare(ExactInteger::mul($area,2),$baseArea)>0)return ConstraintResult::allow(); // Area alone is not stability: a candidate can clear the ratio // while overhanging its own centre of gravity, which the ratio check above // cannot see. Checked only once a minimum ratio is already being enforced, @@ -65,7 +66,7 @@ public function evaluate(ConstraintContext $c):ConstraintResult // code and no behaviour change. $hull=SupportPolygon::convexHull(SupportPolygon::contactHullPoints($box,$supporters)); if(!SupportPolygon::pointInHull(SupportPolygon::doubledCentroid($box),$hull)) - return ConstraintResult::reject('centre_of_gravity_unsupported',sprintf('%d/%d met but centroid outside the %d-point support hull',$area,$baseArea,count($hull))); + return ConstraintResult::reject('centre_of_gravity_unsupported',sprintf('%s/%s met but centroid outside the %d-point support hull',$area,$baseArea,count($hull))); return ConstraintResult::allow(); } @@ -102,4 +103,10 @@ public static function requiredArea(int $baseArea,int $scaled):int { return intdiv($baseArea,self::SCALE)*$scaled+intdiv(($baseArea%self::SCALE)*$scaled,self::SCALE); } + + /** `requiredArea` for a base area past a native int too. */ + private static function exactRequiredArea(int|string $baseArea,int $scaled):int|string + { + return is_int($baseArea)?self::requiredArea($baseArea,$scaled):ExactInteger::floorDiv(ExactInteger::mul($baseArea,$scaled),self::SCALE); + } } diff --git a/src/Constraint/SupportPolygon.php b/src/Constraint/SupportPolygon.php index e584d6a..7789396 100644 --- a/src/Constraint/SupportPolygon.php +++ b/src/Constraint/SupportPolygon.php @@ -2,11 +2,17 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Domain\AxisAlignedBox; +use Packvium\Support\ExactInteger as Exact; final readonly class Point2D { - public function __construct(public int $x, public int $y) {} + /** Doubled ticks: native ints while they fit, exact decimal strings beyond. */ + public function __construct(public int|string $x, public int|string $y) {} public function equals(Point2D $other): bool { return $this->x === $other->x && $this->y === $other->y; } + public function compare(Point2D $other): int + { + return Exact::compare($this->x, $other->x) ?: Exact::compare($this->y, $other->y); + } } /** @@ -14,13 +20,18 @@ public function equals(Point2D $other): bool { return $this->x === $other->x && * * Overlap area is not the same as stability: an item can be supported over enough * area and still overhang its own centre of gravity. Every function here is exact - * integer arithmetic, no trig or division. + * integer arithmetic, no trig or division, and stays exact past a native int: two doubled + * coordinates near `PHP_INT_MAX` ticks multiply to what Python and Rust's `i128` still hold. */ final class SupportPolygon { - private static function cross(Point2D $o, Point2D $a, Point2D $b): int + /** The sign of the cross product (a - o) x (b - o). */ + private static function turn(Point2D $o, Point2D $a, Point2D $b): int { - return ($a->x - $o->x) * ($b->y - $o->y) - ($a->y - $o->y) * ($b->x - $o->x); + return Exact::compare( + Exact::mul(Exact::sub($a->x, $o->x), Exact::sub($b->y, $o->y)), + Exact::mul(Exact::sub($a->y, $o->y), Exact::sub($b->x, $o->x)), + ); } /** @@ -36,19 +47,19 @@ public static function convexHull(array $points): array $unique = []; foreach ($points as $p) { $unique["{$p->x},{$p->y}"] = $p; } $pts = array_values($unique); - usort($pts, static fn(Point2D $a, Point2D $b): int => [$a->x, $a->y] <=> [$b->x, $b->y]); + usort($pts, static fn(Point2D $a, Point2D $b): int => $a->compare($b)); if (count($pts) <= 2) { return $pts; } $lower = []; foreach ($pts as $p) { - while (count($lower) >= 2 && self::cross($lower[count($lower) - 2], $lower[count($lower) - 1], $p) <= 0) { + while (count($lower) >= 2 && self::turn($lower[count($lower) - 2], $lower[count($lower) - 1], $p) <= 0) { array_pop($lower); } $lower[] = $p; } $upper = []; foreach (array_reverse($pts) as $p) { - while (count($upper) >= 2 && self::cross($upper[count($upper) - 2], $upper[count($upper) - 1], $p) <= 0) { + while (count($upper) >= 2 && self::turn($upper[count($upper) - 2], $upper[count($upper) - 1], $p) <= 0) { array_pop($upper); } $upper[] = $p; @@ -60,9 +71,14 @@ public static function convexHull(array $points): array private static function onSegment(Point2D $p, Point2D $a, Point2D $b): bool { - if (self::cross($a, $b, $p) !== 0) { return false; } - return min($a->x, $b->x) <= $p->x && $p->x <= max($a->x, $b->x) - && min($a->y, $b->y) <= $p->y && $p->y <= max($a->y, $b->y); + if (self::turn($a, $b, $p) !== 0) { return false; } + return self::between($p->x, $a->x, $b->x) && self::between($p->y, $a->y, $b->y); + } + + private static function between(int|string $value, int|string $end, int|string $other): bool + { + [$low, $high] = Exact::compare($end, $other) <= 0 ? [$end, $other] : [$other, $end]; + return Exact::compare($low, $value) <= 0 && Exact::compare($value, $high) <= 0; } /** Whether `$point` lies inside or on the boundary of a hull from `convexHull`. @param list $hull */ @@ -73,7 +89,7 @@ public static function pointInHull(Point2D $point, array $hull): bool if ($n === 1) { return $point->equals($hull[0]); } if ($n === 2) { return self::onSegment($point, $hull[0], $hull[1]); } for ($i = 0; $i < $n; $i++) { - if (self::cross($hull[$i], $hull[($i + 1) % $n], $point) < 0) { return false; } + if (self::turn($hull[$i], $hull[($i + 1) % $n], $point) < 0) { return false; } } return true; } @@ -97,7 +113,7 @@ public static function contactHullPoints(AxisAlignedBox $candidate, array $suppo $ox2 = min($cx2, $box->x2()); $oy2 = min($cy2, $box->y2()); if ($ox2 > $ox1 && $oy2 > $oy1) { foreach ([$ox1, $ox2] as $x) { - foreach ([$oy1, $oy2] as $y) { $points[] = new Point2D(2 * $x, 2 * $y); } + foreach ([$oy1, $oy2] as $y) { $points[] = new Point2D(Exact::mul(2, $x), Exact::mul(2, $y)); } } } } @@ -107,6 +123,6 @@ public static function contactHullPoints(AxisAlignedBox $candidate, array $suppo /** Twice the box's own footprint centroid, exact for odd as well as even extents. */ public static function doubledCentroid(AxisAlignedBox $box): Point2D { - return new Point2D($box->origin->x + $box->x2(), $box->origin->y + $box->y2()); + return new Point2D(Exact::add($box->origin->x, $box->x2()), Exact::add($box->origin->y, $box->y2())); } } diff --git a/src/Constraint/TopLoadConstraint.php b/src/Constraint/TopLoadConstraint.php index 045b509..35d65d3 100644 --- a/src/Constraint/TopLoadConstraint.php +++ b/src/Constraint/TopLoadConstraint.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint; use Packvium\Constraint\Internal\{LoadAnalysis,PlacedSupportBase}; +use Packvium\Support\ExactInteger; /** * Rejects a placement that would rest on something unable to carry it. * @@ -23,6 +24,7 @@ public function evaluate(ConstraintContext $c):ConstraintResult $c->envelopeBox(),$c->item->weight()->ticks,$item->maxTopLoad?->ticks,$item->maxStackedItems,$c->item->id(), $item->nestingHeight===null?null:$item->id,$item->nestingHeight?->ticks, $item->compressionRatioPpm,$item->maxCompressionPressureKpa, + ExactInteger::mul($c->dimensions->length->ticks,$c->dimensions->width->ticks), ); [$units,$graph]=($this->support??=new PlacedSupportBase())->withCandidate($c->placements,$unit); $nonStackable=$graph->nonStackableFailure($c->placements,$c->item,count($units)-1); diff --git a/src/Domain/CentreOfMass.php b/src/Domain/CentreOfMass.php index 6df7dca..af2df31 100644 --- a/src/Domain/CentreOfMass.php +++ b/src/Domain/CentreOfMass.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; use Packvium\Support\BigInt; +use Packvium\Support\ExactGeometry; /** * How far the weighted centre of mass sits from the container's own centre. @@ -41,8 +42,8 @@ public static function offsetPpm(Dimensions $inner, array $placements): int $doubledWeightedY = '0'; foreach ($placements as $p) { $weight = (string)$p->instance->weight()->ticks; - $doubledCenterX = (string)(2 * $p->position->x + $p->dimensions->length->ticks); - $doubledCenterY = (string)(2 * $p->position->y + $p->dimensions->width->ticks); + $doubledCenterX = ExactGeometry::doubledCentre($p->position->x, $p->dimensions->length->ticks); + $doubledCenterY = ExactGeometry::doubledCentre($p->position->y, $p->dimensions->width->ticks); $doubledWeightedX = BigInt::add($doubledWeightedX, BigInt::multiply($weight, $doubledCenterX)); $doubledWeightedY = BigInt::add($doubledWeightedY, BigInt::multiply($weight, $doubledCenterY)); } diff --git a/src/Domain/Compression.php b/src/Domain/Compression.php index 8a68ede..573260a 100644 --- a/src/Domain/Compression.php +++ b/src/Domain/Compression.php @@ -39,9 +39,9 @@ final class Compression * * @return array{string,string} numerator and denominator, both non-negative */ - public static function pressure(int $topLoadTicks, int $footprintAreaTicks): array + public static function pressure(int $topLoadTicks, int|string $footprintAreaTicks): array { - if ($footprintAreaTicks <= 0) { + if (\Packvium\Support\ExactInteger::sign($footprintAreaTicks) <= 0) { throw new InvalidArgumentException('footprint area must be positive'); } $metre = Length::TICKS_PER_MM * 1000; diff --git a/src/Domain/Container.php b/src/Domain/Container.php index 40375e7..9dd8df7 100644 --- a/src/Domain/Container.php +++ b/src/Domain/Container.php @@ -42,7 +42,7 @@ public function __construct(public string $id,public Dimensions $innerDimensions 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=array_values(array_filter(SweptRegion::ALL_DIRECTIONS,static fn(string $d):bool=>in_array($d,$accessDirections,true)));} + $this->accessDirections=$accessDirections===[]?[]:array_values(array_filter(SweptRegion::ALL_DIRECTIONS,static fn(string $d):bool=>in_array($d,$accessDirections,true)));} /** The same container holding `$placements` before search. @param list $placements */ public function withPreloaded(array $placements):self{return new self($this->id,$this->innerDimensions,$this->outerDimensions,$this->tareWeight,$this->maxPayload,$this->costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$placements,$this->deformableBoundary,$this->madeToMeasure);} public function isFlatBag():bool{return $this->deformableBoundary!==null;} diff --git a/src/Domain/LatticeSummary.php b/src/Domain/LatticeSummary.php index 45137a7..24a86cf 100644 --- a/src/Domain/LatticeSummary.php +++ b/src/Domain/LatticeSummary.php @@ -4,6 +4,7 @@ use InvalidArgumentException; use Packvium\Support\BigInt; +use Packvium\Support\ExactInteger; /** * Compact, O(1)-to-build description of one GridSolver regular-lattice run. @@ -45,9 +46,11 @@ public function __construct( if ($nx <= 0 || $ny <= 0) { throw new InvalidArgumentException('a lattice summary requires positive per-axis capacity'); } } - private function perLayer(): int { return $this->nx * $this->ny; } - public function fullLayers(): int { return intdiv($this->count, $this->perLayer()); } - public function remainder(): int { return $this->count % $this->perLayer(); } + /** Exact past a native int: a tiny item in a vast container has more slots per layer than an int holds. */ + private function perLayer(): int|string { return ExactInteger::mul($this->nx, $this->ny); } + /** An int: `count` is one, and the quotient is no larger. */ + public function fullLayers(): int { return (int)ExactInteger::floorDiv($this->count, $this->perLayer()); } + public function remainder(): int { return (int)ExactInteger::mod($this->count, $this->perLayer()); } public function layersUsed(): int { return $this->fullLayers() + ($this->remainder() > 0 ? 1 : 0); } /** Plain `int`, matching `Weight::$ticks` and the existing per-placement summation this replaces. */ @@ -71,7 +74,16 @@ public function maxZTicks(): int return $topLayerIndex * $this->layerStep + $this->envelope->height->ticks; } - private function triangular(int $n): int { return intdiv($n * ($n - 1), 2); } + private function triangular(int $n): int|string { return ExactInteger::floorDiv(ExactInteger::mul($n, $n - 1), 2); } + + /** `2 * pitch * indexSum + count * (2 * clearance + side)`: the lattice's doubled centres summed along one axis. */ + private function doubledCentreSum(int $pitch, int|string $indexSum, int $clearance, int $side): int|string + { + return ExactInteger::add( + ExactInteger::mul(ExactInteger::mul(2, $pitch), $indexSum), + ExactInteger::mul($this->count, 2 * $clearance + $side), + ); + } /** * Closed-form equivalent of CentreOfMass::offsetPpm for a uniform lattice of @@ -93,13 +105,23 @@ public function centreOfMassOffsetPpm(int $innerLengthTicks, int $innerWidthTick $rowsInPartial = intdiv($remainder, $nx); $extraCols = $remainder % $nx; - $sumX = $fullLayers * $ny * $this->triangular($nx) + $rowsInPartial * $this->triangular($nx) + $this->triangular($extraCols); - $sumY = $fullLayers * $nx * $this->triangular($ny) + $nx * $this->triangular($rowsInPartial) + $extraCols * $rowsInPartial; + // Exact throughout: a lattice index sum times a doubled pitch passes a native int + // long before the container does. + $sumX = ExactInteger::sum([ + ExactInteger::mul(ExactInteger::mul($fullLayers, $ny), $this->triangular($nx)), + ExactInteger::mul($rowsInPartial, $this->triangular($nx)), + $this->triangular($extraCols), + ]); + $sumY = ExactInteger::sum([ + ExactInteger::mul(ExactInteger::mul($fullLayers, $nx), $this->triangular($ny)), + ExactInteger::mul($nx, $this->triangular($rowsInPartial)), + ExactInteger::mul($extraCols, $rowsInPartial), + ]); $clearance = $this->clearanceTicks; $weight = (string)$this->weightTicks; - $doubledWeightedX = BigInt::multiply($weight, (string)(2 * $this->envelope->length->ticks * $sumX + $this->count * (2 * $clearance + $this->physical->length->ticks))); - $doubledWeightedY = BigInt::multiply($weight, (string)(2 * $this->envelope->width->ticks * $sumY + $this->count * (2 * $clearance + $this->physical->width->ticks))); + $doubledWeightedX = BigInt::multiply($weight, (string)$this->doubledCentreSum($this->envelope->length->ticks, $sumX, $clearance, $this->physical->length->ticks)); + $doubledWeightedY = BigInt::multiply($weight, (string)$this->doubledCentreSum($this->envelope->width->ticks, $sumY, $clearance, $this->physical->width->ticks)); $totalWeight = (string)$this->totalWeightTicks(); $offsetXPpm = $this->axisOffsetPpm($doubledWeightedX, $totalWeight, (string)$innerLengthTicks); @@ -128,7 +150,7 @@ public function expand(array $items): array $nx = $this->nx; $ny = $this->ny; $layerStep = $this->layerStep; $clearance = $this->clearanceTicks; $out = []; for ($index = 0; $index < $this->count; $index++) { - $x = $index % $nx; $y = intdiv($index, $nx) % $ny; $z = intdiv($index, $nx * $ny); + $x = $index % $nx; $y = intdiv($index, $nx) % $ny; $z = (int)ExactInteger::floorDiv($index, $this->perLayer()); $point = new Point($x * $this->envelope->length->ticks, $y * $this->envelope->width->ticks, $z * $layerStep); $position = new Point($point->x + $clearance, $point->y + $clearance, $point->z + $clearance); $out[] = new Placement($items[$index], $position, $this->rotation, $this->physical, $point, $this->envelope, 1.0); diff --git a/src/Domain/Nesting.php b/src/Domain/Nesting.php index f1266ee..3964122 100644 --- a/src/Domain/Nesting.php +++ b/src/Domain/Nesting.php @@ -1,7 +1,7 @@ z2() - $high->origin->z === $nesting->ticks; } + /** + * The physical space a valid nesting pair shares, as a decimal string. + * + * The pair sinks by `nestingHeight` envelope to envelope, so under a clearance the items + * themselves overlap by twice the clearance less, over their own footprint rather than + * the envelope's. Equal to `nestingHeight x base area` with no clearance. O(1). + */ + private static function nestedOverlap(Placement $lower, Placement $upper): string + { + $a = $lower->box(); $b = $upper->box(); + $height = min($a->z2(), $b->z2()) - max($a->origin->z, $b->origin->z); + return $height > 0 ? BigInt::multiply((string)ExactGeometry::overlapAreaXY($a, $b), (string)$height) : '0'; + } + /** * Total double-counted volume between adjacent nested layers, as a decimal * string -- nesting depth times base area can overflow a 64-bit int for a @@ -58,8 +72,7 @@ private static function overlapVolume(array $placements): string for ($i = 0; $i < count($group) - 1; $i++) { $lower = $group[$i]; $upper = $group[$i + 1]; if (self::isValidNesting($lower, $upper)) { - $slice = BigInt::multiply((string)$lower->instance->item->nestingHeight->ticks, (string)$lower->envelopeDimensions->baseAreaTicks()); - $overlap = BigInt::add($overlap, $slice); + $overlap = BigInt::add($overlap, self::nestedOverlap($lower, $upper)); } } } @@ -84,7 +97,7 @@ public static function occupiedVolume(Placement $placement): string } if ($item->maxCompressionPressureKpa === null) { return $placement->dimensions->volumeString(); } $dimensions = $placement->dimensions; - $footprint = $dimensions->baseAreaTicks(); + $footprint = ExactGeometry::baseArea($dimensions); $pressure = Compression::pressure($placement->topLoad->ticks, $footprint); // A crushed item has no meaningful occupied volume, and the arrangement is already // invalid -- the crush check refuses it and the validator reports it. Reporting the @@ -146,8 +159,7 @@ public static function usedVolumeDelta(array $placements, Placement $placement): $overlap = '0'; foreach ($placements as $existing) { if (!self::isValidNesting($existing, $placement)) { continue; } - $slice = BigInt::multiply((string)$nesting->ticks, (string)$placement->envelopeDimensions->baseAreaTicks()); - $overlap = BigInt::add($overlap, $slice); + $overlap = BigInt::add($overlap, self::nestedOverlap($existing, $placement)); } return BigInt::subtract($placement->dimensions->volumeString(), $overlap); } diff --git a/src/Domain/PackedContainer.php b/src/Domain/PackedContainer.php index 8cbfc82..2b2a9e0 100644 --- a/src/Domain/PackedContainer.php +++ b/src/Domain/PackedContainer.php @@ -1,6 +1,7 @@ latticeSummary !== null ? $this->latticeSummary->usedVolumeString() : Nesting::usedVolume($this->placements); } - public function utilization():float{return (float)$this->usedVolumeString()/$this->container->innerDimensions->volumeScore();} + /** Python's `used / inner` exactly rounded: two doubles divided would round twice, and a volume in cubic ticks passes 2^53 at a few centimetres. */ + public function utilization():float{return ExactInteger::ratio($this->usedVolumeString(),$this->container->innerDimensions->volumeString());} public function maxZTicks(): int { diff --git a/src/Extension/CandidateScorer.php b/src/Extension/CandidateScorer.php index 018c3e2..5db559c 100644 --- a/src/Extension/CandidateScorer.php +++ b/src/Extension/CandidateScorer.php @@ -4,9 +4,10 @@ use Packvium\Algorithm\ContainerState; use Packvium\Domain\{Dimensions,Point}; /** - * Ranks feasible placements. Lower sorts first. + * Ranks feasible placements. Lower sorts first, by PHP array comparison: a component may be + * an exact chunk key (see `ExactInteger::sortKey`) where an int would overflow. * * Receives the origin and envelope rather than a Candidate so the finder does not have * to build a throwaway object for every point/rotation pair it scores. */ -interface CandidateScorer{/** @return list */public function score(ContainerState $state,Point $point,Dimensions $envelope):array;} +interface CandidateScorer{/** @return list> */public function score(ContainerState $state,Point $point,Dimensions $envelope):array;} diff --git a/src/Extension/DefaultCandidateScorer.php b/src/Extension/DefaultCandidateScorer.php index 061e5f8..eaf7644 100644 --- a/src/Extension/DefaultCandidateScorer.php +++ b/src/Extension/DefaultCandidateScorer.php @@ -1,9 +1,9 @@ length->ticks-($point->x+$envelope->length->ticks); $ry=$inner->width->ticks-($point->y+$envelope->width->ticks); $rz=$inner->height->ticks-($point->z+$envelope->height->ticks); - return [$point->z,$newHeight,$rx*$ry+$rz,$point->y,$point->x]; + return [$point->z,$newHeight,CandidateFinder::roomLeftKey($rx,$ry,$rz),$point->y,$point->x]; } } diff --git a/src/Objective/ObjectiveRegistry.php b/src/Objective/ObjectiveRegistry.php index 4a39e35..f65faef 100644 --- a/src/Objective/ObjectiveRegistry.php +++ b/src/Objective/ObjectiveRegistry.php @@ -22,10 +22,12 @@ public static function resolve(string $name, ?PackingConfig $config = null): Sol self::$factories ??= [ 'default' => static fn(?PackingConfig $config) => new DefaultSolutionScorer(), 'lowest_cost' => static fn(?PackingConfig $config) => new LowestCostSolutionScorer(), - 'shipping_cost' => ShippingCostSolutionScorer::fromConfig(...), + // Arrow functions rather than first-class callables, which load their class at once: + // without opcache every request compiles what it loads (1.9.0 release frontier). + 'shipping_cost' => static fn(?PackingConfig $config) => ShippingCostSolutionScorer::fromConfig($config), // Inherits the divisor requirement: landed cost is priced off billed // weight, so it needs the same dimensional-weight inputs. - 'lowest_landed_cost' => LandedCostSolutionScorer::fromConfig(...), + 'lowest_landed_cost' => static fn(?PackingConfig $config) => LandedCostSolutionScorer::fromConfig($config), 'open_dimension_height' => static fn(?PackingConfig $config) => new OpenDimensionSolutionScorer(), 'maximum_value' => static fn(?PackingConfig $config) => new MaximumValueSolutionScorer(), 'maximum_volume' => static fn(?PackingConfig $config) => new MaximumVolumeSolutionScorer(), diff --git a/src/Packer.php b/src/Packer.php index 4f131f5..8161cf3 100644 --- a/src/Packer.php +++ b/src/Packer.php @@ -3,7 +3,7 @@ namespace Packvium; -use Packvium\Algorithm\{Deadline, FixedPlacementAdmission, ObjectiveBoundScope, ObjectiveBounds, SolverOrchestrator}; +use Packvium\Algorithm\{Deadline, FixedLoad, FixedPlacementAdmission, ObjectiveBoundScope, ObjectiveBounds, SolverOrchestrator}; use Packvium\Support\{RequestObjects, StableSorter, UnsupportedPlacements}; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, UnratedWeightException}; @@ -120,7 +120,9 @@ private function solve(array $items, array $containers, array $fixedPlacements): } } } - $fixed = FixedPlacementAdmission::admit( + // Without fixed placements every instance is free; answered here so a request that + // fixes nothing never compiles the admission it does not use. + $fixed = $request->fixedPlacements === [] ? new FixedLoad([], $request->instances()) : FixedPlacementAdmission::admit( $request, $this->config->minimumSupportRatio, $this->config->clearance, @@ -243,7 +245,8 @@ private function solve(array $items, array $containers, array $fixedPlacements): // refused -- the same refusal the other three engines give, in the same words. The // refusal is deliberately here and not in the scorer: throwing while *comparing* // candidates would abort runs that have a perfectly shippable answer. - $unpriceable = LandedCostSolutionScorer::unpriceableContainer($best->containers, $this->config); + $landed = $this->config->objective === 'lowest_landed_cost'; + $unpriceable = $landed ? LandedCostSolutionScorer::unpriceableContainer($best->containers, $this->config) : null; if ($unpriceable !== null) { [$containerId, $grams, $bound] = $unpriceable; throw new UnratedWeightException( @@ -258,8 +261,8 @@ private function solve(array $items, array $containers, array $fixedPlacements): $alternatives = array_slice( array_values(array_filter( array_slice($selected, 1), - fn(PackingResult $result): bool => - LandedCostSolutionScorer::unpriceableContainer($result->containers, $this->config) === null, + fn(PackingResult $result): bool => !$landed + || LandedCostSolutionScorer::unpriceableContainer($result->containers, $this->config) === null, )), 0, max(0, $this->config->topK - 1), diff --git a/src/Sequence/LoadingDependencyGraph.php b/src/Sequence/LoadingDependencyGraph.php index d822c26..a38dcd1 100644 --- a/src/Sequence/LoadingDependencyGraph.php +++ b/src/Sequence/LoadingDependencyGraph.php @@ -206,39 +206,82 @@ public static function verifyLoadingPrefixBusinessRules(array $placements, array if ($sortedOrder !== $expected) { throw new SequenceReplayError(-1, -1, 'order is not a permutation of every placement index exactly once'); } + if ($placements === []) { + return; + } $maxDensityTicks = $container->maxStackDensity?->ticks; // A caller may hand this any scene, validated or not, so the stacking-group rule is // re-checked here too -- only when some item declares a list, and only on the edges // of the step's own new placement, since every earlier edge was judged at its step. $grouped = false; + $hasNonStackable = false; + $hasLoadLimits = false; + $hasGroundRules = false; foreach ($placements as $placement) { - $grouped = $grouped || $placement->instance->item->acceptsStackingGroups !== []; + $item = $placement->instance->item; + $grouped = $grouped || $item->acceptsStackingGroups !== []; + $hasNonStackable = $hasNonStackable || !$item->stackable; + $hasLoadLimits = $hasLoadLimits || $item->maxTopLoad !== null || $item->maxStackedItems !== null; + $hasGroundRules = $hasGroundRules || ( + $item->groundContactRule !== null + && $item->groundContactRule !== 'free' + && $placement->envelopeBox()->origin->z !== 0 + ); + } + $hasLoadRules = $maxDensityTicks !== null || $grouped || $hasNonStackable || $hasLoadLimits; + if (!$hasLoadRules && !$hasGroundRules) { + return; } + $allUnits = LoadCalculator::units($placements); $present = []; + $units = []; + $elevatedBases = []; + $anyNesting = false; foreach ($order as $step => $index) { - $present[] = $placements[$index]; - $units = LoadCalculator::units($present); - $analysis = new \Packvium\Constraint\Internal\LoadAnalysis($units); - $problem = $analysis->overloaded() - ?? $analysis->stackLimitExceeded() - ?? $analysis->stackDensityExceeded($maxDensityTicks); - if ($problem === null) { - $counts = $analysis->stackedCounts(); - foreach ($units as $unitIndex => $unit) { - if (!$present[$unitIndex]->instance->item->stackable && $counts[$unitIndex] > 0) { - $problem = ['non_stackable_item_has_load', $unit->label]; - break; + $candidate = $placements[$index]; + $unit = $allUnits[$index]; + $present[] = $candidate; + $units[] = $unit; + $candidateBox = $candidate->envelopeBox(); + if ($candidateBox->origin->z !== 0) { + $elevatedBases[$candidateBox->origin->z] = true; + } + if ($unit->nestingItemId !== null) { + $anyNesting = true; + } + $problem = null; + $isolatedFloorStep = $candidateBox->origin->z === 0 + && !$anyNesting + && !isset($elevatedBases[$candidateBox->z2()]); + if ($isolatedFloorStep) { + if ($maxDensityTicks !== null) { + $bearing = \Packvium\Support\BigInt::multiply($unit->weightTicks, LoadCalculator::SQUARE_METRE_TICKS); + $allowed = \Packvium\Support\BigInt::multiply($maxDensityTicks, \Packvium\Support\ExactGeometry::baseArea($candidateBox->dimensions)); + if (\Packvium\Support\BigInt::compare($bearing, $allowed) > 0) { + $problem = ['stack_density_exceeded', $unit->label]; } } + } elseif ($hasLoadRules) { + $analysis = new \Packvium\Constraint\Internal\LoadAnalysis($units); + $problem = $analysis->overloaded() + ?? $analysis->stackLimitExceeded() + ?? $analysis->stackDensityExceeded($maxDensityTicks); + if ($problem === null && $hasNonStackable) { + $counts = $analysis->stackedCounts(); + foreach ($units as $unitIndex => $u) { + if (!$present[$unitIndex]->instance->item->stackable && $counts[$unitIndex] > 0) { + $problem = ['non_stackable_item_has_load', $u->label]; + break; + } + } + } + if ($problem === null && $grouped) { + $last = count($present) - 1; + $problem = $analysis->graph()->nonStackableFailure($present, $candidate->instance, $last); + } } - if ($problem === null && $grouped) { - $last = count($present) - 1; - $problem = $analysis->graph()->nonStackableFailure($present, $present[$last]->instance, $last); - } - if ($problem === null) { - $candidate = $present[count($present) - 1]; + if ($problem === null && $hasGroundRules) { $rule = $candidate->instance->item->groundContactRule; - $candidateBox = $candidate->envelopeBox(); if ($rule !== null && $rule !== 'free' && $candidateBox->origin->z !== 0) { $support = LoadSupportGraph::candidateView( array_slice($present, 0, -1), $candidate->instance, $candidateBox, diff --git a/src/Serialization/ArrayCodec.php b/src/Serialization/ArrayCodec.php index 893e3c4..f5520fc 100644 --- a/src/Serialization/ArrayCodec.php +++ b/src/Serialization/ArrayCodec.php @@ -221,7 +221,8 @@ private static function model(array $data):array // Rules compile into this engine's own constraint pipeline rather than post-filtering // a chosen answer: an illegal candidate is rejected during search, so the packing // that wins was never allowed to be illegal in the first place. - $extensions=new ExtensionRegistry(PolicyRuleSet::fromArray($data['policy']??null)->constraints()); + // No policy is no policy constraint, without compiling `PolicyRuleSet` to say so. + $extensions=new ExtensionRegistry(($data['policy']??null)===null?[]:PolicyRuleSet::fromArray($data['policy'])->constraints()); $items=array_map(fn($r)=>self::item($r,$unit),$data['items']); $containers=array_map(fn($r)=>self::container($r,$unit),$data['containers']); $fixed=self::fixedPlacements($data['fixed_placements']??null,$unit); diff --git a/src/Support/ExactGeometry.php b/src/Support/ExactGeometry.php new file mode 100644 index 0000000..0f2ee77 --- /dev/null +++ b/src/Support/ExactGeometry.php @@ -0,0 +1,38 @@ +length->ticks * $dimensions->width->ticks; + return is_int($area) ? $area : ExactInteger::mul($dimensions->length->ticks, $dimensions->width->ticks); + } + + public static function overlapAreaXY(AxisAlignedBox $a, AxisAlignedBox $b): int|string + { + $x = max(0, min($a->x2(), $b->x2()) - max($a->origin->x, $b->origin->x)); + $y = max(0, min($a->y2(), $b->y2()) - max($a->origin->y, $b->origin->y)); + $area = $x * $y; + return is_int($area) ? $area : ExactInteger::mul($x, $y); + } + + /** `2 * origin + extent`, the doubled centre of one side, as a decimal string. */ + public static function doubledCentre(int $origin, int $extent): string + { + return (string)ExactInteger::add(ExactInteger::mul(2, $origin), $extent); + } +} diff --git a/src/Support/ExactInteger.php b/src/Support/ExactInteger.php new file mode 100644 index 0000000..e9e9713 --- /dev/null +++ b/src/Support/ExactInteger.php @@ -0,0 +1,244 @@ + $b; + } + return SignedBigInt::compare($a, $b); + } + + public static function sign(int|string $value): int + { + return self::compare($value, 0); + } + + public static function negate(int|string $value): int|string + { + if (is_int($value) && $value !== PHP_INT_MIN) { + return -$value; + } + return self::normalize(SignedBigInt::negate($value)); + } + + public static function abs(int|string $value): int|string + { + return self::sign($value) < 0 ? self::negate($value) : $value; + } + + public static function max(int|string $a, int|string $b): int|string + { + return self::compare($a, $b) >= 0 ? $a : $b; + } + + /** Python's `a // b`. */ + public static function floorDiv(int|string $a, int|string $b): int|string + { + if (self::sign($b) === 0) { + throw new \DivisionByZeroError('Division by zero'); + } + if (is_int($a) && is_int($b) && !($a === PHP_INT_MIN && $b === -1)) { + $quotient = intdiv($a, $b); + return ($a % $b !== 0 && (($a < 0) !== ($b < 0))) ? $quotient - 1 : $quotient; + } + $magnitude = BigInt::divide((string)self::abs($a), (string)self::abs($b)); + $negative = (self::sign($a) < 0) !== (self::sign($b) < 0); + if (!$negative) { + return self::normalize($magnitude); + } + $exact = self::compare(self::mul($magnitude, self::abs($b)), self::abs($a)) === 0; + return self::negate($exact ? self::normalize($magnitude) : self::add($magnitude, 1)); + } + + /** Python's `a % b`, which takes the divisor's sign. */ + public static function mod(int|string $a, int|string $b): int|string + { + return self::sub($a, self::mul(self::floorDiv($a, $b), $b)); + } + + /** @param iterable $values */ + public static function sum(iterable $values): int|string + { + $total = 0; + foreach ($values as $value) { + $total = self::add($total, $value); + } + return $total; + } + + /** `2 ** $power`, exactly. */ + public static function powerOfTwo(int $power): int|string + { + if ($power < 62) { + return 1 << $power; + } + $value = 1 << 61; + for ($i = 61; $i < $power; ++$i) { + $value = self::mul($value, 2); + } + return $value; + } + + /** + * Exact `floor(a * b / d)` for non-negative operands whose quotient fits an `int`: a + * weight shared out by contact area, where the area and its total may not. + */ + public static function mulDiv(int $a, int|string $b, int|string $d): int + { + if (is_int($b) && is_int($d)) { + return Arithmetic::mulDiv($a, $b, $d); + } + $quotient = self::floorDiv(self::mul($a, $b), $d); + if (!is_int($quotient)) { + throw new \OverflowException('quotient exceeds a native integer'); + } + return $quotient; + } + + /** + * Python's `numerator / denominator` for non-negative integers: the double nearest the + * exact quotient, ties to even. PHP converts each operand to a double first, which + * rounds twice once either passes 2^53. O(d^2) in the operands' digit count, and only + * then; below 2^53 it is one native division. + */ + public static function ratio(int|string $numerator, int|string $denominator): float + { + if (is_int($numerator) && is_int($denominator) + && $numerator <= self::EXACT_FLOAT && $denominator <= self::EXACT_FLOAT) { + return $numerator / $denominator; + } + if (self::sign($numerator) === 0) { + return 0.0; + } + $shift = self::QUOTIENT_BITS - self::bitLength($numerator) + self::bitLength($denominator); + // The estimate is within a bit or two; each step doubles or halves the quotient, so + // exactly one shift lands it in [2^54, 2^55). + while (true) { + [$quotient, $inexact] = self::shiftedQuotient($numerator, $denominator, $shift); + if (!is_int($quotient) || $quotient >= 1 << self::QUOTIENT_BITS) { + --$shift; + } elseif ($quotient < 1 << (self::QUOTIENT_BITS - 1)) { + ++$shift; + } else { + break; + } + } + $mantissa = $quotient >> 2; + $dropped = $quotient & 3; + if ($dropped > 2 || ($dropped === 2 && ($inexact || ($mantissa & 1) === 1))) { + ++$mantissa; + } + return $mantissa * 2.0 ** (2 - $shift); + } + + /** + * An order-preserving stand-in for a non-negative value inside a PHP array key: the + * value itself while it is an `int`, and its fixed-width chunks beyond. PHP ranks any + * array above any `int`, and every value that needs chunks exceeds every `int`, so + * comparing keys that hold either form still follows the exact integer order. + * + * @return int|list + */ + public static function sortKey(int|string $value): int|array + { + return is_int($value) ? $value : BigInt::chunks($value, 3, 15); + } + + /** + * Fixed-width chunks of a non-negative value, negated so ascending array order is + * largest first: the same shape as `Dimensions::descendingVolumeKey`. + * + * @return list + */ + public static function descendingKey(int|string $value): array + { + return array_map(static fn(int $chunk): int => -$chunk, BigInt::chunks((string)$value, 3, 15)); + } + + /** Approximate: within a bit or two of the exact length, which `ratio` corrects. */ + private static function bitLength(int|string $value): int + { + $digits = ltrim((string)$value, '-'); + $lead = (float)substr($digits, 0, 15); + return $lead <= 0.0 ? 0 : (int)floor(log($lead, 2) + max(0, strlen($digits) - 15) * log(10, 2)) + 1; + } + + /** + * `floor(n * 2^shift / d)` and whether it dropped a remainder. + * + * @return array{0:int|string,1:bool} + */ + private static function shiftedQuotient(int|string $numerator, int|string $denominator, int $shift): array + { + $scaledNumerator = $shift >= 0 ? self::mul($numerator, self::powerOfTwo($shift)) : $numerator; + $scaledDenominator = $shift < 0 ? self::mul($denominator, self::powerOfTwo(-$shift)) : $denominator; + $quotient = self::floorDiv($scaledNumerator, $scaledDenominator); + $inexact = self::sign(self::sub($scaledNumerator, self::mul($quotient, $scaledDenominator))) !== 0; + return [$quotient, $inexact]; + } +} diff --git a/src/Support/FixedPlacementShape.php b/src/Support/FixedPlacementShape.php index 2e939c5..1ab837f 100644 --- a/src/Support/FixedPlacementShape.php +++ b/src/Support/FixedPlacementShape.php @@ -119,7 +119,7 @@ private static function requireCoordinate($value, string $where, string $field, if ($verdict === MeasureReading::NEGATIVE) { throw self::malformed("{$where} cannot be negative", $field); } - if ($verdict === MeasureReading::UNREADABLE) { + if ($verdict !== MeasureReading::READABLE) { throw self::malformed("{$where} is a measure", $field); } } diff --git a/src/Support/Internal/MeasureOverflow.php b/src/Support/Internal/MeasureOverflow.php new file mode 100644 index 0000000..c225d93 --- /dev/null +++ b/src/Support/Internal/MeasureOverflow.php @@ -0,0 +1,92 @@ + '/^(.+?)\s*(mm|cm|m|in|inch|inches|ft|ticks?)$/i', + Weight::class => '/^(.+?)\s*(mg|kg|g|oz|lbs?|ticks?)$/i', + ]; + + /** + * The verdict on text the native parser overflowed on, read exactly: negative, past the + * tick ceiling of its kind, or -- a vanishing fraction with a vast denominator -- still + * unreadable here. + * Ticks round to nearest, so they pass `MAX` once `n x m / d >= MAX + 1/2`; `MAX` is odd, + * so the tie itself rounds up to even. O(digits^2). + * + * @param int|string|array{value:int|string,unit?:string} $normalised + * @param class-string|class-string $kind + */ + public static function beyondNativeInteger($normalised, string $kind, string $unit): string + { + $text = \is_array($normalised) ? (string) $normalised['value'] : (string) $normalised; + $unit = \is_array($normalised) ? ($normalised['unit'] ?? $unit) : $unit; + if (\is_string($normalised) && \preg_match(self::SUFFIXES[$kind], \trim($normalised), $m)) { + [$text, $unit] = [\trim($m[1]), $m[2]]; + } + $fraction = self::exactFraction(\trim(\str_replace("\u{00A0}", ' ', $text))); + if ($fraction === null || $fraction[1] === '0') { + return MeasureReading::UNREADABLE; + } + [$negative, $numerator, $denominator] = $fraction; + if ($negative) { + return MeasureReading::NEGATIVE; + } + $multiplier = $kind::multiplier($unit); + $doubled = BigInt::multiply(BigInt::multiply($numerator, $multiplier), 2); + $ceiling = $kind === Weight::class ? RequestRules::MAX_WEIGHT_TICKS : JsonValue::MAX_EXACT_MAGNITUDE; + $threshold = BigInt::multiply($denominator, BigInt::add(BigInt::multiply($ceiling, 2), '1')); + return BigInt::compare($doubled, $threshold) >= 0 ? MeasureReading::TOO_LARGE : MeasureReading::UNREADABLE; + } + + /** + * `RationalParser::parse` over decimal strings: an integer, decimal, fraction or mixed + * fraction as its sign, numerator and denominator, or null for any other text. + * + * @return array{0:bool,1:string,2:string}|null + */ + private static function exactFraction(string $text): ?array + { + $negative = \str_starts_with($text, '-'); + if (\preg_match('/^[+-]?(\d+)\s+(\d+)\s*\/\s*(\d+)$/', $text, $m)) { + return self::signed($negative, BigInt::add(BigInt::multiply(self::digits($m[1]), self::digits($m[3])), self::digits($m[2])), $m[3]); + } + if (\preg_match('/^[+-]?(\d+)\s*\/\s*(\d+)$/', $text, $m)) { + return self::signed($negative, $m[1], $m[2]); + } + if (\preg_match('/^[+-]?(\d+)(?:\.(\d+))?$/', $text, $m)) { + $fraction = $m[2] ?? ''; + return self::signed($negative, $m[1] . $fraction, '1' . \str_repeat('0', \strlen($fraction))); + } + return null; + } + + /** @return array{0:bool,1:string,2:string}|null */ + private static function signed(bool $negative, string $numerator, string $denominator): ?array + { + $numerator = self::digits($numerator); + $denominator = self::digits($denominator); + if ($denominator === '0') { + return null; + } + return [$negative && $numerator !== '0', $numerator, $denominator]; + } + + private static function digits(string $digits): string + { + return \ltrim($digits, '0') ?: '0'; + } +} diff --git a/src/Support/Internal/RareRequestRules.php b/src/Support/Internal/RareRequestRules.php new file mode 100644 index 0000000..49a1627 --- /dev/null +++ b/src/Support/Internal/RareRequestRules.php @@ -0,0 +1,161 @@ + $container + * @param mixed $raw + */ + public static function madeToMeasure(\Closure $call, $container, $raw, string $where, string $unit): void + { + $field = "{$where}/made_to_measure"; + $machine = $call('objectAt', $raw, $field); + $call('knownFields', $machine, $field, self::MADE_TO_MEASURE_FIELDS); + foreach (['minimum', 'increment'] as $name) { + $call('required', $machine, $name, $field); + } + foreach (['minimum', 'increment', 'outer_allowance'] as $name) { + $sides = JsonValue::get($machine, $name); + if ($sides !== null) { + $call('dimensions', $sides, "{$field}/{$name}", $unit, false); + } + } + $call('optionalInteger', $machine, 'cost_per_square_metre_minor', $field, 0); + $call('optionalMeasure', $machine, 'tare_per_square_metre', $field, Weight::class, RequestRules::WEIGHT_UNIT); + if (JsonValue::get($container, 'outer_dimensions') !== null) { + throw $call('refuse', 'not_allowed', "{$where}/outer_dimensions", 'cannot be combined with made_to_measure'); + } + $inner = $call('sideTicks', JsonValue::get($container, 'inner_dimensions'), $unit); + $minimum = $call('sideTicks', JsonValue::get($machine, 'minimum'), $unit); + $increment = $call('sideTicks', JsonValue::get($machine, 'increment'), $unit); + foreach (RequestRules::SIDES as $axis => $side) { + if ($minimum[$axis] === 0) { + throw $call('refuse', 'invalid_value', "{$field}/minimum/{$side}", 'must be positive'); + } + if ($increment[$axis] === 0) { + throw $call('refuse', 'invalid_value', "{$field}/increment/{$side}", 'must be positive'); + } + if ($minimum[$axis] > $inner[$axis]) { + throw $call('refuse', 'invalid_value', "{$field}/minimum/{$side}", 'exceeds inner_dimensions'); + } + if (($inner[$axis] - $minimum[$axis]) % $increment[$axis] !== 0) { + throw $call('refuse', 'invalid_value', "{$field}/increment/{$side}", 'does not divide inner_dimensions minus minimum'); + } + } + $price = JsonValue::integer(JsonValue::get($machine, 'cost_per_square_metre_minor') ?? 0); + $fee = JsonValue::integer(JsonValue::get($container, 'cost_minor') ?? 0); + if (BigInt::compare(MadeToMeasure::boxCostFor((int) $price, (int) $fee, $inner), MadeToMeasure::MAX_EXACT_INTEGER) > 0) { + throw $call('refuse', 'invalid_value', "{$field}/cost_per_square_metre_minor", 'prices the largest box above ' . CanonicalJson::MAX_EXACT_MAGNITUDE); + } + } + + /** + * The bag's own shape, then every container field a flat bag refuses, in the + * order of `BAG_EXCLUSIONS`. + * + * @param stdClass|array $container + * @param mixed $raw + */ + public static function deformableBoundary(\Closure $call, $container, $raw, string $where): void + { + $field = "{$where}/deformable_boundary"; + $boundary = $call('objectAt', $raw, $field); + if (!\in_array($call('required', $boundary, 'kind', $field), FlatBag::KINDS, true)) { + throw $call('refuse', 'not_allowed', "{$field}/kind", 'must be one of ' . CanonicalJson::spelling(FlatBag::KINDS)); + } + $call('knownFields', $boundary, $field, ['kind']); + foreach (RequestRules::BAG_EXCLUSIONS as $name) { + if ($call('setBesideABag', $name, JsonValue::get($container, $name))) { + throw $call('refuse', 'not_allowed', "{$where}/{$name}", 'cannot be combined with deformable_boundary'); + } + } + } + + /** @param mixed $raw */ + public static function rateTable(\Closure $call, $raw, string $where): void + { + $table = $call('objectAt', $raw, $where); + foreach (['weight_brackets_g' => 1, 'prices_minor' => 0] as $name => $minimum) { + $values = JsonValue::get($table, $name); + if ($values === null) { + continue; + } + foreach ($call('listAt', $values, "{$where}/{$name}") as $index => $value) { + $call('integer', $value, "{$where}/{$name}/{$index}", $minimum); + } + } + $call('optionalInteger', $table, 'minimum_charge_minor', $where, 0); + $call('optionalInteger', $table, 'fuel_surcharge_permille', $where, 0); + } + + /** @param mixed $raw @param array{0:int,1:int,2:int} $inner */ + public static function obstacles(\Closure $call, $raw, string $where, string $unit, array $inner): void + { + foreach ($call('listAt', $raw, $where) as $index => $entry) { + $at = "{$where}/{$index}"; + $obstacle = $call('objectAt', $entry, $at); + self::placedBox($call, $obstacle, $at, $unit, $inner); + $extra = JsonValue::get($obstacle, 'additional_boxes'); + if ($extra !== null) { + foreach ($call('listAt', $extra, "{$at}/additional_boxes") as $position => $box) { + $part = "{$at}/additional_boxes/{$position}"; + self::placedBox($call, $call('objectAt', $box, $part), $part, $unit, $inner); + } + } + } + } + + /** + * An optional `origin` and required `dimensions`: an obstacle, or one more box of it + *, whose measures are read in the request's unit like every other length, and + * which lies inside the container. + * + * @param stdClass|array $box @param array{0:int,1:int,2:int} $inner + */ + public static function placedBox(\Closure $call, $box, string $at, string $unit, array $inner): void + { + $origin = JsonValue::get($box, 'origin'); + if ($origin !== null) { + $point = $call('objectAt', $origin, "{$at}/origin"); + foreach (['x', 'y', 'z'] as $axis) { + $call('optionalMeasure', $point, $axis, "{$at}/origin", Length::class, $unit); + } + } + $call('dimensions', $call('required', $box, 'dimensions', $at), "{$at}/dimensions", $unit); + $sides = $call('sideTicks', JsonValue::get($box, 'dimensions'), $unit); + foreach (['x', 'y', 'z'] as $index => $axis) { + $start = $origin === null ? null : JsonValue::get($origin, $axis); + $offset = $start === null ? 0 : MeasureReading::ticks($start, Length::class, $unit); + if ($offset + $sides[$index] > $inner[$index]) { + throw $call('refuse', 'invalid_value', $at, 'lies outside inner_dimensions'); + } + } + } + + // ------------------------------------------------------------------------- primitives +} diff --git a/src/Support/MeasureReading.php b/src/Support/MeasureReading.php index b78650c..2596f72 100644 --- a/src/Support/MeasureReading.php +++ b/src/Support/MeasureReading.php @@ -4,6 +4,7 @@ use ArithmeticError; use InvalidArgumentException; +use Packvium\Support\Internal\MeasureOverflow; use Packvium\Unit\Length; use Packvium\Unit\Weight; use TypeError; @@ -23,11 +24,13 @@ final class MeasureReading public const READABLE = 'readable'; public const NEGATIVE = 'negative'; public const UNREADABLE = 'unreadable'; + /** A measure the reference reads whose tick count is past every engine's integers. */ + public const TOO_LARGE = 'too_large'; /** * @param mixed $value * @param class-string|class-string $kind - * @return self::READABLE|self::NEGATIVE|self::UNREADABLE + * @return self::READABLE|self::NEGATIVE|self::UNREADABLE|self::TOO_LARGE */ public static function verdict($value, string $kind, string $unit): string { @@ -38,6 +41,9 @@ public static function verdict($value, string $kind, string $unit): string try { $kind::parse($normalised, $unit); } catch (InvalidArgumentException $error) { + if (\str_contains($error->getMessage(), 'exceeds integer range')) { + return MeasureOverflow::beyondNativeInteger($normalised, $kind, $unit); + } return \str_contains($error->getMessage(), 'cannot be negative') ? self::NEGATIVE : self::UNREADABLE; } catch (TypeError | ValueError | ArithmeticError $error) { return self::UNREADABLE; @@ -45,6 +51,19 @@ public static function verdict($value, string $kind, string $unit): string return self::READABLE; } + /** + * A JSON number past 2^53 - 1 is a whole number to the caller, whether `json_decode` kept it + * an `int` or made it a float, and its ticks are past the ceiling in every unit a bare + * number can carry. + * + * @param mixed $value + */ + public static function isWholeBeyondExact($value): bool + { + $whole = \is_int($value) || (\is_float($value) && \is_finite($value) && \floor($value) === $value); + return $whole && \abs($value) > JsonValue::MAX_EXACT_MAGNITUDE; + } + /** * The ticks of a value `verdict` already found readable, for a rule that compares measures. * An unreadable one reaches the parser as null and is refused there as a `TypeError`. diff --git a/src/Support/PrettyJsonStream.php b/src/Support/PrettyJsonStream.php index 1af591e..f2fc266 100644 --- a/src/Support/PrettyJsonStream.php +++ b/src/Support/PrettyJsonStream.php @@ -29,7 +29,11 @@ final class PrettyJsonStream { /** A placement counts 30 or so; a container with its placements counts thousands. */ private const WHOLE_ELEMENTS = 64; - private const FLUSH_BYTES = 65536; + /** + * Small enough to stay a few heap pages: `.=` reallocates the buffer as it grows, and a + * 64 KB run found no room in two fragmented chunks on br1 `fast` #3 in 1.9. + */ + private const FLUSH_BYTES = 8192; private const FLAGS = \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_THROW_ON_ERROR; private const INDENT = ' '; diff --git a/src/Support/RequestObjects.php b/src/Support/RequestObjects.php index 4c44bc8..4c61ec1 100644 --- a/src/Support/RequestObjects.php +++ b/src/Support/RequestObjects.php @@ -4,6 +4,7 @@ use Packvium\Config\PackingConfig; use Packvium\Domain\Container; +use Packvium\Domain\Dimensions; use Packvium\Domain\FixedPlacement; use Packvium\Domain\Item; use Packvium\Domain\MadeToMeasure; @@ -61,6 +62,10 @@ public static function check(array $items, array $containers, PackingConfig $con self::container($container, "/containers/{$index}"); } RequestRules::requireUniqueIds(\array_map(static fn(Container $container): string => $container->id, $containers), 'containers'); + RequestRules::totalWeight( + \array_map(static fn(Item $item): array => [$item->weight->ticks, $item->quantity], $items), + \array_map(static fn(Container $container): int => $container->tareWeight->ticks, $containers), + ); foreach ($fixedPlacements as $index => $placement) { self::fixedPlacement($placement, "fixed_placements[{$index}]", "/fixed_placements/{$index}"); } @@ -95,6 +100,7 @@ private static function configuration(PackingConfig $config): void $property = self::CONFIGURATION_PROPERTIES[$name]; self::optionalInteger($config->{$property}, "{$where}/{$name}", $minimum); } + RequestRules::lengthTicks($config->clearance->ticks, "{$where}/clearance"); RequestRules::ratio($config->minimumSupportRatio, "{$where}/minimum_support_ratio", 1); $budget = $config->effortBudget; if ($budget === null) { @@ -109,6 +115,10 @@ private static function configuration(PackingConfig $config): void private static function item(Item $item, string $where): void { RequestRules::integer($item->quantity, "{$where}/quantity", 1); + RequestRules::box(self::sides($item->dimensions), "{$where}/dimensions"); + if ($item->nestingHeight !== null) { + RequestRules::lengthTicks($item->nestingHeight->ticks, "{$where}/nesting_height"); + } self::optionalInteger($item->maxStackedItems, "{$where}/max_stacked_items", 1); self::optionalInteger($item->stopIndex, "{$where}/stop_index", 0); self::optionalInteger($item->value, "{$where}/value", 0); @@ -125,6 +135,10 @@ private static function item(Item $item, string $where): void private static function container(Container $container, string $where): void { self::optionalInteger($container->quantity, "{$where}/quantity", 1); + RequestRules::box(self::sides($container->innerDimensions), "{$where}/inner_dimensions"); + if ($container->outerDimensions !== null) { + RequestRules::box(self::sides($container->outerDimensions), "{$where}/outer_dimensions"); + } self::optionalInteger($container->maxItems, "{$where}/max_items", 1); RequestRules::integer($container->costMinor, "{$where}/cost_minor", 0); RequestRules::ratio($container->voidFillReserveRatio, "{$where}/void_fill_reserve_ratio", 1); @@ -191,6 +205,9 @@ private static function flatBag(Container $container, string $where): void private static function madeToMeasure(Container $container, MadeToMeasure $machine, string $where): void { $price = "{$where}/made_to_measure/cost_per_square_metre_minor"; + foreach (['minimum' => $machine->minimum, 'increment' => $machine->increment, 'outer_allowance' => $machine->outerAllowance] as $name => $sides) { + RequestRules::box($sides, "{$where}/made_to_measure/{$name}"); + } RequestRules::integer($machine->costPerSquareMetreMinor, $price, 0); if ($container->outerDimensions !== null) { throw new InvalidRequestException('not_allowed', "{$where}/outer_dimensions", 'cannot be combined with made_to_measure'); @@ -203,6 +220,12 @@ private static function madeToMeasure(Container $container, MadeToMeasure $machi } } + /** @return array{0:int,1:int,2:int} */ + private static function sides(Dimensions $dimensions): array + { + return [$dimensions->length->ticks, $dimensions->width->ticks, $dimensions->height->ticks]; + } + private static function optionalInteger(?int $value, string $field, int $minimum): void { if ($value !== null) { diff --git a/src/Support/RequestRules.php b/src/Support/RequestRules.php index b56a7df..418bc61 100644 --- a/src/Support/RequestRules.php +++ b/src/Support/RequestRules.php @@ -7,6 +7,7 @@ use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\Length; use Packvium\Unit\Weight; +use Packvium\Support\Internal\RareRequestRules; use stdClass; /** @@ -48,16 +49,25 @@ final class RequestRules 'minimum_support_ratio', 'multi_start_orders', 'objective', 'require_placement_coordinates', 'seed', 'solver_profile', 'solvers', 'time_limit_ms', ]; - private const SIDES = ['length', 'width', 'height']; + public const SIDES = ['length', 'width', 'height']; /** The item fields the request schema types `boolean`, in schema order. */ private const ITEM_BOOLEANS = ['keep_upright', 'stackable', 'must_be_on_floor']; /** Container fields a flat bag refuses, in reporting order (docs/DEFORMABLE-CONTAINERS.md). */ public const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', 'outer_dimensions', 'void_fill_reserve_ratio', 'made_to_measure']; - /** Every key the request schema's `made_to_measure` declares; it sets `additionalProperties: false`. */ - private const MADE_TO_MEASURE_FIELDS = ['cost_per_square_metre_minor', 'increment', 'minimum', 'outer_allowance', - 'tare_per_square_metre']; - private const WEIGHT_UNIT = 'g'; + public const WEIGHT_UNIT = 'g'; + /** + * The admission ceiling every engine refuses past: a length is a tick count + * every engine holds exactly, JavaScript's `Number` included, and a box encloses no more than + * the bound path can sum, so `volume x 10^6` stays inside Rust's `i128`. + */ + public const MAX_LENGTH_TICKS = JsonValue::MAX_EXACT_MAGNITUDE; + public const MAX_VOLUME_TICKS3 = '1000000000000000000000000000000'; + /** + * A weight, and every item's weight times its quantity plus the heaviest tare, fit a signed + * 64-bit integer, which is how this engine and Rust add a container's payload (R19-01). + */ + public const MAX_WEIGHT_TICKS = \PHP_INT_MAX; /** * Refuse the request with its first violation, or return. @@ -81,6 +91,35 @@ public static function check($data): void self::container($raw, "/containers/{$index}", $unit); } self::requireUniqueIds(self::identifiers($containers), 'containers'); + self::totalWeight(\array_map( + static fn($item): array => [self::weightOf($item, 'weight'), (int) (JsonValue::get($item, 'quantity') ?? 1)], + $items, + ), \array_map(static fn($container): int => self::weightOf($container, 'tare_weight'), $containers)); + } + + /** + * Every item's weight times its quantity, plus the heaviest tare, against `MAX_WEIGHT_TICKS`: + * no container's gross weight can pass it. Shared with `RequestObjects`. O(items + containers). + * + * @param list $itemWeights weight ticks and quantity + * @param list $tares + */ + public static function totalWeight(array $itemWeights, array $tares): void + { + $total = (string) ($tares === [] ? 0 : \max($tares)); + foreach ($itemWeights as [$weight, $quantity]) { + $total = BigInt::add($total, BigInt::multiply($weight, $quantity)); + } + if (BigInt::compare($total, self::MAX_WEIGHT_TICKS) > 0) { + throw self::refuse('above_maximum', '/items', 'must weigh at most ' . self::MAX_WEIGHT_TICKS . ' ticks in all, with the heaviest tare'); + } + } + + /** @param mixed $holder */ + private static function weightOf($holder, string $name): int + { + $value = JsonValue::get($holder, $name); + return $value === null ? 0 : MeasureReading::ticks($value, Weight::class, self::WEIGHT_UNIT); } /** The RFC 6901 pointer to one member, escaping `~` and `/` in its name. */ @@ -239,70 +278,19 @@ private static function container($raw, string $where, string $unit): void } $rateTable = JsonValue::get($container, 'rate_table'); if ($rateTable !== null) { - self::rateTable($rateTable, "{$where}/rate_table"); + RareRequestRules::rateTable(self::bridge(), $rateTable, "{$where}/rate_table"); } $obstacles = JsonValue::get($container, 'obstacles'); if ($obstacles !== null) { - self::obstacles($obstacles, "{$where}/obstacles", $unit); + RareRequestRules::obstacles(self::bridge(), $obstacles, "{$where}/obstacles", $unit, self::sideTicks(JsonValue::get($container, 'inner_dimensions'), $unit)); } $boundary = JsonValue::get($container, 'deformable_boundary'); if ($boundary !== null) { - self::deformableBoundary($container, $boundary, $where); + RareRequestRules::deformableBoundary(self::bridge(), $container, $boundary, $where); } $machine = JsonValue::get($container, 'made_to_measure'); if ($machine !== null) { - self::madeToMeasure($container, $machine, $where, $unit); - } - } - - /** - * The made-to-measure block's shape top to bottom, then each axis's four rules, - * then the price ceiling. Run after every other container field, so an existing error - * always wins. O(1). - * - * @param stdClass|array $container - * @param mixed $raw - */ - private static function madeToMeasure($container, $raw, string $where, string $unit): void - { - $field = "{$where}/made_to_measure"; - $machine = self::objectAt($raw, $field); - self::knownFields($machine, $field, self::MADE_TO_MEASURE_FIELDS); - foreach (['minimum', 'increment'] as $name) { - self::required($machine, $name, $field); - } - foreach (['minimum', 'increment', 'outer_allowance'] as $name) { - $sides = JsonValue::get($machine, $name); - if ($sides !== null) { - self::dimensions($sides, "{$field}/{$name}", $unit); - } - } - self::optionalInteger($machine, 'cost_per_square_metre_minor', $field, 0); - self::optionalMeasure($machine, 'tare_per_square_metre', $field, Weight::class, self::WEIGHT_UNIT); - if (JsonValue::get($container, 'outer_dimensions') !== null) { - throw self::refuse('not_allowed', "{$where}/outer_dimensions", 'cannot be combined with made_to_measure'); - } - $inner = self::sideTicks(JsonValue::get($container, 'inner_dimensions'), $unit); - $minimum = self::sideTicks(JsonValue::get($machine, 'minimum'), $unit); - $increment = self::sideTicks(JsonValue::get($machine, 'increment'), $unit); - foreach (self::SIDES as $axis => $side) { - if ($minimum[$axis] === 0) { - throw self::refuse('invalid_value', "{$field}/minimum/{$side}", 'must be positive'); - } - if ($increment[$axis] === 0) { - throw self::refuse('invalid_value', "{$field}/increment/{$side}", 'must be positive'); - } - if ($minimum[$axis] > $inner[$axis]) { - throw self::refuse('invalid_value', "{$field}/minimum/{$side}", 'exceeds inner_dimensions'); - } - if (($inner[$axis] - $minimum[$axis]) % $increment[$axis] !== 0) { - throw self::refuse('invalid_value', "{$field}/increment/{$side}", 'does not divide inner_dimensions minus minimum'); - } - } - $price = JsonValue::integer(JsonValue::get($machine, 'cost_per_square_metre_minor') ?? 0); - $fee = JsonValue::integer(JsonValue::get($container, 'cost_minor') ?? 0); - if (BigInt::compare(MadeToMeasure::boxCostFor((int) $price, (int) $fee, $inner), MadeToMeasure::MAX_EXACT_INTEGER) > 0) { - throw self::refuse('invalid_value', "{$field}/cost_per_square_metre_minor", 'prices the largest box above ' . CanonicalJson::MAX_EXACT_MAGNITUDE); + RareRequestRules::madeToMeasure(self::bridge(), $container, $machine, $where, $unit); } } @@ -319,28 +307,6 @@ private static function sideTicks($sides, string $unit): array return $ticks; } - /** - * The bag's own shape, then every container field a flat bag refuses, in the - * order of `BAG_EXCLUSIONS`. - * - * @param stdClass|array $container - * @param mixed $raw - */ - private static function deformableBoundary($container, $raw, string $where): void - { - $field = "{$where}/deformable_boundary"; - $boundary = self::objectAt($raw, $field); - if (!\in_array(self::required($boundary, 'kind', $field), FlatBag::KINDS, true)) { - throw self::refuse('not_allowed', "{$field}/kind", 'must be one of ' . CanonicalJson::spelling(FlatBag::KINDS)); - } - self::knownFields($boundary, $field, ['kind']); - foreach (self::BAG_EXCLUSIONS as $name) { - if (self::setBesideABag($name, JsonValue::get($container, $name))) { - throw self::refuse('not_allowed', "{$where}/{$name}", 'cannot be combined with deformable_boundary'); - } - } - } - /** * An empty obstacle list and a zero reserve change nothing, so only they are let through. * @@ -409,12 +375,53 @@ private static function oneOf($value, string $field, array $allowed): void } } - /** @param mixed $raw */ - private static function dimensions($raw, string $where, string $unit): void + /** + * A box's three sides, each a measure; a box that holds or is something has no empty side + *, while a made-to-measure step states its own rule for zero. + * + * @param mixed $raw + */ + private static function dimensions($raw, string $where, string $unit, bool $positive = true): void { $sides = self::objectAt($raw, $where); foreach (self::SIDES as $side) { - self::measure(self::required($sides, $side, $where), "{$where}/{$side}", Length::class, $unit); + $value = self::required($sides, $side, $where); + self::measure($value, "{$where}/{$side}", Length::class, $unit); + if ($positive && MeasureReading::ticks($value, Length::class, $unit) === 0) { + throw self::refuse('invalid_value', "{$where}/{$side}", 'must be positive'); + } + } + self::enclosure(self::sideTicks($sides, $unit), $where); + } + + /** + * A box's sides in ticks, held to the admission ceiling as the request spells them: each + * side, then what they enclose. Shared with `RequestObjects`. O(1). + * + * @param array{0:int,1:int,2:int} $sides + */ + public static function box(array $sides, string $where): void + { + foreach (self::SIDES as $index => $side) { + self::lengthTicks($sides[$index], "{$where}/{$side}"); + } + self::enclosure($sides, $where); + } + + /** A length the object path holds as ticks, against `MAX_LENGTH_TICKS`. */ + public static function lengthTicks(int $ticks, string $field): void + { + if ($ticks > self::MAX_LENGTH_TICKS) { + throw self::tooLong($field); + } + } + + /** @param array{0:int,1:int,2:int} $sides */ + private static function enclosure(array $sides, string $where): void + { + [$length, $width, $height] = $sides; + if (BigInt::compare(BigInt::multiply(BigInt::multiply($length, $width), $height), self::MAX_VOLUME_TICKS3) > 0) { + throw self::refuse('above_maximum', $where, 'must enclose at most 10^30 cubic ticks'); } } @@ -436,41 +443,6 @@ private static function tagLimits($raw, string $where): void } /** @param mixed $raw */ - private static function rateTable($raw, string $where): void - { - $table = self::objectAt($raw, $where); - foreach (['weight_brackets_g' => 1, 'prices_minor' => 0] as $name => $minimum) { - $values = JsonValue::get($table, $name); - if ($values === null) { - continue; - } - foreach (self::listAt($values, "{$where}/{$name}") as $index => $value) { - self::integer($value, "{$where}/{$name}/{$index}", $minimum); - } - } - self::optionalInteger($table, 'minimum_charge_minor', $where, 0); - self::optionalInteger($table, 'fuel_surcharge_permille', $where, 0); - } - - /** @param mixed $raw */ - private static function obstacles($raw, string $where, string $unit): void - { - foreach (self::listAt($raw, $where) as $index => $entry) { - $at = "{$where}/{$index}"; - $obstacle = self::objectAt($entry, $at); - $origin = JsonValue::get($obstacle, 'origin'); - if ($origin !== null) { - $point = self::objectAt($origin, "{$at}/origin"); - foreach (['x', 'y', 'z'] as $axis) { - self::optionalMeasure($point, $axis, "{$at}/origin", Length::class, $unit); - } - } - self::dimensions(self::required($obstacle, 'dimensions', $at), "{$at}/dimensions", $unit); - } - } - - // ------------------------------------------------------------------------- primitives - /** @param mixed $value */ public static function integer($value, string $field, int $minimum): void { @@ -525,7 +497,9 @@ public static function ratio($value, string $field, ?int $maximum): void */ private static function measure($value, string $field, string $kind, string $unit): void { - $scalar = \is_int($value) || \is_string($value) || (\is_float($value) && JsonValue::integer($value) !== null); + $length = $kind === Length::class; + $scalar = \is_int($value) || \is_string($value) + || (\is_float($value) && (JsonValue::integer($value) !== null || ($length && MeasureReading::isWholeBeyondExact($value)))); if (!$scalar && !self::isMeasureObject($value)) { throw self::refuse('wrong_type', $field, 'must be a measure'); } @@ -538,15 +512,36 @@ private static function measure($value, string $field, string $kind, string $uni throw self::refuse('invalid_unit', $field, 'has an unknown unit ' . CanonicalJson::spelling($stated)); } } + $amount = $scalar ? $value : JsonValue::get($value, 'value'); + if ($length && MeasureReading::isWholeBeyondExact($amount)) { + throw $amount < 0 ? self::refuse('negative_measure', $field, 'cannot be negative') : self::tooLong($field); + } + // Past 2^53 - 1 JavaScript has already rounded a JSON number before it reads it, so a + // weight that large is written as a string, which every engine reads exactly. + if (!$length && MeasureReading::isWholeBeyondExact($amount)) { + throw $amount < 0 ? self::refuse('negative_measure', $field, 'cannot be negative') : self::refuse('invalid_value', $field, 'must be written as a string past ' . JsonValue::MAX_EXACT_MAGNITUDE); + } $verdict = MeasureReading::verdict($value, $kind, $unit); if ($verdict === MeasureReading::NEGATIVE) { throw self::refuse('negative_measure', $field, 'cannot be negative'); } - if ($verdict === MeasureReading::UNREADABLE) { + if ($length && ($verdict === MeasureReading::TOO_LARGE + || ($verdict === MeasureReading::READABLE && MeasureReading::ticks($value, $kind, $unit) > self::MAX_LENGTH_TICKS))) { + throw self::tooLong($field); + } + if (!$length && $verdict === MeasureReading::TOO_LARGE) { + throw self::refuse('above_maximum', $field, 'must be at most ' . self::MAX_WEIGHT_TICKS . ' ticks'); + } + if ($verdict !== MeasureReading::READABLE) { throw self::refuse('wrong_type', $field, 'must be a measure'); } } + private static function tooLong(string $field): InvalidRequestException + { + return self::refuse('above_maximum', $field, 'must be at most ' . self::MAX_LENGTH_TICKS . ' ticks'); + } + /** * An object measure; the empty array is `{}` here, which has no `value` and is refused * as a measure either way. @@ -705,4 +700,10 @@ private static function refuse(string $reason, string $field, string $detail): I { return new InvalidRequestException($reason, $field, $detail); } + + /** `RequestRules`' own private helpers, for `Internal\RareRequestRules` (see there). */ + private static function bridge(): \Closure + { + return static fn(string $method, ...$arguments) => self::{$method}(...$arguments); + } } diff --git a/src/Support/ResultValidation/ContainerCheck.php b/src/Support/ResultValidation/ContainerCheck.php index c12aa7a..4f3658c 100644 --- a/src/Support/ResultValidation/ContainerCheck.php +++ b/src/Support/ResultValidation/ContainerCheck.php @@ -263,13 +263,14 @@ public static function check($packed, ContainerSpec $spec, Ordered $items, $clea [$supporters, $directAbove] = Stacking::supportGraph($entries); Stacking::checkSupportAndLoad($entries, $supporters, $directAbove, $globalSupport, $issues); $loads = Stacking::propagateLoad($entries, $supporters); + Stacking::checkStackTopLoad($entries, $loads, $issues); if ($spec->maxStackDensity !== null) { Stacking::checkStackDensity($packedId, $entries, $loads, $spec->maxStackDensity, $issues); } Stacking::checkCrush($packedId, $entries, $loads, $issues); Stacking::checkRouteRemovalOrder($packedId, $entries, $directAbove, $spec->inner, $spec->accessDirections, $issues); self::checkLimits($packed, $packedId, $placements, $spec, $items, $payload, $issues); - self::checkVolumes($packed, $packedId, $placements, $spec, $items, $byId, $loads, $issues); + self::checkVolumes($packed, $packedId, $placements, $spec, $items, $byId, $loads, $clearance, $issues); $totalWeight = self::payloadOf($packed, $items); self::checkCentreOfMass($packed, $packedId, $placements, $spec, $items, $totalWeight, $issues); self::checkAxles($packed, $packedId, $placements, $spec, $items, $totalWeight, $issues); @@ -351,7 +352,8 @@ private static function checkLimits($packed, Label $packedId, array $placements, * @param mixed $packed @param list $placements @param Ordered $items * @param Ordered $byId @param list $loads @param list $issues */ - private static function checkVolumes($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, Ordered $byId, array $loads, array &$issues): void + /** @param int|string $clearance */ + private static function checkVolumes($packed, Label $packedId, array $placements, ContainerSpec $spec, Ordered $items, Ordered $byId, array $loads, $clearance, array &$issues): void { // Every placement counts, through the envelope its item id resolves to -- a repeated id // resolves to its last placement, as the reference's dict does. @@ -365,8 +367,15 @@ private static function checkVolumes($packed, Label $packedId, array $placements for ($first = 0, $count = \count($entries); $first < $count; ++$first) { for ($second = $first + 1; $second < $count; ++$second) { if (Stacking::validNesting($entries[$first], $entries[$second])) { + // The envelopes sink by the nesting height; the items themselves overlap by + // twice the clearance less, over their own footprint. $left = $entries[$first]; - $used = Exact::sub($used, Exact::mul(Exact::mul($left->spec->nestingHeight, $left->envelope->length), $left->envelope->width)); + $margin = Exact::mul(2, $clearance); + $overlap = Exact::sub($left->spec->nestingHeight, $margin); + if (Exact::sign($overlap) > 0) { + $footprint = Exact::mul(Exact::sub($left->envelope->length, $margin), Exact::sub($left->envelope->width, $margin)); + $used = Exact::sub($used, Exact::mul($overlap, $footprint)); + } } } } diff --git a/src/Support/ResultValidation/Stacking.php b/src/Support/ResultValidation/Stacking.php index ef43d03..3a41cb1 100644 --- a/src/Support/ResultValidation/Stacking.php +++ b/src/Support/ResultValidation/Stacking.php @@ -113,6 +113,9 @@ public static function checkSupportAndLoad(array $entries, array $supporters, ar if (Exact::compare($area, self::requiredSupportArea($entry->envelope->baseArea, ContainerCheck::ratioPpm($required))) < 0) { $ratio = Ratio::of($area, $entry->envelope->baseArea); $issues[] = new ResultIssue('insufficient_support', "{$itemId}: " . PyFormat::fixed6($ratio->toFloat()) . ' < ' . PyFormat::fixed6($required->toFloat())); + } elseif (Exact::compare(Exact::mul($area, 2), $entry->envelope->baseArea) <= 0 + && !self::centroidSupported($entry->envelope, \array_map(static function (array $edge) use ($entries) { return $entries[$edge[0]]->envelope; }, $supporting))) { + $issues[] = new ResultIssue('centre_of_gravity_unsupported', "{$itemId}: centroid outside its support hull"); } } foreach ($supporting as [$lower]) { @@ -126,9 +129,6 @@ public static function checkSupportAndLoad(array $entries, array $supporters, ar } elseif ($lowerSpec->acceptsStackingGroups !== [] && !Accounting::holds($lowerSpec->acceptsStackingGroups, $spec->stackingGroup)) { $issues[] = new ResultIssue('stacking_group_incompatible', "{$itemId} rests on {$lowerId}"); } - if ($lowerSpec->maxTopLoad !== null && Exact::compare($spec->weight, $lowerSpec->maxTopLoad) > 0) { - $issues[] = new ResultIssue('top_load_exceeded', "{$itemId} ({$spec->weight} ticks) on {$lowerId} (limit {$lowerSpec->maxTopLoad})"); - } } } foreach ($entries as $index => $entry) { @@ -154,6 +154,77 @@ public static function checkSupportAndLoad(array $entries, array $supporters, ar } /** Exact `floor(baseArea * ppm / 10^6)`, the least supported area the ratio allows. @param int|string $baseArea @return int|string */ + /** + * Whether the base centroid lies in the convex hull of the contact areas, the + * rule the searches apply once a support ratio is enforced; reached only at or below half + * the base, where it can refuse. Coordinates are doubled so the centroid is an + * integer for odd extents, and every product goes through Exact. The corners come four to + * a positive-area overlap, so the hull is empty or has at least three vertices. + * O(s log s) time and O(s) space for s supporters. + * + * @param list $surfaces + */ + private static function centroidSupported(Cuboid $envelope, array $surfaces): bool + { + $points = []; + foreach ($surfaces as $surface) { + foreach ([Exact::max($envelope->x, $surface->x), Exact::compare($envelope->x2, $surface->x2) <= 0 ? $envelope->x2 : $surface->x2] as $x) { + foreach ([Exact::max($envelope->y, $surface->y), Exact::compare($envelope->y2, $surface->y2) <= 0 ? $envelope->y2 : $surface->y2] as $y) { + $points[Exact::mul($x, 2) . ',' . Exact::mul($y, 2)] = [Exact::mul($x, 2), Exact::mul($y, 2)]; + } + } + } + $points = \array_values($points); + \usort($points, static function (array $a, array $b): int { + return Exact::compare($a[0], $b[0]) ?: Exact::compare($a[1], $b[1]); + }); + $hull = \array_merge(self::halfHull($points), self::halfHull(\array_reverse($points))); + $centroid = [Exact::add($envelope->x, $envelope->x2), Exact::add($envelope->y, $envelope->y2)]; + $count = \count($hull); + if ($count === 0) { + return false; + } + for ($index = 0; $index < $count; $index++) { + if (Exact::sign(self::cross($hull[$index], $hull[($index + 1) % $count], $centroid)) < 0) { + return false; + } + } + return true; + } + + /** + * One half of Andrew's monotone chain, its last point dropped for the other half to close. + * + * @param list $points + * @return list + */ + private static function halfHull(array $points): array + { + $chain = []; + foreach ($points as $point) { + while (\count($chain) >= 2 && Exact::sign(self::cross($chain[\count($chain) - 2], $chain[\count($chain) - 1], $point)) <= 0) { + \array_pop($chain); + } + $chain[] = $point; + } + \array_pop($chain); + return $chain; + } + + /** + * @param array{0: int|string, 1: int|string} $o + * @param array{0: int|string, 1: int|string} $a + * @param array{0: int|string, 1: int|string} $b + * @return int|string + */ + private static function cross(array $o, array $a, array $b) + { + return Exact::sub( + Exact::mul(Exact::sub($a[0], $o[0]), Exact::sub($b[1], $o[1])), + Exact::mul(Exact::sub($a[1], $o[1]), Exact::sub($b[0], $o[0])) + ); + } + private static function requiredSupportArea($baseArea, int $ppm) { return Exact::floorDiv(Exact::mul($baseArea, $ppm), ContainerCheck::SCORE_SCALE); @@ -242,6 +313,24 @@ private static function pressure($load, $baseArea): Ratio ); } + /** + * `max_top_load` against the whole stack an item bears, as every engine checks it. + * The only top-load rule since 1.9.0: an item resting on several bearers shares its + * weight among them by contact area. O(n) over the loads `propagateLoad` built. + * + * @param list $entries @param list $loads @param list $issues + */ + public static function checkStackTopLoad(array $entries, array $loads, array &$issues): void + { + foreach ($entries as $index => $entry) { + $limit = $entry->spec === null ? null : $entry->spec->maxTopLoad; + if ($limit === null || Exact::compare($loads[$index], $limit) <= 0) { + continue; + } + $issues[] = new ResultIssue('top_load_exceeded', PyFormat::str($entry->id) . " bears {$loads[$index]} ticks (limit {$limit})"); + } + } + /**: no `compressible` item may carry more pressure than it declared. @param list $entries @param list $loads @param list $issues */ public static function checkCrush(Label $packedId, array $entries, array $loads, array &$issues): void { @@ -250,7 +339,8 @@ public static function checkCrush(Label $packedId, array $entries, array $loads, if ($limit === null) { continue; } - $pressure = self::pressure($loads[$index], $entry->envelope->baseArea); + [$length, $width] = self::physicalSides($entry->placement); + $pressure = self::pressure($loads[$index], Exact::mul($length, $width)); if ($pressure->compareInt($limit) > 0) { $issues[] = new ResultIssue('crush_violation', PyFormat::str($entry->id) . " in {$packedId}: " . PyFormat::fixed6($pressure->toFloat()) . " kPa exceeds {$limit} kPa"); } @@ -259,27 +349,38 @@ public static function checkCrush(Label $packedId, array $entries, array $loads, /** * Occupied height under load, rounded up, never below one tick. A crushed item keeps its - * height: `checkCrush` already reports it. + * height: `checkCrush` already reports it. The load presses on the item itself, so the + * footprint and the height are its own, not its envelope's. * - * @param int|string $load @return int|string + * @param int $height @param int|string $footprint @param int|string $load @return int|string */ - public static function compressedHeight(Cuboid $envelope, ItemSpec $spec, $load) + public static function compressedHeight(int $height, $footprint, ItemSpec $spec, $load) { $limit = $spec->maxCompressionPressureKpa; if ($limit === null) { - return $envelope->height; + return $height; } if ($spec->compressionRatioPpm === null) { // The reference asserts the pair: a pressure limit without a ratio is not a request it reads. throw MalformedResult::shape("{$spec->id}: max_compression_pressure_kpa without compression_ratio"); } - $pressure = self::pressure($load, $envelope->baseArea); + $pressure = self::pressure($load, $footprint); if ($pressure->compareInt($limit) > 0 || $limit === 0) { - return $envelope->height; + return $height; } $divisor = Exact::mul(Exact::mul($limit, 1000000), $pressure->denominator); $retained = Exact::sub($divisor, Exact::mul($spec->compressionRatioPpm, $pressure->numerator)); - return Exact::max(1, Exact::ceilDiv(Exact::mul($envelope->height, $retained), $divisor)); + return Exact::max(1, Exact::ceilDiv(Exact::mul($height, $retained), $divisor)); + } + + /** The placed item's own sides, without the clearance its envelope adds. @param mixed $placement @return array{0:int,1:int,2:int} */ + private static function physicalSides($placement): array + { + $dimensions = Json::at($placement, 'dimensions'); + $side = static function (string $name) use ($dimensions): int { + return Json::int(Json::at(Json::at($dimensions, $name), 'ticks'), 'a placement dimension'); + }; + return [$side('length'), $side('width'), $side('height')]; } /**: weight per square metre of an item's own base, at every level of the stack. @param list $entries @param list $loads @param int|string $maxDensity @param list $issues */ @@ -415,18 +516,17 @@ public static function validNesting(Entry $left, Entry $right): bool public static function occupiedVolume(Cuboid $envelope, $placement, ?ItemSpec $spec, $load) { if ($spec !== null && $spec->maxCompressionPressureKpa !== null) { - return Exact::mul($envelope->baseArea, self::compressedHeight($envelope, $spec, $load)); + [$length, $width, $height] = self::physicalSides($placement); + $footprint = Exact::mul($length, $width); + return Exact::mul($footprint, self::compressedHeight($height, $footprint, $spec, $load)); } if ($spec !== null && $spec->isConvexHull() && $spec->hullVertices !== null) { return Geometry::hullVolume(Geometry::rotateHull($spec->hullVertices, Geometry::axes(Json::text(Json::at($placement, 'orientation'), 'orientation')))); } $solid = self::placedHull($envelope, $placement, $spec); if ($solid === $envelope->vertices()) { - $dimensions = Json::at($placement, 'dimensions'); - $side = static function (string $name) use ($dimensions): int { - return Json::int(Json::at(Json::at($dimensions, $name), 'ticks'), 'a placement dimension'); - }; - return Exact::mul(Exact::mul($side('length'), $side('width')), $side('height')); + [$length, $width, $height] = self::physicalSides($placement); + return Exact::mul(Exact::mul($length, $width), $height); } return Geometry::hullVolume($solid); } diff --git a/tests/CommerceCatalogDatesTest.php b/tests/CommerceCatalogDatesTest.php new file mode 100644 index 0000000..c4742f5 --- /dev/null +++ b/tests/CommerceCatalogDatesTest.php @@ -0,0 +1,52 @@ + catalogVersionInfo( + $document, ['catalog_id' => $catalogId, 'version' => 1, 'resolved_at' => -1], + )); + } + } + + public static function testNegativeRollbackDatesAreInputErrors(): void + { + foreach ([ + ['rollback_to' => 1, 'published_at' => 0, 'effective_at' => -1], + ['rollback_to' => 1, 'published_at' => -1, 'effective_at' => 0], + ['rollback_to' => 1, 'published_at' => -1], + ] as $rollback) { + self::assertThrows(CommerceInputException::class, static fn() => catalogVersionInfo( + self::document($rollback), ['catalog_id' => 'c', 'version' => 2, 'resolved_at' => 0], + )); + } + } + + public static function testZeroDatesAreValidForARollback(): void + { + $result = catalogVersionInfo( + self::document(['rollback_to' => 1, 'published_at' => 0]), + ['catalog_id' => 'c', 'as_of' => 0, 'resolved_at' => 0], + ); + self::assertSame('ok', $result['status']); + self::assertSame(2, $result['catalog']['version']); + self::assertSame(0, $result['catalog']['effective_at']); + self::assertSame(0, $result['catalog']['published_at']); + self::assertSame(0, $result['catalog']['resolved_at']); + } + + private static function document(?array $rollback = null): array + { + $versions = [['effective_at' => 0, 'published_at' => 0, 'snapshot' => []]]; + if ($rollback !== null) { $versions[] = $rollback; } + return ['catalogs' => [['catalog_id' => 'c', 'versions' => $versions]]]; + } +} diff --git a/tests/CommercePolicyValuesTest.php b/tests/CommercePolicyValuesTest.php new file mode 100644 index 0000000..f55bb7c --- /dev/null +++ b/tests/CommercePolicyValuesTest.php @@ -0,0 +1,46 @@ + [1, ['flag' => true]], 'b' => null], + ['b' => null, 'a' => [true, ['flag' => 1]]], false], + ['not_equals', ['a' => null], ['b' => null], false], + ['equals', ['a' => null], ['b' => null], true], + ['equals', ['a' => [1, 2]], ['a' => [2, 1]], true], + ['in', [['a' => 1, 'b' => true]], ['b' => 1, 'a' => true], false], + ['not_in', [['a' => 1]], ['a' => 2], false], + ['in', ['a' => null], 'a', false], + ['in', ['a' => 'b'], 'b', true], + ['not_in', ['a' => 1], 'missing', false], + ['in', ['a' => 1], ['a'], true], + ] as [$operator, $value, $actual, $allowed]) { + $decision = self::decision($operator, $value, ['x' => $actual]); + self::assertSame($allowed, $decision['allowed'], $operator . ' structured value'); + self::assertSame($allowed, $decision['citation'] === null); + } + } + + public static function testMissingFieldsNeverMatchBinaryOperators(): void + { + foreach (['equals', 'not_equals', 'in', 'not_in'] as $operator) { + self::assertSame(null, self::decision($operator, ['a' => 1], [])['citation']); + } + } + + private static function decision(string $operator, mixed $value, array $context): array + { + $document = ['policy_rules' => [['rule_id' => 'restriction', 'versions' => [[ + 'scope' => 'facility', 'action' => 'reject', 'priority' => 1, 'effective_at' => 0, + 'predicates' => [['scope' => 'facility', 'field' => 'x', + 'operator' => $operator, 'value' => $value]], + ]]]]]; + return evaluatePolicy($document, ['scope' => 'facility', 'context' => $context, 'as_of' => 0])['decision']; + } +} diff --git a/tests/CommerceTariffIdentityTest.php b/tests/CommerceTariffIdentityTest.php new file mode 100644 index 0000000..db3ed41 --- /dev/null +++ b/tests/CommerceTariffIdentityTest.php @@ -0,0 +1,62 @@ + [self::history("a\0b", 'c', 100)]]; + foreach ([['tariff_version' => 1], ['as_of' => 0]] as $pin) { + $result = quote($document, self::request('a', "b\0c") + $pin); + + self::assertSame('rejected', $result['status']); + self::assertSame('tariff_not_found', $result['error']['code']); + self::assertSame( + ['carrier_id' => 'a', 'service_id' => "b\0c"] + (isset($pin['tariff_version']) ? $pin : []), + $result['error']['fields'], + ); + } + } + + public static function testDistinctPairsHaveIndependentHistories(): void + { + $document = ['tariffs' => [ + self::history("a\0b", 'c', 100), + self::history('a', "b\0c", 700), + ]]; + foreach ([['tariff_version' => 1], ['as_of' => 0]] as $pin) { + foreach ([["a\0b", 'c', 100], ['a', "b\0c", 700]] as [$carrier, $service, $total]) { + $result = quote($document, self::request($carrier, $service) + $pin); + + self::assertSame('ok', $result['status']); + self::assertSame($carrier, $result['quote']['carrier_id']); + self::assertSame($service, $result['quote']['service_id']); + self::assertSame(1, $result['quote']['tariff_version']); + self::assertSame($total, $result['quote']['total_minor']); + } + } + } + + /** @return array */ + private static function history(string $carrier, string $service, int $rate): array + { + return ['carrier_id' => $carrier, 'service_id' => $service, 'versions' => [[ + 'effective_at' => 0, + 'dimensional_weight_divisor' => 5000, + 'cost_per_dimensional_kg_minor' => ['z' => $rate], + ]]]; + } + + /** @return array */ + private static function request(string $carrier, string $service): array + { + return [ + 'carrier_id' => $carrier, 'service_id' => $service, 'zone' => 'z', + 'actual_weight_g' => 1000, 'volume_mm3' => 0, + ]; + } +} diff --git a/tests/ExactIntegerTest.php b/tests/ExactIntegerTest.php new file mode 100644 index 0000000..a955fd9 --- /dev/null +++ b/tests/ExactIntegerTest.php @@ -0,0 +1,117 @@ + ExactInteger::floorDiv(1, 0)); + } + + public static function testMulDivSharesAWeightByAnAreaPastANativeInt(): void + { + // Two equal contacts of (3.2e12 ticks)^2 each share 1001 ticks: 500 and the rest. + $area = ExactInteger::mul(3_200_000_000_000, 3_200_000_000_000); + self::assertSame(500, ExactInteger::mulDiv(1001, $area, ExactInteger::mul($area, 2))); + } + + public static function testARatioIsTheDoubleNearestTheExactQuotient(): void + { + self::assertSame(1 / 3, ExactInteger::ratio(1, 3)); + self::assertSame(0.0, ExactInteger::ratio(0, '340282366920938463463374607431768211455')); + self::assertSame(1.0, ExactInteger::ratio('340282366920938463463374607431768211455', '340282366920938463463374607431768211455')); + // Python: 9007199254740993 / 9007199254740995 == 0.9999999999999998; PHP's own + // division rounds both operands to doubles first and answers 1.0. + self::assertSame(0.9999999999999998, ExactInteger::ratio(9_007_199_254_740_993, 9_007_199_254_740_995)); + } + + public static function testAnExactHalfBetweenTwoDoublesRoundsToEven(): void + { + // (2^53 + 1) / 2^54 lies exactly between two doubles; Python picks the even one. + self::assertSame(0.5, ExactInteger::ratio(9_007_199_254_740_993, '18014398509481984')); + // (2^53 + 3) / 2^54 rounds up to the even neighbour above. + self::assertSame(0.5000000000000002, ExactInteger::ratio(9_007_199_254_740_995, '18014398509481984')); + } + + public static function testARatioWhoseFirstEstimateFallsShortIsCorrected(): void + { + // 2^56 / (2^57 + 1): the bit-length estimate starts one shift low. + self::assertSame(0.5, ExactInteger::ratio(72_057_594_037_927_936, '144115188075855873')); + } + + public static function testAShareTooLargeForANativeIntIsRefused(): void + { + self::assertThrows(\OverflowException::class, static fn() => ExactInteger::mulDiv(PHP_INT_MAX, '36893488147419103232', 2)); + } + + public static function testNegationKeepsANativeIntNative(): void + { + self::assertSame(-5, ExactInteger::negate(5)); + self::assertSame(5, ExactInteger::abs(-5)); + } + + public static function testASortKeyKeepsTheIntegerOrderAcrossBothForms(): void + { + $keys = [ + ExactInteger::sortKey(ExactInteger::mul(PHP_INT_MAX, 3)), + ExactInteger::sortKey(5), + ExactInteger::sortKey(ExactInteger::mul(PHP_INT_MAX, 2)), + ExactInteger::sortKey(PHP_INT_MAX), + ]; + usort($keys, static fn($a, $b): int => $a <=> $b); + self::assertSame([5, PHP_INT_MAX], array_slice($keys, 0, 2)); + self::assertTrue($keys[2] < $keys[3], 'twice before three times PHP_INT_MAX'); + } + + public static function testADescendingKeyPutsTheLargestFirst(): void + { + $large = ExactInteger::descendingKey(ExactInteger::mul(PHP_INT_MAX, 3)); + $small = ExactInteger::descendingKey(PHP_INT_MAX); + self::assertTrue($large < $small); + self::assertSame([0, 0, -1], ExactInteger::descendingKey(1)); + } + + public static function testPowersOfTwoAreExactPastANativeInt(): void + { + self::assertSame(1 << 61, ExactInteger::powerOfTwo(61)); + self::assertSame('18446744073709551616', ExactInteger::powerOfTwo(64)); + } +} diff --git a/tests/ExtensionTest.php b/tests/ExtensionTest.php index 9499b01..f63ae7f 100644 --- a/tests/ExtensionTest.php +++ b/tests/ExtensionTest.php @@ -260,6 +260,32 @@ public function packOne(Container $container, int $sequence, array $items, } } + + /** + * A solver the clock stops inside a container-plan beam, whose trials run in + * `Internal\ContainerPlanBeam` (1.9.0): the beam ends with what it has, and the pack answers + * rather than letting `TimeLimitReached` escape. + */ + public static function testAContainerPlanBeamKeepsAnsweringWhenItsSolverIsStoppedByTheClock(): void + { + $givesUp = new class implements SingleContainerSolver { + public function name(): string + { + return 'gives_up'; + } + + public function packOne(Container $container, int $sequence, array $items, + PackingConfig $config, SearchStats $stats, Deadline $deadline): SingleContainerSolution + { + throw new TimeLimitReached('this solver never finishes'); + } + }; + $items = [Support::item('a', 40, 40, 40, ['quantity' => 3])]; + $containers = [Support::box('c', 100, 100, 100)]; + $config = new PackingConfig(topK: 8, containerPlanBeamWidth: 2, containerPlanNodeLimit: 8); + $result = (new Packer($config, new ExtensionRegistry([], [], [$givesUp])))->pack($items, $containers); + self::assertTrue($result->complete()); + } public static function testASolverThatRunsOutOfTimeOnAFixedContainerStillKeepsIt(): void { // A start whose solver gives up while filling a container that already holds a diff --git a/tests/FixedPlacementTest.php b/tests/FixedPlacementTest.php index 8f1255e..df6946a 100644 --- a/tests/FixedPlacementTest.php +++ b/tests/FixedPlacementTest.php @@ -115,6 +115,7 @@ public static function testAFixedSetThatCannotHoldIsRefusedBeforeSearch(): void 'insufficient_support' => static function (array &$d): void { $d['configuration'] = ['minimum_support_ratio' => 1]; $d['fixed_placements'][0]['position']['z'] = '50'; }, '2 box named, 1 available' => static function (array &$d): void { $d['containers'][0]['quantity'] = 1; $d['fixed_placements'][] = self::fixed('0', '0', '0', 2); }, 'max_containers is 1' => static function (array &$d): void { $d['configuration'] = ['max_containers' => 1]; $d['fixed_placements'][] = self::fixed('0', '0', '0', 2); }, + 'centre_of_gravity_unsupported' => static function (array &$d): void { $d['configuration'] = ['minimum_support_ratio' => 0.25]; $d['fixed_placements'][] = self::fixed('40', '0', '100'); }, ]; foreach ($cases as $fragment => $mutate) { $data = self::request(); diff --git a/tests/IrregularItemsTest.php b/tests/IrregularItemsTest.php index 534f110..3c050b2 100644 --- a/tests/IrregularItemsTest.php +++ b/tests/IrregularItemsTest.php @@ -253,7 +253,7 @@ public static function testTheContainerPlanBoundCountsAWedgePairAsOneCrate(): vo $crate = new Container('cube', Dimensions::mm(100, 100, 100)); [$lower] = self::hullItem('lower', self::lowerWedge())->instances(); [$upper] = self::hullItem('upper', self::upperWedge())->instances(); - $bound = new ReflectionMethod(SolverOrchestrator::class, 'additionalContainerLowerBound'); + $bound = new ReflectionMethod(\Packvium\Algorithm\Internal\ContainerPlanBeam::class, 'additionalContainerLowerBound'); $bound->setAccessible(true); $plan = ['remaining' => [$lower, $upper], 'inventory' => ['cube' => 2]]; self::assertSame(1, $bound->invoke(null, $plan, [$crate])); diff --git a/tests/KilometreScaleTest.php b/tests/KilometreScaleTest.php new file mode 100644 index 0000000..29f1665 --- /dev/null +++ b/tests/KilometreScaleTest.php @@ -0,0 +1,93 @@ + ExactInteger::descendingKey(ExactGeometry::baseArea($dimensions)); + self::assertTrue($key($larger) < $key($field)); + self::assertTrue($key($field) < $key(Dimensions::mm(1, 1, 1))); + } + + public static function testTheCentroidRuleStaysExactNextToTheLargestCoordinate(): void + { + // A centroid half a tick from the support's edge, where doubled coordinates pass a native int. + $candidate = self::box(self::FAR - 101, 0, 101, 10); + $hull = static fn(int $length): array => SupportPolygon::convexHull( + SupportPolygon::contactHullPoints($candidate, [self::box(self::FAR - 101, 0, $length, 10)]), + ); + $centroid = SupportPolygon::doubledCentroid($candidate); + self::assertTrue(SupportPolygon::pointInHull($centroid, $hull(51))); + self::assertFalse(SupportPolygon::pointInHull($centroid, $hull(50))); + } + + public static function testADoubledCentreNearTheLargestCoordinateIsExact(): void + { + self::assertSame('18446744073709549615', ExactGeometry::doubledCentre(self::FAR, 1)); + self::assertSame('21', ExactGeometry::doubledCentre(10, 1)); + } + + public static function testTheRoomLeftScoreOrdersPastANativeInt(): void + { + $vast = CandidateFinder::roomLeftKey(4_000_000_000, 4_000_000_001, 0); + $vaster = CandidateFinder::roomLeftKey(4_000_000_000, 4_000_000_002, 0); + self::assertSame(17, CandidateFinder::roomLeftKey(3, 5, 2)); + self::assertTrue([0, $vast] < [0, $vaster], 'the exact keys keep their order'); + self::assertTrue([0, PHP_INT_MAX] < [0, $vast], 'any exact key ranks above every int'); + } + + public static function testALatticeWithMoreSlotsPerLayerThanAnIntHoldsCountsOneLayer(): void + { + $grain = new Dimensions(new Length(1), new Length(1), new Length(1)); + $lattice = new LatticeSummary('grain', Rotation::LWH, $grain, $grain, 4_000_000_000, 4_000_000_000, 1, 0, 5, 0); + self::assertSame(0, $lattice->fullLayers()); + self::assertSame(5, $lattice->remainder()); + self::assertSame(1, $lattice->layersUsed()); + } + + public static function testPressureOverAFootprintPastANativeIntIsExact(): void + { + [$numerator, $denominator] = Compression::pressure(8_000_000, '16000000000000000000'); + self::assertTrue(Compression::exceeds([$numerator, $denominator], 0)); + self::assertFalse(Compression::exceeds([$numerator, $denominator], 1)); + } +} diff --git a/tests/MadeToMeasureTest.php b/tests/MadeToMeasureTest.php index 59c0351..de2b247 100644 --- a/tests/MadeToMeasureTest.php +++ b/tests/MadeToMeasureTest.php @@ -199,9 +199,9 @@ private static function chain(ScriptedRungSolver $solver, ?Deadline $deadline = { $declared = new Container('machine', Dimensions::mm(1510, 1510, 1510), costMinor: 40, madeToMeasure: self::machine(costPerSquareMetreMinor: 1000)); $items = Item::create('cube', Dimensions::mm(100, 100, 100), 0, 3)->instances(); - $method = new ReflectionMethod(SolverOrchestrator::class, 'madeToMeasureTrial'); - $method->setAccessible(true); - return $method->invoke(new SolverOrchestrator(), $solver, $declared, 1, $items, PackingConfig::fast(), $solver->stats ?? new SearchStats(), $deadline ?? Deadline::ofMilliseconds(60_000)); + $bridge = new ReflectionMethod(SolverOrchestrator::class, 'bridge'); + $bridge->setAccessible(true); + return \Packvium\Algorithm\Internal\MadeToMeasureTrial::madeToMeasureTrial($bridge->invoke(new SolverOrchestrator()), null, $solver, $declared, 1, $items, PackingConfig::fast(), $solver->stats ?? new SearchStats(), $deadline ?? Deadline::ofMilliseconds(60_000)); } private static function assertRefusedWith(string $class, string $fragment, array $request): void diff --git a/tests/MeasureReadingTest.php b/tests/MeasureReadingTest.php new file mode 100644 index 0000000..6b2e192 --- /dev/null +++ b/tests/MeasureReadingTest.php @@ -0,0 +1,51 @@ + self::VAST, 'unit' => 'ticks'], Length::class, 'mm')); + } + + public static function testAVanishingFractionIsNotPastTheCeiling(): void + { + foreach (['1/' . self::VAST, '0/' . self::VAST, self::VAST . '/0', '1/' . self::VAST . ' m'] as $text) { + self::assertSame(MeasureReading::UNREADABLE, MeasureReading::verdict($text, Length::class, 'mm'), $text); + } + } + + public static function testAWholeNumberPastTheLargestExactIntegerIsWholeHoweverItWasDecoded(): void + { + self::assertTrue(MeasureReading::isWholeBeyondExact(9_007_199_254_740_992)); + self::assertTrue(MeasureReading::isWholeBeyondExact(1e20)); + self::assertTrue(MeasureReading::isWholeBeyondExact(-1e20)); + self::assertFalse(MeasureReading::isWholeBeyondExact(9_007_199_254_740_991)); + self::assertFalse(MeasureReading::isWholeBeyondExact('100000000000000000000')); + self::assertFalse(MeasureReading::isWholeBeyondExact(1.5)); + self::assertFalse(MeasureReading::isWholeBeyondExact(\INF)); + } +} diff --git a/tests/PackingSequenceTest.php b/tests/PackingSequenceTest.php index e155ef9..12074c7 100644 --- a/tests/PackingSequenceTest.php +++ b/tests/PackingSequenceTest.php @@ -841,6 +841,12 @@ public static function testSharedFourLanguageSequenceFixtures(): void // ------------------------------------ business-rule prefix replay + public static function testAnEmptyScenePassesThePrefixReplay(): void + { + LoadingDependencyGraph::verifyLoadingPrefixBusinessRules([], [], Container::create('c', Dimensions::mm(10, 10, 20))); + self::assertTrue(true); + } + public static function testALoadingPrefixThatOverloadsAFragileSupporterIsCaughtAtItsStep(): void { $fragile = Item::create('fragile', Dimensions::mm(10, 10, 5), weight: '1kg', maxTopLoad: '500g'); diff --git a/tests/PrettyJsonStreamTest.php b/tests/PrettyJsonStreamTest.php index f760c1f..1a06a19 100644 --- a/tests/PrettyJsonStreamTest.php +++ b/tests/PrettyJsonStreamTest.php @@ -75,7 +75,7 @@ public static function testOutputLargerThanTheBufferIsWrittenWhole(): void { $value = ['rows' => \array_fill(0, 5000, ['id' => 'item-0001', 'size' => [1, 2, 3]])]; $streamed = self::streamed($value); - self::assertGreaterThan(65536 * 4, \strlen($streamed)); + self::assertGreaterThan(8192 * 4, \strlen($streamed)); self::assertSame(\json_encode($value, self::FLAGS), $streamed); } diff --git a/tests/RequestObjectsCorpusTest.php b/tests/RequestObjectsCorpusTest.php index 3b64cda..293059e 100644 --- a/tests/RequestObjectsCorpusTest.php +++ b/tests/RequestObjectsCorpusTest.php @@ -34,11 +34,28 @@ final class RequestObjectsCorpusTest extends TestCase private const UNITS = 'the request\'s length unit is an argument of each measure, not an object packed'; private const CONSTRUCTOR_FIRST = 'two faults: a constructor refuses its own value as the object is built, ' . 'before Packer::pack walks the request in the JSON order'; + private const CEILING_SECOND = 'a length past the admission ceiling also breaks its constructor\'s own rule, ' + . 'which refuses it as the object is built, before Packer::pack reaches the ceiling'; private const NEGATIVE_POSITION = 'a Point cannot hold a negative coordinate; the measure it is read with ' . 'refuses it as negative_measure, where the JSON path names the placement'; + private const JSON_NUMBER = 'a JSON number past 2^53 - 1 is a rule of the JSON text; an object holds the exact integer'; /** Cases with no object form: the value cannot be held, or the codec changes it. */ private const NOT_OBJECTS = [ + 'item.weight=2^63 ticks' => 'a Weight cannot hold more than PHP_INT_MAX ticks', + 'item.max_top_load=2^63 ticks' => 'a Weight cannot hold more than PHP_INT_MAX ticks', + 'container.tare_weight=2^63 ticks' => 'a Weight cannot hold more than PHP_INT_MAX ticks', + 'container.max_payload=2^63 ticks' => 'a Weight cannot hold more than PHP_INT_MAX ticks', + 'container.max_stack_density=2^63 ticks' => 'a Weight cannot hold more than PHP_INT_MAX ticks', + 'container.made_to_measure.tare_per_square_metre=2^63 ticks' => 'a Weight cannot hold more than PHP_INT_MAX ticks', + 'obstacle-origin-false' => 'ArrayCodec::point takes an array, not a boolean', + 'obstacle-origin-zero' => 'ArrayCodec::point takes an array, not a number', + 'obstacle-origin-nonempty-list' => 'the private codec reads a coordinate list as a different, valid Point at the origin', + 'obstacle-origin-empty-string' => 'ArrayCodec::point takes an array, not text', + 'obstacle-additional-origin-false' => 'ArrayCodec::point takes an array, not a boolean', + 'obstacle-additional-origin-zero' => 'ArrayCodec::point takes an array, not a number', + 'obstacle-additional-origin-nonempty-list' => 'the private codec reads a coordinate list as a different, valid Point at the origin', + 'obstacle-additional-origin-empty-string' => 'ArrayCodec::point takes an array, not text', 'request-not-object' => 'a request that is not an object has no objects', 'items-missing' => 'Packer::pack takes the items as an argument', 'items-not-list' => 'Packer::pack takes the items as a list of Item', @@ -77,6 +94,13 @@ final class RequestObjectsCorpusTest extends TestCase 'item-side-fraction' => self::TYPED, 'item-stacking-group-number' => self::TYPED, 'fixed-position-unparsable' => 'a Point holds integer ticks, not text', + // A length past a native int has no `Length` to hold it. + 'item-side-whole-beyond-exact' => self::TYPED, + 'item-side-negative-beyond-exact' => self::TYPED, + 'item-side-beyond-native-integers' => self::TYPED, + 'item-side-vast-mixed-fraction' => self::TYPED, + 'item-side-vast-with-a-unit-suffix' => 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, 'fixed_placements.position.y="-1"' => self::NEGATIVE_POSITION, @@ -133,12 +157,28 @@ final class RequestObjectsCorpusTest extends TestCase 'an-item-id-before-its-quantity' => self::CONSTRUCTOR_FIRST, 'item-ids-before-containers' => self::CONSTRUCTOR_FIRST, 'container-ids-before-fixed-placements' => self::CONSTRUCTOR_FIRST, + 'item.nesting_height=2^53 ticks' => self::CEILING_SECOND, + 'container.made_to_measure.minimum.length=2^53 ticks' => self::CEILING_SECOND, + 'container.made_to_measure.minimum.width=2^53 ticks' => self::CEILING_SECOND, + 'container.made_to_measure.minimum.height=2^53 ticks' => self::CEILING_SECOND, + 'container.made_to_measure.increment.length=2^53 ticks' => self::CEILING_SECOND, + 'container.made_to_measure.increment.height=2^53 ticks' => self::CEILING_SECOND, + 'container.obstacles.origin.x=2^53 ticks' => self::CEILING_SECOND, + 'container.obstacles.origin.y=2^53 ticks' => self::CEILING_SECOND, + 'container.obstacles.origin.z=2^53 ticks' => self::CEILING_SECOND, + 'container.obstacles.dimensions.length=2^53 ticks' => self::CEILING_SECOND, 'configuration-boolean-before-effort-budget' => 'two faults: the EffortBudget is built, and refuses its own ' . 'value, before the PackingConfig that holds it', + 'item.weight=2^53 as a number' => self::JSON_NUMBER, + 'item.max_top_load=2^53 as a number' => self::JSON_NUMBER, + 'container.tare_weight=2^53 as a number' => self::JSON_NUMBER, + 'container.max_payload=2^53 as a number' => self::JSON_NUMBER, + 'container.max_stack_density=2^53 as a number' => self::JSON_NUMBER, + 'container.made_to_measure.tare_per_square_metre=2^53 as a number' => self::JSON_NUMBER, ]; /** Pinned, so the skip set cannot grow without this line changing too. */ - private const SKIPPED = 88; + private const SKIPPED = 124; public static function testTheSkipSetIsPinnedAndNamesOnlyCorpusCases(): void { diff --git a/tests/SolverTest.php b/tests/SolverTest.php index f764ea0..2d32025 100644 --- a/tests/SolverTest.php +++ b/tests/SolverTest.php @@ -18,10 +18,12 @@ use Packvium\Algorithm\GroupBatcher; use Packvium\Algorithm\LayerSolver; use Packvium\Algorithm\MaximalSpaceSolver; +use Packvium\Algorithm\RawSolution; use Packvium\Algorithm\SearchStats; use Packvium\Algorithm\SingleContainerSolution; use Packvium\Algorithm\SolverOrchestrator; use Packvium\Algorithm\Space; +use Packvium\Algorithm\SpaceSubtraction; use Packvium\Algorithm\TimeLimitReached; use Packvium\Algorithm\UnknownSolverException; use Packvium\Config\PackingConfig; @@ -564,6 +566,58 @@ public static function testTheFastBlockStartEnumeratesOneModeAndBalancedBoth(): self::assertSame(['count','volume'],self::blockStart($cartons,PackingConfig::balanced(),$box)->modes); } + /** + * `quality` with a container-plan beam runs Python's stages -- every greedy order, + * each item type moved last in the best greedy order, then one wide refinement of the best + * order found. Pinned from Python on the same request; PHP refined the first two orders + * whatever they scored, and had no late-type neighbourhoods. + */ + public static function testAQualityBeamRunsPythonsStagedStarts(): void + { + $items=[...self::instances('b',40,40,40,['quantity'=>2]),...self::instances('a',30,30,30)]; + $box=Container::create('c',Dimensions::mm(100,100,100)); + $run=(new SolverOrchestrator())->solvePortfolio($items,[$box],PackingConfig::quality(),self::generous()); + $started=array_map(static fn($record):string=>$record->id,array_values(array_filter($run->starts,static fn($record):bool=>$record->started))); + self::assertSame([ + 'exact_small:small_edge:greedy','exact_small:volume:greedy','exact_small:seeded_2:greedy','exact_small:seeded_3:greedy', + 'exact_small:seeded_4:greedy','exact_small:seeded_5:greedy','homogeneous_blocks:small_edge', + 'extreme_points:small_edge:greedy','extreme_points:volume:greedy','extreme_points:seeded_2:greedy','extreme_points:seeded_3:greedy', + 'extreme_points:seeded_4:greedy','extreme_points:seeded_5:greedy', + 'maximal_spaces:small_edge:greedy','maximal_spaces:volume:greedy','maximal_spaces:seeded_2:greedy','maximal_spaces:seeded_3:greedy', + 'maximal_spaces:seeded_4:greedy','maximal_spaces:seeded_5:greedy','layer:small_edge:greedy', + 'extreme_points:seeded_3:greedy:late_a','extreme_points:seeded_3:greedy:late_b','extreme_points:seeded_3:greedy:beam', + ],$started); + } + + public static function testEachQualityStageSearchesAtItsOwnWidth(): void + { + $config=new PackingConfig(profile:SolverProfile::Quality,maxCandidatesPerItem:16,containerPlanBeamWidth:16,containerPlanNodeLimit:100_000,accessDirections:['+x']); + $width=static fn(string $name):PackingConfig=>(new ReflectionMethod(SolverOrchestrator::class,'startConfig'))->invoke(null,$name,$config); + foreach(['volume:greedy','volume:greedy:late_a'] as $name){ + self::assertSame([1,1,1],[$width($name)->maxCandidatesPerItem,$width($name)->containerPlanBeamWidth,$width($name)->containerPlanNodeLimit]); + self::assertSame(['+x'],$width($name)->accessDirections); + } + self::assertSame([4,4,100_000],[$width('volume:greedy:late_a:beam')->maxCandidatesPerItem,$width('volume:greedy:late_a:beam')->containerPlanBeamWidth,$width('volume:greedy:late_a:beam')->containerPlanNodeLimit]); + self::assertSame($config,$width('volume:greedy:beam')); + } + + public static function testANeighbourhoodWaitsForAGreedyExtremePointAnswer(): void + { + $stage=new ReflectionMethod(\Packvium\Algorithm\Internal\QualityStages::class,'stagedStart'); + $items=[...self::instances('b',40,40,40),...self::instances('a',30,30,30)]; + $layer=new LayerSolver(); + $layerOnly=[new RawSolution('layer:volume:greedy',[],[],new SearchStats())]; + $completed=['layer:volume:greedy'=>[$layer,'volume:greedy',$items]]; + self::assertSame(null,$stage->invoke(null,'neighborhood:a',$layerOnly,$completed,PackingConfig::quality())); + $extreme=new ExtremePointSolver(); + $late=[new RawSolution('extreme_points:volume:greedy:late_a',[],[],new SearchStats())]; + $completed=['extreme_points:volume:greedy:late_a'=>[$extreme,'volume:greedy:late_a',$items]]; + self::assertSame(null,$stage->invoke(null,'neighborhood:b',$late,$completed,PackingConfig::quality())); + [$solver,$name,$order]=$stage->invoke(null,'best:beam',$late,$completed,PackingConfig::quality()); + self::assertSame([$extreme,'volume:greedy:late_a:beam'],[$solver,$name]); + self::assertSame($items,$order); + } + public static function testBeamPackerPrecomputedFutureMatchesStandardEvaluation(): void { $box = Container::create('box', Dimensions::mm(300, 200, 200), quantity: 1); @@ -649,6 +703,18 @@ public static function testContainerPlanSearchRanksSeveralSurvivingPlansByTheirB self::assertSame([], Support::problems($result, $items, $containers)); } + /** Every two envelopes that intersect are a valid nesting pair. */ + private static function assertOnlyAdjacentPairsNest(ContainerState $state): void + { + foreach ($state->placements as $index => $placement) { + foreach (array_slice($state->placements, $index + 1) as $other) { + if ($placement->envelopeBox()->intersects($other->envelopeBox())) { + self::assertTrue(\Packvium\Domain\Nesting::isValidNesting($placement, $other), 'two placements overlap without nesting'); + } + } + } + } + private static function assertPhysicallySound(ContainerState $state): void { $boundary = new AxisAlignedBox(new Point(0, 0, 0), $state->container->innerDimensions); @@ -737,6 +803,20 @@ public static function testAnInjectedClockExpiresMidSearchWithoutSleeping(): voi self::assertSame(count($items),$packed+count($solution->unpacked)); } + /** 1.9.0 release frontier: twenty late-type neighbourhoods weigh one start between them. */ + public static function testLateTypeNeighbourhoodsWeighOneStartTogetherInTheTimeSlicing(): void + { + $weights=new ReflectionMethod(SolverOrchestrator::class,'sliceWeights'); + $solver=new ExtremePointSolver(); + $starts=[[$solver,'small_edge:greedy',[]],[$solver,'volume:greedy',[]],[$solver,'neighborhood:a',[]],[$solver,'neighborhood:b',[]],[$solver,'best:beam',[]]]; + self::assertSame([2,2,1,1,2],$weights->invoke(null,$starts)); + self::assertSame([1,1],$weights->invoke(null,\array_slice($starts,0,2))); + $frozen=Deadline::ofMilliseconds(1000,static fn():int=>0); + self::assertSame(250_000_000,$frozen->share(2,8)->remainingNs()); + self::assertSame(1_000_000_000,$frozen->share(3,3)->remainingNs()); + self::assertSame($frozen->share(1,4)->remainingNs(),$frozen->slice(4)->remainingNs()); + } + public static function testASliceKeepsTheInjectedClock(): void { $clock=self::checkBudgetClock(); @@ -1016,7 +1096,7 @@ public function score(ContainerState $state,Point $point,Dimensions $envelope):a public static function testSpaceAndNodeMetricsCountTheirOwnSolverWork(): void { $stats=new SearchStats(); - MaximalSpaceSolver::subtractAll( + SpaceSubtraction::subtractAll( [self::space(0,0,0,100,100,100)], [self::solid(20,20,20,30,30,30)], $stats, @@ -1170,19 +1250,19 @@ public static function testFlattenIsTheInverseOfBatching(): void public static function testCarvingNothingLeavesTheSpaceUntouched(): void { $whole = self::space(0, 0, 0, 100, 100, 100); - self::assertCount(1, MaximalSpaceSolver::subtractAll([$whole], [])); + self::assertCount(1, SpaceSubtraction::subtractAll([$whole], [])); } public static function testCarvingTheWholeSpaceLeavesNothing(): void { - self::assertSame([], MaximalSpaceSolver::subtractAll( + self::assertSame([], SpaceSubtraction::subtractAll( [self::space(0, 0, 0, 100, 100, 100)], [self::solid(0, 0, 0, 100, 100, 100)])); } public static function testNoRemainingSpaceOverlapsTheCarvedSolid(): void { $obstacle = self::solid(20, 20, 0, 30, 30, 100); - foreach (MaximalSpaceSolver::subtractAll([self::space(0, 0, 0, 100, 100, 100)], [$obstacle]) as $remaining) { + foreach (SpaceSubtraction::subtractAll([self::space(0, 0, 0, 100, 100, 100)], [$obstacle]) as $remaining) { self::assertFalse((new AxisAlignedBox($remaining->origin, $remaining->dimensions))->intersects($obstacle)); } } @@ -1191,7 +1271,7 @@ public static function testNoRemainingSpaceIsContainedInAnother(): void { // Without this filter every placement multiplies the space list and the solver // degenerates into an exponential scan of overlapping duplicates. - $spaces = MaximalSpaceSolver::subtractAll( + $spaces = SpaceSubtraction::subtractAll( [self::space(0, 0, 0, 100, 100, 100)], [self::solid(20, 20, 20, 30, 30, 30)]); foreach ($spaces as $index => $one) { foreach ($spaces as $position => $other) { @@ -1219,8 +1299,8 @@ public static function testTheFreeSpaceListNeverExceedsTheBudget(): void $x = ($k * 131) % 2900; $y = ($k * 277) % 2900; $z = ($k * 419) % 2900; - $spaces = MaximalSpaceSolver::subtractAll($spaces, [self::solid($x, $y, $z, $size, $size, $size)]); - self::assertLessThanOrEqual(MaximalSpaceSolver::MAX_MAXIMAL_SPACES, count($spaces)); + $spaces = SpaceSubtraction::subtractAll($spaces, [self::solid($x, $y, $z, $size, $size, $size)]); + self::assertLessThanOrEqual(SpaceSubtraction::MAX_MAXIMAL_SPACES, count($spaces)); } } @@ -1237,7 +1317,7 @@ public static function testTheFreeSpaceOrderIsPinned(): void for ($k = 0; $k < 90; $k++) { [$l, $w, $h] = [40 + ($k * 37) % 300, 30 + ($k * 53) % 250, 20 + ($k * 71) % 200]; [$x, $y, $z] = [($k * 131) % 2700, $k % 3 === 0 ? 0 : ($k * 277) % 1750, $k % 4 === 0 ? 0 : ($k * 419) % 1300]; - $spaces = MaximalSpaceSolver::subtractAll($spaces, [self::solid($x, $y, $z, $l, $w, $h), self::solid($x, $y, $z, $l, $w, intdiv($h, 2))], $stats); + $spaces = SpaceSubtraction::subtractAll($spaces, [self::solid($x, $y, $z, $l, $w, $h), self::solid($x, $y, $z, $l, $w, intdiv($h, 2))], $stats); foreach ($spaces as $space) { $trace .= "{$space->origin->x},{$space->origin->y},{$space->origin->z},{$space->dimensions->length->ticks},{$space->dimensions->width->ticks},{$space->dimensions->height->ticks};"; } @@ -1291,7 +1371,7 @@ public static function testEveryFreePointIsStillCoveredAfterCarving(): void // The decisive property of a maximal-space decomposition: carving may not lose // room. Sampled on a lattice across the container. $obstacles = [self::solid(20, 20, 0, 30, 30, 100), self::solid(70, 0, 0, 30, 100, 40)]; - $spaces = MaximalSpaceSolver::subtractAll([self::space(0, 0, 0, 100, 100, 100)], $obstacles); + $spaces = SpaceSubtraction::subtractAll([self::space(0, 0, 0, 100, 100, 100)], $obstacles); for ($x = 0; $x < 100; $x += 7) { for ($y = 0; $y < 100; $y += 7) { for ($z = 0; $z < 100; $z += 13) { @@ -1424,6 +1504,36 @@ public static function testTheLatticeKeepsDifferentDeclaredNestingTypesOutOfOneC self::assertPhysicallySound($solution->state); } + public static function testALatticeNestsADeepColumnInPairs(): void + { + // A third 120mm cup sunk 100mm into the second would reach 80mm into the first, + // and only an adjacent pair may overlap, so each pair is 140mm tall. + $nesting = ['quantity' => 5, 'nestingHeight' => Length::mm(100), 'allowedRotations' => [Rotation::LWH]]; + $heights = static function (int $room) use ($nesting): array { + $solution = (new GridSolver())->packOne( + Container::create('c', Dimensions::mm(100, 100, $room)), 1, + self::instances('cup', 100, 100, 120, $nesting), PackingConfig::fast(), new SearchStats(), self::generous(), + ); + self::assertOnlyAdjacentPairsNest($solution->state); + return array_map(static fn($placement): int => intdiv($placement->position->z, 16000), $solution->state->placements); + }; + + self::assertSame([0, 20, 140, 160, 280], $heights(400)); + self::assertSame([0, 20, 140, 160], $heights(399)); + } + + public static function testALatticeChainsAColumnNestingAtMostHalfItsHeight(): void + { + $nesting = ['quantity' => 3, 'nestingHeight' => Length::mm(50), 'allowedRotations' => [Rotation::LWH]]; + $solution = (new GridSolver())->packOne( + Container::create('c', Dimensions::mm(100, 100, 200)), 1, + self::instances('cup', 100, 100, 100, $nesting), PackingConfig::fast(), new SearchStats(), self::generous(), + ); + + self::assertSame([0, 800000, 1600000], array_map(static fn($placement): int => $placement->position->z, $solution->state->placements)); + self::assertOnlyAdjacentPairsNest($solution->state); + } + public static function testTwelveRotationEquivalentItemsSplitAcrossTwoTypesStillShareOneContainer(): void { $box = Container::create('c', Dimensions::mm(25, 36, 21)); diff --git a/tests/SupportPolygonTest.php b/tests/SupportPolygonTest.php index 774d54e..f4b6e40 100644 --- a/tests/SupportPolygonTest.php +++ b/tests/SupportPolygonTest.php @@ -136,4 +136,67 @@ public static function testTwoNarrowSupportersCanStillBracketTheCentroid(): void $hull = SupportPolygon::convexHull(SupportPolygon::contactHullPoints($candidate, [$leftRail, $rightRail])); self::assertTrue(SupportPolygon::pointInHull(SupportPolygon::doubledCentroid($candidate), $hull)); } + + // ------------------------------------------------------- rare and absurd supports + + /** @param list $supporters */ + private static function supported(AxisAlignedBox $candidate, array $supporters): bool + { + $hull = SupportPolygon::convexHull(SupportPolygon::contactHullPoints($candidate, $supporters)); + return SupportPolygon::pointInHull(SupportPolygon::doubledCentroid($candidate), $hull); + } + + public static function testAOneTickKnifeEdgeUnderTheCentroidCarriesTheBox(): void + { + self::assertTrue(self::supported(self::box(0, 0, 10, 10), [self::box(5, 0, 1, 10)])); + self::assertFalse(self::supported(self::box(0, 0, 10, 10), [self::box(6, 0, 1, 10)])); + } + + public static function testASupporterWiderThanTheFootprintIsClippedToIt(): void + { + $points = SupportPolygon::contactHullPoints(self::box(10, 10, 10, 10), [self::box(0, 0, 100, 100)]); + self::assertSame([[20, 20], [20, 40], [40, 20], [40, 40]], self::pairs($points)); + } + + public static function testACornerSquareWhoseInnerCornerIsTheCentroidCarriesIt(): void + { + self::assertTrue(self::supported(self::box(0, 0, 40, 40), [self::box(0, 0, 20, 20)])); + self::assertFalse(self::supported(self::box(0, 0, 40, 40), [self::box(0, 0, 20, 19)])); + } + + /** @return list */ + private static function legsOnACircle(callable $keep): array + { + $legs = []; + for ($degree = 0; $degree < 360; $degree++) { + $angle = deg2rad($degree); + if ($keep($angle)) { + $legs[] = self::box((int) round(500 + 400 * cos($angle)), (int) round(500 + 400 * sin($angle)), 1, 1); + } + } + return $legs; + } + + public static function testThreeHundredAndSixtyLegsOnACircleCarryTheCentroid(): void + { + self::assertTrue(self::supported(self::box(0, 0, 1000, 1000), self::legsOnACircle(static fn(float $a): bool => true))); + } + + public static function testLegsOnHalfACircleLeaveTheCentroidHanging(): void + { + $legs = self::legsOnACircle(static fn(float $a): bool => sin($a) > 0.1); + self::assertFalse(self::supported(self::box(0, 0, 1000, 1000), $legs)); + } + + public static function testRepeatedAndReorderedSupportersGiveTheSameHull(): void + { + $legs = [self::box(0, 0, 5, 5), self::box(35, 0, 5, 5), self::box(0, 35, 5, 5)]; + $candidate = self::box(0, 0, 40, 40); + $hull = static fn(array $order): array => self::pairs( + SupportPolygon::convexHull(SupportPolygon::contactHullPoints($candidate, $order)) + ); + self::assertSame($hull($legs), $hull(array_reverse($legs))); + self::assertSame($hull($legs), $hull(array_merge($legs, $legs))); + self::assertTrue(self::supported($candidate, $legs)); + } }