diff --git a/CHANGELOG.md b/CHANGELOG.md index 26ba317..26ce644 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,44 @@ 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.6.0] + +Boxes cut to measure, flat bags, stacking groups and a volume-first objective, all additive. A +request that uses none of them keeps its meaning; `fast` and `balanced` may now answer better. + +### Added + +- **`Packvium\Config\EffortBudget`**, a public name for the effort budget, and + **`OperationalArtifact::replayLevel($result)`**. +- **`Packvium\Domain\MadeToMeasure` and `Container`'s `$madeToMeasure`.** A container becomes an + on-demand box machine (largest box, minimum, cut step, board price and weight per m²); each + packed box is the load's extent rounded up onto the machine grid and priced as cut. + `PackedContainer::achievedDimensions()` reports the extent. +- **Flat bags: `Container`'s `$deformableBoundary = 'flat_bag'`** and `Packvium\Domain\FlatBag`. + A poly mailer admits a load when length plus thickness and width plus thickness fit; + dimensional weight is billed from the load's size. +- **Stacking groups: `Item`'s `$stackingGroup` and `$acceptsStackingGroups`.** Which item + classes + may rest directly on which. +- **The `maximum_volume` objective** and `Packvium\Objective\MaximumVolumeSolutionScorer`. +- **A warning for items resting on nothing** when `minimumSupportRatio` is 0 + (`unsupported_placements: N ...` in the result's warnings). No answer changes. + +### Changed + +- **An unpacked item names the limit that left it out, the same in every engine.** + Where the search used to fall back to `no_feasible_placement` or `search_exhausted`, an item a + fresh container would take but none is left reports `container_inventory_exhausted`, and one + that overloads an axle wherever it stands alone reports `axle_overloaded`; both are + `inferred`. Code that matched the old reason for these cases must match the new one. +- **`quality` orders its beam by a `convex_hull` item's own solid**, not its box, so + it no longer assumes a second wedge cannot fit when it can. +- **The container plan counts a `convex_hull` item by its own solid too**, so + `quality` no longer ranks a plan as if wedges that share a container each needed their own. +- **`fast` and `balanced` add the block solver as one more start** on multi-type loads and keep + its answer only when strictly better. +- **The exact solver ranks volume first under `maximum_volume`.** + ## [1.5.0] No API changes. The beam search is faster with identical placements, a block answer reports diff --git a/CITATION.cff b/CITATION.cff index e11c019..5ca759e 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,7 +5,7 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.5.0" +version: "1.6.0" license: MIT url: "https://packvium.com" repository-code: "https://github.com/toxakara/packvium-php" diff --git a/README.md b/README.md index 04da502..24c3f2e 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.5.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.6.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) @@ -70,6 +70,12 @@ echo '{"items":[{"id":"box","quantity":8,"dimensions":{"length":"50","width":"50 | vendor/bin/packvium ``` +Support is not required by default: `minimum_support_ratio` is 0, so an item may rest on +nothing above the container floor, and the result then says so in `warnings` +(`unsupported_placements: N placement(s) rest on nothing above the container floor; ...`). +To require support, set it above 0 — `'configuration' => ['minimum_support_ratio' => 0.75]`, or +`new PackingConfig(minimumSupportRatio: 0.75)` in the object API. + The library is framework-independent: no facades, no static state, no container bindings. Construct a `Packer` and call it. @@ -333,7 +339,7 @@ CodeMeta form. @software{packvium_php, author = {{Packvium contributors}}, title = {Packvium for PHP}, - version = {1.5.0}, + version = {1.6.0}, license = {MIT}, url = {https://packvium.com} } diff --git a/bin/packvium b/bin/packvium index 1139852..1f08ddf 100755 --- a/bin/packvium +++ b/bin/packvium @@ -3,7 +3,9 @@ declare(strict_types=1); require dirname(__DIR__) . '/autoload.php'; use Packvium\Serialization\ArrayCodec; +use Packvium\Support\PrettyJsonStream; $input = stream_get_contents(STDIN); if ($input === false || trim($input) === '') { fwrite(STDERR, "Expected packing JSON on stdin\n"); exit(2); } -try { $data=json_decode($input,true,512,JSON_THROW_ON_ERROR); echo json_encode(ArrayCodec::pack($data),JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES),"\n"; } +// Streamed, not `echo json_encode(...)`: the encoded result is never held next to its array. +try { $result=ArrayCodec::pack(json_decode($input,true,512,JSON_THROW_ON_ERROR)); PrettyJsonStream::write($result,STDOUT); fwrite(STDOUT,"\n"); } catch(Throwable $e){ fwrite(STDERR,$e->getMessage()."\n"); exit(1); } diff --git a/codemeta.json b/codemeta.json index 93173ab..e998cd9 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.5.0", + "version": "1.6.0", "license": "https://spdx.org/licenses/MIT", "author": [ { diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index 6f2b855..1ee0c28 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -52,7 +52,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.5.0` freezes the public API. Field names, status codes, the objective +Version `1.6.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 b3d3799..df8fd8c 100644 --- a/docs/PUBLIC-API.md +++ b/docs/PUBLIC-API.md @@ -3,6 +3,20 @@ ## Core inputs - `Item`: id, dimensions, weight, quantity, rotations, upright/floor/stacking rules, top-load limit, support ratio, group, tags, metadata, and an optional `nesting_height` (how much this item sinks into an identical one beneath it when stacked). Only the same item type with the exact same footprint may nest; its adjacent predecessor is one full-footprint direct supporter for support ratio, ground-contact, stack/load and route rules, while non-adjacent same-column face coincidences are shadowed. An optional, exact non-negative integer `value` (no unit or currency — the caller's own economic scale) means nothing to placement or to any other objective; only the `maximum_value` objective reads it. +- **Building a Rust `Item` or `Container` in code.** `Item::new(id, dimensions, + weight, quantity)` and `Container::new(id, inner_dimensions)` fill every other field with + the value a JSON request gets when it leaves that field out. Set the rest with struct update + syntax (`Item { stackable: false, ..Item::new(...) }`), which keeps compiling when a release + adds a field; a full struct literal does not. +- **Stacking groups.** `stacking_group` (a non-empty string, default none) names an + item's class; `accepts_stacking_groups` (non-empty strings, default empty) lists the classes + it may carry directly on its top face. Empty is unconstrained; a non-empty list refuses every + other class and every item with no class, edge by edge, never transitively; `stackable: + false` dominates. The engines expose the same two fields on their item type: Python + `Item.stacking_group` / `Item.accepts_stacking_groups`, PHP trailing constructor parameters + `$stackingGroup` / `$acceptsStackingGroups`, Rust `Item::stacking_group` / + `Item::accepts_stacking_groups`, and the TypeScript request type. See + STACKING-GROUPS.md. - **Item geometry beyond the box.** `shape_type` is an enum — `rigid_cuboid` (the default), `convex_hull`, `compressible` — accompanied by `hull_vertices`, `compression_ratio` and `max_compression_pressure_kpa`. **A request that @@ -45,12 +59,51 @@ scorer precisely so all four engines can be held to the same price; only the `lowest_landed_cost` objective reads it, and a request that omits it behaves exactly as it did before the field existed. +- **Flat bags.** `deformable_boundary: {"kind": "flat_bag"}` (absent or `null`: a rigid + container) makes the container a two-sheet bag of usable flat size `inner_dimensions.length` + x `.width`, filled to at most `.height`. A packing is admitted only when, with `a`, `b`, `c` + the largest envelope `x2`, `y2`, `z2` of its placements, `a + c <= L` and `b + c <= W` as well + as the ordinary boundary; equality fits. Each packed bag reports `achieved_dimensions` + `(a, b, c)`, the package dimensional weight is billed on (and the size a nested level packs + it as); objective key 3 still uses the declared `L·W·H`. Next to `obstacles` (non-empty), + `axles`, `access_directions`, `max_stack_density`, `outer_dimensions`, `made_to_measure` or a + positive `void_fill_reserve_ratio` it is refused with `invalid_request` / `not_allowed`, and a + fixed set past its girth with `invalid_fixed_placement` / `cannot_hold`, detail + `bag_girth_exceeded: `. The engines expose it as Python + `Container.deformable_boundary` (`"flat_bag"` or None, last field) with + `PackedContainer.achieved_dimensions` / `.billed_dimensions`, PHP the trailing constructor + parameter `$deformableBoundary` with `PackedContainer::achievedDimensions()` / + `billedDimensions()`, Rust `Container::deformable_boundary: Option` with + `PackedContainer::achieved_dimensions()` / `billed_dimensions()`, and the TypeScript request + type. See DEFORMABLE-CONTAINERS.md. +- **Made-to-measure containers.** `made_to_measure` (absent or `null`: a stock + container) makes the container an on-demand box machine whose largest box is + `inner_dimensions`: `minimum` and `increment` per axis (required; `minimum` equal to + `inner_dimensions` pins an axis, and `inner_dimensions - minimum` must be a multiple of + `increment`), `cost_per_square_metre_minor` (integer, default 0), `tare_per_square_metre` + (a weight measure, default 0) and `outer_allowance` (per axis, default 0). Each packed + container is the box cut for it: `inner_dimensions` the achieved extent rounded up onto the + grid, `outer_dimensions` that plus `outer_allowance`, and a `made_to_measure` result block + with its `cost_minor` (declared `cost_minor` plus `ceil(price x 2(LW + LH + WH) / 1 m^2)`) + and `tare_weight` (declared tare plus the board, rounded up the same way), both inside every + objective and `gross_weight`; `achieved_dimensions` reports the extent before rounding. + `outer_dimensions` or `deformable_boundary` next to it is `invalid_request` / `not_allowed`; + `axles`, non-empty `obstacles`, a positive `void_fill_reserve_ratio` or a fixed placement in + the container is `unsupported_feature`; a largest box priced above `2^53 - 1` is + `invalid_value`. The engines expose it as Python `Container.made_to_measure` (a + `packvium.MadeToMeasure`, last field), PHP the trailing constructor parameter + `?MadeToMeasure $madeToMeasure` (`Packvium\Domain\MadeToMeasure`), Rust + `Container::made_to_measure: Option`, and the TypeScript request type. See + MADE-TO-MEASURE-CONTAINERS.md. - `PackingConfig`: solver profile, deadline, alternatives, deterministic seed, clearance, - support threshold, exact-search limit, beam/order budgets, the portable + support threshold (`minimum_support_ratio`, default 0: support is not required, and an + item may rest on nothing above the floor; set it above 0 to require that share of the + base to be carried), exact-search limit, beam/order budgets, the portable `max_candidate_points` search-memory bound, deterministic global-plan controls `container_plan_beam_width` / `container_plan_node_limit`, and an optional `effort_budget` that bounds all four stable implementations by counted work instead of wall-clock - time. `solvers` is an ordered list: every named strategy is run, stable ties prefer + time. In code it is Python `packvium.EffortBudget`, PHP `Packvium\Config\EffortBudget` and + Rust `packvium_core::EffortBudget`. `solvers` is an ordered list: every named strategy is run, stable ties prefer the earlier name, and an unknown name is a structured error. The optional The stable solver names are `grid`, `extreme_points`, `homogeneous_blocks`, `layer`, `maximal_spaces` and `exact_small`. `homogeneous_blocks` is the unrestricted @@ -124,7 +177,10 @@ move backwards. This is a testing seam, not a serialized request field. - objective score — a five-key lexicographic vector of exact integers, identical across every implementation (OBJECTIVE.md) — and solver statistics; - the exact `catalog_versions_used` lineage from the request (an empty array when no catalog was involved), preserved by Python, PHP, Rust and JavaScript; -- warnings and top-K alternatives. +- warnings and top-K alternatives. With `minimum_support_ratio` at its default 0, a result + with a placement resting on nothing above the floor carries one + `unsupported_placements: N placement(s) rest on nothing above the container floor; ...` + line, byte-identical in every engine; each alternative carries its own. ### `alternatives`, and what it is not @@ -315,6 +371,10 @@ by the same `packvium_core::rebalance_json` adapter: - Python/PyO3 and WebAssembly: `rebalance_json(request, result, max_moves)`; - N-API: `rebalanceJson(request, result, maxMoves)`. +`@packvium/browser` wraps the WebAssembly operation as `rebalanceWeight(request, result, +{maxMoves})`, the Node package's name and signature, resolving to the same document +. + The Node package's public `rebalanceWeight` automatically uses that N-API operation when the addon is healthy and otherwise runs the deterministic JavaScript implementation. Boundary adapters exchange canonical JSON and do not duplicate the @@ -439,6 +499,17 @@ details. A structural bound takes precedence over a deadline: an oversized item `proven` even if the overall run timed out. Conversely, `time_limit`, `search_exhausted` and other unfinished-search outcomes can never carry `proven`. +Container, axle and stop limits have one code each, the same in every engine. +Among the containers that admit an item on every structural count, an axle that would be +overloaded wherever the item stood alone in each of them gives `axle_overloaded`. Failing +that, when every such container that would take the item alone is out of stock, or +`max_containers` is reached, the item is `container_inventory_exhausted`: `max_items`, a +cumulative `max_payload`, `tag_limits`, stop accessibility and an axle's share of a full +load can only refuse an item a fresh container would take, so they all end there. Both are +`inferred` -- neither is a certificate, since a counterweight behind the rear axle can +relieve the front one -- and both rank after the structural proofs, the deadline, the +effort budget and `group_cannot_fit_together`. + ## Commercial and control-plane API Three deterministic functions over one canonical JSON document -- a carrier quote, an @@ -559,7 +630,9 @@ looked up in the plan's order and never re-ordered. **Replay is stated, not assumed.** `provenance.replay.level` is `exact` only when solving the embedded request again must reproduce the result. When the search stopped on wall-clock time, or the result does not record how it was solved, the level is `not_guaranteed`, and `because` -names the field that decided it. +names the field that decided it. Python `packvium.artifacts.replay_level(result)` and PHP +`OperationalArtifact::replayLevel($result)` answer the same level without building the +artifact. **Refusals use one closed set of codes** in every language (`invalid_request`, `invalid_result`, `invalid_plan_input`, `mixed_units`, `number_out_of_range`, `invalid_string`, `invalid_value`, diff --git a/examples/extensions.php b/examples/extensions.php index d661eed..ff0ad84 100644 --- a/examples/extensions.php +++ b/examples/extensions.php @@ -27,8 +27,8 @@ require dirname(__DIR__) . '/autoload.php'; -use Packvium\Algorithm\{EffortBudget, RawSolution, SingleContainerSolution}; -use Packvium\Config\{PackingConfig, SolverProfile}; +use Packvium\Algorithm\{RawSolution, SingleContainerSolution}; +use Packvium\Config\{EffortBudget, PackingConfig, SolverProfile}; use Packvium\Constraint\{ConstraintContext, ConstraintResult, PlacementConstraint}; use Packvium\Domain\{Container, Dimensions, Item, Rotation}; use Packvium\Extension\{ContainerSelector, DefaultContainerSelector, ExtensionRegistry}; @@ -36,9 +36,11 @@ use Packvium\Packer; use Packvium\Unit\Length; -// The interfaces take a few types that live in `Packvium\Algorithm` (`RawSolution`, -// `SingleContainerSolution`, `EffortBudget`). Implementing an interface means naming them; -// read only what is shown here from them, since that namespace is not frozen like the rest. +// `SolutionScorer` and `ContainerSelector` are handed the solver's own results, +// `RawSolution` and `SingleContainerSolution`, which live in the internal +// `Packvium\Algorithm` namespace. Implementing either interface means naming them, and +// their names are held by the interfaces' frozen signatures; read only what is shown here +// from them -- a `RawSolution`'s `containers` and `unpacked` -- since the rest is not frozen. /** * Counted work, not a clock, bounds every solve here, so the example prints the same on diff --git a/examples/reproducibility.php b/examples/reproducibility.php index 13408ea..0acb5e0 100644 --- a/examples/reproducibility.php +++ b/examples/reproducibility.php @@ -29,8 +29,8 @@ require dirname(__DIR__) . '/autoload.php'; -use Packvium\Algorithm\EffortBudget; -use Packvium\Config\{PackingConfig, SolverProfile}; +use Packvium\Artifacts\OperationalArtifact; +use Packvium\Config\{EffortBudget, PackingConfig, SolverProfile}; use Packvium\Domain\{Container, Dimensions, Item}; use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; @@ -74,20 +74,14 @@ function solveOn(PackingConfig $config, int $step, array $items, array $boxes): return (new Packer($config, new ExtensionRegistry(), null, host($step)))->pack($items, $boxes); } -/** - * Whether an artifact of this result could promise an exact replay: only when no clock - * stopped the search. It is the rule `Packvium\Artifacts\OperationalArtifact` applies. - */ -function replayLevel(PackingResult $result): string -{ - return $result->toArray()['algorithm']['time_limit_reached'] ? 'not_guaranteed' : 'exact'; -} - function describe(PackingResult $result): string { $opened = implode(',', array_map(static fn($packed): string => $packed->container->id, $result->containers)); + // The replay promise an operational artifact of this result would make: `exact` only + // when no clock stopped the search. + $replay = OperationalArtifact::replayLevel($result->toArray()); return sprintf('%-6s left out %2d termination %-12s replay %s', - $opened, count($result->unpacked), $result->termination->code, replayLevel($result)); + $opened, count($result->unpacked), $result->termination->code, $replay); } function section(string $title): void diff --git a/examples/trucking.php b/examples/trucking.php index 5579ad3..e6846ef 100644 --- a/examples/trucking.php +++ b/examples/trucking.php @@ -29,8 +29,7 @@ require dirname(__DIR__) . '/autoload.php'; -use Packvium\Algorithm\EffortBudget; -use Packvium\Config\{PackingConfig, SolverProfile}; +use Packvium\Config\{EffortBudget, PackingConfig, SolverProfile}; use Packvium\Domain\{Axle, Container, Dimensions, Item, Rotation}; use Packvium\Packer; use Packvium\Result\PackingResult; diff --git a/src-legacy/Algorithm/BeamPacker.php b/src-legacy/Algorithm/BeamPacker.php index 9a93cbc..bb7db24 100644 --- a/src-legacy/Algorithm/BeamPacker.php +++ b/src-legacy/Algorithm/BeamPacker.php @@ -3,7 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; use Packvium\Constraint\PlacementConstraint; -use Packvium\Domain\{Container,ItemInstance,Placement}; +use Packvium\Domain\{Container,ItemInstance,Nesting,Placement}; use Packvium\Extension\CandidateScorer; use Packvium\Support\{BigInt,StableSorter}; final class BeamPacker @@ -21,6 +21,7 @@ public static function pack(Container $container,int $sequence,array $items,Pack $branchWidth=max(1,$config->maxCandidatesPerItem); $width=max(1,$config->containerPlanBeamWidth); if($width===1)return self::packLegacy($container,$sequence,$items,$config,$constraints,$stats,$deadline,$scorer,$branchWidth); + $byVolume=self::ranksByVolume($config); $nodeLimit=$width>1?$config->containerPlanNodeLimit:null; $nodes=0; $batches=GroupBatcher::batches($items); @@ -36,7 +37,7 @@ public static function pack(Container $container,int $sequence,array $items,Pack // nodeKey builds an O(m) placement signature and BigInt chunks; computing it once // per node instead of once per usort comparison (and once per incumbent test) // changes no ordering: usort is stable and the keys are identical values. - $incumbentKey=self::nodeKey($incumbent); + $incumbentKey=self::nodeKey($incumbent,$byVolume); foreach($batches as $position=>$batch){ $expansions=[];$exhausted=false; foreach($beam as [$state,$unplaced]){ @@ -52,33 +53,29 @@ public static function pack(Container $container,int $sequence,array $items,Pack $futureCount=count($future); foreach($expansions as [$state,$unplaced]){ $unplacedCount=count($unplaced)+$futureCount; - // More unplaced items loses on the key's first component; skip building a signature that cannot win. - if($unplacedCount>$incumbentKey[0])continue; - $used=$state->usedVolume;$signature=[]; - foreach($state->placements as $p){ - $signature[]=$p->instance->id().'@'.$p->envelopeOrigin->x.','.$p->envelopeOrigin->y.','.$p->envelopeOrigin->z; - } - $descendingUsed=array_map(static function (int $c): int { - return -$c; - },\Packvium\Support\BigInt::chunks($used)); - $candidateKey=array_merge([$unplacedCount,$unplacedCount,-count($state->placements),$state->maxZ],$descendingUsed,[implode('|',$signature)]); + $descendingUsed=self::descending($state->usedVolume); + // A worse leading component loses whatever follows; skip building a signature that cannot win. + if($byVolume?$descendingUsed>array_slice($incumbentKey,0,count($descendingUsed)):$unplacedCount>$incumbentKey[0])continue; + $candidateKey=$byVolume + ?array_merge($descendingUsed,$descendingUsed,[$unplacedCount,$state->maxZ,$state->placementSignature()]) + :array_merge([$unplacedCount,$unplacedCount,-count($state->placements),$state->maxZ],$descendingUsed,[$state->placementSignature()]); if($candidateKey<$incumbentKey){$incumbent=[$state,array_merge($unplaced,$future)];$incumbentKey=$candidateKey;} } if($expansions===[])break; $futureInfo=self::precomputeFuture($future,($nullsafeVariable1 = $container->maxPayload) ? $nullsafeVariable1->ticks : null); - $beam=array_slice(StableSorter::sortBy($expansions,static function (array $node) use ($futureInfo): array { - return self::nodeKeyPrecomputed($node,$futureInfo); + $beam=array_slice(StableSorter::sortBy($expansions,static function (array $node) use ($futureInfo, $byVolume): array { + return self::nodeKeyPrecomputed($node,$futureInfo,$byVolume); }),0,$width); if($exhausted){ [$state,$unplaced]=$incumbent; return new SingleContainerSolution($state,$unplaced,false,$deadline->expired()); } } - $ordered=StableSorter::sortBy($beam,static function (array $node): array { - return self::nodeKey($node); + $ordered=StableSorter::sortBy($beam,static function (array $node) use ($byVolume): array { + return self::nodeKey($node,$byVolume); }); $completed=$ordered[0]??null; - [$state,$unplaced]=$completed!==null&&self::nodeKey($completed)<$incumbentKey?$completed:$incumbent; + [$state,$unplaced]=$completed!==null&&self::nodeKey($completed,$byVolume)<$incumbentKey?$completed:$incumbent; return new SingleContainerSolution($state,$unplaced); } @@ -92,6 +89,7 @@ public static function pack(Container $container,int $sequence,array $items,Pack private static function packLegacy(Container $container,int $sequence,array $items,PackingConfig $config,array $constraints,SearchStats $stats,Deadline $deadline,CandidateScorer $scorer,int $width):SingleContainerSolution { $batches=GroupBatcher::batches($items); + $byVolume=self::ranksByVolume($config); $beam=[[new ContainerState($container,$sequence),[]]]; foreach($batches as $position=>$batch){ $expansions=[];$exhausted=false; @@ -102,8 +100,8 @@ private static function packLegacy(Container $container,int $sequence,array $ite if($children!==[]){foreach($children as $child)$expansions[]=[$child,$unplaced];} else $expansions[]=[$state,array_merge($unplaced,$batch)]; } - $beam=array_slice(StableSorter::sortBy($expansions,static function (array $node): array { - return self::nodeKey($node); + $beam=array_slice(StableSorter::sortBy($expansions,static function (array $node) use ($byVolume): array { + return self::nodeKey($node,$byVolume); }),0,$width); if($exhausted){ [$state,$unplaced]=$beam[0]; @@ -193,8 +191,10 @@ private static function precomputeFuture(array $future,?int $maxPayloadTicks):ar } $volumes=null; if(!$hasNesting){ + // Occupied, not declared: the free space these are compared with is occupied + // volume, and two wedges each declaring the whole crate both fit in it. $volumes=array_map(static function (ItemInstance $item): string { - return $item->dimensions()->volumeString(); + return Nesting::itemOccupiedVolume($item); },$future); usort($volumes,static function (string $a, string $b): int { return BigInt::compare($a,$b); @@ -236,30 +236,49 @@ private static function unpackedLowerBoundPrecomputed(ContainerState $state,int return $unplacedCount+$futureCount-$possible; } - private static function nodeKeyPrecomputed(array $node,array $futureInfo):array + private static function ranksByVolume(PackingConfig $config):bool { - [$state,$unplaced]=$node; - $used=$state->usedVolume;$signature=[]; - foreach($state->placements as $p){ - $signature[]=$p->instance->id().'@'.$p->envelopeOrigin->x.','.$p->envelopeOrigin->y.','.$p->envelopeOrigin->z; - } - $descendingUsed=array_map(static function (int $c): int { + return $config->objective==='maximum_volume'; + } + + /** @return list Chunks negated, so ascending array order means the larger value first. */ + private static function descending(string $value):array + { + return array_map(static function (int $c): int { return -$c; - },\Packvium\Support\BigInt::chunks($used)); - return array_merge([self::unpackedLowerBoundPrecomputed($state,count($unplaced),$futureInfo),count($unplaced),-count($state->placements),$state->maxZ],$descendingUsed,[implode('|',$signature)]); + },BigInt::chunks($value)); } - /** @param array{0:ContainerState,1:list} $node */ - private static function nodeKey(array $node):array + /** + * An upper bound on the volume this node can still end with: what is placed, plus the + * future items' total volume capped by the free space. For nesting, nominal volumes + * are not additive, so the free space alone is the bound. + */ + private static function reachableVolume(ContainerState $state,array $futureInfo):string + { + if($futureInfo['count']===0)return $state->usedVolume; + $free=BigInt::subtract($state->container->innerDimensions->volumeString(),$state->usedVolume); + $volumes=$futureInfo['volumes']; + $future=$volumes===null?$free:$volumes[count($volumes)-1]; + return BigInt::add($state->usedVolume,BigInt::compare($future,$free)<0?$future:$free); + } + + private static function signature(ContainerState $state):string + { + return $state->placementSignature(); + } + + private static function nodeKeyPrecomputed(array $node,array $futureInfo,bool $byVolume=false):array { [$state,$unplaced]=$node; - $used=$state->usedVolume;$signature=[]; - foreach($state->placements as $p){ - $signature[]=$p->instance->id().'@'.$p->envelopeOrigin->x.','.$p->envelopeOrigin->y.','.$p->envelopeOrigin->z; - } - $descendingUsed=array_map(static function (int $c): int { - return -$c; - },\Packvium\Support\BigInt::chunks($used)); - return array_merge([count($unplaced),count($unplaced),-count($state->placements),$state->maxZ],$descendingUsed,[implode('|',$signature)]); + $descendingUsed=self::descending($state->usedVolume); + if($byVolume)return array_merge(self::descending(self::reachableVolume($state,$futureInfo)),$descendingUsed,[count($unplaced),$state->maxZ,self::signature($state)]); + return array_merge([self::unpackedLowerBoundPrecomputed($state,count($unplaced),$futureInfo),count($unplaced),-count($state->placements),$state->maxZ],$descendingUsed,[self::signature($state)]); + } + + /** @param array{0:ContainerState,1:list} $node */ + private static function nodeKey(array $node,bool $byVolume=false):array + { + return self::nodeKeyPrecomputed($node,['count'=>0,'volumes'=>null,'weights'=>null],$byVolume); } } diff --git a/src-legacy/Algorithm/CandidateFinder.php b/src-legacy/Algorithm/CandidateFinder.php index 35ee5a3..9db5145 100644 --- a/src-legacy/Algorithm/CandidateFinder.php +++ b/src-legacy/Algorithm/CandidateFinder.php @@ -32,6 +32,10 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf } $inner=$container->innerDimensions; $limitX=$inner->length->ticks;$limitY=$inner->width->ticks;$limitZ=$inner->height->ticks; + // A flat bag also needs a + c <= L and b + c <= W over the running extents grown by + // the candidate: O(1), and the extents only grow, so no verdict flips. + $bag=$container->isFlatBag(); + $bagX=$state->maxX;$bagY=$state->maxY;$bagZ=$state->maxZ; $clearance=$config->clearance->ticks; // Envelope and extents depend only on the rotation, so they are built once // instead of once per (point, rotation) pair. @@ -94,6 +98,11 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf $stats->placementsAttempted++; $x2=$x1+$dx;$y2=$y1+$dy;$z2=$z1+$dz; if($x2>$limitX||$y2>$limitY||$z2>$limitZ)continue; + if($bag){ + // Ternaries rather than max(): the call made this test dearer (44 ns against 74 ns). + $thickness=$z2>$bagZ?$z2:$bagZ; + if(($x2>$bagX?$x2:$bagX)+$thickness>$limitX||($y2>$bagY?$y2:$bagY)+$thickness>$limitY)continue; + } $tentative=null; if($nesting){ $position=new Point($x1+$clearance,$y1+$clearance,$z1+$clearance); diff --git a/src-legacy/Algorithm/ContainerState.php b/src-legacy/Algorithm/ContainerState.php index f213a63..dba8d42 100644 --- a/src-legacy/Algorithm/ContainerState.php +++ b/src-legacy/Algorithm/ContainerState.php @@ -2,7 +2,8 @@ declare(strict_types=1); namespace Packvium\Algorithm; use Packvium\Constraint\VolumeReserve; -use Packvium\Domain\{AxisAlignedBox,Container,ItemInstance,LatticeSummary,Nesting,Placement,Point,ShapeType}; +use Packvium\Config\PackingConfig; +use Packvium\Domain\{AxisAlignedBox,Container,FlatBag,ItemInstance,LatticeSummary,Nesting,Placement,Point,ShapeType}; use Packvium\Support\BigInt; /** * Placed boxes plus the candidate points they expose. @@ -16,7 +17,6 @@ final class ContainerState { /** - * @readonly * @var \Packvium\Domain\Container */ public $container; @@ -62,10 +62,20 @@ final class ContainerState * @var bool */ public $compressionSensitive=false; + /** Largest envelope x2 and y2 so far; with `$maxZ`, a flat bag's running extents. + * @var int */ + public $maxX=0; + /** + * @var int + */ + public $maxY=0; /** * @var int */ public $maxZ=0; + /** Null means a direct lattice/block placement invalidated the lazy beam key. + * @var string|null */ + private $placementSignature=''; /** * @var \Packvium\Algorithm\SpatialIndex */ @@ -82,6 +92,10 @@ final class ContainerState */ private $usableVolumeTicks; + /** + * `$container` is not readonly only so a made-to-measure trial can be committed as the box + * cut for it (`withContainer`); nothing else reassigns it. + */ public function __construct(Container $container,int $sequence) { $this->container = $container; @@ -107,6 +121,32 @@ public function __construct(Container $container,int $sequence) /** Clone rather than reconstruct: the constructor's point seeding would be discarded. */ public function copy():self{return clone $this;} + public function placementSignature():string + { + if($this->placementSignature!==null)return $this->placementSignature; + $parts=[]; + foreach($this->placements as $placement)$parts[]=self::signatureElement($placement); + return $this->placementSignature=implode('|',$parts); + } + + private static function signatureElement(Placement $placement):string + { + return $placement->instance->id().'@'.$placement->envelopeOrigin->x.','.$placement->envelopeOrigin->y.','.$placement->envelopeOrigin->z; + } + + /** + * This state as a trial of another container of the same contents: a made-to-measure rung + * committed as the box cut for it. Only read after the trial ends, so the + * candidate points and index sized for the rung are never searched again. + */ + public function withContainer(Container $container):self + { + $copy=clone $this; + $copy->container=$container; + $copy->usableVolumeTicks=null; + return $copy; + } + /** * PHP arrays are value types, so `clone` already deep-copies `$bounds`/`$occupied`/ * `$points` correctly; `$index` is an object, which `clone` only shallow-copies by @@ -132,14 +172,18 @@ public function add(Placement $placement):void else $this->usedVolume=BigInt::add($this->usedVolume,Nesting::usedVolumeDelta($this->placements,$placement)); $this->placements[]=$placement; + if($this->placementSignature!==null){ + $elem=self::signatureElement($placement); + $this->placementSignature=$this->placementSignature==='' ? $elem : $this->placementSignature.'|'.$elem; + } $this->payloadTicks+=$placement->instance->weight()->ticks; $item=$placement->instance->item; $this->stackSensitive=$this->stackSensitive||$item->isStackSensitive(); $this->routeSensitive=$this->routeSensitive||$item->stopIndex!==null; $this->compressionSensitive=$compressionSensitive; - if($box->z2()>$this->maxZ)$this->maxZ=$box->z2(); $this->occupied[]=$box; $bound=$box->extent(); + $this->extendExtent($bound[3],$bound[4],$bound[5]); $this->index->add(count($this->bounds),$bound); $this->bounds[]=$bound; $shape=$placement->hullShape(); @@ -179,11 +223,42 @@ public function addDirect(Placement $placement):void // could drift from `add`, so the direct lattice path remains the proven O(1) delta. $this->usedVolume=BigInt::add($this->usedVolume,Nesting::usedVolumeDelta($this->placements,$placement)); $this->placements[]=$placement; + $this->placementSignature=null; $this->payloadTicks+=$placement->instance->weight()->ticks; $item=$placement->instance->item; $this->stackSensitive=$this->stackSensitive||$item->isStackSensitive(); $this->routeSensitive=$this->routeSensitive||$item->stopIndex!==null; - if($box->z2()>$this->maxZ)$this->maxZ=$box->z2(); + $this->extendExtent($box->x2(),$box->y2(),$box->z2()); + } + + private function extendExtent(int $x2,int $y2,int $z2):void + { + if($x2>$this->maxX)$this->maxX=$x2; + if($y2>$this->maxY)$this->maxY=$y2; + if($z2>$this->maxZ)$this->maxZ=$z2; + } + + /** + * The dimensional weight, in weight ticks, a carrier bills for this container as filled. + * + * A flat bag is billed on its running extents, the parcel a carrier measures; an empty bag + * has no parcel yet and bills nothing by volume. A rigid container is billed on its declared + * outer size, else its inner size. O(1). + */ + public function billedDimensionalWeight(PackingConfig $config):int + { + $container=$this->container; + if($container->isFlatBag()){ + if($this->placements===[])return 0; + $dimensions=FlatBag::asDimensions([$this->maxX,$this->maxY,$this->maxZ]); + }else{ + $dimensions=$container->outerDimensions??$container->innerDimensions; + } + return $dimensions->dimensionalWeight( + (int)$config->dimensionalWeightDivisor, + $config->dimensionalWeightLengthUnit, + $config->dimensionalWeightWeightUnit, + )->ticks; } public function placementCount():int diff --git a/src-legacy/Algorithm/Deadline.php b/src-legacy/Algorithm/Deadline.php index 673a055..b65d494 100644 --- a/src-legacy/Algorithm/Deadline.php +++ b/src-legacy/Algorithm/Deadline.php @@ -98,6 +98,18 @@ public static function until(int $absoluteNs):self public function elapsedMs():int{return intdiv(($this->clock)()-$this->started,1000000);} public function remainingNs():int{return $this->limitNs-(($this->clock)()-$this->started);} public function effortExceeded():bool{return $this->effortBudget!==null && $this->stats!==null && $this->effortBudget->exceeded($this->stats);} + /** + * How many more search nodes counted into `$counted` may expand before `effortExceeded()` + * trips, while nothing else that budget counts moves: zero once it has tripped, and + * `PHP_INT_MAX` when no node budget reads `$counted`. A solver that counts a run of nodes + * in one step stops on the same node as one that checks before each. + */ + public function searchNodesLeft(SearchStats $counted):int + { + if($this->effortExceeded())return 0; + if($this->effortBudget===null||$this->effortBudget->maxSearchNodes===null||$this->stats!==$counted)return PHP_INT_MAX; + return $this->effortBudget->maxSearchNodes-$counted->searchNodesExpanded; + } public function expired():bool{return $this->effortExceeded() || $this->remainingNs()<=0;} public function slice(int $parts):self diff --git a/src-legacy/Algorithm/EffortBudget.php b/src-legacy/Algorithm/EffortBudget.php index 26f321a..c705623 100644 --- a/src-legacy/Algorithm/EffortBudget.php +++ b/src-legacy/Algorithm/EffortBudget.php @@ -63,3 +63,9 @@ public function exceeded(SearchStats $stats):bool || ($this->maxSearchNodes!==null && $stats->searchNodesExpanded>=$this->maxSearchNodes); } } + +// The public name of this class is `Packvium\Config\EffortBudget`: one class under +// two names, so an instance from either spelling satisfies a type declared with the other. +// Registered here, beside the declaration, because PHP does not autoload for a type check: +// a budget decoded by `ArrayCodec` must already answer to the public name. +\class_alias(EffortBudget::class, \Packvium\Config\EffortBudget::class); diff --git a/src-legacy/Algorithm/ExactSmallSolver.php b/src-legacy/Algorithm/ExactSmallSolver.php index eab209d..2485744 100644 --- a/src-legacy/Algorithm/ExactSmallSolver.php +++ b/src-legacy/Algorithm/ExactSmallSolver.php @@ -69,13 +69,7 @@ public static function isBetterState(ContainerState $candidate,ContainerState $i private static function landedCharge(ContainerState $state,PackingConfig $config):int { $container=$state->container; - $dimensions=$container->outerDimensions??$container->innerDimensions; - $dimensional=$dimensions->dimensionalWeight( - $config->dimensionalWeightDivisor, - $config->dimensionalWeightLengthUnit, - $config->dimensionalWeightWeightUnit, - )->ticks; - $billed=max($container->tareWeight->ticks+$state->payloadTicks,$dimensional); + $billed=max($container->tareWeight->ticks+$state->payloadTicks,$state->billedDimensionalWeight($config)); return (($nullsafeVariable1 = $container->rateTable) ? $nullsafeVariable1->chargeMinorOrNull(LandedCostSolutionScorer::grams($billed)) : null)??LandedCostSolutionScorer::UNPRICEABLE_MINOR; } @@ -86,6 +80,11 @@ private static function isBetterForObjective( ):bool { $candidateCount=count($candidate->placements); $incumbentCount=count($incumbent->placements); + if(self::ranksByVolume($config)){ + // `maximum_volume` fills volume before it counts pieces. + $byVolume=BigInt::compare($candidateVolume,$incumbentVolume); + return $byVolume!==0?$byVolume>0:$candidateCount>$incumbentCount; + } if($candidateCount!==$incumbentCount)return $candidateCount>$incumbentCount; if($config->objective==='lowest_landed_cost'){ $candidateCharge=self::landedCharge($candidate,$config); @@ -95,6 +94,11 @@ private static function isBetterForObjective( return BigInt::compare($candidateVolume,$incumbentVolume)>0; } + private static function ranksByVolume(PackingConfig $config):bool + { + return $config->objective==='maximum_volume'; + } + public function packOne(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):SingleContainerSolution { if(count($items)>$config->exactItemLimit)throw new InvalidArgumentException('Exact-small item limit exceeded'); @@ -126,8 +130,13 @@ public function packOne(Container $container,int $sequence,array $items,PackingC if($index>=count($batches))return; $potentialCount=$stateCount+$reachable; $bestCount=count($best->placements); - if($potentialCount<$bestCount)return; - if($config->objective!=='lowest_landed_cost'&&$potentialCount===$bestCount&&BigInt::compare(BigInt::add($stateVolume,$suffixVolumes[$index]),$bestVolume)<=0)return; + if(self::ranksByVolume($config)){ + // Fewer pieces can still be more volume, so only the volume bound cuts; + // an equal bound wins only on a strictly larger count. + $bound=BigInt::compare(BigInt::add($stateVolume,$suffixVolumes[$index]),$bestVolume); + if($bound<0||($bound===0&&$potentialCount<=$bestCount))return; + }elseif($potentialCount<$bestCount)return; + elseif($config->objective!=='lowest_landed_cost'&&$potentialCount===$bestCount&&BigInt::compare(BigInt::add($stateVolume,$suffixVolumes[$index]),$bestVolume)<=0)return; $batch=$batches[$index]; $remaining=$reachable-count($batch); foreach(BeamPacker::placeBatch($state,$batch,$config,$constraints,$stats,$deadline,$scorer,null) as $child){ diff --git a/src-legacy/Algorithm/GridSolver.php b/src-legacy/Algorithm/GridSolver.php index 9351df9..ffd25e1 100644 --- a/src-legacy/Algorithm/GridSolver.php +++ b/src-legacy/Algorithm/GridSolver.php @@ -31,6 +31,7 @@ private static function latticeProfile(\Packvium\Domain\Item $item):string $tags=$item->tags;sort($tags); $incompatibleTags=$item->incompatibleTags;sort($incompatibleTags); $eligibleContainerTags=$item->eligibleContainerTags;sort($eligibleContainerTags); + $acceptsStackingGroups=$item->acceptsStackingGroups;sort($acceptsStackingGroups,SORT_STRING); return json_encode([ $footprints,$item->weight->ticks,$item->stackable,$item->mustBeOnFloor, ($nullsafeVariable1 = $item->maxTopLoad) ? $nullsafeVariable1->ticks : null,$tags,$incompatibleTags,$eligibleContainerTags, @@ -45,6 +46,9 @@ private static function latticeProfile(\Packvium\Domain\Item $item):string // with an unlimited item, or stop 0 with stop 1, produces a tiling neither // one allows. $item->maxStackedItems,$item->stopIndex, + // A lattice joins same-type items only, so two types may share one exactly when + // they share the stacking rule as well. + $item->stackingGroup,$acceptsStackingGroups, ]); } @@ -76,6 +80,10 @@ public function packOne(Container $container,int $sequence,array $items,PackingC return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); if($container->voidFillReserveRatio>0) return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); + if($container->isFlatBag()) + // The lattice counts cells against the rigid frame alone; a bag's girth rule + // couples the axes, which the per-candidate check applies exactly. + return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); if($container->maxStackDensity!==null) // The single-layer heuristic below only ever reasons about one item // resting on one other, never the cumulative load a tall column presses @@ -98,7 +106,9 @@ public function packOne(Container $container,int $sequence,array $items,PackingC // Every non-floor lattice cell has one full-area direct supporter, including // an exact nesting predecessor. That satisfies ratio=1, covered and single; // multiple is satisfiable only on the floor, so cap instead of delegating. - $singleLayer=$prototype->mustBeOnFloor||!$prototype->stackable||$prototype->groundContactRule==='multiple'; + // Every lattice edge joins two items of this type, so the stacking-group rule holds + // for the whole lattice exactly when the type carries itself. + $singleLayer=$prototype->mustBeOnFloor||!$prototype->carriesItself()||$prototype->groundContactRule==='multiple'; // How much less than the full height each layer above the first consumes: // zero (the ordinary lattice) unless the item declares it sinks into an // identical one beneath it. Reduces to the original nz/z formulas diff --git a/src-legacy/Algorithm/HomogeneousBlockSolver.php b/src-legacy/Algorithm/HomogeneousBlockSolver.php index 7d9e223..bff67ab 100644 --- a/src-legacy/Algorithm/HomogeneousBlockSolver.php +++ b/src-legacy/Algorithm/HomogeneousBlockSolver.php @@ -16,7 +16,9 @@ * Candidate enumeration is O(B*S*T*R*X*Y) time and O(S+n) space. B is committed * blocks, S the capped maximal-space count, T declared item types, R unique * rotations, and X/Y the block grid extents. Both Deadline and - * containerPlanNodeLimit bound the product explicitly. + * containerPlanNodeLimit bound the product explicitly. The X*Y lattice nodes of a + * group are counted in O(X), and only a group that can still lead walks its nodes, + * so the X*Y factor is the worst case, not the usual one. */ final class HomogeneousBlockSolver implements SingleContainerSolver { @@ -24,10 +26,35 @@ final class HomogeneousBlockSolver implements SingleContainerSolver * @var list */ private $constraints = []; - /** @param list $constraints */ - public function __construct(array $constraints=[], ?CandidateScorer $scorer=null) + /** + * @var list + * @readonly + */ + public $modes = self::MODES; + /** + * @readonly + * @var int|null + */ + public $nodeLimit; + public const MODES=['count','volume']; + /** Far above the 4-ulp error of a float product of three lengths and a count. */ + private const FLOAT_MARGIN=1e-12; + /** Lattice nodes between two clock reads are a power of two: 1 << CLOCK_SHIFT. */ + private const CLOCK_SHIFT=6; + private const CLOCK_STRIDE=(1< $constraints + * @param list $modes + */ + public function __construct(array $constraints=[], ?CandidateScorer $scorer=null, array $modes=self::MODES, ?int $nodeLimit=null) { $this->constraints = $constraints; + $this->modes = $modes; + $this->nodeLimit = $nodeLimit; } public function name():string{return 'homogeneous_blocks';} @@ -37,26 +64,31 @@ public function packOne(Container $container,int $sequence,array $items,PackingC { if(!$this->supports($container,$items,$config)) return (new ExtremePointSolver($this->constraints))->packOne($container,$sequence,$items,$config,$stats,$deadline); + $nodeLimit=$this->nodeLimit??$config->containerPlanNodeLimit; $best=null;$reached=false; - foreach(['count','volume'] as $mode){ + foreach($this->modes as $mode){ if($deadline->expired()){$reached=true;break;} - $solution=$this->packMode($container,$sequence,$items,$config,$stats,$deadline,$mode); + $solution=$this->packMode($container,$sequence,$items,$config,$stats,$deadline,$mode,$nodeLimit); $reached=$reached||$solution->timeLimitReached; - if($best===null||$this->solutionKey($solution)<$this->solutionKey($best))$best=$solution; + $byVolume=$config->objective==='maximum_volume'; + if($best===null||$this->solutionKey($solution,$byVolume)<$this->solutionKey($best,$byVolume))$best=$solution; } if($best===null)return new SingleContainerSolution(new ContainerState($container,$sequence),$items,false,$reached); return new SingleContainerSolution($best->state,$best->unpacked,false,$reached); } - private function supports(Container $container,array $items,PackingConfig $config):bool + public function supports(Container $container,array $items,PackingConfig $config):bool { // A block set on a smaller one overhangs it, so a request that asks for support // is left to the per-item search. if($config->minimumSupportRatio>0)return false; - if($this->constraints!==[]||$container->obstacles!==[]||$container->preloaded!==[]||$container->axles!==null||$container->tagLimits!==[]||$container->maxStackDensity!==null||$container->voidFillReserveRatio>0)return false; + if($this->constraints!==[]||$container->obstacles!==[]||$container->preloaded!==[]||$container->axles!==null||$container->tagLimits!==[]||$container->maxStackDensity!==null||$container->voidFillReserveRatio>0||$container->isFlatBag())return false; foreach($items as $instance){ $item=$instance->item; if($item->shapeType!==ShapeType::RIGID_CUBOID||$item->group!==null||$item->tags!==[]||$item->incompatibleTags!==[]||$item->eligibleContainerTags!==[]||!$item->stackable||$item->mustBeOnFloor||$item->maxTopLoad!==null||$item->maxStackedItems!==null||$item->minimumSupportRatio!=0.0||!in_array($item->groundContactRule,[null,'free'],true)||$item->nestingHeight!==null||$item->stopIndex!==null)return false; + // Block-on-block contacts would need a second implementation of the stacking-group + // rule; the general solver already walks every edge. + if($item->acceptsStackingGroups!==[])return false; } return true; } @@ -69,60 +101,230 @@ private static function memberSupport(ContainerState $state,ItemInstance $instan return $support->supportingArea/$envelope->baseAreaTicks(); } - private function solutionKey(SingleContainerSolution $solution):array + private function solutionKey(SingleContainerSolution $solution,bool $byVolume=false):array { $signature=[]; foreach($solution->state->placements as $placement)$signature[]=$placement->instance->id().'@'.$placement->envelopeOrigin->x.','.$placement->envelopeOrigin->y.','.$placement->envelopeOrigin->z; - return array_merge([count($solution->unpacked)], array_map(static function (int $chunk): int { + $descendingUsed=array_map(static function (int $chunk): int { return -$chunk; - },BigInt::chunks($solution->state->usedVolume)), [$solution->state->maxZ, implode('|',$signature)]); + },BigInt::chunks($solution->state->usedVolume)); + if($byVolume)return array_merge($descendingUsed, [count($solution->unpacked), $solution->state->maxZ, implode('|',$signature)]); + return array_merge([count($solution->unpacked)], $descendingUsed, [$solution->state->maxZ, implode('|',$signature)]); + } + + /** + * The distinct rotations of one item type with what every lattice of them shares. + * + * @return list + */ + private static function lattices(ItemInstance $prototype,PackingConfig $config):array + { + $lattices=[]; + foreach($prototype->dimensions()->uniqueRotations($prototype->item->allowedRotations) as [$rotation,$physical]){ + $envelope=$config->clearance->ticks?$physical->expand($config->clearance):$physical; + $lattices[]=['rotation'=>$rotation,'rotationName'=>$rotation,'physical'=>$physical,'envelope'=>$envelope,'extents'=>[$envelope->length->ticks,$envelope->width->ticks,$envelope->height->ticks],'volume'=>$physical->volumeString(),'approximateVolume'=>$physical->volumeScore()]; + } + return $lattices; + } + + /** + * Whether a block ranks strictly before the incumbent under the exact key. + * + * The key is the lead -- count, fill of its space in parts per million, then exact used + * volume under `count`; volume, fill, then count otherwise -- and then the anchor, + * type, rotation and extents. Fields are compared one at a time, each with `<=>` as + * the whole-array comparison would, so a decimal-string volume is only built when the + * float volumes cannot separate the pair. + * + * @param array $candidate + * @param array $best + */ + private static function leads(array $candidate,array $best,string $mode):bool + { + if($mode==='count'){ + if($candidate['count']!==$best['count'])return $candidate['count']>$best['count']; + $order=(self::fillPpm($best)<=>self::fillPpm($candidate))?:self::volumeOrder($candidate,$best); + }else{ + $order=self::volumeOrder($candidate,$best)?:(self::fillPpm($best)<=>self::fillPpm($candidate))?:($best['count']<=>$candidate['count']); + } + if($order===0){ + $mine=$candidate['space']->origin;$theirs=$best['space']->origin; + $order=($mine->z<=>$theirs->z)?:($mine->y<=>$theirs->y)?:($mine->x<=>$theirs->x) + ?:($candidate['itemId']<=>$best['itemId'])?:($candidate['rotationName']<=>$best['rotationName']) + ?:($candidate['nx']<=>$best['nx'])?:($candidate['ny']<=>$best['ny'])?:($candidate['nz']<=>$best['nz']); + } + return $order<0; + } + + /** + * -1 when the candidate uses strictly more volume, the order of the descending volume key. + * + * A float volume carries a relative error below 4e-16, so one apart by the margin is + * apart exactly; only a closer pair builds both decimal-string volumes. + * + * @param array $candidate + * @param array $best + */ + private static function volumeOrder(array $candidate,array $best):int + { + if($candidate['approximateUsed']>$best['approximateUsed']*(1+self::FLOAT_MARGIN))return -1; + if($candidate['approximateUsed']<$best['approximateUsed']*(1-self::FLOAT_MARGIN))return 1; + return BigInt::compare(BigInt::multiply($best['count'],$best['volume']),BigInt::multiply($candidate['count'],$candidate['volume'])); + } + + /** + * floor(used * 1e6 / space volume), the block's fill of its space in parts per million. + * + * The float quotient is at most 1e6 and carries a relative error near 1e-15, so its + * floor is exact unless it lies within 1e-6 of an integer; only then is the + * decimal-string long division run. + * + * @param array $block + */ + private static function fillPpm(array $block):int + { + $space=$block['space']->dimensions; + $quotient=$block['approximateUsed']*1000000/$space->volumeScore(); + $floor=floor($quotient); + if($quotient-$floor>self::FLOAT_MARGIN*1000000&&$floor+1-$quotient>self::FLOAT_MARGIN*1000000)return (int)$floor; + return (int)BigInt::divide(BigInt::multiply(BigInt::multiply($block['count'],$block['volume']),1000000),$space->volumeString()); + } + + /** + * The lattice nodes of one group: sum over nx <= min(X, c) of min(Y, floor(c / nx)). + * + * Every row up to floor(c / Y) is Y nodes wide, so only the rows past it are summed: + * O(min(X, c)) against the group's O(X * Y) nodes. + */ + private static function latticeNodes(int $maximumX,int $maximumY,int $capacity):int + { + $maximumNx=min($maximumX,$capacity); + $fullRows=min($maximumNx,intdiv($capacity,$maximumY)); + $nodes=$fullRows*$maximumY; + for($nx=$fullRows+1;$nx<=$maximumNx;$nx++)$nodes+=intdiv($capacity,$nx); + return $nodes; + } + + /** + * How many of a group's nodes expand before a stop, the count the per-node loop reached. + * + * `$stopAt` is the node a counted limit trips at. The clock is read once, on the first + * node of the group at a 64-node stride, and a stop there lands on that node: only where + * a wall-clock stop lands can move, never a counted one. + */ + private static function expandable(int $nodes,int $groupNodes,int $stopAt,Deadline $deadline):int + { + $expandable=min($groupNodes,$stopAt-$nodes); + $clockRead=($nodes+self::CLOCK_STRIDE)&~self::CLOCK_STRIDE; + if($clockRead<$nodes+$expandable&&$deadline->expired())return $clockRead-$nodes; + return $expandable; + } + + /** + * The group's first largest block in (nx, ny) order, as [count, nx, ny, nz]. + * + * For a capacity below the whole lattice: no node exceeds the capacity, so the first one + * to reach it ends the walk. (With room for the whole lattice, the whole lattice is the + * only node of its count.) + * + * @return array{int,int,int,int} + */ + private static function largestBlock(int $maximumX,int $maximumY,int $maximumZ,int $capacity):array + { + $count=0;$bestNx=0;$bestNy=0;$bestNz=0; + $maximumNx=$maximumX<$capacity?$maximumX:$capacity; + for($nx=1;$nx<=$maximumNx;$nx++){ + $maximumNy=intdiv($capacity,$nx); + if($maximumY<$maximumNy)$maximumNy=$maximumY; + for($ny=1;$ny<=$maximumNy;$ny++){ + $nz=intdiv($capacity,$nx*$ny); + if($maximumZ<$nz)$nz=$maximumZ; + if($nx*$ny*$nz<=$count)continue; + $count=$nx*$ny*$nz;$bestNx=$nx;$bestNy=$ny;$bestNz=$nz; + if($count===$capacity)return [$count,$bestNx,$bestNy,$bestNz]; + } + } + return [$count,$bestNx,$bestNy,$bestNz]; + } + + /** + * The round's leading block over every (space, type, rotation) group, or null. + * + * Every group's nodes count toward the limits before any is ranked, and a stop inside a + * group lands on the node the per-node loop stopped at: a stopped round places nothing, + * so which node led it is never read. Inside one group every key field except the + * count-derived lead is equal, and fill and volume grow with the count, so the group's + * first largest count is the only node that can lead. No node exceeds the capacity or + * the whole lattice, and a group whose bound already trails the incumbent cannot lead: + * the cheap lead is monotone in the count, since a float product is. + * + * @param list $spaces + * @param array $capacities + * @param array>> $rotations + * @return array|null + */ + private static function leadingBlock(array $spaces,array $capacities,array $rotations,string $mode,int &$nodes,int $stopAt,SearchStats $stats,Deadline $deadline,bool &$reached):?array + { + $best=null;$byCount=$mode==='count'; + // The incumbent's cheap lead as scalars: its count, and its float volume less the margin. + $leadCount=0;$leadFloor=-INF; + foreach($spaces as $space){ + $spaceLength=$space->dimensions->length->ticks;$spaceWidth=$space->dimensions->width->ticks;$spaceHeight=$space->dimensions->height->ticks; + foreach($capacities as $itemId=>$capacity){ + foreach($rotations[$itemId] as $lattice){ + [$envelopeLength,$envelopeWidth,$envelopeHeight]=$lattice['extents']; + 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); + // 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); + $nodes+=$expanded;$stats->searchNodesExpanded+=$expanded; + if($expanded<$groupNodes){$reached=true;return null;} + }else{$nodes+=$groupNodes;$stats->searchNodesExpanded+=$groupNodes;} + if($envelopeHeight>$spaceHeight)continue; + $maximumZ=intdiv($spaceHeight,$envelopeHeight); + $whole=$maximumX*$maximumY*$maximumZ; + $volume=$lattice['approximateVolume']; + $largest=$capacity<$whole?$capacity:$whole; + if($byCount?$largest<$leadCount:$largest*$volume<$leadFloor)continue; + [$count,$nx,$ny,$nz]=$capacity>=$whole?[$whole,$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]; + if($best!==null&&!self::leads($candidate,$best,$mode))continue; + $best=$candidate;$leadCount=$count;$leadFloor=$approximateUsed*(1-self::FLOAT_MARGIN); + } + } + } + return $best; } - private function packMode(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode):SingleContainerSolution + private function packMode(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit):SingleContainerSolution { $state=new ContainerState($container,$sequence); $spaces=[new Space(new Point(0,0,0),$container->innerDimensions)]; $remaining=[]; foreach($items as $instance)$remaining[$instance->item->id][]=$instance; ksort($remaining,SORT_STRING); - $nodes=0;$reached=false; + $nodes=0;$reached=false;$rotations=[]; while($spaces!==[]&&array_sum(array_map('count',$remaining))>0){ - $best=null; - foreach($spaces as $space){ - $spaceVolume=$space->dimensions->volumeString(); - foreach($remaining as $itemId=>$available){ - if($available===[])continue; - $prototype=$available[0];$capacity=count($available); - if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems-$state->placementCount()); - if($container->maxPayload!==null&&$prototype->weight()->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks-$state->payloadTicks,$prototype->weight()->ticks)); - if($capacity<=0)continue; - foreach($prototype->dimensions()->uniqueRotations($prototype->item->allowedRotations) as [$rotation,$physical]){ - $envelope=$config->clearance->ticks?$physical->expand($config->clearance):$physical; - $maximumX=intdiv($space->dimensions->length->ticks,$envelope->length->ticks); - $maximumY=intdiv($space->dimensions->width->ticks,$envelope->width->ticks); - $maximumZ=intdiv($space->dimensions->height->ticks,$envelope->height->ticks); - for($nx=1;$nx<=min($maximumX,$capacity);$nx++){ - $maximumNy=min($maximumY,intdiv($capacity,$nx)); - for($ny=1;$ny<=$maximumNy;$ny++){ - if($nodes>=$config->containerPlanNodeLimit||$deadline->expired()){$reached=true;break 5;} - $nodes++;$stats->searchNodesExpanded++; - $nz=min($maximumZ,intdiv($capacity,$nx*$ny)); - if($nz<=0)continue; - $count=$nx*$ny*$nz; - $usedVolume=BigInt::multiply($count,$physical->volumeString()); - $spaceFill=(int)BigInt::divide(BigInt::multiply($usedVolume,1000000),$spaceVolume); - $volumeKey=array_map(static function (int $chunk): int { - return -$chunk; - },BigInt::chunks($usedVolume)); - $lead=$mode==='count'?array_merge([-$count, -$spaceFill], $volumeKey):array_merge($volumeKey, [-$spaceFill, -$count]); - $score=array_merge($lead, [$space->origin->z, $space->origin->y, $space->origin->x, $itemId, $rotation, $nx, $ny, $nz]); - $candidate=compact('space','itemId','rotation','physical','envelope','nx','ny','nz','count','usedVolume','score'); - if($best===null||$score<$best['score'])$best=$candidate; - } - } - } - } + // Only the node count moves a counted limit inside one round: candidates and + // placements are counted when a block is placed, after it. + $stopAt=$nodes+max(0,min($nodeLimit-$nodes,$deadline->searchNodesLeft($stats))); + // A type's capacity and lattices do not depend on the space they are tried in. + $capacities=[]; + foreach($remaining as $itemId=>$available){ + if($available===[])continue; + $prototype=$available[0];$capacity=count($available); + if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems-$state->placementCount()); + if($container->maxPayload!==null&&$prototype->weight()->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks-$state->payloadTicks,$prototype->weight()->ticks)); + if($capacity<=0)continue; + $capacities[$itemId]=$capacity; + $rotations[$itemId] = $rotations[$itemId] ?? self::lattices($prototype,$config); } + $best=self::leadingBlock($spaces,$capacities,$rotations,$mode,$nodes,$stopAt,$stats,$deadline,$reached); if($best===null||$reached)break; $chosen=array_slice($remaining[$best['itemId']],0,$best['count']); $remaining[$best['itemId']]=array_slice($remaining[$best['itemId']],$best['count']); diff --git a/src-legacy/Algorithm/MaximalSpaceSolver.php b/src-legacy/Algorithm/MaximalSpaceSolver.php index 5b48136..de572f5 100644 --- a/src-legacy/Algorithm/MaximalSpaceSolver.php +++ b/src-legacy/Algorithm/MaximalSpaceSolver.php @@ -34,6 +34,8 @@ final class MaximalSpaceSolver implements SingleContainerSolver * 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) @@ -86,22 +88,25 @@ private static function choose(ContainerState $state,array $spaces,ItemInstance return null; } - /** The six maximal slabs of $space that survive carving $box out of it. @return list */ - private static function subtract(Space $space,AxisAlignedBox $box):array + /** + * 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 { - $source=new AxisAlignedBox($space->origin,$space->dimensions); - if(!$source->intersects($box))return [$space]; + [$x1,$y1,$z1,$x2,$y2,$z2]=$s; $out=[]; - $push=static function(int $x1,int $y1,int $z1,int $x2,int $y2,int $z2)use(&$out):void{ - if($x2>$x1&&$y2>$y1&&$z2>$z1) - $out[]=new Space(new Point($x1,$y1,$z1),new Dimensions(new Length($x2-$x1),new Length($y2-$y1),new Length($z2-$z1))); - }; - $push($source->origin->x,$source->origin->y,$source->origin->z,min($source->x2(),$box->origin->x),$source->y2(),$source->z2()); - $push(max($source->origin->x,$box->x2()),$source->origin->y,$source->origin->z,$source->x2(),$source->y2(),$source->z2()); - $push($source->origin->x,$source->origin->y,$source->origin->z,$source->x2(),min($source->y2(),$box->origin->y),$source->z2()); - $push($source->origin->x,max($source->origin->y,$box->y2()),$source->origin->z,$source->x2(),$source->y2(),$source->z2()); - $push($source->origin->x,$source->origin->y,$source->origin->z,$source->x2(),$source->y2(),min($source->z2(),$box->origin->z)); - $push($source->origin->x,$source->origin->y,max($source->origin->z,$box->z2()),$source->x2(),$source->y2(),$source->z2()); + 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; } @@ -112,47 +117,78 @@ private static function subtract(Space $space,AxisAlignedBox $box):array * 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 { - $current=array_map(static function (Space $space): array { - return [$space,false]; - },$spaces); + // [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 [$space,$isNew]){ - if(!(new AxisAlignedBox($space->origin,$space->dimensions))->intersects($box)){$next[]=[$space,$isNew];continue;} - foreach(self::subtract($space,$box) as $part)$next[]=[$part,true]; + 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 $pair){ - [$space,]=$pair; - $d=$space->dimensions; - $unique["{$space->origin->x}:{$space->origin->y}:{$space->origin->z}:{$d->length->ticks}:{$d->width->ticks}:{$d->height->ticks}"]=$pair; + 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; } - // descendingVolumeKey parses BigInt chunks; one key per space instead of one - // per stable-usort comparison, with the ordering unchanged. - $kept=StableSorter::sortBy(array_values($unique),static function (array $pair): array { - return array_merge([$pair[0]->origin->z,$pair[0]->origin->y,$pair[0]->origin->x],$pair[0]->dimensions->descendingVolumeKey()); - }); + 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_map(static function (array $pair): array { - return [ - $pair[0]->origin->x,$pair[0]->origin->y,$pair[0]->origin->z, - $pair[0]->origin->x+$pair[0]->dimensions->length->ticks, - $pair[0]->origin->y+$pair[0]->dimensions->width->ticks, - $pair[0]->origin->z+$pair[0]->dimensions->height->ticks, - ]; - },$kept); + $extents=array_column($kept,0); $result=[]; - foreach($kept as $index=>[$space,$isNew]){ - if($isNew&&self::isContained($extents,$index))continue; - $result[]=$space; + 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 { diff --git a/src-legacy/Algorithm/SolverOrchestrator.php b/src-legacy/Algorithm/SolverOrchestrator.php index ae5d089..2502872 100644 --- a/src-legacy/Algorithm/SolverOrchestrator.php +++ b/src-legacy/Algorithm/SolverOrchestrator.php @@ -3,8 +3,8 @@ namespace Packvium\Algorithm; use Packvium\Config\{PackingConfig,SolverProfile}; -use Packvium\Constraint\{ConstraintSet,ProvenRejection,SupportConstraint}; -use Packvium\Domain\{Container,ItemInstance,PackedContainer,Rotation,UnpackedItem}; +use Packvium\Constraint\{AxleLoad,ConstraintSet,ProvenRejection,SupportConstraint}; +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}; @@ -57,13 +57,45 @@ public function solve(array $items,array $containers,PackingConfig $config,Deadl */ public function solvePortfolio(array $items,array $containers,PackingConfig $config,Deadline $deadline,array $preloaded=[]):PortfolioRun { - $starts=$this->starts($items,$config); + $starts=$this->starts($items,$config,$containers); $effortBudget=$config->effortBudget; if($effortBudget!==null&&$effortBudget->maxRestarts!==null)$starts=array_slice($starts,0,$effortBudget->maxRestarts); - if($this->eligibleForConcurrentExecution($deadline,$config)&&count($starts)>1){ - return $this->solveConcurrent($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded); + $run=$this->eligibleForConcurrentExecution($deadline,$config)&&count($starts)>1 + ? $this->solveConcurrent($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded) + : $this->solveSequential($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded); + return self::withoutABlockStartThatOnlyTies($run,$starts,$config); + } + + /** + * Drop the added block start's answer unless it strictly beats the profile's own. + * + * The start is there to improve an answer, not to replace an equal one: on a tie + * the ranking falls to the solver name, which would hand the result to a lattice + * that knows nothing of the orderings the profile's own starts honour. + * + * @param list}> $starts + */ + private static function withoutABlockStartThatOnlyTies(PortfolioRun $run,array $starts,PackingConfig $config):PortfolioRun + { + if($starts===[])return $run; + [$solver,$orderName]=$starts[array_key_last($starts)]; + if(!$solver instanceof HomogeneousBlockSolver||$solver->nodeLimit===null)return $run; + $scorer=ObjectiveRegistry::resolve($config->objective,$config); + $added=$solver->name().':'.$orderName; + $bestOwn=null; + foreach($run->solutions as $solution){ + if($solution->solverName===$added)continue; + $score=$scorer->score($solution); + if($bestOwn===null||$score->compare($bestOwn)<0)$bestOwn=$score; } - return $this->solveSequential($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded); + if($bestOwn===null)return $run; + $kept=array_values(array_filter( + $run->solutions, + static function (RawSolution $solution) use ($added, $scorer, $bestOwn): bool { + return $solution->solverName!==$added||$scorer->score($solution)->compare($bestOwn)<0; + }, + )); + return new PortfolioRun($kept,$run->starts); } /** @@ -334,6 +366,15 @@ function ($i) use ($containers) { return new PortfolioRun($results,$records); } + /** + * Whether one box of these dimensions fits this container empty: the frame, and for a flat + * bag the girth rule too, so a bag too thin for an item proves it unplaceable. + */ + private static function fitsAlone(Container $container,Dimensions $dimensions):bool + { + return $container->isFlatBag()?FlatBag::fitsAlone($container->innerDimensions,$dimensions):$dimensions->fitsInside($container->innerDimensions); + } + /** @param list $containers */ /** @return array{0:string,1:list} */ private function unpackedReason(ItemInstance $item,array $containers,bool $reached):array @@ -341,7 +382,7 @@ private function unpackedReason(ItemInstance $item,array $containers,bool $reach $dimension=false;$weight=false; foreach($containers as $container){ foreach($item->dimensions()->uniqueRotations($item->item->allowedRotations) as [,$dimensions]) - if($dimensions->fitsInside($container->innerDimensions)){$dimension=true;break 2;} + if(self::fitsAlone($container,$dimensions)){$dimension=true;break 2;} } // Same geometric check with every physical orientation allowed, not only the // item's own restricted set -- distinguishes "genuinely too big in any @@ -351,7 +392,7 @@ private function unpackedReason(ItemInstance $item,array $containers,bool $reach $fitsAnyRotation=false; foreach($containers as $container){ foreach($item->dimensions()->uniqueRotations(Rotation::all()) as [,$dimensions]) - if($dimensions->fitsInside($container->innerDimensions)){$fitsAnyRotation=true;break 2;} + if(self::fitsAlone($container,$dimensions)){$fitsAnyRotation=true;break 2;} } foreach($containers as $container) if($container->maxPayload===null||$item->weight()->ticks<=$container->maxPayload->ticks){$weight=true;break;} @@ -381,6 +422,66 @@ private function unpackedReason(ItemInstance $item,array $containers,bool $reach return ['no_feasible_placement',[]]; } + /** + * The container limit that left `$item` out, for the `no_feasible_placement` + * fallback, or null when no limit explains it. + * + * Only containers that admit the item on every structural count -- a fitting + * rotation, its weight, its eligibility tags -- are asked. When an axle refuses the + * item alone in every one of them, the axle is the reason. Otherwise, when every one + * that would take it alone is out of stock, or `maxContainers` is reached, the reason + * is the inventory: `max_items`, cumulative `max_payload`, `tag_limits`, the + * stop-accessibility rule and an axle's share of a full load can only refuse an item + * a fresh container would take, so they surface here too. `$opened` is + * `openedByType()` of the final layout. O(C*R). + * + * @param list $containers @param array $opened + */ + private static function limitReason(ItemInstance $item,array $containers,array $opened,PackingConfig $config):?string + { + $envelopes=[]; + foreach($item->dimensions()->uniqueRotations($item->item->allowedRotations) as [,$dimensions])$envelopes[]=$dimensions->expand($config->clearance); + $weight=$item->weight()->ticks;$eligibleTags=$item->item->eligibleContainerTags; + $admitting=[];$compatible=false; + foreach($containers as $container){ + $fitting=array_values(array_filter($envelopes,static function (Dimensions $envelope) use ($container): bool { + return self::fitsAlone($container,$envelope); + })); + if($fitting===[])continue; + if($container->maxPayload!==null&&$weight>$container->maxPayload->ticks)continue; + if($eligibleTags!==[]&&array_intersect($eligibleTags,$container->tags)===[])continue; + $compatible=true; + if(self::axlesAdmitAlone($container,$fitting,$weight))$admitting[]=$container; + } + if(!$compatible)return null; + if($admitting===[])return 'axle_overloaded'; + if($config->maxContainers!==null&&array_sum($opened)>=$config->maxContainers)return 'container_inventory_exhausted'; + foreach($admitting as $container) + if($container->quantity===null||($opened[$container->id]??0)<$container->quantity)return null; + return 'container_inventory_exhausted'; + } + + /** + * How many containers of each template a layout opened. O(P), once per layout. + * + * @param list $packed @return array + */ + private static function openedByType(array $packed):array + { + $opened=[]; + foreach($packed as $packedContainer)$opened[$packedContainer->container->id]=($opened[$packedContainer->container->id]??0)+1; + return $opened; + } + + /** @param list $envelopes envelopes that already fit `$container` */ + private static function axlesAdmitAlone(Container $container,array $envelopes,int $weight):bool + { + if($container->axles===null)return true; + foreach($envelopes as $envelope) + if(AxleLoad::admitsAlone($container->axles,$container->tareWeight->ticks,$container->innerDimensions->length->ticks,$weight,$envelope->length->ticks))return true; + return false; + } + /** * Post-hoc diagnosis for the `no_feasible_placement` fallback: true * when `$item` could be placed in at least one already-packed container's @@ -423,8 +524,48 @@ private function supportIsTheBlocker(ItemInstance $item,array $packed,PackingCon return false; } - /** @return list}> */ - private function starts(array $items,PackingConfig $config):array + /** + * Lattice nodes the block start added to `fast` and `balanced` may enumerate per mode -- + * the bound `quality` gives the same solver through `containerPlanNodeLimit`. + */ + private const BLOCK_START_NODE_LIMIT=100000; + + /** + * The block start `fast` and `balanced` add to their own, or `null`. + * + * Single-type blocks fill a carton load in milliseconds where a per-item search + * spends its whole budget, so the low-latency profiles run them as one more start + * and let the score decide. Only where the lattice can express the whole request: + * a start that fell back to the per-item solver would repeat one already in the + * portfolio. One item type is `GridSolver`'s case, and it is exact there. + * + * @param list $items + * @param list $containers + */ + private function blockStart(array $items,PackingConfig $config,array $containers):?HomogeneousBlockSolver + { + $fast=$config->profile===SolverProfile::Fast; + if((!$fast&&$config->profile!==SolverProfile::Balanced)||$config->solvers!==[])return null; + if($this->customSolvers!==[]||$this->customConstraints!==[])return null; + $types=[];foreach($items as $instance)$types[$instance->item->id]=true; + if(count($types)<2)return null; + // A lattice takes whichever type fills best; it cannot honour a caller's say over + // which item goes first, so it stays out when the items do not all lead alike. + $lead=ItemOrdering::lead($items[0],$config); + foreach($items as $instance)if(ItemOrdering::lead($instance,$config)!=$lead)return null; + // One enumeration, the one the objective ranks by: `fast` is latency-bound. + $modes=!$fast?HomogeneousBlockSolver::MODES:($config->objective==='maximum_volume'?['volume']:['count']); + $solver=new HomogeneousBlockSolver([],null,$modes,self::BLOCK_START_NODE_LIMIT); + if($containers===[])return null; + foreach($containers as $container)if(!$solver->supports($container,$items,$config))return null; + return $solver; + } + + /** + * @param list $containers + * @return list}> + */ + private function starts(array $items,PackingConfig $config,array $containers=[]):array { $orders=$this->orders($items,$config); $starts=[]; @@ -433,6 +574,8 @@ private function starts(array $items,PackingConfig $config):array $chosen=(method_exists($solver,'orderInsensitive')&&$solver->orderInsensitive())?array_slice($orders,0,1):$orders; foreach($chosen as [$name,$order])$starts[]=[$solver,$name,$order]; } + // Last, so a restart budget drops it first and the profile's own starts keep theirs. + if($orders!==[]&&($blocks=$this->blockStart($items,$config,$containers))!==null)$starts[]=array_merge([$blocks], is_array($orders[0]) ? $orders[0] : iterator_to_array(is_array($orders[0]) ? new \ArrayIterator($orders[0]) : $orders[0])); if($config->containerPlanBeamWidth<=1||$config->profile!==SolverProfile::Quality)return $starts; $greedy=array_map(static function (array $start): array { return $start[0]->name()==='homogeneous_blocks'?$start:[$start[0],$start[1].':greedy',$start[2]]; @@ -453,6 +596,19 @@ private static function greedyConfig(PackingConfig $config):PackingConfig ); } + /** The same configuration with placement coordinates required: no compact lattice form (D12). */ + private static function withCoordinates(PackingConfig $config):PackingConfig + { + return new PackingConfig( + $config->profile,$config->timeLimitMs,$config->topK,$config->seed,$config->maxContainers, + $config->clearance,$config->minimumSupportRatio,$config->exactItemLimit,$config->multiStartOrders, + $config->validateResult,$config->maxCandidatesPerItem,$config->maxCandidatePoints,$config->solvers,$config->objective, + $config->effortBudget,$config->dimensionalWeightDivisor,$config->dimensionalWeightLengthUnit, + $config->dimensionalWeightWeightUnit,true,$config->parallelStarts, + $config->containerPlanBeamWidth,$config->containerPlanNodeLimit,$config->accessDirections, + ); + } + /** @var array */ private const SOLVER_FACTORIES=[ 'grid'=>null, // constructed without constraints/scorer; handled explicitly below @@ -498,8 +654,7 @@ private function orders(array $items,PackingConfig $config):array { // Every strategy is keyed behind `ItemOrdering::lead`, which carries priority // and, under `maximum_value`, the item's own value. - $strategies=[]; - if($config->profile===SolverProfile::Quality)$strategies=[ + $smallFirst=$config->profile!==SolverProfile::Quality?[]:[ ['small_edge',static function (ItemInstance $i) use ($config): array { return array_merge(ItemOrdering::lead($i,$config), [$i->dimensions()->maxEdge()], $i->dimensions()->volumeKey(), [$i->id()]); }], @@ -507,7 +662,7 @@ private function orders(array $items,PackingConfig $config):array return array_merge(ItemOrdering::lead($i,$config), $i->dimensions()->volumeKey(), [$i->dimensions()->maxEdge(), $i->id()]); }], ]; - $strategies=array_merge($strategies, [ + $largeFirst=[ ['volume',static function (ItemInstance $i) use ($config): array { return array_merge(ItemOrdering::lead($i,$config), $i->dimensions()->descendingVolumeKey(), [-$i->dimensions()->maxEdge(), -$i->weight()->ticks, $i->id()]); }], @@ -520,7 +675,10 @@ private function orders(array $items,PackingConfig $config):array ['constrained',static function (ItemInstance $i) use ($config): array { return array_merge(ItemOrdering::lead($i,$config), [count($i->item->allowedRotations), -$i->item->minimumSupportRatio], $i->dimensions()->descendingVolumeKey(), [$i->id()]); }], - ]); + ]; + // Small items first places the most pieces; large items first fills the most space. + // The objective decides which family gets the early, fully funded starts. + $strategies=$config->objective==='maximum_volume'?array_merge($largeFirst, $smallFirst):array_merge($smallFirst, $largeFirst); $limit=$config->profile===SolverProfile::Fast?1:$config->multiStartOrders; $out=[];$seen=[]; foreach($strategies as [$name,$key]){ @@ -572,9 +730,120 @@ private static function recordRootBound(SingleContainerSolver $solver,bool $beam if($stats->objectiveLowerBound!==null)return; if(!$beam&&$solver->name()!=='exact_small')return; if($config->objective!=='default')return; + // Its unused-volume and height keys are ratios against a declared size, and a + // made-to-measure box has none until it is cut: the bound would not be admissible. + foreach($containers as $container)if($container->madeToMeasure!==null)return; $stats->objectiveLowerBound=ObjectiveBounds::compute($items,$containers); } + /** + * The greedy round's key for one trial, read from the container the trial built: a + * made-to-measure trial carries its fabricated box, so the key prices the box that ships, + * never the machine maximum the loop declared. The trial chain ranks an + * incomplete round's rungs by this same key. + * + * @param list $roundItems + * @return list + */ + private static function roundScore(SingleContainerSolution $one,array $roundItems,PackingConfig $config,ContainerSelector $selector):array + { + $container=$one->state->container; + if(($config->objective==='shipping_cost'||$config->objective==='lowest_landed_cost')&&$config->dimensionalWeightDivisor!==null){ + $dimensional=$one->state->billedDimensionalWeight($config); + $gross=$container->tareWeight->ticks+$one->state->payloadTicks; + $billed=max($gross,$dimensional); + $placed=$one->state->placementCount(); + if($config->objective==='shipping_cost'){ + $candidateScore=[-$placed,$billed,$container->id]; + }else{ + // Landed cost ranks the round by the money the finished score will + // charge, not by the grams it is derived from. This loop commits the + // trial verbatim, so its billed weight is already final and the tariff + // can be read now; a bracket step or a minimum charge makes the cheaper + // shipment the heavier one, and a trial the tariff cannot price is + // unshippable rather than merely dear, so it sorts behind every + // priceable alternative. Keys after the charge mirror Rust's + // and Python's, so the three engines pick the same container. + $charge=($nullsafeVariable1 = $container->rateTable) ? $nullsafeVariable1->chargeMinorOrNull(LandedCostSolutionScorer::grams($billed)) : null; + $candidateScore=[ + $charge??LandedCostSolutionScorer::UNPRICEABLE_MINOR, + intdiv(count($roundItems)+max($placed,1)-1,max($placed,1)), + -$placed, + $container->id, + ]; + } + }elseif($config->objective==='maximum_volume'&&$selector instanceof DefaultContainerSelector){ + // The round keeps the trial that loaded the most volume, not the one + // that seated the most pieces. A caller's own selector is left alone. + $used=$one->state->usedVolume; + $leftover=BigInt::chunks(BigInt::subtract($container->innerDimensions->volumeString(),$used)); + $candidateScore=array_merge(array_map(static function (int $c): int { + return -$c; + },BigInt::chunks($used)), [$container->costMinor], $leftover, [$container->id]); + }else{ + $candidateScore=$selector->score($container,$one); + } + return $candidateScore; + } + + /** + * One container's trial for a round, and how many single-container solves it spent. A + * declared container is one solve; a made-to-measure one runs the rung chain and returns + * its trial already fabricated. + * + * @param list $items + * @return array{0:SingleContainerSolution,1:int} + */ + private function trial(SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array + { + if($container->madeToMeasure===null)return [$solver->packOne($container,$sequence,$items,$config,$stats,$deadline),1]; + return $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]; + } + + /** A rung trial as the box cut for it: the achieved extent of its placements, envelope far faces with clearance, rounded up onto the machine grid (D14). O(p). */ + private static function fabricated(Container $declared,SingleContainerSolution $one):SingleContainerSolution + { + $box=$declared->fabricate(FlatBag::extentOf($one->state->placements)); + return new SingleContainerSolution($one->state->withContainer($box),$one->unpacked,false,$one->timeLimitReached,false); + } + /** @param list $preloaded */ private function acrossContainers(SingleContainerSolver $solver,array $items,array $containers,PackingConfig $config,SearchStats $stats,Deadline $deadline,array $preloaded=[]):array { @@ -598,42 +867,11 @@ private function acrossContainers(SingleContainerSolver $solver,array $items,arr $candidates=[]; foreach($ordered as $container){ if($inventory[$container->id]!==null&&$inventory[$container->id]<=0)continue; - try{$one=$solver->packOne($container,$seq[$container->id]+1,$remaining,$config,$stats,$deadline);} + try{[$one]=$this->trial($solver,$container,$seq[$container->id]+1,$remaining,$config,$stats,$deadline);} catch(TimeLimitReached $exception){$reached=true;break;} if($one->timeLimitReached)$reached=true; if($one->state->placementCount()===0){if($reached)break;continue;} - if(($config->objective==='shipping_cost'||$config->objective==='lowest_landed_cost')&&$config->dimensionalWeightDivisor!==null){ - $dimensions=$container->outerDimensions??$container->innerDimensions; - $dimensional=$dimensions->dimensionalWeight( - $config->dimensionalWeightDivisor, - $config->dimensionalWeightLengthUnit, - $config->dimensionalWeightWeightUnit, - )->ticks; - $gross=$container->tareWeight->ticks+$one->state->payloadTicks; - $billed=max($gross,$dimensional); - $placed=$one->state->placementCount(); - if($config->objective==='shipping_cost'){ - $candidateScore=[-$placed,$billed,$container->id]; - }else{ - // Landed cost ranks the round by the money the finished score will - // charge, not by the grams it is derived from. This loop commits the - // trial verbatim, so its billed weight is already final and the tariff - // can be read now; a bracket step or a minimum charge makes the cheaper - // shipment the heavier one, and a trial the tariff cannot price is - // unshippable rather than merely dear, so it sorts behind every - // priceable alternative. Keys after the charge mirror Rust's - // and Python's, so the three engines pick the same container. - $charge=($nullsafeVariable1 = $container->rateTable) ? $nullsafeVariable1->chargeMinorOrNull(LandedCostSolutionScorer::grams($billed)) : null; - $candidateScore=[ - $charge??LandedCostSolutionScorer::UNPRICEABLE_MINOR, - intdiv(count($remaining)+max($placed,1)-1,max($placed,1)), - -$placed, - $container->id, - ]; - } - }else{ - $candidateScore=$selector->score($container,$one); - } + $candidateScore=self::roundScore($one,$remaining,$config,$selector); $candidates[]=[$candidateScore,$one]; if($reached)break; } @@ -652,10 +890,11 @@ private function acrossContainers(SingleContainerSolver $solver,array $items,arr })); if($reached)break; } - $unpacked=[]; + $unpacked=[];$opened=self::openedByType($packed); foreach($remaining as $i){ [$reason,$details]=$this->unpackedReason($i,$containers,$reached); if($reason==='no_feasible_placement'&&$this->supportIsTheBlocker($i,$packed,$config))$reason='insufficient_support'; + if($reason==='no_feasible_placement')$reason=self::limitReason($i,$containers,$opened,$config)??$reason; $unpacked[]=new UnpackedItem($i,$reason,$details); } // Optimality may only be claimed when an exhaustive search filled a single @@ -738,7 +977,7 @@ private static function additionalContainerLowerBound(array $plan,array $contain })){ $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,$item->dimensions()->volumeString()); + $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)); } } @@ -788,8 +1027,10 @@ private function acrossContainerPlans(SingleContainerSolver $solver,array $items if($nodes>=$config->containerPlanNodeLimit)break; if($deadline->expired()){$reached=true;break;} if($plan['inventory'][$container->id]!==null&&$plan['inventory'][$container->id]<=0)continue; - $nodes++; - try{$one=$solver->packOne($container,$plan['sequences'][$container->id]+1,$plan['remaining'],$config,$stats,$deadline);}catch(TimeLimitReached $exception){$reached=true;break;} + // 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()]); @@ -816,7 +1057,7 @@ private function acrossContainerPlans(SingleContainerSolver $solver,array $items 0,$config->containerPlanBeamWidth, ); } - $unpacked=[];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';$unpacked[]=new UnpackedItem($item,$reason,$details);} + $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']]; } diff --git a/src-legacy/Artifacts/OperationalArtifact.php b/src-legacy/Artifacts/OperationalArtifact.php index 644ad60..3c778f3 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.5.0'; + public const SUITE_VERSION = '1.6.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']; @@ -128,6 +128,22 @@ public static function parse(string $json) } } + /** + * `exact` or `not_guaranteed`: the replay promise an artifact of this result would make, + * without building the artifact. The same rule {@see build()} records under + * `provenance.replay.level`, and the twin of Python's `packvium.artifacts.replay_level`. + * + * @param mixed $result a JSON object: a `stdClass` or an associative array + * @throws OperationalArtifactException `invalid_result` when `algorithm` is malformed + */ + public static function replayLevel($result): string + { + if (!JsonValue::isObject($result)) { + throw new OperationalArtifactException('invalid_result', 'a result is a JSON object'); + } + return self::replay(self::solver(JsonValue::get($result, 'algorithm')))['level']; + } + /** * The artifact's RFC 8785 canonical form, the bytes four engines are compared on. * diff --git a/src-legacy/Config/EffortBudget.php b/src-legacy/Config/EffortBudget.php new file mode 100644 index 0000000..7a8f0be --- /dev/null +++ b/src-legacy/Config/EffortBudget.php @@ -0,0 +1,17 @@ +maxLoad !== null ? $origins[0] : 0; + $highest = $rear->maxLoad !== null ? $origins[count($origins) - 1] : $lastOrigin; + return max(0, $lowest) <= min($lastOrigin, $highest); + } + private static function sNeg(string $v): string { if ($v === '0') { return '0'; } diff --git a/src-legacy/Constraint/Internal/ConstraintActivity.php b/src-legacy/Constraint/Internal/ConstraintActivity.php index 9931033..668900c 100644 --- a/src-legacy/Constraint/Internal/ConstraintActivity.php +++ b/src-legacy/Constraint/Internal/ConstraintActivity.php @@ -53,7 +53,8 @@ public static function isInert( return !$routeSensitive; } if ($constraint instanceof StopAccessibilityConstraint) { - return !$routeSensitive + // A flat bag has no walls, so it inherits no doors either. + return !$routeSensitive || $container->isFlatBag() || ($container->accessDirections === [] && $defaultAccessDirections === []); } if ($constraint instanceof AxleLoadConstraint) { diff --git a/src-legacy/Constraint/Internal/LoadSupportGraph.php b/src-legacy/Constraint/Internal/LoadSupportGraph.php index 19acf5a..9fdc08f 100644 --- a/src-legacy/Constraint/Internal/LoadSupportGraph.php +++ b/src-legacy/Constraint/Internal/LoadSupportGraph.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint\Internal; use Packvium\Constraint\{ContactEdge,ContactGraph,LoadUnit}; -use Packvium\Domain\{AxisAlignedBox,ItemInstance,Placement}; +use Packvium\Domain\{AxisAlignedBox,Item,ItemInstance,Placement}; /** * Direct load support: ordinary face contact plus exact adjacent nesting contact. @@ -174,20 +174,37 @@ public function supporters(int $index):array{return $this->nested?$this->support public function children(int $index):array{return $this->nested?$this->children[$index]:$this->face->children($index);} /** - * A direct-support edge may never originate at a non-stackable item. + * The first direct-support edge at the candidate its lower item refuses, or null. + * + * Supporters ascending, then children ascending. `non_stackable` is tested before the + * stacking-group rule on every edge, so a scene invalid before keeps its code; + * the group test rides this same walk, one keyed lookup per edge and no pass of its own. * * @param list $placements * @return array{0:string,1:string}|null */ public function nonStackableFailure(array $placements,ItemInstance $item,int $candidateIndex):?array { + $upperGroup=$item->item->stackingGroup; foreach($this->supporters($candidateIndex) as $edge){ - $supporter=$placements[$edge->index]; - if(!$supporter->instance->item->stackable) - return ['non_stackable',$supporter->instance->item->id]; + $lower=$placements[$edge->index]->instance->item; + $code=self::stackingRefusal($lower,$upperGroup); + if($code!==null)return [$code,$lower->id]; + } + $lower=$item->item; + if($lower->stackable&&$lower->acceptsStackingGroups===[])return null; + foreach($this->children($candidateIndex) as $child){ + $code=self::stackingRefusal($lower,$placements[$child]->instance->item->stackingGroup); + if($code!==null)return [$code,$lower->id]; } - if(!$item->item->stackable&&$this->children($candidateIndex)!==[]) - return ['non_stackable',$item->item->id]; + return null; + } + + /** Why `$lower` refuses an item of `$upperGroup` resting directly on it, or null. O(1). */ + private static function stackingRefusal(Item $lower,?string $upperGroup):?string + { + if(!$lower->stackable)return 'non_stackable'; + if(!$lower->acceptsStackingGroup($upperGroup))return 'stacking_group_incompatible'; return null; } diff --git a/src-legacy/Constraint/StopAccessibilityConstraint.php b/src-legacy/Constraint/StopAccessibilityConstraint.php index 9683ba0..4199165 100644 --- a/src-legacy/Constraint/StopAccessibilityConstraint.php +++ b/src-legacy/Constraint/StopAccessibilityConstraint.php @@ -131,8 +131,8 @@ public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->routeSensitive)return ConstraintResult::allow(); // The container's own doors win; the configured list is what a container that - // states none inherits. - $directions=$c->container->accessDirections!==[]?$c->container->accessDirections:$this->defaultDirections; + // states none inherits. A flat bag has no walls, so it inherits none. + $directions=$c->container->isFlatBag()?[]:($c->container->accessDirections!==[]?$c->container->accessDirections:$this->defaultDirections); if($directions===[])return ConstraintResult::allow(); $candidateStop=$c->item->item->stopIndex??INF; $inner=$c->container->innerDimensions; diff --git a/src-legacy/Domain/Container.php b/src-legacy/Domain/Container.php index de95521..cdba94c 100644 --- a/src-legacy/Domain/Container.php +++ b/src-legacy/Domain/Container.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; use InvalidArgumentException; +use Packvium\Unit\Length; use Packvium\Unit\Weight; final class Container { @@ -90,6 +91,16 @@ final class Container * @var mixed[] */ public $preloaded = []; + /** + * @readonly + * @var string|null + */ + public $deformableBoundary; + /** + * @readonly + * @var \Packvium\Domain\MadeToMeasure|null + */ + public $madeToMeasure; /** * Which walls this container can be unloaded through. * @@ -115,9 +126,12 @@ final class Container * solver's `ContainerState` starts from them without knowing they exist; a packed result * carries the container with this emptied again (docs/PLAN-REVISIONS.md). * + * `$deformableBoundary`: `'flat_bag'` makes this a flexible bag whose package conforms to its + * contents (`FlatBag`); null is a rigid container. + * * @param list $obstacles @param list $tags @param array $tagLimits @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections @param list $preloaded */ - public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $outerDimensions=null,?Weight $tareWeight=null,?Weight $maxPayload=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],?Weight $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],array $preloaded=[]) + public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $outerDimensions=null,?Weight $tareWeight=null,?Weight $maxPayload=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],?Weight $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],array $preloaded=[],?string $deformableBoundary=null,?MadeToMeasure $madeToMeasure=null) {$tareWeight = $tareWeight ?? new Weight(0); $this->id = $id; $this->innerDimensions = $innerDimensions; @@ -136,7 +150,9 @@ public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $ $this->axles = $axles; $this->rateTable = $rateTable; $this->preloaded = $preloaded; - if($id==='')throw new InvalidArgumentException('Container id is required');if($quantity!==null&&$quantity<=0)throw new InvalidArgumentException('Container quantity must be positive');if($costMinor<0)throw new InvalidArgumentException('Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new InvalidArgumentException('Container max_items must be at least 1');if($voidFillReserveRatio<0||$voidFillReserveRatio>1)throw new InvalidArgumentException('void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new InvalidArgumentException('tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new InvalidArgumentException('Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new InvalidArgumentException("Obstacle {$o->id} lies outside container"); + $this->deformableBoundary = $deformableBoundary; + $this->madeToMeasure = $madeToMeasure; + if($id==='')throw new InvalidArgumentException('Container id is required');($nullsafeVariable1 = $madeToMeasure) ? $nullsafeVariable1->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]) : null;if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio);if($quantity!==null&&$quantity<=0)throw new InvalidArgumentException('Container quantity must be positive');if($costMinor<0)throw new InvalidArgumentException('Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new InvalidArgumentException('Container max_items must be at least 1');if($voidFillReserveRatio<0||$voidFillReserveRatio>1)throw new InvalidArgumentException('void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new InvalidArgumentException('tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new InvalidArgumentException('Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new InvalidArgumentException("Obstacle {$o->id} lies outside container"); if($axles!==null){[$front,$rear]=$axles;if($front->position->ticks>=$rear->position->ticks)throw new InvalidArgumentException('The front axle must be strictly nearer the origin than the rear axle');if($front->position->ticks<0||$rear->position->ticks>$innerDimensions->length->ticks)throw new InvalidArgumentException("Axle positions must lie within the container's length");} 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 @@ -145,11 +161,50 @@ public function __construct(string $id,Dimensions $innerDimensions,?Dimensions $ return in_array($d,$accessDirections,true); }));} /** The same container holding `$placements` before search. @param list $placements */ - public function withPreloaded(array $placements):self{return new self($this->id,$this->innerDimensions,$this->outerDimensions,$this->tareWeight,$this->maxPayload,$this->costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$placements);} + 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;} + /** The declared container solved inside `$rung`: same id, everything else unchanged. @param array{0:int,1:int,2:int} $rung */ + public function withEnvelope(array $rung):self{return $this->resized(self::dimensionsOf($rung),null,$this->costMinor,$this->tareWeight);} + /** + * The box cut for an achieved extent: equal to this declared machine except its size, outer + * size, price and tare. O(1). Containment is a theorem, not a check: every placement lies + * inside `$achieved`, and the grid never rounds below it or past the maximum (D4). + * + * @param array{0:int,1:int,2:int} $achieved + */ + public function fabricate(array $achieved):self + { + $machine=$this->madeToMeasure; + if($machine===null)throw new \LogicException("container {$this->id} is not made to measure"); + $maximum=[$this->innerDimensions->length->ticks,$this->innerDimensions->width->ticks,$this->innerDimensions->height->ticks]; + $sides=[];$outer=[]; + for($axis=0;$axis<3;$axis++){ + $sides[]=$machine->grid($axis,$achieved[$axis]); + if($sides[$axis]>$maximum[$axis])throw new \LogicException('fabricated box exceeds the machine'); + $outer[]=$sides[$axis]+$machine->outerAllowance[$axis]; + } + return $this->resized(self::dimensionsOf($sides),self::dimensionsOf($outer),$machine->boxCostMinor($this->costMinor,$sides),new Weight($machine->boxTareTicks($this->tareWeight->ticks,$sides))); + } + private function resized(Dimensions $inner,?Dimensions $outer,int $costMinor,Weight $tareWeight):self{return new self($this->id,$inner,$outer,$tareWeight,$this->maxPayload,$costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure);} + /** @param array{0:int,1:int,2:int} $sides */ + private static function dimensionsOf(array $sides):Dimensions{return new Dimensions(new Length($sides[0]),new Length($sides[1]),new Length($sides[2]));} + /** + * A bag has no walls, floor plan or chassis for a wall-anchored field to refer to, so those + * fields are refused rather than read against a frame that moves with its contents. The JSON + * path names the same fields as request errors first. + * + * @param list $obstacles @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections + */ + private static function requireBagFields(string $kind,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio):void + { + if(!in_array($kind,FlatBag::KINDS,true))throw new InvalidArgumentException("unknown deformable_boundary kind {$kind}"); + $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'max_stack_density'=>$maxStackDensity!==null,'outer_dimensions'=>$outerDimensions!==null,'void_fill_reserve_ratio'=>$voidFillReserveRatio>0]; + foreach($present as $name=>$set)if($set)throw new InvalidArgumentException("{$name} cannot be combined with deformable_boundary"); + } /** * @param \Packvium\Unit\Weight|int|string|mixed[] $tareWeight * @param \Packvium\Unit\Weight|int|string|mixed[]|null $maxPayload * @param \Packvium\Unit\Weight|int|string|mixed[]|null $maxStackDensity */ - public static function create(string $id,Dimensions $innerDimensions,$tareWeight=0,$maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],$maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[]):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections);} + public static function create(string $id,Dimensions $innerDimensions,$tareWeight=0,$maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],$maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],?string $deformableBoundary=null):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections,[],$deformableBoundary);} } diff --git a/src-legacy/Domain/FlatBag.php b/src-legacy/Domain/FlatBag.php new file mode 100644 index 0000000..e5ea524 --- /dev/null +++ b/src-legacy/Domain/FlatBag.php @@ -0,0 +1,51 @@ +length->ticks&&$b+$c<=$inner->width->ticks; + } + + /** Whether one box of these dimensions, alone at the origin, fits a flat bag. */ + public static function fitsAlone(Dimensions $inner,Dimensions $box):bool + { + return $box->fitsInside($inner)&&self::girthAdmits($inner,$box->length->ticks,$box->width->ticks,$box->height->ticks); + } + + /** + * `[max x2, max y2, max z2]` over the envelopes, `[0, 0, 0]` for none. O(p). + * + * @param list $placements @return array{0:int,1:int,2:int} + */ + public static function extentOf(array $placements):array + { + $a=$b=$c=0; + foreach($placements as $p){$e=$p->envelopeBox();$a=max($a,$e->x2());$b=max($b,$e->y2());$c=max($c,$e->z2());} + return [$a,$b,$c]; + } + + /** The achieved extent as dimensions; a packed bag always holds at least one box. @param array{0:int,1:int,2:int} $extent */ + public static function asDimensions(array $extent):Dimensions + { + return new Dimensions(new Length($extent[0]),new Length($extent[1]),new Length($extent[2])); + } +} diff --git a/src-legacy/Domain/Item.php b/src-legacy/Domain/Item.php index 1ebefb0..e020a75 100644 --- a/src-legacy/Domain/Item.php +++ b/src-legacy/Domain/Item.php @@ -130,7 +130,22 @@ final class Item * @var int|null */ public $maxCompressionPressureKpa; - public function __construct(string $id,Dimensions $dimensions,?Weight $weight=null,int $quantity=1,array $allowedRotations=[Rotation::LWH,Rotation::LHW,Rotation::WLH,Rotation::WHL,Rotation::HLW,Rotation::HWL],bool $keepUpright=false,bool $stackable=true,bool $mustBeOnFloor=false,?Weight $maxTopLoad=null,float $minimumSupportRatio=0.0,?string $group=null,array $tags=[],array $incompatibleTags=[],int $priority=0,array $metadata=[],?int $maxStackedItems=null,array $eligibleContainerTags=[],?string $groundContactRule=null,?Length $nestingHeight=null,?int $stopIndex=null,?int $value=null,string $shapeType=ShapeType::RIGID_CUBOID,?array $hullVertices=null,?int $compressionRatioPpm=null,?int $maxCompressionPressureKpa=null) + // Which stacking class this item belongs to, and which classes it may carry directly on + // its top face (docs/STACKING-GROUPS.md). An empty list is unconstrained, like + // tags; a non-empty one is closed, so an item with no class rests on no constrained + // item -- a forgotten classification fails closed, never open. + /** + * @readonly + * @var string|null + */ + public $stackingGroup; + /** @var list + * @readonly */ + public $acceptsStackingGroups; + /** @var array the same list keyed, so each support edge costs one lookup + * @readonly */ + private $acceptedStackingGroups; + public function __construct(string $id,Dimensions $dimensions,?Weight $weight=null,int $quantity=1,array $allowedRotations=[Rotation::LWH,Rotation::LHW,Rotation::WLH,Rotation::WHL,Rotation::HLW,Rotation::HWL],bool $keepUpright=false,bool $stackable=true,bool $mustBeOnFloor=false,?Weight $maxTopLoad=null,float $minimumSupportRatio=0.0,?string $group=null,array $tags=[],array $incompatibleTags=[],int $priority=0,array $metadata=[],?int $maxStackedItems=null,array $eligibleContainerTags=[],?string $groundContactRule=null,?Length $nestingHeight=null,?int $stopIndex=null,?int $value=null,string $shapeType=ShapeType::RIGID_CUBOID,?array $hullVertices=null,?int $compressionRatioPpm=null,?int $maxCompressionPressureKpa=null,?string $stackingGroup=null,array $acceptsStackingGroups=[]) { if($id==='')throw new InvalidArgumentException('Item id is required');if($quantity<=0)throw new InvalidArgumentException('Item quantity must be positive');if($minimumSupportRatio<0||$minimumSupportRatio>1)throw new InvalidArgumentException('Minimum support ratio must be between 0 and 1');if($maxStackedItems!==null&&$maxStackedItems<1)throw new InvalidArgumentException('max_stacked_items must be at least 1');if($groundContactRule!==null&&!in_array($groundContactRule,self::GROUND_CONTACT_RULES,true))throw new InvalidArgumentException('ground_contact_rule must be one of '.implode(', ',self::GROUND_CONTACT_RULES)); if($nestingHeight!==null&&!($nestingHeight->ticks>=0&&$nestingHeight->ticks<$dimensions->height->ticks))throw new InvalidArgumentException("nesting_height must be at least zero and strictly less than the item's own height"); @@ -143,12 +158,14 @@ public function __construct(string $id,Dimensions $dimensions,?Weight $weight=nu $this->shapeType=$shapeType; $this->hullVertices=self::admitShape($shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa,$dimensions,$nestingHeight); $this->compressionRatioPpm=$compressionRatioPpm;$this->maxCompressionPressureKpa=$maxCompressionPressureKpa; + $this->stackingGroup=$stackingGroup;$this->acceptsStackingGroups=array_values(array_unique($acceptsStackingGroups)); + $this->acceptedStackingGroups=array_fill_keys($this->acceptsStackingGroups,true); } /** * @param \Packvium\Unit\Weight|int|string|mixed[] $weight * @param \Packvium\Unit\Weight|int|string|mixed[]|null $maxTopLoad */ - public static function create(string $id,Dimensions $dimensions,$weight=0,int $quantity=1,array $allowedRotations=[Rotation::LWH,Rotation::LHW,Rotation::WLH,Rotation::WHL,Rotation::HLW,Rotation::HWL],bool $keepUpright=false,bool $stackable=true,bool $mustBeOnFloor=false,$maxTopLoad=null,float $minimumSupportRatio=0.0,?string $group=null,array $tags=[],array $incompatibleTags=[],int $priority=0,array $metadata=[],?int $maxStackedItems=null,array $eligibleContainerTags=[],?string $groundContactRule=null,?Length $nestingHeight=null,?int $stopIndex=null,?int $value=null,string $shapeType=ShapeType::RIGID_CUBOID,?array $hullVertices=null,?int $compressionRatioPpm=null,?int $maxCompressionPressureKpa=null):self{return new self($id,$dimensions,Weight::parse($weight),$quantity,$allowedRotations,$keepUpright,$stackable,$mustBeOnFloor,$maxTopLoad===null?null:Weight::parse($maxTopLoad),$minimumSupportRatio,$group,$tags,$incompatibleTags,$priority,$metadata,$maxStackedItems,$eligibleContainerTags,$groundContactRule,$nestingHeight,$stopIndex,$value,$shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa);} + public static function create(string $id,Dimensions $dimensions,$weight=0,int $quantity=1,array $allowedRotations=[Rotation::LWH,Rotation::LHW,Rotation::WLH,Rotation::WHL,Rotation::HLW,Rotation::HWL],bool $keepUpright=false,bool $stackable=true,bool $mustBeOnFloor=false,$maxTopLoad=null,float $minimumSupportRatio=0.0,?string $group=null,array $tags=[],array $incompatibleTags=[],int $priority=0,array $metadata=[],?int $maxStackedItems=null,array $eligibleContainerTags=[],?string $groundContactRule=null,?Length $nestingHeight=null,?int $stopIndex=null,?int $value=null,string $shapeType=ShapeType::RIGID_CUBOID,?array $hullVertices=null,?int $compressionRatioPpm=null,?int $maxCompressionPressureKpa=null,?string $stackingGroup=null,array $acceptsStackingGroups=[]):self{return new self($id,$dimensions,Weight::parse($weight),$quantity,$allowedRotations,$keepUpright,$stackable,$mustBeOnFloor,$maxTopLoad===null?null:Weight::parse($maxTopLoad),$minimumSupportRatio,$group,$tags,$incompatibleTags,$priority,$metadata,$maxStackedItems,$eligibleContainerTags,$groundContactRule,$nestingHeight,$stopIndex,$value,$shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa,$stackingGroup,$acceptsStackingGroups);} /** * Admit this item's shape, or refuse it with the reason. * @@ -210,7 +227,21 @@ private static function admitShape(string $shapeType,?array $hullVertices,?int $ */ public function isStackSensitive():bool { - return !$this->stackable||$this->maxTopLoad!==null||$this->maxStackedItems!==null||$this->maxCompressionPressureKpa!==null; + // A stacking group alone does not count: such an item is refused only by a + // constrained item beneath it, which already switched the graph on. + return !$this->stackable||$this->acceptsStackingGroups!==[]||$this->maxTopLoad!==null||$this->maxStackedItems!==null||$this->maxCompressionPressureKpa!==null; + } + + /** Whether an item of `$group` may rest directly on this one, ignoring `stackable`. O(1). */ + public function acceptsStackingGroup(?string $group):bool + { + return $this->acceptsStackingGroups===[]||($group!==null&&isset($this->acceptedStackingGroups[$group])); + } + + /** Whether a column of this one item type passes every stacking edge. */ + public function carriesItself():bool + { + return $this->stackable&&$this->acceptsStackingGroup($this->stackingGroup); } /** @return list */ public function instances():array{$out=[];for($i=1;$i<=$this->quantity;$i++)$out[]=new ItemInstance($this,$i);return $out;} diff --git a/src-legacy/Domain/MadeToMeasure.php b/src-legacy/Domain/MadeToMeasure.php new file mode 100644 index 0000000..b1bccf5 --- /dev/null +++ b/src-legacy/Domain/MadeToMeasure.php @@ -0,0 +1,191 @@ +minimum = $minimum; + $this->increment = $increment; + $this->costPerSquareMetreMinor = $costPerSquareMetreMinor; + $this->tarePerSquareMetre = $tarePerSquareMetre; + $this->outerAllowance = $outerAllowance; + if(min($minimum)<=0)throw new InvalidArgumentException('made_to_measure minimum must be positive'); + if(min($increment)<=0)throw new InvalidArgumentException('made_to_measure increment must be positive'); + if($costPerSquareMetreMinor<0||$tarePerSquareMetre<0)throw new InvalidArgumentException('made_to_measure prices cannot be negative'); + if(min($outerAllowance)<0)throw new InvalidArgumentException('made_to_measure outer_allowance cannot be negative'); + } + + /** + * Refuse a machine whose grid does not land on its own maximum. O(1). Every reachable size + * is then unambiguous, and rounding an achieved extent inside the maximum up onto the grid + * can never pass it (D3, D4). + * + * @param array{0:int,1:int,2:int} $maximum + */ + public function admits(array $maximum):void + { + foreach(['length','width','height'] as $axis=>$name){ + if($this->minimum[$axis]>$maximum[$axis])throw new InvalidArgumentException("made_to_measure minimum {$name} exceeds inner_dimensions"); + if(($maximum[$axis]-$this->minimum[$axis])%$this->increment[$axis]!==0)throw new InvalidArgumentException("made_to_measure increment {$name} does not divide inner_dimensions minus minimum"); + } + } + + /** The smallest cuttable size on `$axis` that is at least `$value`. */ + public function grid(int $axis,int $value):int + { + $minimum=$this->minimum[$axis];$step=$this->increment[$axis]; + return $minimum+intdiv(max($value,$minimum)-$minimum+$step-1,$step)*$step; + } + + /** `grid`, capped at the machine maximum: sizes a solving envelope, never a box. */ + public function clamp(int $axis,int $value,int $maximum):int{return min($maximum,$this->grid($axis,$value));} + + /** The inner surface of a closed box, 2(LW + LH + WH), in square ticks. @param array{0:int,1:int,2:int} $sides */ + public static function surfaceArea(array $sides):string + { + [$l,$w,$h]=$sides; + return BigInt::multiply('2',BigInt::add(BigInt::add(BigInt::multiply($l,$w),BigInt::multiply($l,$h)),BigInt::multiply($w,$h))); + } + + /** + * ceil(rate * area / 1 m^2), as `p*q + ceil(p*r / T^2)` with `q, r = divmod(area, T^2)` -- + * the split Rust needs to stay inside i128, kept here so the engines share one formula. + */ + public static function perSquareMetre(int $rate,string $area):string + { + $whole=BigInt::divide($area,self::SQUARE_METRE_TICKS2); + $fraction=BigInt::subtract($area,BigInt::multiply($whole,self::SQUARE_METRE_TICKS2)); + $numerator=BigInt::multiply($rate,$fraction); + $part=BigInt::divide($numerator,self::SQUARE_METRE_TICKS2); + if(BigInt::compare(BigInt::multiply($part,self::SQUARE_METRE_TICKS2),$numerator)<0)$part=BigInt::add($part,'1'); + return BigInt::add(BigInt::multiply($rate,$whole),$part); + } + + /** + * A box's price: the container's own fee plus its material at `$priceMinor` per square + * metre, rounded up. Cost grows with every side, so the machine maximum bounds them all. + * + * @param array{0:int,1:int,2:int} $sides + */ + public static function boxCostFor(int $priceMinor,int $feeMinor,array $sides):string + { + return BigInt::add((string)$feeMinor,self::perSquareMetre($priceMinor,self::surfaceArea($sides))); + } + + /** @param array{0:int,1:int,2:int} $sides */ + public function boxCostMinor(int $feeMinor,array $sides):int{return (int)self::boxCostFor($this->costPerSquareMetreMinor,$feeMinor,$sides);} + + /** The fabricated box's weight: the declared tare plus its board, rounded up. @param array{0:int,1:int,2:int} $sides */ + public function boxTareTicks(int $declaredTare,array $sides):int + { + return (int)BigInt::add((string)$declaredTare,self::perSquareMetre($this->tarePerSquareMetre,self::surfaceArea($sides))); + } + + /** The smallest non-negative c with c^3 >= value: doubling, then bisection, O(log value) steps. */ + public static function icbrtCeil(string $value):string + { + $cube=static function (string $x): string { + return BigInt::multiply(BigInt::multiply($x,$x),$x); + }; + $high='1'; + while(BigInt::compare($cube($high),$value)<0)$high=BigInt::multiply($high,'2'); + $low='0'; + while(BigInt::compare($low,$high)<0){ + $middle=BigInt::divide(BigInt::add($low,$high),'2'); + if(BigInt::compare($cube($middle),$value)>=0)$high=$middle;else $low=BigInt::add($middle,'1'); + } + return $low; + } + + /** + * The rungs one trial tries, ascending on every axis, the machine maximum last. + * + * `$edges` are each remaining instance's envelope edges (nominal plus twice the clearance). + * O(r) over the r instances plus the cube root; the list depends only on their multiset. + * + * @param array{0:int,1:int,2:int} $maximum @param list $edges + * @return list + */ + public function solvingEnvelopes(array $maximum,array $edges):array + { + $volume='0';$floors=[0,0,0]; + foreach($edges as $instance){ + $volume=BigInt::add($volume,BigInt::multiply(BigInt::multiply($instance[0],$instance[1]),$instance[2])); + $ranked=$instance;rsort($ranked); + for($rank=0;$rank<3;$rank++)$floors[$rank]=max($floors[$rank],$ranked[$rank]); + } + $side=self::icbrtCeil($volume); + $rungs=[]; + foreach(self::RUNG_FACTORS as [$numerator,$denominator]){ + $scaled=(int)BigInt::divide(BigInt::add(BigInt::multiply($side,$numerator),(string)($denominator-1)),(string)$denominator); + $rung=[]; + for($axis=0;$axis<3;$axis++)$rung[]=$this->clamp($axis,max($scaled,$floors[$axis]),$maximum[$axis]); + if(BigInt::compare(BigInt::multiply(BigInt::multiply($rung[0],$rung[1]),$rung[2]),$volume)<0||in_array($rung,$rungs,true))continue; + $rungs[]=$rung; + } + if(!in_array($maximum,$rungs,true))$rungs[]=$maximum; + return $rungs; + } + + /** + * Each instance's envelope edges, the input `solvingEnvelopes` sizes rungs from. + * + * @param list $items @return list + */ + public static function instanceEdges(array $items,int $clearanceTicks):array + { + $grow=2*$clearanceTicks; + return array_map(static function(ItemInstance $item)use($grow):array{$d=$item->dimensions();return [$d->length->ticks+$grow,$d->width->ticks+$grow,$d->height->ticks+$grow];},$items); + } +} diff --git a/src-legacy/Domain/Nesting.php b/src-legacy/Domain/Nesting.php index e80a8e5..364f086 100644 --- a/src-legacy/Domain/Nesting.php +++ b/src-legacy/Domain/Nesting.php @@ -103,6 +103,23 @@ public static function occupiedVolume(Placement $placement): string return BigInt::multiply((string)$footprint, (string)$height); } + /** + * The volume `occupiedVolume` counts for this item before it is placed, in any orientation. + * + * A hull occupies its authored solid and a proper rotation keeps that volume, so one + * orientation answers for all six through the memoised shape. A compressible item keeps + * its declared box: collision and support use the uncompressed box, so placed boxes never + * share space and their declared volumes stay additive. + */ + public static function itemOccupiedVolume(ItemInstance $instance): string + { + $item = $instance->item; + if ($item->shapeType === ShapeType::CONVEX_HULL) { + return HullShape::shapeFor($item->hullVertices, Rotation::LWH)->volume; + } + return $instance->dimensions()->volumeString(); + } + /** * Physical volume actually occupied by `$placements`, nesting overlap removed. * diff --git a/src-legacy/Domain/PackedContainer.php b/src-legacy/Domain/PackedContainer.php index 981908d..4637070 100644 --- a/src-legacy/Domain/PackedContainer.php +++ b/src-legacy/Domain/PackedContainer.php @@ -98,11 +98,29 @@ public function expandPlacements(): array return $this->latticeSummary !== null ? $this->latticeSummary->expand($this->latticeItems) : $this->placements; } + /** + * The largest envelope x2, y2 and z2 of its placements: a flat bag's conformed package + *, or a made-to-measure box's extent before it is rounded onto the machine grid + *; null for any other container. O(p). + */ + public function achievedDimensions():?Dimensions + { + if(!$this->container->isFlatBag()&&$this->container->madeToMeasure===null)return null; + return FlatBag::asDimensions(FlatBag::extentOf($this->placements)); + } + + /** What a carrier measures: a bag's achieved package, else the declared outer size. */ + public function billedDimensions():Dimensions + { + $achieved=$this->container->isFlatBag()?$this->achievedDimensions():null; + return $achieved??$this->container->outerDimensions??$this->container->innerDimensions; + } + public function asItem(?string $id=null,bool $keepUpright=true,?Weight $maxTopLoad=null):Item { return Item::create( $id??$this->id(), - $this->container->outerDimensions??$this->container->innerDimensions, + $this->billedDimensions(), $this->grossWeight(), 1, Rotation::all(), diff --git a/src-legacy/Explain/Explain.php b/src-legacy/Explain/Explain.php index 8323729..335057b 100644 --- a/src-legacy/Explain/Explain.php +++ b/src-legacy/Explain/Explain.php @@ -58,6 +58,8 @@ final class Explain 'was not placed because the exact search ended before proving a final answer', 'container_inventory_exhausted' => 'requires another compatible container, but the declared inventory is exhausted', + 'axle_overloaded' => + 'would overload an axle wherever it stood alone in any container that otherwise admits it', ]; /** diff --git a/src-legacy/Objective/LandedCostSolutionScorer.php b/src-legacy/Objective/LandedCostSolutionScorer.php index 889ac74..1e65866 100644 --- a/src-legacy/Objective/LandedCostSolutionScorer.php +++ b/src-legacy/Objective/LandedCostSolutionScorer.php @@ -51,7 +51,7 @@ public function score(RawSolution $solution): ObjectiveScore . "'{$container->container->id}' has none", ); } - $dimensions = $container->container->outerDimensions ?? $container->container->innerDimensions; + $dimensions = $container->billedDimensions(); $dimensionalWeight = $dimensions->dimensionalWeight($this->divisor, $this->lengthUnit, $this->weightUnit); $billedTicks = max($container->grossWeight()->ticks, $dimensionalWeight->ticks); $charge = $table->chargeMinorOrNull(self::grams($billedTicks)); @@ -82,7 +82,7 @@ public static function unpriceableContainer(array $containers, PackingConfig $co return null; } foreach ($containers as $container) { - $dimensions = $container->container->outerDimensions ?? $container->container->innerDimensions; + $dimensions = $container->billedDimensions(); $dimensional = $dimensions->dimensionalWeight( $config->dimensionalWeightDivisor, $config->dimensionalWeightLengthUnit, diff --git a/src-legacy/Objective/MaximumVolumeSolutionScorer.php b/src-legacy/Objective/MaximumVolumeSolutionScorer.php new file mode 100644 index 0000000..524ce8d --- /dev/null +++ b/src-legacy/Objective/MaximumVolumeSolutionScorer.php @@ -0,0 +1,57 @@ +score($solution)->components; + $unpackedVolume = '0'; + foreach ($solution->unpacked as $item) { + $unpackedVolume = BigInt::add($unpackedVolume, $item->instance->dimensions()->volumeString()); + } + $requested = $unpackedVolume; + foreach ($solution->containers as $container) { + $instances = $container->latticeItems !== [] + ? $container->latticeItems + : array_map(static function ($placement) { + return $placement->instance; + }, $container->placements); + foreach ($instances as $instance) { + $requested = BigInt::add($requested, $instance->dimensions()->volumeString()); + } + } + return new ObjectiveScore([self::ceilingPpm($unpackedVolume, $requested), $unpacked, $containers, $cost, $unused]); + } + + private static function ceilingPpm(string $part, string $whole): int + { + if (BigInt::compare($whole, '0') === 0) { + return 0; + } + $rounded = BigInt::add(BigInt::multiply($part, (string)self::SCALE), BigInt::subtract($whole, '1')); + return (int)BigInt::divide($rounded, $whole); + } +} diff --git a/src-legacy/Objective/ObjectiveRegistry.php b/src-legacy/Objective/ObjectiveRegistry.php index a299d12..9fa4d8f 100644 --- a/src-legacy/Objective/ObjectiveRegistry.php +++ b/src-legacy/Objective/ObjectiveRegistry.php @@ -36,6 +36,9 @@ public static function resolve(string $name, ?PackingConfig $config = null): Sol 'maximum_value' => static function (?PackingConfig $config) { return new MaximumValueSolutionScorer(); }, + 'maximum_volume' => static function (?PackingConfig $config) { + return new MaximumVolumeSolutionScorer(); + }, ]; $factory = self::$factories[$name] ?? null; if ($factory === null) { diff --git a/src-legacy/Objective/ShippingCostSolutionScorer.php b/src-legacy/Objective/ShippingCostSolutionScorer.php index 3cf3ca2..ff2038f 100644 --- a/src-legacy/Objective/ShippingCostSolutionScorer.php +++ b/src-legacy/Objective/ShippingCostSolutionScorer.php @@ -73,7 +73,7 @@ public function score(RawSolution $solution): ObjectiveScore $billable = 0; foreach ($solution->containers as $container) { - $dimensions = $container->container->outerDimensions ?? $container->container->innerDimensions; + $dimensions = $container->billedDimensions(); $dimensionalWeight = $dimensions->dimensionalWeight($this->divisor, $this->lengthUnit, $this->weightUnit); $billable += max($container->grossWeight()->ticks, $dimensionalWeight->ticks); } diff --git a/src-legacy/Packer.php b/src-legacy/Packer.php index 515d5f6..8b14be4 100644 --- a/src-legacy/Packer.php +++ b/src-legacy/Packer.php @@ -4,7 +4,7 @@ namespace Packvium; use Packvium\Algorithm\{Deadline, FixedPlacementAdmission, SolverOrchestrator}; -use Packvium\Support\StableSorter; +use Packvium\Support\{StableSorter, UnsupportedPlacements}; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, UnratedWeightException}; use Packvium\Extension\ExtensionRegistry; @@ -142,6 +142,10 @@ static function ($c) { } } } + $unsupported = UnsupportedPlacements::warning($raw->containers, $this->config->minimumSupportRatio); + if ($unsupported !== null) { + $warnings[] = $unsupported; + } $starts = []; $winnerMarked = false; foreach ($portfolio->starts as $record) { diff --git a/src-legacy/Result/PackingResult.php b/src-legacy/Result/PackingResult.php index b4073b2..70c5701 100644 --- a/src-legacy/Result/PackingResult.php +++ b/src-legacy/Result/PackingResult.php @@ -4,7 +4,8 @@ namespace Packvium\Result; use Packvium\Constraint\{AxleLoad, LoadCalculator, VolumeReserve}; -use Packvium\Domain\{PackedContainer, UnpackedItem}; +use Packvium\Domain\{Dimensions, PackedContainer, Point, UnpackedItem}; +use Packvium\Unit\Length; final class PackingResult { @@ -158,6 +159,15 @@ public function toArray( string $weightUnit = 'g', bool $includeAlternatives = true ): array { + // Equal quantities share one array: placements repeat a type's dimensions, a lattice + // coordinate and a zero top load, and a shared array serializes to the same bytes. + $shared = ['length' => [], 'weight' => [], 'dimensions' => []]; + return $this->serialized($lengthUnit, $weightUnit, $includeAlternatives, $shared); + } + + /** @param array{length:array,weight:array,dimensions:array>>} $shared */ + private function serialized(string $lengthUnit, string $weightUnit, bool $includeAlternatives, array &$shared): array + { $containers = []; foreach ($this->containers as $container) { $placements = []; @@ -165,11 +175,11 @@ public function toArray( $placements[] = [ 'item_id' => $placement->instance->id(), 'item_type' => $placement->instance->item->id, - 'position' => $placement->position->toArray($lengthUnit), - 'dimensions' => $placement->dimensions->toArray($lengthUnit), + 'position' => self::point($placement->position, $lengthUnit, $shared), + 'dimensions' => self::dimensions($placement->dimensions, $lengthUnit, $shared), 'orientation' => $placement->rotation, 'support_ratio' => sprintf('%.6f', $placement->supportRatio), - 'top_load' => $placement->topLoad->toArray($weightUnit), + 'top_load' => $shared['weight'][$placement->topLoad->ticks] = $shared['weight'][$placement->topLoad->ticks] ?? $placement->topLoad->toArray($weightUnit), ]; // Absent unless true, so a request without fixed placements keeps its bytes. if ($placement->fixed) { @@ -190,6 +200,20 @@ public function toArray( 'void_fill_reserve_ticks3' => VolumeReserve::reserved($container->container), 'placements' => $placements, ]; + // Present exactly when the container conforms to its contents, so a + // rigid container's bytes are unchanged. + $achieved = $container->achievedDimensions(); + if ($achieved !== null) { + $serialized['achieved_dimensions'] = $achieved->toArray($lengthUnit); + } + // A packed made-to-measure container is the fabricated box, so its own price and + // tare are the box's; absent for every other container. + if ($container->container->madeToMeasure !== null) { + $serialized['made_to_measure'] = [ + 'cost_minor' => $container->container->costMinor, + 'tare_weight' => $container->container->tareWeight->toArray($weightUnit), + ]; + } if ($container->latticeSummary !== null) { // Compact form: when `configuration.require_placement_coordinates` // was false and GridSolver's lattice fast path applied, `placements` stays @@ -238,6 +262,13 @@ public function toArray( ]; } + $alternatives = []; + if ($includeAlternatives) { + foreach ($this->alternatives as $alternative) { + $alternatives[] = $alternative->serialized($lengthUnit, $weightUnit, false, $shared); + } + } + return [ 'status' => $this->status, 'feasibility' => $this->feasibility->toArray(), @@ -266,11 +297,23 @@ public function toArray( 'unpacked_items' => $unpacked, 'catalog_versions_used' => [], 'warnings' => $this->warnings, - 'alternatives' => $includeAlternatives - ? array_map(function (self $alternative) use ($lengthUnit, $weightUnit) { - return $alternative->toArray($lengthUnit, $weightUnit, false); - }, $this->alternatives) - : [], + 'alternatives' => $alternatives, ]; } + + /** `Point::toArray`, from shared length arrays. */ + private static function point(Point $point, string $unit, array &$shared): array + { + return [ + 'x' => $shared['length'][$point->x] = $shared['length'][$point->x] ?? (new Length($point->x))->toArray($unit), + 'y' => $shared['length'][$point->y] = $shared['length'][$point->y] ?? (new Length($point->y))->toArray($unit), + 'z' => $shared['length'][$point->z] = $shared['length'][$point->z] ?? (new Length($point->z))->toArray($unit), + ]; + } + + /** `Dimensions::toArray`, one shared array per distinct size. */ + private static function dimensions(Dimensions $dimensions, string $unit, array &$shared): array + { + return $shared['dimensions'][$dimensions->length->ticks][$dimensions->width->ticks][$dimensions->height->ticks] = $shared['dimensions'][$dimensions->length->ticks][$dimensions->width->ticks][$dimensions->height->ticks] ?? $dimensions->toArray($unit); + } } diff --git a/src-legacy/Sequence/LoadingDependencyGraph.php b/src-legacy/Sequence/LoadingDependencyGraph.php index b4e1b7f..94818d3 100644 --- a/src-legacy/Sequence/LoadingDependencyGraph.php +++ b/src-legacy/Sequence/LoadingDependencyGraph.php @@ -219,6 +219,13 @@ public static function verifyLoadingPrefixBusinessRules(array $placements, array throw new SequenceReplayError(-1, -1, 'order is not a permutation of every placement index exactly once'); } $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; + foreach ($placements as $placement) { + $grouped = $grouped || $placement->instance->item->acceptsStackingGroups !== []; + } $present = []; foreach ($order as $step => $index) { $present[] = $placements[$index]; @@ -235,6 +242,10 @@ public static function verifyLoadingPrefixBusinessRules(array $placements, array } } } + if ($problem === null && $grouped) { + $last = count($present) - 1; + $problem = (new LoadSupportGraph($units))->nonStackableFailure($present, $present[$last]->instance, $last); + } if ($problem === null) { $candidate = $present[count($present) - 1]; $rule = $candidate->instance->item->groundContactRule; diff --git a/src-legacy/Sequence/UnloadingDependencyGraph.php b/src-legacy/Sequence/UnloadingDependencyGraph.php index 5e77890..eafa37f 100644 --- a/src-legacy/Sequence/UnloadingDependencyGraph.php +++ b/src-legacy/Sequence/UnloadingDependencyGraph.php @@ -96,24 +96,28 @@ public static function safeRemovalOrder(array $boxes, Dimensions $container, arr $present = array_fill_keys(array_keys($boxes), true); $order = []; while ($present !== []) { - $removable = []; + $unblocked = []; foreach (array_keys($present) as $index) { $blockedBySupport = false; foreach (array_keys($dependsOn[$index] ?? []) as $dependency) { if (isset($present[$dependency])) { $blockedBySupport = true; break; } } if ($blockedBySupport) { continue; } + $unblocked[] = $index; + } + sort($unblocked); + $chosen = null; + foreach ($unblocked as $index) { if (SequenceGeometry::clearDirection($index, $boxes[$index], $boxes, $present, $container, $directions) !== null) { - $removable[] = $index; + $chosen = $index; + break; } } - if ($removable === []) { + if ($chosen === null) { throw new SequenceError(array_keys($present)); } // Deterministic: the lowest index among this step's candidates, not // arbitrary array iteration order. - sort($removable); - $chosen = $removable[0]; $order[] = $chosen; unset($present[$chosen]); } @@ -166,24 +170,28 @@ public static function safeRouteRemovalOrder(array $boxes, array $stops, Dimensi if ($stops[$index] === $stop) { $due[$index] = true; } } while ($due !== []) { - $removable = []; + $unblocked = []; foreach (array_keys($due) as $index) { $blockedBySupport = false; foreach (array_keys($dependsOn[$index] ?? []) as $dependency) { if (isset($remaining[$dependency])) { $blockedBySupport = true; break; } } if ($blockedBySupport) { continue; } + $unblocked[] = $index; + } + sort($unblocked); + $chosen = null; + foreach ($unblocked as $index) { if (SequenceGeometry::clearDirection($index, $boxes[$index], $boxes, $remaining, $container, $directions) !== null) { - $removable[] = $index; + $chosen = $index; + break; } } - if ($removable === []) { + if ($chosen === null) { throw new RouteSequenceError($stop, array_keys($due)); } // Deterministic: the lowest index among this step's candidates, not // arbitrary array iteration order. - sort($removable); - $chosen = $removable[0]; $order[] = $chosen; unset($remaining[$chosen]); unset($due[$chosen]); diff --git a/src-legacy/Serialization/ArrayCodec.php b/src-legacy/Serialization/ArrayCodec.php index 85528d3..9b5268b 100644 --- a/src-legacy/Serialization/ArrayCodec.php +++ b/src-legacy/Serialization/ArrayCodec.php @@ -5,11 +5,11 @@ use InvalidArgumentException; use Packvium\Algorithm\EffortBudget; use Packvium\Config\{PackingConfig,SolverProfile}; -use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,Item,Obstacle,Point,RateTable,Rotation,ShapeType}; +use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,Item,MadeToMeasure,Obstacle,Point,RateTable,Rotation,ShapeType}; use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; use Packvium\Policy\PolicyRuleSet; -use Packvium\Support\{FixedPlacementShape,JsonValue,RequestRules}; +use Packvium\Support\{FixedPlacementShape,JsonValue,MeasureReading,RequestRules}; use Packvium\Unit\{Length,Weight}; use Throwable; use TypeError; @@ -103,6 +103,7 @@ public static function rejectUnsupported(array $data,?array $unsupported=null,?a } } } + foreach(self::madeToMeasureCombinations($data) as $name)$found[$name]=true; foreach(self::entries($data,'items') as $entry){ if(!is_array($entry))continue; $shape=$entry['shape_type']??null; @@ -118,6 +119,36 @@ public static function rejectUnsupported(array $data,?array $unsupported=null,?a ); } + /** + * The made-to-measure combinations 1.6 refuses (D10, docs/MADE-TO-MEASURE-CONTAINERS.md). + * Each reads a container dimension or position the fabricated box does not keep. Checked on + * the raw request, before any request error. O(containers + fixed placements). + * + * @param array $data + * @return list + */ + public static function madeToMeasureCombinations(array $data):array + { + $found=[];$measured=[]; + foreach(self::entries($data,'containers') as $entry){ + if(!is_array($entry)||($entry['made_to_measure']??null)===null)continue; + if(is_string($entry['id']??null))$measured[$entry['id']]=true; + if(($entry['axles']??null)!==null)$found['container.made_to_measure+axles']=true; + $obstacles=$entry['obstacles']??null; + if(JsonValue::isList($obstacles)&&$obstacles!==[])$found['container.made_to_measure+obstacles']=true; + $reserve=$entry['void_fill_reserve_ratio']??null; + if((is_int($reserve)||is_float($reserve))&&$reserve>0)$found['container.made_to_measure+void_fill_reserve_ratio']=true; + } + $fixed=$data['fixed_placements']??null; + if($measured!==[]&&is_array($fixed)){ + foreach($fixed as $entry){ + $type=is_array($entry)?($entry['container_type']??null):null; + if(is_string($type)&&isset($measured[$type])){$found['fixed_placements+container.made_to_measure']=true;break;} + } + } + return array_keys($found); + } + /** @return array a collection to scan, or nothing when it is not one */ private static function entries(array $data,string $collection):array{$entries=$data[$collection]??[];return is_array($entries)?$entries:[];} @@ -229,7 +260,8 @@ private static function item(array $r,string $unit):Item{$rot=array_map(function },Rotation::all()));return new Item((string)$r['id'],Dimensions::fromArray($r['dimensions'],$unit),Weight::parse($r['weight']??0), (int)($r['quantity']??1),$rot,(bool)($r['keep_upright']??false),(bool)($r['stackable']??true),(bool)($r['must_be_on_floor']??false),isset($r['max_top_load'])?Weight::parse($r['max_top_load']):null,(float)($r['minimum_support_ratio']??0),$r['group']??null,$r['tags']??[],$r['incompatible_tags']??[],(int)($r['priority']??0),$r['metadata']??[],isset($r['max_stacked_items'])?(int)$r['max_stacked_items']:null,$r['eligible_container_tags']??[],$r['ground_contact_rule']??null,isset($r['nesting_height'])?Length::parse($r['nesting_height'],$unit):null,isset($r['stop_index'])?(int)$r['stop_index']:null,isset($r['value'])?(int)$r['value']:null, ShapeType::from((string)($r['shape_type']??ShapeType::RIGID_CUBOID)),self::hullVertices($r['hull_vertices']??null,$unit), isset($r['compression_ratio'])?Compression::ratioToPpm((float)$r['compression_ratio']):null, - isset($r['max_compression_pressure_kpa'])?(int)$r['max_compression_pressure_kpa']:null);} + isset($r['max_compression_pressure_kpa'])?(int)$r['max_compression_pressure_kpa']:null, + $r['stacking_group']??null,$r['accepts_stacking_groups']??[]);} /** * Parse `hull_vertices` into the integer tick frame before any geometry runs. @@ -268,6 +300,19 @@ private static function container(array $r,string $unit):Container{$obs=[];forea return (int)$v; },$r['tag_limits']??[]),isset($r['max_stack_density'])?Weight::parse($r['max_stack_density']):null,self::axles($r['axles']??null,$unit),self::rateTable($r['rate_table']??null),array_map(static function ($d) { return (string)$d; - },$r['access_directions']??[]));} + },$r['access_directions']??[]),[],isset($r['deformable_boundary'])?(string)$r['deformable_boundary']['kind']:null,self::madeToMeasure($r['made_to_measure']??null,$unit));} + /** @param array|null $r */ + private static function madeToMeasure(?array $r,string $unit):?MadeToMeasure + { + if($r===null)return null; + $sides=static function($value)use($unit):array{ + if($value===null)return [0,0,0]; + return array_map(static function (string $axis) use ($value, $unit): int { + return MeasureReading::ticks($value[$axis],Length::class,$unit); + },['length','width','height']); + }; + $tare=$r['tare_per_square_metre']??null; + return new MadeToMeasure($sides($r['minimum']??null),$sides($r['increment']??null),(int)($r['cost_per_square_metre_minor']??0),$tare===null?0:MeasureReading::ticks($tare,Weight::class,'g'),$sides($r['outer_allowance']??null)); + } private static function rateTable(?array $r):?RateTable{if($r===null)return null;return new RateTable(array_map('intval',$r['weight_brackets_g']),array_map('intval',$r['prices_minor']),(int)($r['minimum_charge_minor']??0),(int)($r['fuel_surcharge_permille']??0));} } diff --git a/src-legacy/Support/BigInt.php b/src-legacy/Support/BigInt.php index 8ab9315..6051d0f 100644 --- a/src-legacy/Support/BigInt.php +++ b/src-legacy/Support/BigInt.php @@ -11,14 +11,23 @@ */ final class BigInt { + /** Decimal digits of one limb: a limb product plus two limbs stays below PHP_INT_MAX. */ + private const LIMB_DIGITS=9; + private const LIMB=1000000000; + /** Digits of the largest value whose sum or product with another of its size is a native integer. */ + private const NATIVE_DIGITS=18; + public static function add(string $a, string $b): string { - $i = strlen($a) - 1; $j = strlen($b) - 1; $carry = 0; $out = ''; - while ($i >= 0 || $j >= 0 || $carry > 0) { - $sum = ($i >= 0 ? ord($a[$i--]) - 48 : 0) + ($j >= 0 ? ord($b[$j--]) - 48 : 0) + $carry; - $out = (string)($sum % 10) . $out; $carry = intdiv($sum, 10); + if (strlen($a) <= self::NATIVE_DIGITS && strlen($b) <= self::NATIVE_DIGITS) { return (string)((int)$a + (int)$b); } + $x = self::limbs($a); $y = self::limbs($b); $sum = []; $carry = 0; + for ($i = 0, $n = max(count($x), count($y)); $i < $n; ++$i) { + $limb = ($x[$i] ?? 0) + ($y[$i] ?? 0) + $carry; + $carry = $limb >= self::LIMB ? 1 : 0; + $sum[] = $limb - $carry * self::LIMB; } - return ltrim($out, '0') ?: '0'; + if ($carry > 0) { $sum[] = $carry; } + return self::fromLimbs($sum); } /** @@ -47,16 +56,21 @@ public static function chunks(string $value, int $groups = 6, int $width = 15): */ public static function multiply($a, $b): string { - $a = ltrim((string)$a, '0') ?: '0'; $b = ltrim((string)$b, '0') ?: '0'; - if ($a === '0' || $b === '0') { return '0'; } - $digits = array_fill(0, strlen($a) + strlen($b), 0); - for ($i = strlen($a)-1; $i >= 0; --$i) { - for ($j = strlen($b)-1; $j >= 0; --$j) { - $p = (ord($a[$i])-48) * (ord($b[$j])-48) + $digits[$i+$j+1]; - $digits[$i+$j+1] = $p % 10; $digits[$i+$j] += intdiv($p,10); + $a = (string)$a; $b = (string)$b; + if (strlen($a) + strlen($b) <= self::NATIVE_DIGITS) { return (string)((int)$a * (int)$b); } + $x = self::limbs($a); $y = self::limbs($b); + $product = array_fill(0, count($x) + count($y), 0); + foreach ($x as $i => $left) { + if ($left === 0) { continue; } + $carry = 0; + foreach ($y as $j => $right) { + $limb = $product[$i + $j] + $left * $right + $carry; + $carry = intdiv($limb, self::LIMB); + $product[$i + $j] = $limb - $carry * self::LIMB; } + $product[$i + count($y)] += $carry; } - return ltrim(implode('', $digits), '0') ?: '0'; + return self::fromLimbs($product); } /** Compare two non-negative decimal strings: -1, 0 or 1. @@ -82,13 +96,14 @@ public static function subtract($a, $b): string if (self::compare($a, $b) < 0) { throw new \InvalidArgumentException("BigInt::subtract would be negative: {$a} - {$b}"); } - $i = strlen($a) - 1; $j = strlen($b) - 1; $borrow = 0; $out = ''; - while ($i >= 0) { - $digit = (ord($a[$i--]) - 48) - $borrow - ($j >= 0 ? ord($b[$j--]) - 48 : 0); - if ($digit < 0) { $digit += 10; $borrow = 1; } else { $borrow = 0; } - $out = (string)$digit . $out; + if (strlen($a) <= self::NATIVE_DIGITS) { return (string)((int)$a - (int)$b); } + $x = self::limbs($a); $y = self::limbs($b); $difference = []; $borrow = 0; + foreach ($x as $i => $limb) { + $limb -= ($y[$i] ?? 0) + $borrow; + $borrow = $limb < 0 ? 1 : 0; + $difference[] = $limb + $borrow * self::LIMB; } - return ltrim($out, '0') ?: '0'; + return self::fromLimbs($difference); } /** @@ -103,6 +118,42 @@ public static function divide($a, $b): string $a = self::normalize($a); $b = self::normalize($b); if ($b === '0') { throw new \DivisionByZeroError('BigInt::divide by zero'); } if (self::compare($a, $b) < 0) { return '0'; } + if (strlen($a) <= self::NATIVE_DIGITS) { return (string)intdiv((int)$a, (int)$b); } + if (strlen($b) <= self::LIMB_DIGITS) { return self::divideByLimb($a, (int)$b); } + return self::divideByEstimate($a, $b); + } + + /** Short division by a divisor below one limb: each step divides a value below LIMB^2. */ + private static function divideByLimb(string $a, int $b): string + { + $quotient = []; $remainder = 0; + foreach (array_reverse(self::limbs($a)) as $limb) { + $remainder = $remainder * self::LIMB + $limb; + $quotient[] = intdiv($remainder, $b); + $remainder %= $b; + } + return self::fromLimbs(array_reverse($quotient)); + } + + /** + * A float quotient corrected until q * b <= a < (q + 1) * b, which only the floor meets. + * + * Below 2^50 the float estimate is within a few units of the floor, so the correction + * takes a step or two; a larger quotient falls back to digit-by-digit long division. + */ + private static function divideByEstimate(string $a, string $b): string + { + $estimate = floor((float)$a / (float)$b); + if (!($estimate < 2 ** 50)) { return self::longDivide($a, $b); } + $quotient = (int)$estimate; + $product = self::multiply($quotient, $b); + while (self::compare($product, $a) > 0) { --$quotient; $product = self::subtract($product, $b); } + while (self::compare($next = self::add($product, $b), $a) <= 0) { ++$quotient; $product = $next; } + return (string)$quotient; + } + + private static function longDivide(string $a, string $b): string + { $quotient = ''; $remainder = '0'; for ($i = 0, $n = strlen($a); $i < $n; ++$i) { // Schoolbook long division: shift the next digit in, then find the largest @@ -119,6 +170,27 @@ public static function divide($a, $b): string return ltrim($quotient, '0') ?: '0'; } + /** @return list The value's base-LIMB digits, least significant first. */ + private static function limbs(string $digits): array + { + $limbs = []; + for ($end = strlen($digits); $end > 0; $end -= self::LIMB_DIGITS) { + $start = $end > self::LIMB_DIGITS ? $end - self::LIMB_DIGITS : 0; + $limbs[] = (int)substr($digits, $start, $end - $start); + } + return $limbs; + } + + /** @param non-empty-list $limbs Least significant first. */ + private static function fromLimbs(array $limbs): string + { + $top = count($limbs) - 1; + while ($top > 0 && $limbs[$top] === 0) { --$top; } + $out = (string)$limbs[$top]; + for ($i = $top - 1; $i >= 0; --$i) { $out .= str_pad((string)$limbs[$i], self::LIMB_DIGITS, '0', STR_PAD_LEFT); } + return $out; + } + /** * @param string|int $value */ diff --git a/src-legacy/Support/MeasureReading.php b/src-legacy/Support/MeasureReading.php index eae6006..bc7fd50 100644 --- a/src-legacy/Support/MeasureReading.php +++ b/src-legacy/Support/MeasureReading.php @@ -45,6 +45,18 @@ public static function verdict($value, string $kind, string $unit): string return self::READABLE; } + /** + * 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`. + * + * @param mixed $value + * @param class-string|class-string $kind + */ + public static function ticks($value, string $kind, string $unit): int + { + return $kind::parse(self::normalised($value), $unit)->ticks; + } + /** @param class-string|class-string $kind */ public static function knowsUnit(string $kind, string $unit): bool { diff --git a/src-legacy/Support/PrettyJsonStream.php b/src-legacy/Support/PrettyJsonStream.php new file mode 100644 index 0000000..1af591e --- /dev/null +++ b/src-legacy/Support/PrettyJsonStream.php @@ -0,0 +1,103 @@ +stream = $stream; + } + + /** + * @param mixed $value + * @param resource $stream + * @throws \JsonException + */ + public static function write($value, $stream): void + { + $writer = new self($stream); + $writer->value($value, 0); + $writer->flush(); + } + + /** @param mixed $value */ + private function value($value, int $depth): void + { + if (!\is_array($value) || \count($value, \COUNT_RECURSIVE) <= self::WHOLE_ELEMENTS) { + $this->append(self::encoded($value, $depth)); + return; + } + $list = JsonValue::isList($value); + $separator = "\n" . \str_repeat(self::INDENT, $depth + 1); + $this->append($list ? '[' : '{'); + $first = true; + foreach ($value as $key => $member) { + $this->append(($first ? '' : ',') . $separator); + $first = false; + if (!$list) { + $this->append(\json_encode((string) $key, self::FLAGS) . ': '); + } + $this->value($member, $depth + 1); + } + $this->append("\n" . \str_repeat(self::INDENT, $depth) . ($list ? ']' : '}')); + } + + /** @param mixed $value */ + private static function encoded($value, int $depth): string + { + $json = \json_encode($value, self::FLAGS); + return $depth === 0 ? $json : \str_replace("\n", "\n" . \str_repeat(self::INDENT, $depth), $json); + } + + private function append(string $text): void + { + $this->buffer .= $text; + if (\strlen($this->buffer) >= self::FLUSH_BYTES) { + $this->flush(); + } + } + + private function flush(): void + { + if (\fwrite($this->stream, $this->buffer) !== \strlen($this->buffer)) { + throw new \RuntimeException('could not write the result to the output stream'); + } + $this->buffer = ''; + } +} diff --git a/src-legacy/Support/RequestRules.php b/src-legacy/Support/RequestRules.php index a949fca..fcb3af3 100644 --- a/src-legacy/Support/RequestRules.php +++ b/src-legacy/Support/RequestRules.php @@ -2,6 +2,8 @@ declare(strict_types=1); namespace Packvium\Support; +use Packvium\Domain\FlatBag; +use Packvium\Domain\MadeToMeasure; use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\Length; use Packvium\Unit\Weight; @@ -21,7 +23,7 @@ final class RequestRules { public const SOLVER_PROFILES = ['fast', 'balanced', 'quality', 'exact_small']; - public const OBJECTIVES = ['default', 'lowest_cost', 'shipping_cost', 'lowest_landed_cost', 'open_dimension_height', 'maximum_value']; + public const OBJECTIVES = ['default', 'lowest_cost', 'shipping_cost', 'lowest_landed_cost', 'open_dimension_height', 'maximum_value', 'maximum_volume']; public const ACCESS_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; private const CONFIGURATION_INTEGERS = [ @@ -39,6 +41,12 @@ final class RequestRules 'solver_profile', 'solvers', 'time_limit_ms', ]; private const SIDES = ['length', 'width', 'height']; + /** Container fields a flat bag refuses, in reporting order (docs/DEFORMABLE-CONTAINERS.md). */ + private const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', + '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'; /** @@ -138,6 +146,27 @@ private static function item($raw, string $where, string $unit): void self::optionalInteger($item, 'max_compression_pressure_kpa', $where, 0); self::optionalRatio($item, 'minimum_support_ratio', $where, 1); self::optionalRatio($item, 'compression_ratio', $where, null); + $stackingGroup = JsonValue::get($item, 'stacking_group'); + if ($stackingGroup !== null) { + self::stackingGroupName($stackingGroup, "{$where}/stacking_group"); + } + $accepts = JsonValue::get($item, 'accepts_stacking_groups'); + if ($accepts !== null) { + foreach (self::listAt($accepts, "{$where}/accepts_stacking_groups") as $index => $name) { + self::stackingGroupName($name, "{$where}/accepts_stacking_groups/{$index}"); + } + } + } + + /** @param mixed $value */ + private static function stackingGroupName($value, string $field): void + { + if (!\is_string($value)) { + throw self::refuse('wrong_type', $field, 'must be a string'); + } + if ($value === '') { + throw self::refuse('invalid_value', $field, 'must not be empty'); + } } /** @param mixed $raw */ @@ -173,6 +202,116 @@ private static function container($raw, string $where, string $unit): void if ($obstacles !== null) { self::obstacles($obstacles, "{$where}/obstacles", $unit); } + $boundary = JsonValue::get($container, 'deformable_boundary'); + if ($boundary !== null) { + self::deformableBoundary($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); + } + } + + /** + * @param stdClass|array $sides + * @return array{0:int,1:int,2:int} + */ + private static function sideTicks($sides, string $unit): array + { + $ticks = []; + foreach (self::SIDES as $side) { + $ticks[] = MeasureReading::ticks(JsonValue::get($sides, $side), Length::class, $unit); + } + 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. + * + * @param mixed $value + */ + private static function setBesideABag(string $name, $value): bool + { + if ($name === 'obstacles') { + return $value !== null && $value !== []; + } + if ($name === 'void_fill_reserve_ratio') { + return $value !== null && $value > 0; + } + return $value !== null; } /** @param mixed $raw */ diff --git a/src-legacy/Support/UnsupportedPlacements.php b/src-legacy/Support/UnsupportedPlacements.php new file mode 100644 index 0000000..d0cc89a --- /dev/null +++ b/src-legacy/Support/UnsupportedPlacements.php @@ -0,0 +1,39 @@ + $containers */ + public static function warning(array $containers, float $minimumSupportRatio): ?string + { + if ($minimumSupportRatio !== 0.0) { + return null; + } + $count = 0; + foreach ($containers as $container) { + foreach ($container->placements as $placement) { + if ($placement->supportRatio === 0.0 && $placement->position->z > 0) { + $count++; + } + } + } + if ($count === 0) { + return null; + } + return "unsupported_placements: {$count} placement(s) rest on nothing above the container floor; " + . 'set configuration.minimum_support_ratio above 0 to require support'; + } +} diff --git a/src-legacy/Validation/IndependentSolutionValidator.php b/src-legacy/Validation/IndependentSolutionValidator.php index 7a7dd2e..5d05742 100644 --- a/src-legacy/Validation/IndependentSolutionValidator.php +++ b/src-legacy/Validation/IndependentSolutionValidator.php @@ -3,7 +3,7 @@ namespace Packvium\Validation; use Packvium\Constraint\{AxleLoad,CompatibilityConstraint,ConstraintContext,LoadCalculator,SupportConstraint,TagCountConstraint}; use Packvium\Constraint\Internal\LoadSupportGraph; -use Packvium\Domain\{AxisAlignedBox,Nesting,PackedContainer,PackingRequest,Placement,Point,UnpackedItem}; +use Packvium\Domain\{AxisAlignedBox,FlatBag,Nesting,PackedContainer,PackingRequest,Placement,Point,UnpackedItem}; use Packvium\Sequence\{RouteSequenceError,UnloadingDependencyGraph}; use Packvium\Unit\Length; /** @@ -30,7 +30,8 @@ public function validate(PackingRequest $request,array $containers,float $minimu $item=$placement->instance->item; if($item->tags!==[]||$item->incompatibleTags!==[])$compatibilitySensitive=true; if($item->minimumSupportRatio>0||($item->groundContactRule!==null&&$item->groundContactRule!=='free'))$supportSensitive=true; - if(!$item->stackable)$stackSensitive=true; + // A stacking-group list refuses load on the same edges `stackable` does. + if(!$item->stackable||$item->acceptsStackingGroups!==[])$stackSensitive=true; } $stackGraph=$stackSensitive?new LoadSupportGraph(LoadCalculator::units($placements)):null; foreach(self::collisionPairs($placements) as [$left,$right]) @@ -88,6 +89,11 @@ public function validate(PackingRequest $request,array $containers,float $minimu ); if($axleFailure!==null)$issues[]=new ValidationIssue($axleFailure[0],$packed->id().': '.$axleFailure[1]); } + if($packed->container->isFlatBag()){ + // The girth rule over the envelopes alone; the frame is checked above. + [$a,$b,$c]=FlatBag::extentOf($packed->placements); + if(!FlatBag::girthAdmits($packed->container->innerDimensions,$a,$b,$c))$issues[]=new ValidationIssue('bag_girth_exceeded',$packed->id()); + } $onRoute=false;foreach($placements as $p)if($p->instance->item->stopIndex!==null){$onRoute=true;break;} if($onRoute){ $routeIssue=self::unloadingOrderViolation($packed); @@ -115,12 +121,38 @@ public function validate(PackingRequest $request,array $containers,float $minimu sort($unknown); foreach($unknown as $id)$issues[]=new ValidationIssue('unknown_item',$id); foreach(self::splitGroups($containers) as $detail)$issues[]=new ValidationIssue('group_split',$detail); + array_push($issues,...self::madeToMeasureIssues($request,$containers)); array_push($issues,...self::fixedPlacementIssues($request,$containers)); if($unpacked!==null) foreach(self::partialGroups($request,$containers) as $detail)$issues[]=new ValidationIssue('group_partial',$detail); return new ValidationReport($issues===[],$issues); } + /** + * Every made-to-measure box is the one its placements call for. Containment in + * the box was checked above like any container's; this re-cuts it from the declared + * machine and the achieved extent, so a trial committed with a stale or mixed-up box is + * caught. O(p) per container. + * + * @param list $containers @return list + */ + private static function madeToMeasureIssues(PackingRequest $request,array $containers):array + { + $declared=[];foreach($request->containers as $container)$declared[$container->id]=$container; + $issues=[]; + foreach($containers as $packed){ + $machine=$declared[$packed->container->id]??null; + if($machine===null||$machine->madeToMeasure===null||$packed->container->madeToMeasure===null)continue; + $expected=$machine->fabricate(FlatBag::extentOf($packed->placements)); + $box=$packed->container; + if($box->innerDimensions!=$expected->innerDimensions)$issues[]=new ValidationIssue('fabricated_dimensions_mismatch',$packed->id()); + if($box->outerDimensions!=$expected->outerDimensions)$issues[]=new ValidationIssue('outer_dimensions_mismatch',$packed->id()); + if($box->costMinor!==$expected->costMinor)$issues[]=new ValidationIssue('made_to_measure_cost_mismatch',$packed->id()); + if($box->tareWeight->ticks!==$expected->tareWeight->ticks)$issues[]=new ValidationIssue('made_to_measure_tare_mismatch',$packed->id()); + } + return $issues; + } + /** * @param list $placements @return list * diff --git a/src/Algorithm/BeamPacker.php b/src/Algorithm/BeamPacker.php index c4df07b..7982a98 100644 --- a/src/Algorithm/BeamPacker.php +++ b/src/Algorithm/BeamPacker.php @@ -3,7 +3,7 @@ namespace Packvium\Algorithm; use Packvium\Config\PackingConfig; use Packvium\Constraint\PlacementConstraint; -use Packvium\Domain\{Container,ItemInstance,Placement}; +use Packvium\Domain\{Container,ItemInstance,Nesting,Placement}; use Packvium\Extension\CandidateScorer; use Packvium\Support\{BigInt,StableSorter}; final class BeamPacker @@ -21,6 +21,7 @@ public static function pack(Container $container,int $sequence,array $items,Pack $branchWidth=max(1,$config->maxCandidatesPerItem); $width=max(1,$config->containerPlanBeamWidth); if($width===1)return self::packLegacy($container,$sequence,$items,$config,$constraints,$stats,$deadline,$scorer,$branchWidth); + $byVolume=self::ranksByVolume($config); $nodeLimit=$width>1?$config->containerPlanNodeLimit:null; $nodes=0; $batches=GroupBatcher::batches($items); @@ -36,7 +37,7 @@ public static function pack(Container $container,int $sequence,array $items,Pack // nodeKey builds an O(m) placement signature and BigInt chunks; computing it once // per node instead of once per usort comparison (and once per incumbent test) // changes no ordering: usort is stable and the keys are identical values. - $incumbentKey=self::nodeKey($incumbent); + $incumbentKey=self::nodeKey($incumbent,$byVolume); foreach($batches as $position=>$batch){ $expansions=[];$exhausted=false; foreach($beam as [$state,$unplaced]){ @@ -52,27 +53,25 @@ public static function pack(Container $container,int $sequence,array $items,Pack $futureCount=count($future); foreach($expansions as [$state,$unplaced]){ $unplacedCount=count($unplaced)+$futureCount; - // More unplaced items loses on the key's first component; skip building a signature that cannot win. - if($unplacedCount>$incumbentKey[0])continue; - $used=$state->usedVolume;$signature=[]; - foreach($state->placements as $p){ - $signature[]=$p->instance->id().'@'.$p->envelopeOrigin->x.','.$p->envelopeOrigin->y.','.$p->envelopeOrigin->z; - } - $descendingUsed=array_map(static fn(int $c):int=>-$c,\Packvium\Support\BigInt::chunks($used)); - $candidateKey=array_merge([$unplacedCount,$unplacedCount,-count($state->placements),$state->maxZ],$descendingUsed,[implode('|',$signature)]); + $descendingUsed=self::descending($state->usedVolume); + // A worse leading component loses whatever follows; skip building a signature that cannot win. + if($byVolume?$descendingUsed>array_slice($incumbentKey,0,count($descendingUsed)):$unplacedCount>$incumbentKey[0])continue; + $candidateKey=$byVolume + ?array_merge($descendingUsed,$descendingUsed,[$unplacedCount,$state->maxZ,$state->placementSignature()]) + :array_merge([$unplacedCount,$unplacedCount,-count($state->placements),$state->maxZ],$descendingUsed,[$state->placementSignature()]); if($candidateKey<$incumbentKey){$incumbent=[$state,array_merge($unplaced,$future)];$incumbentKey=$candidateKey;} } if($expansions===[])break; $futureInfo=self::precomputeFuture($future,$container->maxPayload?->ticks); - $beam=array_slice(StableSorter::sortBy($expansions,static fn(array $node):array=>self::nodeKeyPrecomputed($node,$futureInfo)),0,$width); + $beam=array_slice(StableSorter::sortBy($expansions,static fn(array $node):array=>self::nodeKeyPrecomputed($node,$futureInfo,$byVolume)),0,$width); if($exhausted){ [$state,$unplaced]=$incumbent; return new SingleContainerSolution($state,$unplaced,false,$deadline->expired()); } } - $ordered=StableSorter::sortBy($beam,static fn(array $node):array=>self::nodeKey($node)); + $ordered=StableSorter::sortBy($beam,static fn(array $node):array=>self::nodeKey($node,$byVolume)); $completed=$ordered[0]??null; - [$state,$unplaced]=$completed!==null&&self::nodeKey($completed)<$incumbentKey?$completed:$incumbent; + [$state,$unplaced]=$completed!==null&&self::nodeKey($completed,$byVolume)<$incumbentKey?$completed:$incumbent; return new SingleContainerSolution($state,$unplaced); } @@ -86,6 +85,7 @@ public static function pack(Container $container,int $sequence,array $items,Pack private static function packLegacy(Container $container,int $sequence,array $items,PackingConfig $config,array $constraints,SearchStats $stats,Deadline $deadline,CandidateScorer $scorer,int $width):SingleContainerSolution { $batches=GroupBatcher::batches($items); + $byVolume=self::ranksByVolume($config); $beam=[[new ContainerState($container,$sequence),[]]]; foreach($batches as $position=>$batch){ $expansions=[];$exhausted=false; @@ -96,7 +96,7 @@ private static function packLegacy(Container $container,int $sequence,array $ite if($children!==[]){foreach($children as $child)$expansions[]=[$child,$unplaced];} else $expansions[]=[$state,array_merge($unplaced,$batch)]; } - $beam=array_slice(StableSorter::sortBy($expansions,static fn(array $node):array=>self::nodeKey($node)),0,$width); + $beam=array_slice(StableSorter::sortBy($expansions,static fn(array $node):array=>self::nodeKey($node,$byVolume)),0,$width); if($exhausted){ [$state,$unplaced]=$beam[0]; $pending=GroupBatcher::flatten(array_slice($batches,$position+1)); @@ -181,7 +181,9 @@ private static function precomputeFuture(array $future,?int $maxPayloadTicks):ar } $volumes=null; if(!$hasNesting){ - $volumes=array_map(static fn(ItemInstance $item):string=>$item->dimensions()->volumeString(),$future); + // Occupied, not declared: the free space these are compared with is occupied + // volume, and two wedges each declaring the whole crate both fit in it. + $volumes=array_map(static fn(ItemInstance $item):string=>Nesting::itemOccupiedVolume($item),$future); usort($volumes,static fn(string $a,string $b):int=>BigInt::compare($a,$b)); $used='0'; foreach($volumes as $index=>$volume)$volumes[$index]=$used=BigInt::add($used,$volume); @@ -218,26 +220,47 @@ private static function unpackedLowerBoundPrecomputed(ContainerState $state,int return $unplacedCount+$futureCount-$possible; } - private static function nodeKeyPrecomputed(array $node,array $futureInfo):array + private static function ranksByVolume(PackingConfig $config):bool + { + return $config->objective==='maximum_volume'; + } + + /** @return list Chunks negated, so ascending array order means the larger value first. */ + private static function descending(string $value):array + { + return array_map(static fn(int $c):int=>-$c,BigInt::chunks($value)); + } + + /** + * An upper bound on the volume this node can still end with: what is placed, plus the + * future items' total volume capped by the free space. For nesting, nominal volumes + * are not additive, so the free space alone is the bound. + */ + private static function reachableVolume(ContainerState $state,array $futureInfo):string + { + if($futureInfo['count']===0)return $state->usedVolume; + $free=BigInt::subtract($state->container->innerDimensions->volumeString(),$state->usedVolume); + $volumes=$futureInfo['volumes']; + $future=$volumes===null?$free:$volumes[count($volumes)-1]; + return BigInt::add($state->usedVolume,BigInt::compare($future,$free)<0?$future:$free); + } + + private static function signature(ContainerState $state):string + { + return $state->placementSignature(); + } + + private static function nodeKeyPrecomputed(array $node,array $futureInfo,bool $byVolume=false):array { [$state,$unplaced]=$node; - $used=$state->usedVolume;$signature=[]; - foreach($state->placements as $p){ - $signature[]=$p->instance->id().'@'.$p->envelopeOrigin->x.','.$p->envelopeOrigin->y.','.$p->envelopeOrigin->z; - } - $descendingUsed=array_map(static fn(int $c):int=>-$c,\Packvium\Support\BigInt::chunks($used)); - return array_merge([self::unpackedLowerBoundPrecomputed($state,count($unplaced),$futureInfo),count($unplaced),-count($state->placements),$state->maxZ],$descendingUsed,[implode('|',$signature)]); + $descendingUsed=self::descending($state->usedVolume); + if($byVolume)return array_merge(self::descending(self::reachableVolume($state,$futureInfo)),$descendingUsed,[count($unplaced),$state->maxZ,self::signature($state)]); + return array_merge([self::unpackedLowerBoundPrecomputed($state,count($unplaced),$futureInfo),count($unplaced),-count($state->placements),$state->maxZ],$descendingUsed,[self::signature($state)]); } /** @param array{0:ContainerState,1:list} $node */ - private static function nodeKey(array $node):array + private static function nodeKey(array $node,bool $byVolume=false):array { - [$state,$unplaced]=$node; - $used=$state->usedVolume;$signature=[]; - foreach($state->placements as $p){ - $signature[]=$p->instance->id().'@'.$p->envelopeOrigin->x.','.$p->envelopeOrigin->y.','.$p->envelopeOrigin->z; - } - $descendingUsed=array_map(static fn(int $c):int=>-$c,\Packvium\Support\BigInt::chunks($used)); - return array_merge([count($unplaced),count($unplaced),-count($state->placements),$state->maxZ],$descendingUsed,[implode('|',$signature)]); + return self::nodeKeyPrecomputed($node,['count'=>0,'volumes'=>null,'weights'=>null],$byVolume); } } diff --git a/src/Algorithm/CandidateFinder.php b/src/Algorithm/CandidateFinder.php index 9e0f82f..082e3f8 100644 --- a/src/Algorithm/CandidateFinder.php +++ b/src/Algorithm/CandidateFinder.php @@ -32,6 +32,10 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf } $inner=$container->innerDimensions; $limitX=$inner->length->ticks;$limitY=$inner->width->ticks;$limitZ=$inner->height->ticks; + // A flat bag also needs a + c <= L and b + c <= W over the running extents grown by + // the candidate: O(1), and the extents only grow, so no verdict flips. + $bag=$container->isFlatBag(); + $bagX=$state->maxX;$bagY=$state->maxY;$bagZ=$state->maxZ; $clearance=$config->clearance->ticks; // Envelope and extents depend only on the rotation, so they are built once // instead of once per (point, rotation) pair. @@ -90,6 +94,11 @@ public static function find(ContainerState $state,ItemInstance $item,PackingConf $stats->placementsAttempted++; $x2=$x1+$dx;$y2=$y1+$dy;$z2=$z1+$dz; if($x2>$limitX||$y2>$limitY||$z2>$limitZ)continue; + if($bag){ + // Ternaries rather than max(): the call made this test dearer (44 ns against 74 ns). + $thickness=$z2>$bagZ?$z2:$bagZ; + if(($x2>$bagX?$x2:$bagX)+$thickness>$limitX||($y2>$bagY?$y2:$bagY)+$thickness>$limitY)continue; + } $tentative=null; if($nesting){ $position=new Point($x1+$clearance,$y1+$clearance,$z1+$clearance); diff --git a/src/Algorithm/ContainerState.php b/src/Algorithm/ContainerState.php index f00549b..a30ef62 100644 --- a/src/Algorithm/ContainerState.php +++ b/src/Algorithm/ContainerState.php @@ -2,7 +2,8 @@ declare(strict_types=1); namespace Packvium\Algorithm; use Packvium\Constraint\VolumeReserve; -use Packvium\Domain\{AxisAlignedBox,Container,ItemInstance,LatticeSummary,Nesting,Placement,Point,ShapeType}; +use Packvium\Config\PackingConfig; +use Packvium\Domain\{AxisAlignedBox,Container,FlatBag,ItemInstance,LatticeSummary,Nesting,Placement,Point,ShapeType}; use Packvium\Support\BigInt; /** * Placed boxes plus the candidate points they expose. @@ -39,7 +40,12 @@ final class ContainerState public bool $stackSensitive=false; public bool $routeSensitive=false; public bool $compressionSensitive=false; + /** Largest envelope x2 and y2 so far; with `$maxZ`, a flat bag's running extents. */ + public int $maxX=0; + public int $maxY=0; public int $maxZ=0; + /** Null means a direct lattice/block placement invalidated the lazy beam key. */ + private ?string $placementSignature=''; public SpatialIndex $index; /** * Set instead of appending to `$placements` when GridSolver's quantity- @@ -49,7 +55,11 @@ final class ContainerState /** @var list */ public array $latticeItems=[]; private ?string $usableVolumeTicks=null; - public function __construct(public readonly Container $container,public readonly int $sequence) + /** + * `$container` is not readonly only so a made-to-measure trial can be committed as the box + * cut for it (`withContainer`); nothing else reassigns it. + */ + public function __construct(public Container $container,public readonly int $sequence) { $d=$container->innerDimensions; $this->index=new SpatialIndex($d->length->ticks,$d->width->ticks,$d->height->ticks); @@ -72,6 +82,32 @@ public function __construct(public readonly Container $container,public readonly /** Clone rather than reconstruct: the constructor's point seeding would be discarded. */ public function copy():self{return clone $this;} + public function placementSignature():string + { + if($this->placementSignature!==null)return $this->placementSignature; + $parts=[]; + foreach($this->placements as $placement)$parts[]=self::signatureElement($placement); + return $this->placementSignature=implode('|',$parts); + } + + private static function signatureElement(Placement $placement):string + { + return $placement->instance->id().'@'.$placement->envelopeOrigin->x.','.$placement->envelopeOrigin->y.','.$placement->envelopeOrigin->z; + } + + /** + * This state as a trial of another container of the same contents: a made-to-measure rung + * committed as the box cut for it. Only read after the trial ends, so the + * candidate points and index sized for the rung are never searched again. + */ + public function withContainer(Container $container):self + { + $copy=clone $this; + $copy->container=$container; + $copy->usableVolumeTicks=null; + return $copy; + } + /** * PHP arrays are value types, so `clone` already deep-copies `$bounds`/`$occupied`/ * `$points` correctly; `$index` is an object, which `clone` only shallow-copies by @@ -97,14 +133,18 @@ public function add(Placement $placement):void else $this->usedVolume=BigInt::add($this->usedVolume,Nesting::usedVolumeDelta($this->placements,$placement)); $this->placements[]=$placement; + if($this->placementSignature!==null){ + $elem=self::signatureElement($placement); + $this->placementSignature=$this->placementSignature==='' ? $elem : $this->placementSignature.'|'.$elem; + } $this->payloadTicks+=$placement->instance->weight()->ticks; $item=$placement->instance->item; $this->stackSensitive=$this->stackSensitive||$item->isStackSensitive(); $this->routeSensitive=$this->routeSensitive||$item->stopIndex!==null; $this->compressionSensitive=$compressionSensitive; - if($box->z2()>$this->maxZ)$this->maxZ=$box->z2(); $this->occupied[]=$box; $bound=$box->extent(); + $this->extendExtent($bound[3],$bound[4],$bound[5]); $this->index->add(count($this->bounds),$bound); $this->bounds[]=$bound; $shape=$placement->hullShape(); @@ -144,11 +184,42 @@ public function addDirect(Placement $placement):void // could drift from `add`, so the direct lattice path remains the proven O(1) delta. $this->usedVolume=BigInt::add($this->usedVolume,Nesting::usedVolumeDelta($this->placements,$placement)); $this->placements[]=$placement; + $this->placementSignature=null; $this->payloadTicks+=$placement->instance->weight()->ticks; $item=$placement->instance->item; $this->stackSensitive=$this->stackSensitive||$item->isStackSensitive(); $this->routeSensitive=$this->routeSensitive||$item->stopIndex!==null; - if($box->z2()>$this->maxZ)$this->maxZ=$box->z2(); + $this->extendExtent($box->x2(),$box->y2(),$box->z2()); + } + + private function extendExtent(int $x2,int $y2,int $z2):void + { + if($x2>$this->maxX)$this->maxX=$x2; + if($y2>$this->maxY)$this->maxY=$y2; + if($z2>$this->maxZ)$this->maxZ=$z2; + } + + /** + * The dimensional weight, in weight ticks, a carrier bills for this container as filled. + * + * A flat bag is billed on its running extents, the parcel a carrier measures; an empty bag + * has no parcel yet and bills nothing by volume. A rigid container is billed on its declared + * outer size, else its inner size. O(1). + */ + public function billedDimensionalWeight(PackingConfig $config):int + { + $container=$this->container; + if($container->isFlatBag()){ + if($this->placements===[])return 0; + $dimensions=FlatBag::asDimensions([$this->maxX,$this->maxY,$this->maxZ]); + }else{ + $dimensions=$container->outerDimensions??$container->innerDimensions; + } + return $dimensions->dimensionalWeight( + (int)$config->dimensionalWeightDivisor, + $config->dimensionalWeightLengthUnit, + $config->dimensionalWeightWeightUnit, + )->ticks; } public function placementCount():int diff --git a/src/Algorithm/Deadline.php b/src/Algorithm/Deadline.php index dfb3011..1b5ca75 100644 --- a/src/Algorithm/Deadline.php +++ b/src/Algorithm/Deadline.php @@ -67,6 +67,18 @@ public static function until(int $absoluteNs):self public function elapsedMs():int{return intdiv(($this->clock)()-$this->started,1_000_000);} public function remainingNs():int{return $this->limitNs-(($this->clock)()-$this->started);} public function effortExceeded():bool{return $this->effortBudget!==null && $this->stats!==null && $this->effortBudget->exceeded($this->stats);} + /** + * How many more search nodes counted into `$counted` may expand before `effortExceeded()` + * trips, while nothing else that budget counts moves: zero once it has tripped, and + * `PHP_INT_MAX` when no node budget reads `$counted`. A solver that counts a run of nodes + * in one step stops on the same node as one that checks before each. + */ + public function searchNodesLeft(SearchStats $counted):int + { + if($this->effortExceeded())return 0; + if($this->effortBudget===null||$this->effortBudget->maxSearchNodes===null||$this->stats!==$counted)return PHP_INT_MAX; + return $this->effortBudget->maxSearchNodes-$counted->searchNodesExpanded; + } public function expired():bool{return $this->effortExceeded() || $this->remainingNs()<=0;} public function slice(int $parts):self diff --git a/src/Algorithm/EffortBudget.php b/src/Algorithm/EffortBudget.php index 42d3156..36a693e 100644 --- a/src/Algorithm/EffortBudget.php +++ b/src/Algorithm/EffortBudget.php @@ -39,3 +39,9 @@ public function exceeded(SearchStats $stats):bool || ($this->maxSearchNodes!==null && $stats->searchNodesExpanded>=$this->maxSearchNodes); } } + +// The public name of this class is `Packvium\Config\EffortBudget`: one class under +// two names, so an instance from either spelling satisfies a type declared with the other. +// Registered here, beside the declaration, because PHP does not autoload for a type check: +// a budget decoded by `ArrayCodec` must already answer to the public name. +\class_alias(EffortBudget::class, \Packvium\Config\EffortBudget::class); diff --git a/src/Algorithm/ExactSmallSolver.php b/src/Algorithm/ExactSmallSolver.php index 19b7cc7..439bbab 100644 --- a/src/Algorithm/ExactSmallSolver.php +++ b/src/Algorithm/ExactSmallSolver.php @@ -57,13 +57,7 @@ public static function isBetterState(ContainerState $candidate,ContainerState $i private static function landedCharge(ContainerState $state,PackingConfig $config):int { $container=$state->container; - $dimensions=$container->outerDimensions??$container->innerDimensions; - $dimensional=$dimensions->dimensionalWeight( - $config->dimensionalWeightDivisor, - $config->dimensionalWeightLengthUnit, - $config->dimensionalWeightWeightUnit, - )->ticks; - $billed=max($container->tareWeight->ticks+$state->payloadTicks,$dimensional); + $billed=max($container->tareWeight->ticks+$state->payloadTicks,$state->billedDimensionalWeight($config)); return $container->rateTable?->chargeMinorOrNull( LandedCostSolutionScorer::grams($billed), )??LandedCostSolutionScorer::UNPRICEABLE_MINOR; @@ -76,6 +70,11 @@ private static function isBetterForObjective( ):bool { $candidateCount=count($candidate->placements); $incumbentCount=count($incumbent->placements); + if(self::ranksByVolume($config)){ + // `maximum_volume` fills volume before it counts pieces. + $byVolume=BigInt::compare($candidateVolume,$incumbentVolume); + return $byVolume!==0?$byVolume>0:$candidateCount>$incumbentCount; + } if($candidateCount!==$incumbentCount)return $candidateCount>$incumbentCount; if($config->objective==='lowest_landed_cost'){ $candidateCharge=self::landedCharge($candidate,$config); @@ -85,6 +84,11 @@ private static function isBetterForObjective( return BigInt::compare($candidateVolume,$incumbentVolume)>0; } + private static function ranksByVolume(PackingConfig $config):bool + { + return $config->objective==='maximum_volume'; + } + public function packOne(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):SingleContainerSolution { if(count($items)>$config->exactItemLimit)throw new InvalidArgumentException('Exact-small item limit exceeded'); @@ -116,8 +120,13 @@ public function packOne(Container $container,int $sequence,array $items,PackingC if($index>=count($batches))return; $potentialCount=$stateCount+$reachable; $bestCount=count($best->placements); - if($potentialCount<$bestCount)return; - if($config->objective!=='lowest_landed_cost'&&$potentialCount===$bestCount&&BigInt::compare(BigInt::add($stateVolume,$suffixVolumes[$index]),$bestVolume)<=0)return; + if(self::ranksByVolume($config)){ + // Fewer pieces can still be more volume, so only the volume bound cuts; + // an equal bound wins only on a strictly larger count. + $bound=BigInt::compare(BigInt::add($stateVolume,$suffixVolumes[$index]),$bestVolume); + if($bound<0||($bound===0&&$potentialCount<=$bestCount))return; + }elseif($potentialCount<$bestCount)return; + elseif($config->objective!=='lowest_landed_cost'&&$potentialCount===$bestCount&&BigInt::compare(BigInt::add($stateVolume,$suffixVolumes[$index]),$bestVolume)<=0)return; $batch=$batches[$index]; $remaining=$reachable-count($batch); foreach(BeamPacker::placeBatch($state,$batch,$config,$constraints,$stats,$deadline,$scorer,null) as $child){ diff --git a/src/Algorithm/GridSolver.php b/src/Algorithm/GridSolver.php index a515934..9ab6612 100644 --- a/src/Algorithm/GridSolver.php +++ b/src/Algorithm/GridSolver.php @@ -31,6 +31,7 @@ private static function latticeProfile(\Packvium\Domain\Item $item):string $tags=$item->tags;sort($tags); $incompatibleTags=$item->incompatibleTags;sort($incompatibleTags); $eligibleContainerTags=$item->eligibleContainerTags;sort($eligibleContainerTags); + $acceptsStackingGroups=$item->acceptsStackingGroups;sort($acceptsStackingGroups,SORT_STRING); return json_encode([ $footprints,$item->weight->ticks,$item->stackable,$item->mustBeOnFloor, $item->maxTopLoad?->ticks,$tags,$incompatibleTags,$eligibleContainerTags, @@ -45,6 +46,9 @@ private static function latticeProfile(\Packvium\Domain\Item $item):string // with an unlimited item, or stop 0 with stop 1, produces a tiling neither // one allows. $item->maxStackedItems,$item->stopIndex, + // A lattice joins same-type items only, so two types may share one exactly when + // they share the stacking rule as well. + $item->stackingGroup,$acceptsStackingGroups, ]); } @@ -76,6 +80,10 @@ public function packOne(Container $container,int $sequence,array $items,PackingC return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); if($container->voidFillReserveRatio>0) return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); + if($container->isFlatBag()) + // The lattice counts cells against the rigid frame alone; a bag's girth rule + // couples the axes, which the per-candidate check applies exactly. + return (new ExtremePointSolver())->packOne($container,$sequence,$items,$config,$stats,$deadline); if($container->maxStackDensity!==null) // The single-layer heuristic below only ever reasons about one item // resting on one other, never the cumulative load a tall column presses @@ -98,7 +106,9 @@ public function packOne(Container $container,int $sequence,array $items,PackingC // Every non-floor lattice cell has one full-area direct supporter, including // an exact nesting predecessor. That satisfies ratio=1, covered and single; // multiple is satisfiable only on the floor, so cap instead of delegating. - $singleLayer=$prototype->mustBeOnFloor||!$prototype->stackable||$prototype->groundContactRule==='multiple'; + // Every lattice edge joins two items of this type, so the stacking-group rule holds + // for the whole lattice exactly when the type carries itself. + $singleLayer=$prototype->mustBeOnFloor||!$prototype->carriesItself()||$prototype->groundContactRule==='multiple'; // How much less than the full height each layer above the first consumes: // zero (the ordinary lattice) unless the item declares it sinks into an // identical one beneath it. Reduces to the original nz/z formulas diff --git a/src/Algorithm/HomogeneousBlockSolver.php b/src/Algorithm/HomogeneousBlockSolver.php index 8b9ee35..03bcfb7 100644 --- a/src/Algorithm/HomogeneousBlockSolver.php +++ b/src/Algorithm/HomogeneousBlockSolver.php @@ -16,12 +16,27 @@ * Candidate enumeration is O(B*S*T*R*X*Y) time and O(S+n) space. B is committed * blocks, S the capped maximal-space count, T declared item types, R unique * rotations, and X/Y the block grid extents. Both Deadline and - * containerPlanNodeLimit bound the product explicitly. + * containerPlanNodeLimit bound the product explicitly. The X*Y lattice nodes of a + * group are counted in O(X), and only a group that can still lead walks its nodes, + * so the X*Y factor is the worst case, not the usual one. */ final class HomogeneousBlockSolver implements SingleContainerSolver { - /** @param list $constraints */ - public function __construct(private array $constraints=[],?CandidateScorer $scorer=null){} + public const MODES=['count','volume']; + /** Far above the 4-ulp error of a float product of three lengths and a count. */ + private const FLOAT_MARGIN=1e-12; + /** Lattice nodes between two clock reads are a power of two: 1 << CLOCK_SHIFT. */ + private const CLOCK_SHIFT=6; + private const CLOCK_STRIDE=(1< $constraints + * @param list $modes + */ + public function __construct(private array $constraints=[],?CandidateScorer $scorer=null,public readonly array $modes=self::MODES,public readonly ?int $nodeLimit=null){} public function name():string{return 'homogeneous_blocks';} public function orderInsensitive():bool{return true;} @@ -30,26 +45,31 @@ public function packOne(Container $container,int $sequence,array $items,PackingC { if(!$this->supports($container,$items,$config)) return (new ExtremePointSolver($this->constraints))->packOne($container,$sequence,$items,$config,$stats,$deadline); + $nodeLimit=$this->nodeLimit??$config->containerPlanNodeLimit; $best=null;$reached=false; - foreach(['count','volume'] as $mode){ + foreach($this->modes as $mode){ if($deadline->expired()){$reached=true;break;} - $solution=$this->packMode($container,$sequence,$items,$config,$stats,$deadline,$mode); + $solution=$this->packMode($container,$sequence,$items,$config,$stats,$deadline,$mode,$nodeLimit); $reached=$reached||$solution->timeLimitReached; - if($best===null||$this->solutionKey($solution)<$this->solutionKey($best))$best=$solution; + $byVolume=$config->objective==='maximum_volume'; + if($best===null||$this->solutionKey($solution,$byVolume)<$this->solutionKey($best,$byVolume))$best=$solution; } if($best===null)return new SingleContainerSolution(new ContainerState($container,$sequence),$items,false,$reached); return new SingleContainerSolution($best->state,$best->unpacked,false,$reached); } - private function supports(Container $container,array $items,PackingConfig $config):bool + public function supports(Container $container,array $items,PackingConfig $config):bool { // A block set on a smaller one overhangs it, so a request that asks for support // is left to the per-item search. if($config->minimumSupportRatio>0)return false; - if($this->constraints!==[]||$container->obstacles!==[]||$container->preloaded!==[]||$container->axles!==null||$container->tagLimits!==[]||$container->maxStackDensity!==null||$container->voidFillReserveRatio>0)return false; + if($this->constraints!==[]||$container->obstacles!==[]||$container->preloaded!==[]||$container->axles!==null||$container->tagLimits!==[]||$container->maxStackDensity!==null||$container->voidFillReserveRatio>0||$container->isFlatBag())return false; foreach($items as $instance){ $item=$instance->item; if($item->shapeType!==ShapeType::RIGID_CUBOID||$item->group!==null||$item->tags!==[]||$item->incompatibleTags!==[]||$item->eligibleContainerTags!==[]||!$item->stackable||$item->mustBeOnFloor||$item->maxTopLoad!==null||$item->maxStackedItems!==null||$item->minimumSupportRatio!=0.0||!in_array($item->groundContactRule,[null,'free'],true)||$item->nestingHeight!==null||$item->stopIndex!==null)return false; + // Block-on-block contacts would need a second implementation of the stacking-group + // rule; the general solver already walks every edge. + if($item->acceptsStackingGroups!==[])return false; } return true; } @@ -62,56 +82,228 @@ private static function memberSupport(ContainerState $state,ItemInstance $instan return $support->supportingArea/$envelope->baseAreaTicks(); } - private function solutionKey(SingleContainerSolution $solution):array + private function solutionKey(SingleContainerSolution $solution,bool $byVolume=false):array { $signature=[]; foreach($solution->state->placements as $placement)$signature[]=$placement->instance->id().'@'.$placement->envelopeOrigin->x.','.$placement->envelopeOrigin->y.','.$placement->envelopeOrigin->z; - return [count($solution->unpacked),...array_map(static fn(int $chunk):int=>-$chunk,BigInt::chunks($solution->state->usedVolume)),$solution->state->maxZ,implode('|',$signature)]; + $descendingUsed=array_map(static fn(int $chunk):int=>-$chunk,BigInt::chunks($solution->state->usedVolume)); + if($byVolume)return [...$descendingUsed,count($solution->unpacked),$solution->state->maxZ,implode('|',$signature)]; + return [count($solution->unpacked),...$descendingUsed,$solution->state->maxZ,implode('|',$signature)]; + } + + /** + * The distinct rotations of one item type with what every lattice of them shares. + * + * @return list + */ + private static function lattices(ItemInstance $prototype,PackingConfig $config):array + { + $lattices=[]; + foreach($prototype->dimensions()->uniqueRotations($prototype->item->allowedRotations) as [$rotation,$physical]){ + $envelope=$config->clearance->ticks?$physical->expand($config->clearance):$physical; + $lattices[]=['rotation'=>$rotation,'rotationName'=>$rotation->value,'physical'=>$physical,'envelope'=>$envelope,'extents'=>[$envelope->length->ticks,$envelope->width->ticks,$envelope->height->ticks],'volume'=>$physical->volumeString(),'approximateVolume'=>$physical->volumeScore()]; + } + return $lattices; + } + + /** + * Whether a block ranks strictly before the incumbent under the exact key. + * + * The key is the lead -- count, fill of its space in parts per million, then exact used + * volume under `count`; volume, fill, then count otherwise -- and then the anchor, + * type, rotation and extents. Fields are compared one at a time, each with `<=>` as + * the whole-array comparison would, so a decimal-string volume is only built when the + * float volumes cannot separate the pair. + * + * @param array $candidate + * @param array $best + */ + private static function leads(array $candidate,array $best,string $mode):bool + { + if($mode==='count'){ + if($candidate['count']!==$best['count'])return $candidate['count']>$best['count']; + $order=(self::fillPpm($best)<=>self::fillPpm($candidate))?:self::volumeOrder($candidate,$best); + }else{ + $order=self::volumeOrder($candidate,$best)?:(self::fillPpm($best)<=>self::fillPpm($candidate))?:($best['count']<=>$candidate['count']); + } + if($order===0){ + $mine=$candidate['space']->origin;$theirs=$best['space']->origin; + $order=($mine->z<=>$theirs->z)?:($mine->y<=>$theirs->y)?:($mine->x<=>$theirs->x) + ?:($candidate['itemId']<=>$best['itemId'])?:($candidate['rotationName']<=>$best['rotationName']) + ?:($candidate['nx']<=>$best['nx'])?:($candidate['ny']<=>$best['ny'])?:($candidate['nz']<=>$best['nz']); + } + return $order<0; + } + + /** + * -1 when the candidate uses strictly more volume, the order of the descending volume key. + * + * A float volume carries a relative error below 4e-16, so one apart by the margin is + * apart exactly; only a closer pair builds both decimal-string volumes. + * + * @param array $candidate + * @param array $best + */ + private static function volumeOrder(array $candidate,array $best):int + { + if($candidate['approximateUsed']>$best['approximateUsed']*(1+self::FLOAT_MARGIN))return -1; + if($candidate['approximateUsed']<$best['approximateUsed']*(1-self::FLOAT_MARGIN))return 1; + return BigInt::compare(BigInt::multiply($best['count'],$best['volume']),BigInt::multiply($candidate['count'],$candidate['volume'])); + } + + /** + * floor(used * 1e6 / space volume), the block's fill of its space in parts per million. + * + * The float quotient is at most 1e6 and carries a relative error near 1e-15, so its + * floor is exact unless it lies within 1e-6 of an integer; only then is the + * decimal-string long division run. + * + * @param array $block + */ + private static function fillPpm(array $block):int + { + $space=$block['space']->dimensions; + $quotient=$block['approximateUsed']*1_000_000/$space->volumeScore(); + $floor=floor($quotient); + if($quotient-$floor>self::FLOAT_MARGIN*1_000_000&&$floor+1-$quotient>self::FLOAT_MARGIN*1_000_000)return (int)$floor; + return (int)BigInt::divide(BigInt::multiply(BigInt::multiply($block['count'],$block['volume']),1_000_000),$space->volumeString()); + } + + /** + * The lattice nodes of one group: sum over nx <= min(X, c) of min(Y, floor(c / nx)). + * + * Every row up to floor(c / Y) is Y nodes wide, so only the rows past it are summed: + * O(min(X, c)) against the group's O(X * Y) nodes. + */ + private static function latticeNodes(int $maximumX,int $maximumY,int $capacity):int + { + $maximumNx=min($maximumX,$capacity); + $fullRows=min($maximumNx,intdiv($capacity,$maximumY)); + $nodes=$fullRows*$maximumY; + for($nx=$fullRows+1;$nx<=$maximumNx;$nx++)$nodes+=intdiv($capacity,$nx); + return $nodes; + } + + /** + * How many of a group's nodes expand before a stop, the count the per-node loop reached. + * + * `$stopAt` is the node a counted limit trips at. The clock is read once, on the first + * node of the group at a 64-node stride, and a stop there lands on that node: only where + * a wall-clock stop lands can move, never a counted one. + */ + private static function expandable(int $nodes,int $groupNodes,int $stopAt,Deadline $deadline):int + { + $expandable=min($groupNodes,$stopAt-$nodes); + $clockRead=($nodes+self::CLOCK_STRIDE)&~self::CLOCK_STRIDE; + if($clockRead<$nodes+$expandable&&$deadline->expired())return $clockRead-$nodes; + return $expandable; } - private function packMode(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode):SingleContainerSolution + /** + * The group's first largest block in (nx, ny) order, as [count, nx, ny, nz]. + * + * For a capacity below the whole lattice: no node exceeds the capacity, so the first one + * to reach it ends the walk. (With room for the whole lattice, the whole lattice is the + * only node of its count.) + * + * @return array{int,int,int,int} + */ + private static function largestBlock(int $maximumX,int $maximumY,int $maximumZ,int $capacity):array + { + $count=0;$bestNx=0;$bestNy=0;$bestNz=0; + $maximumNx=$maximumX<$capacity?$maximumX:$capacity; + for($nx=1;$nx<=$maximumNx;$nx++){ + $maximumNy=intdiv($capacity,$nx); + if($maximumY<$maximumNy)$maximumNy=$maximumY; + for($ny=1;$ny<=$maximumNy;$ny++){ + $nz=intdiv($capacity,$nx*$ny); + if($maximumZ<$nz)$nz=$maximumZ; + if($nx*$ny*$nz<=$count)continue; + $count=$nx*$ny*$nz;$bestNx=$nx;$bestNy=$ny;$bestNz=$nz; + if($count===$capacity)return [$count,$bestNx,$bestNy,$bestNz]; + } + } + return [$count,$bestNx,$bestNy,$bestNz]; + } + + /** + * The round's leading block over every (space, type, rotation) group, or null. + * + * Every group's nodes count toward the limits before any is ranked, and a stop inside a + * group lands on the node the per-node loop stopped at: a stopped round places nothing, + * so which node led it is never read. Inside one group every key field except the + * count-derived lead is equal, and fill and volume grow with the count, so the group's + * first largest count is the only node that can lead. No node exceeds the capacity or + * the whole lattice, and a group whose bound already trails the incumbent cannot lead: + * the cheap lead is monotone in the count, since a float product is. + * + * @param list $spaces + * @param array $capacities + * @param array>> $rotations + * @return array|null + */ + private static function leadingBlock(array $spaces,array $capacities,array $rotations,string $mode,int &$nodes,int $stopAt,SearchStats $stats,Deadline $deadline,bool &$reached):?array + { + $best=null;$byCount=$mode==='count'; + // The incumbent's cheap lead as scalars: its count, and its float volume less the margin. + $leadCount=0;$leadFloor=-INF; + foreach($spaces as $space){ + $spaceLength=$space->dimensions->length->ticks;$spaceWidth=$space->dimensions->width->ticks;$spaceHeight=$space->dimensions->height->ticks; + foreach($capacities as $itemId=>$capacity){ + foreach($rotations[$itemId] as $lattice){ + [$envelopeLength,$envelopeWidth,$envelopeHeight]=$lattice['extents']; + 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); + // 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); + $nodes+=$expanded;$stats->searchNodesExpanded+=$expanded; + if($expanded<$groupNodes){$reached=true;return null;} + }else{$nodes+=$groupNodes;$stats->searchNodesExpanded+=$groupNodes;} + if($envelopeHeight>$spaceHeight)continue; + $maximumZ=intdiv($spaceHeight,$envelopeHeight); + $whole=$maximumX*$maximumY*$maximumZ; + $volume=$lattice['approximateVolume']; + $largest=$capacity<$whole?$capacity:$whole; + if($byCount?$largest<$leadCount:$largest*$volume<$leadFloor)continue; + [$count,$nx,$ny,$nz]=$capacity>=$whole?[$whole,$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]; + if($best!==null&&!self::leads($candidate,$best,$mode))continue; + $best=$candidate;$leadCount=$count;$leadFloor=$approximateUsed*(1-self::FLOAT_MARGIN); + } + } + } + return $best; + } + + private function packMode(Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline,string $mode,int $nodeLimit):SingleContainerSolution { $state=new ContainerState($container,$sequence); $spaces=[new Space(new Point(0,0,0),$container->innerDimensions)]; $remaining=[]; foreach($items as $instance)$remaining[$instance->item->id][]=$instance; ksort($remaining,SORT_STRING); - $nodes=0;$reached=false; + $nodes=0;$reached=false;$rotations=[]; while($spaces!==[]&&array_sum(array_map('count',$remaining))>0){ - $best=null; - foreach($spaces as $space){ - $spaceVolume=$space->dimensions->volumeString(); - foreach($remaining as $itemId=>$available){ - if($available===[])continue; - $prototype=$available[0];$capacity=count($available); - if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems-$state->placementCount()); - if($container->maxPayload!==null&&$prototype->weight()->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks-$state->payloadTicks,$prototype->weight()->ticks)); - if($capacity<=0)continue; - foreach($prototype->dimensions()->uniqueRotations($prototype->item->allowedRotations) as [$rotation,$physical]){ - $envelope=$config->clearance->ticks?$physical->expand($config->clearance):$physical; - $maximumX=intdiv($space->dimensions->length->ticks,$envelope->length->ticks); - $maximumY=intdiv($space->dimensions->width->ticks,$envelope->width->ticks); - $maximumZ=intdiv($space->dimensions->height->ticks,$envelope->height->ticks); - for($nx=1;$nx<=min($maximumX,$capacity);$nx++){ - $maximumNy=min($maximumY,intdiv($capacity,$nx)); - for($ny=1;$ny<=$maximumNy;$ny++){ - if($nodes>=$config->containerPlanNodeLimit||$deadline->expired()){$reached=true;break 5;} - $nodes++;$stats->searchNodesExpanded++; - $nz=min($maximumZ,intdiv($capacity,$nx*$ny)); - if($nz<=0)continue; - $count=$nx*$ny*$nz; - $usedVolume=BigInt::multiply($count,$physical->volumeString()); - $spaceFill=(int)BigInt::divide(BigInt::multiply($usedVolume,1_000_000),$spaceVolume); - $volumeKey=array_map(static fn(int $chunk):int=>-$chunk,BigInt::chunks($usedVolume)); - $lead=$mode==='count'?[-$count,-$spaceFill,...$volumeKey]:[...$volumeKey,-$spaceFill,-$count]; - $score=[...$lead,$space->origin->z,$space->origin->y,$space->origin->x,$itemId,$rotation->value,$nx,$ny,$nz]; - $candidate=compact('space','itemId','rotation','physical','envelope','nx','ny','nz','count','usedVolume','score'); - if($best===null||$score<$best['score'])$best=$candidate; - } - } - } - } + // Only the node count moves a counted limit inside one round: candidates and + // placements are counted when a block is placed, after it. + $stopAt=$nodes+max(0,min($nodeLimit-$nodes,$deadline->searchNodesLeft($stats))); + // A type's capacity and lattices do not depend on the space they are tried in. + $capacities=[]; + foreach($remaining as $itemId=>$available){ + if($available===[])continue; + $prototype=$available[0];$capacity=count($available); + if($container->maxItems!==null)$capacity=min($capacity,$container->maxItems-$state->placementCount()); + if($container->maxPayload!==null&&$prototype->weight()->ticks>0)$capacity=min($capacity,intdiv($container->maxPayload->ticks-$state->payloadTicks,$prototype->weight()->ticks)); + if($capacity<=0)continue; + $capacities[$itemId]=$capacity; + $rotations[$itemId]??=self::lattices($prototype,$config); } + $best=self::leadingBlock($spaces,$capacities,$rotations,$mode,$nodes,$stopAt,$stats,$deadline,$reached); if($best===null||$reached)break; $chosen=array_slice($remaining[$best['itemId']],0,$best['count']); $remaining[$best['itemId']]=array_slice($remaining[$best['itemId']],$best['count']); diff --git a/src/Algorithm/MaximalSpaceSolver.php b/src/Algorithm/MaximalSpaceSolver.php index 79d74ed..c3489ea 100644 --- a/src/Algorithm/MaximalSpaceSolver.php +++ b/src/Algorithm/MaximalSpaceSolver.php @@ -26,6 +26,8 @@ final class MaximalSpaceSolver implements SingleContainerSolver * 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){} @@ -72,22 +74,25 @@ private static function choose(ContainerState $state,array $spaces,ItemInstance return null; } - /** The six maximal slabs of $space that survive carving $box out of it. @return list */ - private static function subtract(Space $space,AxisAlignedBox $box):array + /** + * 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 { - $source=new AxisAlignedBox($space->origin,$space->dimensions); - if(!$source->intersects($box))return [$space]; + [$x1,$y1,$z1,$x2,$y2,$z2]=$s; $out=[]; - $push=static function(int $x1,int $y1,int $z1,int $x2,int $y2,int $z2)use(&$out):void{ - if($x2>$x1&&$y2>$y1&&$z2>$z1) - $out[]=new Space(new Point($x1,$y1,$z1),new Dimensions(new Length($x2-$x1),new Length($y2-$y1),new Length($z2-$z1))); - }; - $push($source->origin->x,$source->origin->y,$source->origin->z,min($source->x2(),$box->origin->x),$source->y2(),$source->z2()); - $push(max($source->origin->x,$box->x2()),$source->origin->y,$source->origin->z,$source->x2(),$source->y2(),$source->z2()); - $push($source->origin->x,$source->origin->y,$source->origin->z,$source->x2(),min($source->y2(),$box->origin->y),$source->z2()); - $push($source->origin->x,max($source->origin->y,$box->y2()),$source->origin->z,$source->x2(),$source->y2(),$source->z2()); - $push($source->origin->x,$source->origin->y,$source->origin->z,$source->x2(),$source->y2(),min($source->z2(),$box->origin->z)); - $push($source->origin->x,$source->origin->y,max($source->origin->z,$box->z2()),$source->x2(),$source->y2(),$source->z2()); + 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; } @@ -98,41 +103,76 @@ private static function subtract(Space $space,AxisAlignedBox $box):array * 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 { - $current=array_map(static fn(Space $space):array=>[$space,false],$spaces); + // [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 [$space,$isNew]){ - if(!(new AxisAlignedBox($space->origin,$space->dimensions))->intersects($box)){$next[]=[$space,$isNew];continue;} - foreach(self::subtract($space,$box) as $part)$next[]=[$part,true]; + 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 $pair){ - [$space,]=$pair; - $d=$space->dimensions; - $unique["{$space->origin->x}:{$space->origin->y}:{$space->origin->z}:{$d->length->ticks}:{$d->width->ticks}:{$d->height->ticks}"]=$pair; + 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; } - // descendingVolumeKey parses BigInt chunks; one key per space instead of one - // per stable-usort comparison, with the ordering unchanged. - $kept=StableSorter::sortBy(array_values($unique),static fn(array $pair):array=>array_merge([$pair[0]->origin->z,$pair[0]->origin->y,$pair[0]->origin->x],$pair[0]->dimensions->descendingVolumeKey())); + 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_map(static fn(array $pair):array=>[ - $pair[0]->origin->x,$pair[0]->origin->y,$pair[0]->origin->z, - $pair[0]->origin->x+$pair[0]->dimensions->length->ticks, - $pair[0]->origin->y+$pair[0]->dimensions->width->ticks, - $pair[0]->origin->z+$pair[0]->dimensions->height->ticks, - ],$kept); + $extents=array_column($kept,0); $result=[]; - foreach($kept as $index=>[$space,$isNew]){ - if($isNew&&self::isContained($extents,$index))continue; - $result[]=$space; + 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()); diff --git a/src/Algorithm/SolverOrchestrator.php b/src/Algorithm/SolverOrchestrator.php index 7058e9d..f321faf 100644 --- a/src/Algorithm/SolverOrchestrator.php +++ b/src/Algorithm/SolverOrchestrator.php @@ -3,8 +3,8 @@ namespace Packvium\Algorithm; use Packvium\Config\{PackingConfig,SolverProfile}; -use Packvium\Constraint\{ConstraintSet,ProvenRejection,SupportConstraint}; -use Packvium\Domain\{Container,ItemInstance,PackedContainer,Rotation,UnpackedItem}; +use Packvium\Constraint\{AxleLoad,ConstraintSet,ProvenRejection,SupportConstraint}; +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}; @@ -30,13 +30,43 @@ public function solve(array $items,array $containers,PackingConfig $config,Deadl */ public function solvePortfolio(array $items,array $containers,PackingConfig $config,Deadline $deadline,array $preloaded=[]):PortfolioRun { - $starts=$this->starts($items,$config); + $starts=$this->starts($items,$config,$containers); $effortBudget=$config->effortBudget; if($effortBudget!==null&&$effortBudget->maxRestarts!==null)$starts=array_slice($starts,0,$effortBudget->maxRestarts); - if($this->eligibleForConcurrentExecution($deadline,$config)&&count($starts)>1){ - return $this->solveConcurrent($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded); + $run=$this->eligibleForConcurrentExecution($deadline,$config)&&count($starts)>1 + ? $this->solveConcurrent($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded) + : $this->solveSequential($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded); + return self::withoutABlockStartThatOnlyTies($run,$starts,$config); + } + + /** + * Drop the added block start's answer unless it strictly beats the profile's own. + * + * The start is there to improve an answer, not to replace an equal one: on a tie + * the ranking falls to the solver name, which would hand the result to a lattice + * that knows nothing of the orderings the profile's own starts honour. + * + * @param list}> $starts + */ + private static function withoutABlockStartThatOnlyTies(PortfolioRun $run,array $starts,PackingConfig $config):PortfolioRun + { + if($starts===[])return $run; + [$solver,$orderName]=$starts[array_key_last($starts)]; + if(!$solver instanceof HomogeneousBlockSolver||$solver->nodeLimit===null)return $run; + $scorer=ObjectiveRegistry::resolve($config->objective,$config); + $added=$solver->name().':'.$orderName; + $bestOwn=null; + foreach($run->solutions as $solution){ + if($solution->solverName===$added)continue; + $score=$scorer->score($solution); + if($bestOwn===null||$score->compare($bestOwn)<0)$bestOwn=$score; } - return $this->solveSequential($items,$containers,$config,$deadline,$starts,$effortBudget,$preloaded); + if($bestOwn===null)return $run; + $kept=array_values(array_filter( + $run->solutions, + static fn(RawSolution $solution):bool=>$solution->solverName!==$added||$scorer->score($solution)->compare($bestOwn)<0, + )); + return new PortfolioRun($kept,$run->starts); } /** @@ -289,6 +319,15 @@ private function finishPortfolio(array $items,array $containers,Deadline $deadli return new PortfolioRun($results,$records); } + /** + * Whether one box of these dimensions fits this container empty: the frame, and for a flat + * bag the girth rule too, so a bag too thin for an item proves it unplaceable. + */ + private static function fitsAlone(Container $container,Dimensions $dimensions):bool + { + return $container->isFlatBag()?FlatBag::fitsAlone($container->innerDimensions,$dimensions):$dimensions->fitsInside($container->innerDimensions); + } + /** @param list $containers */ /** @return array{0:string,1:list} */ private function unpackedReason(ItemInstance $item,array $containers,bool $reached):array @@ -296,7 +335,7 @@ private function unpackedReason(ItemInstance $item,array $containers,bool $reach $dimension=false;$weight=false; foreach($containers as $container){ foreach($item->dimensions()->uniqueRotations($item->item->allowedRotations) as [,$dimensions]) - if($dimensions->fitsInside($container->innerDimensions)){$dimension=true;break 2;} + if(self::fitsAlone($container,$dimensions)){$dimension=true;break 2;} } // Same geometric check with every physical orientation allowed, not only the // item's own restricted set -- distinguishes "genuinely too big in any @@ -306,7 +345,7 @@ private function unpackedReason(ItemInstance $item,array $containers,bool $reach $fitsAnyRotation=false; foreach($containers as $container){ foreach($item->dimensions()->uniqueRotations(Rotation::all()) as [,$dimensions]) - if($dimensions->fitsInside($container->innerDimensions)){$fitsAnyRotation=true;break 2;} + if(self::fitsAlone($container,$dimensions)){$fitsAnyRotation=true;break 2;} } foreach($containers as $container) if($container->maxPayload===null||$item->weight()->ticks<=$container->maxPayload->ticks){$weight=true;break;} @@ -336,6 +375,64 @@ private function unpackedReason(ItemInstance $item,array $containers,bool $reach return ['no_feasible_placement',[]]; } + /** + * The container limit that left `$item` out, for the `no_feasible_placement` + * fallback, or null when no limit explains it. + * + * Only containers that admit the item on every structural count -- a fitting + * rotation, its weight, its eligibility tags -- are asked. When an axle refuses the + * item alone in every one of them, the axle is the reason. Otherwise, when every one + * that would take it alone is out of stock, or `maxContainers` is reached, the reason + * is the inventory: `max_items`, cumulative `max_payload`, `tag_limits`, the + * stop-accessibility rule and an axle's share of a full load can only refuse an item + * a fresh container would take, so they surface here too. `$opened` is + * `openedByType()` of the final layout. O(C*R). + * + * @param list $containers @param array $opened + */ + private static function limitReason(ItemInstance $item,array $containers,array $opened,PackingConfig $config):?string + { + $envelopes=[]; + foreach($item->dimensions()->uniqueRotations($item->item->allowedRotations) as [,$dimensions])$envelopes[]=$dimensions->expand($config->clearance); + $weight=$item->weight()->ticks;$eligibleTags=$item->item->eligibleContainerTags; + $admitting=[];$compatible=false; + foreach($containers as $container){ + $fitting=array_values(array_filter($envelopes,static fn(Dimensions $envelope):bool=>self::fitsAlone($container,$envelope))); + if($fitting===[])continue; + if($container->maxPayload!==null&&$weight>$container->maxPayload->ticks)continue; + if($eligibleTags!==[]&&array_intersect($eligibleTags,$container->tags)===[])continue; + $compatible=true; + if(self::axlesAdmitAlone($container,$fitting,$weight))$admitting[]=$container; + } + if(!$compatible)return null; + if($admitting===[])return 'axle_overloaded'; + if($config->maxContainers!==null&&array_sum($opened)>=$config->maxContainers)return 'container_inventory_exhausted'; + foreach($admitting as $container) + if($container->quantity===null||($opened[$container->id]??0)<$container->quantity)return null; + return 'container_inventory_exhausted'; + } + + /** + * How many containers of each template a layout opened. O(P), once per layout. + * + * @param list $packed @return array + */ + private static function openedByType(array $packed):array + { + $opened=[]; + foreach($packed as $packedContainer)$opened[$packedContainer->container->id]=($opened[$packedContainer->container->id]??0)+1; + return $opened; + } + + /** @param list $envelopes envelopes that already fit `$container` */ + private static function axlesAdmitAlone(Container $container,array $envelopes,int $weight):bool + { + if($container->axles===null)return true; + foreach($envelopes as $envelope) + if(AxleLoad::admitsAlone($container->axles,$container->tareWeight->ticks,$container->innerDimensions->length->ticks,$weight,$envelope->length->ticks))return true; + return false; + } + /** * Post-hoc diagnosis for the `no_feasible_placement` fallback: true * when `$item` could be placed in at least one already-packed container's @@ -376,8 +473,48 @@ private function supportIsTheBlocker(ItemInstance $item,array $packed,PackingCon return false; } - /** @return list}> */ - private function starts(array $items,PackingConfig $config):array + /** + * Lattice nodes the block start added to `fast` and `balanced` may enumerate per mode -- + * the bound `quality` gives the same solver through `containerPlanNodeLimit`. + */ + private const BLOCK_START_NODE_LIMIT=100_000; + + /** + * The block start `fast` and `balanced` add to their own, or `null`. + * + * Single-type blocks fill a carton load in milliseconds where a per-item search + * spends its whole budget, so the low-latency profiles run them as one more start + * and let the score decide. Only where the lattice can express the whole request: + * a start that fell back to the per-item solver would repeat one already in the + * portfolio. One item type is `GridSolver`'s case, and it is exact there. + * + * @param list $items + * @param list $containers + */ + private function blockStart(array $items,PackingConfig $config,array $containers):?HomogeneousBlockSolver + { + $fast=$config->profile===SolverProfile::Fast; + if((!$fast&&$config->profile!==SolverProfile::Balanced)||$config->solvers!==[])return null; + if($this->customSolvers!==[]||$this->customConstraints!==[])return null; + $types=[];foreach($items as $instance)$types[$instance->item->id]=true; + if(count($types)<2)return null; + // A lattice takes whichever type fills best; it cannot honour a caller's say over + // which item goes first, so it stays out when the items do not all lead alike. + $lead=ItemOrdering::lead($items[0],$config); + foreach($items as $instance)if(ItemOrdering::lead($instance,$config)!=$lead)return null; + // One enumeration, the one the objective ranks by: `fast` is latency-bound. + $modes=!$fast?HomogeneousBlockSolver::MODES:($config->objective==='maximum_volume'?['volume']:['count']); + $solver=new HomogeneousBlockSolver([],null,$modes,self::BLOCK_START_NODE_LIMIT); + if($containers===[])return null; + foreach($containers as $container)if(!$solver->supports($container,$items,$config))return null; + return $solver; + } + + /** + * @param list $containers + * @return list}> + */ + private function starts(array $items,PackingConfig $config,array $containers=[]):array { $orders=$this->orders($items,$config); $starts=[]; @@ -386,6 +523,8 @@ private function starts(array $items,PackingConfig $config):array $chosen=(method_exists($solver,'orderInsensitive')&&$solver->orderInsensitive())?array_slice($orders,0,1):$orders; foreach($chosen as [$name,$order])$starts[]=[$solver,$name,$order]; } + // Last, so a restart budget drops it first and the profile's own starts keep theirs. + 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]; @@ -404,6 +543,19 @@ private static function greedyConfig(PackingConfig $config):PackingConfig ); } + /** The same configuration with placement coordinates required: no compact lattice form (D12). */ + private static function withCoordinates(PackingConfig $config):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:$config->maxCandidatesPerItem,maxCandidatePoints:$config->maxCandidatePoints,solvers:$config->solvers,objective:$config->objective, + effortBudget:$config->effortBudget,dimensionalWeightDivisor:$config->dimensionalWeightDivisor,dimensionalWeightLengthUnit:$config->dimensionalWeightLengthUnit, + dimensionalWeightWeightUnit:$config->dimensionalWeightWeightUnit,requirePlacementCoordinates:true,parallelStarts:$config->parallelStarts, + containerPlanBeamWidth:$config->containerPlanBeamWidth,containerPlanNodeLimit:$config->containerPlanNodeLimit,accessDirections:$config->accessDirections, + ); + } + /** @var array */ private const SOLVER_FACTORIES=[ 'grid'=>null, // constructed without constraints/scorer; handled explicitly below @@ -449,17 +601,19 @@ private function orders(array $items,PackingConfig $config):array { // Every strategy is keyed behind `ItemOrdering::lead`, which carries priority // and, under `maximum_value`, the item's own value. - $strategies=[]; - if($config->profile===SolverProfile::Quality)$strategies=[ + $smallFirst=$config->profile!==SolverProfile::Quality?[]:[ ['small_edge',static fn(ItemInstance $i):array=>[...ItemOrdering::lead($i,$config),$i->dimensions()->maxEdge(),...$i->dimensions()->volumeKey(),$i->id()]], ['small_volume',static fn(ItemInstance $i):array=>[...ItemOrdering::lead($i,$config),...$i->dimensions()->volumeKey(),$i->dimensions()->maxEdge(),$i->id()]], ]; - $strategies=[...$strategies,...[ + $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()]], ['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()]], - ]]; + ]; + // Small items first places the most pieces; large items first fills the most space. + // The objective decides which family gets the early, fully funded starts. + $strategies=$config->objective==='maximum_volume'?[...$largeFirst,...$smallFirst]:[...$smallFirst,...$largeFirst]; $limit=$config->profile===SolverProfile::Fast?1:$config->multiStartOrders; $out=[];$seen=[]; foreach($strategies as [$name,$key]){ @@ -505,9 +659,118 @@ private static function recordRootBound(SingleContainerSolver $solver,bool $beam if($stats->objectiveLowerBound!==null)return; if(!$beam&&$solver->name()!=='exact_small')return; if($config->objective!=='default')return; + // Its unused-volume and height keys are ratios against a declared size, and a + // made-to-measure box has none until it is cut: the bound would not be admissible. + foreach($containers as $container)if($container->madeToMeasure!==null)return; $stats->objectiveLowerBound=ObjectiveBounds::compute($items,$containers); } + /** + * The greedy round's key for one trial, read from the container the trial built: a + * made-to-measure trial carries its fabricated box, so the key prices the box that ships, + * never the machine maximum the loop declared. The trial chain ranks an + * incomplete round's rungs by this same key. + * + * @param list $roundItems + * @return list + */ + private static function roundScore(SingleContainerSolution $one,array $roundItems,PackingConfig $config,ContainerSelector $selector):array + { + $container=$one->state->container; + if(($config->objective==='shipping_cost'||$config->objective==='lowest_landed_cost')&&$config->dimensionalWeightDivisor!==null){ + $dimensional=$one->state->billedDimensionalWeight($config); + $gross=$container->tareWeight->ticks+$one->state->payloadTicks; + $billed=max($gross,$dimensional); + $placed=$one->state->placementCount(); + if($config->objective==='shipping_cost'){ + $candidateScore=[-$placed,$billed,$container->id]; + }else{ + // Landed cost ranks the round by the money the finished score will + // charge, not by the grams it is derived from. This loop commits the + // trial verbatim, so its billed weight is already final and the tariff + // can be read now; a bracket step or a minimum charge makes the cheaper + // shipment the heavier one, and a trial the tariff cannot price is + // unshippable rather than merely dear, so it sorts behind every + // priceable alternative. Keys after the charge mirror Rust's + // and Python's, so the three engines pick the same container. + $charge=$container->rateTable?->chargeMinorOrNull(LandedCostSolutionScorer::grams($billed)); + $candidateScore=[ + $charge??LandedCostSolutionScorer::UNPRICEABLE_MINOR, + intdiv(count($roundItems)+max($placed,1)-1,max($placed,1)), + -$placed, + $container->id, + ]; + } + }elseif($config->objective==='maximum_volume'&&$selector instanceof DefaultContainerSelector){ + // The round keeps the trial that loaded the most volume, not the one + // that seated the most pieces. A caller's own selector is left alone. + $used=$one->state->usedVolume; + $leftover=BigInt::chunks(BigInt::subtract($container->innerDimensions->volumeString(),$used)); + $candidateScore=[...array_map(static fn(int $c):int=>-$c,BigInt::chunks($used)),$container->costMinor,...$leftover,$container->id]; + }else{ + $candidateScore=$selector->score($container,$one); + } + return $candidateScore; + } + + /** + * One container's trial for a round, and how many single-container solves it spent. A + * declared container is one solve; a made-to-measure one runs the rung chain and returns + * its trial already fabricated. + * + * @param list $items + * @return array{0:SingleContainerSolution,1:int} + */ + private function trial(SingleContainerSolver $solver,Container $container,int $sequence,array $items,PackingConfig $config,SearchStats $stats,Deadline $deadline):array + { + if($container->madeToMeasure===null)return [$solver->packOne($container,$sequence,$items,$config,$stats,$deadline),1]; + return $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]; + } + + /** A rung trial as the box cut for it: the achieved extent of its placements, envelope far faces with clearance, rounded up onto the machine grid (D14). O(p). */ + private static function fabricated(Container $declared,SingleContainerSolution $one):SingleContainerSolution + { + $box=$declared->fabricate(FlatBag::extentOf($one->state->placements)); + return new SingleContainerSolution($one->state->withContainer($box),$one->unpacked,false,$one->timeLimitReached,false); + } + /** @param list $preloaded */ private function acrossContainers(SingleContainerSolver $solver,array $items,array $containers,PackingConfig $config,SearchStats $stats,Deadline $deadline,array $preloaded=[]):array { @@ -527,42 +790,11 @@ private function acrossContainers(SingleContainerSolver $solver,array $items,arr $candidates=[]; foreach($ordered as $container){ if($inventory[$container->id]!==null&&$inventory[$container->id]<=0)continue; - try{$one=$solver->packOne($container,$seq[$container->id]+1,$remaining,$config,$stats,$deadline);} + try{[$one]=$this->trial($solver,$container,$seq[$container->id]+1,$remaining,$config,$stats,$deadline);} catch(TimeLimitReached){$reached=true;break;} if($one->timeLimitReached)$reached=true; if($one->state->placementCount()===0){if($reached)break;continue;} - if(($config->objective==='shipping_cost'||$config->objective==='lowest_landed_cost')&&$config->dimensionalWeightDivisor!==null){ - $dimensions=$container->outerDimensions??$container->innerDimensions; - $dimensional=$dimensions->dimensionalWeight( - $config->dimensionalWeightDivisor, - $config->dimensionalWeightLengthUnit, - $config->dimensionalWeightWeightUnit, - )->ticks; - $gross=$container->tareWeight->ticks+$one->state->payloadTicks; - $billed=max($gross,$dimensional); - $placed=$one->state->placementCount(); - if($config->objective==='shipping_cost'){ - $candidateScore=[-$placed,$billed,$container->id]; - }else{ - // Landed cost ranks the round by the money the finished score will - // charge, not by the grams it is derived from. This loop commits the - // trial verbatim, so its billed weight is already final and the tariff - // can be read now; a bracket step or a minimum charge makes the cheaper - // shipment the heavier one, and a trial the tariff cannot price is - // unshippable rather than merely dear, so it sorts behind every - // priceable alternative. Keys after the charge mirror Rust's - // and Python's, so the three engines pick the same container. - $charge=$container->rateTable?->chargeMinorOrNull(LandedCostSolutionScorer::grams($billed)); - $candidateScore=[ - $charge??LandedCostSolutionScorer::UNPRICEABLE_MINOR, - intdiv(count($remaining)+max($placed,1)-1,max($placed,1)), - -$placed, - $container->id, - ]; - } - }else{ - $candidateScore=$selector->score($container,$one); - } + $candidateScore=self::roundScore($one,$remaining,$config,$selector); $candidates[]=[$candidateScore,$one]; if($reached)break; } @@ -577,10 +809,11 @@ private function acrossContainers(SingleContainerSolver $solver,array $items,arr $remaining=array_values(array_filter($remaining,static fn($i)=>!isset($ids[$i->id()]))); if($reached)break; } - $unpacked=[]; + $unpacked=[];$opened=self::openedByType($packed); foreach($remaining as $i){ [$reason,$details]=$this->unpackedReason($i,$containers,$reached); if($reason==='no_feasible_placement'&&$this->supportIsTheBlocker($i,$packed,$config))$reason='insufficient_support'; + if($reason==='no_feasible_placement')$reason=self::limitReason($i,$containers,$opened,$config)??$reason; $unpacked[]=new UnpackedItem($i,$reason,$details); } // Optimality may only be claimed when an exhaustive search filled a single @@ -655,7 +888,7 @@ private static function additionalContainerLowerBound(array $plan,array $contain 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,$item->dimensions()->volumeString()); + $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)); } } @@ -693,8 +926,10 @@ private function acrossContainerPlans(SingleContainerSolver $solver,array $items if($nodes>=$config->containerPlanNodeLimit)break; if($deadline->expired()){$reached=true;break;} if($plan['inventory'][$container->id]!==null&&$plan['inventory'][$container->id]<=0)continue; - $nodes++; - try{$one=$solver->packOne($container,$plan['sequences'][$container->id]+1,$plan['remaining'],$config,$stats,$deadline);}catch(TimeLimitReached){$reached=true;break;} + // 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]--; @@ -715,7 +950,7 @@ private function acrossContainerPlans(SingleContainerSolver $solver,array $items 0,$config->containerPlanBeamWidth, ); } - $unpacked=[];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';$unpacked[]=new UnpackedItem($item,$reason,$details);} + $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']]; } diff --git a/src/Artifacts/OperationalArtifact.php b/src/Artifacts/OperationalArtifact.php index 644ad60..3c778f3 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.5.0'; + public const SUITE_VERSION = '1.6.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']; @@ -128,6 +128,22 @@ public static function parse(string $json) } } + /** + * `exact` or `not_guaranteed`: the replay promise an artifact of this result would make, + * without building the artifact. The same rule {@see build()} records under + * `provenance.replay.level`, and the twin of Python's `packvium.artifacts.replay_level`. + * + * @param mixed $result a JSON object: a `stdClass` or an associative array + * @throws OperationalArtifactException `invalid_result` when `algorithm` is malformed + */ + public static function replayLevel($result): string + { + if (!JsonValue::isObject($result)) { + throw new OperationalArtifactException('invalid_result', 'a result is a JSON object'); + } + return self::replay(self::solver(JsonValue::get($result, 'algorithm')))['level']; + } + /** * The artifact's RFC 8785 canonical form, the bytes four engines are compared on. * diff --git a/src/Config/EffortBudget.php b/src/Config/EffortBudget.php new file mode 100644 index 0000000..7a8f0be --- /dev/null +++ b/src/Config/EffortBudget.php @@ -0,0 +1,17 @@ +maxLoad !== null ? $origins[0] : 0; + $highest = $rear->maxLoad !== null ? $origins[count($origins) - 1] : $lastOrigin; + return max(0, $lowest) <= min($lastOrigin, $highest); + } + private static function sNeg(string $v): string { if ($v === '0') { return '0'; } diff --git a/src/Constraint/Internal/ConstraintActivity.php b/src/Constraint/Internal/ConstraintActivity.php index cb7656e..a0211c4 100644 --- a/src/Constraint/Internal/ConstraintActivity.php +++ b/src/Constraint/Internal/ConstraintActivity.php @@ -53,7 +53,8 @@ public static function isInert( return !$routeSensitive; } if ($constraint instanceof StopAccessibilityConstraint) { - return !$routeSensitive + // A flat bag has no walls, so it inherits no doors either. + return !$routeSensitive || $container->isFlatBag() || ($container->accessDirections === [] && $defaultAccessDirections === []); } if ($constraint instanceof AxleLoadConstraint) { diff --git a/src/Constraint/Internal/LoadSupportGraph.php b/src/Constraint/Internal/LoadSupportGraph.php index 0874058..6948318 100644 --- a/src/Constraint/Internal/LoadSupportGraph.php +++ b/src/Constraint/Internal/LoadSupportGraph.php @@ -2,7 +2,7 @@ declare(strict_types=1); namespace Packvium\Constraint\Internal; use Packvium\Constraint\{ContactEdge,ContactGraph,LoadUnit}; -use Packvium\Domain\{AxisAlignedBox,ItemInstance,Placement}; +use Packvium\Domain\{AxisAlignedBox,Item,ItemInstance,Placement}; /** * Direct load support: ordinary face contact plus exact adjacent nesting contact. @@ -164,20 +164,37 @@ public function supporters(int $index):array{return $this->nested?$this->support public function children(int $index):array{return $this->nested?$this->children[$index]:$this->face->children($index);} /** - * A direct-support edge may never originate at a non-stackable item. + * The first direct-support edge at the candidate its lower item refuses, or null. + * + * Supporters ascending, then children ascending. `non_stackable` is tested before the + * stacking-group rule on every edge, so a scene invalid before keeps its code; + * the group test rides this same walk, one keyed lookup per edge and no pass of its own. * * @param list $placements * @return array{0:string,1:string}|null */ public function nonStackableFailure(array $placements,ItemInstance $item,int $candidateIndex):?array { + $upperGroup=$item->item->stackingGroup; foreach($this->supporters($candidateIndex) as $edge){ - $supporter=$placements[$edge->index]; - if(!$supporter->instance->item->stackable) - return ['non_stackable',$supporter->instance->item->id]; + $lower=$placements[$edge->index]->instance->item; + $code=self::stackingRefusal($lower,$upperGroup); + if($code!==null)return [$code,$lower->id]; + } + $lower=$item->item; + if($lower->stackable&&$lower->acceptsStackingGroups===[])return null; + foreach($this->children($candidateIndex) as $child){ + $code=self::stackingRefusal($lower,$placements[$child]->instance->item->stackingGroup); + if($code!==null)return [$code,$lower->id]; } - if(!$item->item->stackable&&$this->children($candidateIndex)!==[]) - return ['non_stackable',$item->item->id]; + return null; + } + + /** Why `$lower` refuses an item of `$upperGroup` resting directly on it, or null. O(1). */ + private static function stackingRefusal(Item $lower,?string $upperGroup):?string + { + if(!$lower->stackable)return 'non_stackable'; + if(!$lower->acceptsStackingGroup($upperGroup))return 'stacking_group_incompatible'; return null; } diff --git a/src/Constraint/StopAccessibilityConstraint.php b/src/Constraint/StopAccessibilityConstraint.php index 9f7edca..755a967 100644 --- a/src/Constraint/StopAccessibilityConstraint.php +++ b/src/Constraint/StopAccessibilityConstraint.php @@ -125,8 +125,8 @@ public function evaluate(ConstraintContext $c):ConstraintResult { if(!$c->routeSensitive)return ConstraintResult::allow(); // The container's own doors win; the configured list is what a container that - // states none inherits. - $directions=$c->container->accessDirections!==[]?$c->container->accessDirections:$this->defaultDirections; + // states none inherits. A flat bag has no walls, so it inherits none. + $directions=$c->container->isFlatBag()?[]:($c->container->accessDirections!==[]?$c->container->accessDirections:$this->defaultDirections); if($directions===[])return ConstraintResult::allow(); $candidateStop=$c->item->item->stopIndex??INF; $inner=$c->container->innerDimensions; diff --git a/src/Domain/Container.php b/src/Domain/Container.php index 46a4ee5..004f533 100644 --- a/src/Domain/Container.php +++ b/src/Domain/Container.php @@ -2,6 +2,7 @@ declare(strict_types=1); namespace Packvium\Domain; use InvalidArgumentException; +use Packvium\Unit\Length; use Packvium\Unit\Weight; final readonly class Container { @@ -29,16 +30,58 @@ * solver's `ContainerState` starts from them without knowing they exist; a packed result * carries the container with this emptied again (docs/PLAN-REVISIONS.md). * + * `$deformableBoundary`: `'flat_bag'` makes this a flexible bag whose package conforms to its + * contents (`FlatBag`); null is a rigid container. + * * @param list $obstacles @param list $tags @param array $tagLimits @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections @param list $preloaded */ - public function __construct(public string $id,public Dimensions $innerDimensions,public ?Dimensions $outerDimensions=null,public Weight $tareWeight=new Weight(0),public ?Weight $maxPayload=null,public int $costMinor=0,public ?int $quantity=null,public array $obstacles=[],public array $tags=[],public ?int $maxItems=null,public array $metadata=[],public float $voidFillReserveRatio=0.0,public array $tagLimits=[],public ?Weight $maxStackDensity=null,public ?array $axles=null,public ?RateTable $rateTable=null,array $accessDirections=[],public array $preloaded=[]) - {if($id==='')throw new InvalidArgumentException('Container id is required');if($quantity!==null&&$quantity<=0)throw new InvalidArgumentException('Container quantity must be positive');if($costMinor<0)throw new InvalidArgumentException('Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new InvalidArgumentException('Container max_items must be at least 1');if($voidFillReserveRatio<0||$voidFillReserveRatio>1)throw new InvalidArgumentException('void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new InvalidArgumentException('tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new InvalidArgumentException('Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new InvalidArgumentException("Obstacle {$o->id} lies outside container"); + public function __construct(public string $id,public Dimensions $innerDimensions,public ?Dimensions $outerDimensions=null,public Weight $tareWeight=new Weight(0),public ?Weight $maxPayload=null,public int $costMinor=0,public ?int $quantity=null,public array $obstacles=[],public array $tags=[],public ?int $maxItems=null,public array $metadata=[],public float $voidFillReserveRatio=0.0,public array $tagLimits=[],public ?Weight $maxStackDensity=null,public ?array $axles=null,public ?RateTable $rateTable=null,array $accessDirections=[],public array $preloaded=[],public ?string $deformableBoundary=null,public ?MadeToMeasure $madeToMeasure=null) + {if($id==='')throw new InvalidArgumentException('Container id is required');$madeToMeasure?->admits([$innerDimensions->length->ticks,$innerDimensions->width->ticks,$innerDimensions->height->ticks]);if($deformableBoundary!==null)self::requireBagFields($deformableBoundary,$obstacles,$axles,$accessDirections,$maxStackDensity,$outerDimensions,$voidFillReserveRatio);if($quantity!==null&&$quantity<=0)throw new InvalidArgumentException('Container quantity must be positive');if($costMinor<0)throw new InvalidArgumentException('Container cost cannot be negative');if($maxItems!==null&&$maxItems<1)throw new InvalidArgumentException('Container max_items must be at least 1');if($voidFillReserveRatio<0||$voidFillReserveRatio>1)throw new InvalidArgumentException('void_fill_reserve_ratio must be between 0 and 1');foreach($tagLimits as $limit)if($limit<1)throw new InvalidArgumentException('tag_limits must be at least 1');if($outerDimensions!==null&&!$innerDimensions->fitsInside($outerDimensions))throw new InvalidArgumentException('Outer dimensions cannot be smaller than inner dimensions');$boundary=new AxisAlignedBox(new Point(0,0,0),$innerDimensions);foreach($obstacles as $o)foreach($o->boxes() as $box)if(!$boundary->contains($box))throw new InvalidArgumentException("Obstacle {$o->id} lies outside container"); if($axles!==null){[$front,$rear]=$axles;if($front->position->ticks>=$rear->position->ticks)throw new InvalidArgumentException('The front axle must be strictly nearer the origin than the rear axle');if($front->position->ticks<0||$rear->position->ticks>$innerDimensions->length->ticks)throw new InvalidArgumentException("Axle positions must lie within the container's length");} 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)));} /** 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);} - public static function create(string $id,Dimensions $innerDimensions,Weight|int|string|array $tareWeight=0,Weight|int|string|array|null $maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],Weight|int|string|array|null $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[]):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections);} + 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;} + /** The declared container solved inside `$rung`: same id, everything else unchanged. @param array{0:int,1:int,2:int} $rung */ + public function withEnvelope(array $rung):self{return $this->resized(self::dimensionsOf($rung),null,$this->costMinor,$this->tareWeight);} + /** + * The box cut for an achieved extent: equal to this declared machine except its size, outer + * size, price and tare. O(1). Containment is a theorem, not a check: every placement lies + * inside `$achieved`, and the grid never rounds below it or past the maximum (D4). + * + * @param array{0:int,1:int,2:int} $achieved + */ + public function fabricate(array $achieved):self + { + $machine=$this->madeToMeasure; + if($machine===null)throw new \LogicException("container {$this->id} is not made to measure"); + $maximum=[$this->innerDimensions->length->ticks,$this->innerDimensions->width->ticks,$this->innerDimensions->height->ticks]; + $sides=[];$outer=[]; + for($axis=0;$axis<3;$axis++){ + $sides[]=$machine->grid($axis,$achieved[$axis]); + if($sides[$axis]>$maximum[$axis])throw new \LogicException('fabricated box exceeds the machine'); + $outer[]=$sides[$axis]+$machine->outerAllowance[$axis]; + } + return $this->resized(self::dimensionsOf($sides),self::dimensionsOf($outer),$machine->boxCostMinor($this->costMinor,$sides),new Weight($machine->boxTareTicks($this->tareWeight->ticks,$sides))); + } + private function resized(Dimensions $inner,?Dimensions $outer,int $costMinor,Weight $tareWeight):self{return new self($this->id,$inner,$outer,$tareWeight,$this->maxPayload,$costMinor,$this->quantity,$this->obstacles,$this->tags,$this->maxItems,$this->metadata,$this->voidFillReserveRatio,$this->tagLimits,$this->maxStackDensity,$this->axles,$this->rateTable,$this->accessDirections,$this->preloaded,$this->deformableBoundary,$this->madeToMeasure);} + /** @param array{0:int,1:int,2:int} $sides */ + private static function dimensionsOf(array $sides):Dimensions{return new Dimensions(new Length($sides[0]),new Length($sides[1]),new Length($sides[2]));} + /** + * A bag has no walls, floor plan or chassis for a wall-anchored field to refer to, so those + * fields are refused rather than read against a frame that moves with its contents. The JSON + * path names the same fields as request errors first. + * + * @param list $obstacles @param array{0:Axle,1:Axle}|null $axles @param list $accessDirections + */ + private static function requireBagFields(string $kind,array $obstacles,?array $axles,array $accessDirections,?Weight $maxStackDensity,?Dimensions $outerDimensions,float $voidFillReserveRatio):void + { + if(!in_array($kind,FlatBag::KINDS,true))throw new InvalidArgumentException("unknown deformable_boundary kind {$kind}"); + $present=['obstacles'=>$obstacles!==[],'axles'=>$axles!==null,'access_directions'=>$accessDirections!==[],'max_stack_density'=>$maxStackDensity!==null,'outer_dimensions'=>$outerDimensions!==null,'void_fill_reserve_ratio'=>$voidFillReserveRatio>0]; + foreach($present as $name=>$set)if($set)throw new InvalidArgumentException("{$name} cannot be combined with deformable_boundary"); + } + public static function create(string $id,Dimensions $innerDimensions,Weight|int|string|array $tareWeight=0,Weight|int|string|array|null $maxPayload=null,?Dimensions $outerDimensions=null,int $costMinor=0,?int $quantity=null,array $obstacles=[],array $tags=[],?int $maxItems=null,array $metadata=[],float $voidFillReserveRatio=0.0,array $tagLimits=[],Weight|int|string|array|null $maxStackDensity=null,?array $axles=null,?RateTable $rateTable=null,array $accessDirections=[],?string $deformableBoundary=null):self{return new self($id,$innerDimensions,$outerDimensions,Weight::parse($tareWeight),$maxPayload===null?null:Weight::parse($maxPayload),$costMinor,$quantity,$obstacles,$tags,$maxItems,$metadata,$voidFillReserveRatio,$tagLimits,$maxStackDensity===null?null:Weight::parse($maxStackDensity),$axles,$rateTable,$accessDirections,[],$deformableBoundary);} } diff --git a/src/Domain/FlatBag.php b/src/Domain/FlatBag.php new file mode 100644 index 0000000..e5ea524 --- /dev/null +++ b/src/Domain/FlatBag.php @@ -0,0 +1,51 @@ +length->ticks&&$b+$c<=$inner->width->ticks; + } + + /** Whether one box of these dimensions, alone at the origin, fits a flat bag. */ + public static function fitsAlone(Dimensions $inner,Dimensions $box):bool + { + return $box->fitsInside($inner)&&self::girthAdmits($inner,$box->length->ticks,$box->width->ticks,$box->height->ticks); + } + + /** + * `[max x2, max y2, max z2]` over the envelopes, `[0, 0, 0]` for none. O(p). + * + * @param list $placements @return array{0:int,1:int,2:int} + */ + public static function extentOf(array $placements):array + { + $a=$b=$c=0; + foreach($placements as $p){$e=$p->envelopeBox();$a=max($a,$e->x2());$b=max($b,$e->y2());$c=max($c,$e->z2());} + return [$a,$b,$c]; + } + + /** The achieved extent as dimensions; a packed bag always holds at least one box. @param array{0:int,1:int,2:int} $extent */ + public static function asDimensions(array $extent):Dimensions + { + return new Dimensions(new Length($extent[0]),new Length($extent[1]),new Length($extent[2])); + } +} diff --git a/src/Domain/Item.php b/src/Domain/Item.php index c12ce66..e7afc96 100644 --- a/src/Domain/Item.php +++ b/src/Domain/Item.php @@ -40,7 +40,15 @@ /** @var list|null */ public ?array $hullVertices; public ?int $compressionRatioPpm; public ?int $maxCompressionPressureKpa; - public function __construct(string $id,Dimensions $dimensions,?Weight $weight=null,int $quantity=1,array $allowedRotations=[Rotation::LWH,Rotation::LHW,Rotation::WLH,Rotation::WHL,Rotation::HLW,Rotation::HWL],bool $keepUpright=false,bool $stackable=true,bool $mustBeOnFloor=false,?Weight $maxTopLoad=null,float $minimumSupportRatio=0.0,?string $group=null,array $tags=[],array $incompatibleTags=[],int $priority=0,array $metadata=[],?int $maxStackedItems=null,array $eligibleContainerTags=[],?string $groundContactRule=null,?Length $nestingHeight=null,?int $stopIndex=null,?int $value=null,ShapeType $shapeType=ShapeType::RIGID_CUBOID,?array $hullVertices=null,?int $compressionRatioPpm=null,?int $maxCompressionPressureKpa=null) + // Which stacking class this item belongs to, and which classes it may carry directly on + // its top face (docs/STACKING-GROUPS.md). An empty list is unconstrained, like + // tags; a non-empty one is closed, so an item with no class rests on no constrained + // item -- a forgotten classification fails closed, never open. + public ?string $stackingGroup; + /** @var list */ public array $acceptsStackingGroups; + /** @var array the same list keyed, so each support edge costs one lookup */ + private array $acceptedStackingGroups; + public function __construct(string $id,Dimensions $dimensions,?Weight $weight=null,int $quantity=1,array $allowedRotations=[Rotation::LWH,Rotation::LHW,Rotation::WLH,Rotation::WHL,Rotation::HLW,Rotation::HWL],bool $keepUpright=false,bool $stackable=true,bool $mustBeOnFloor=false,?Weight $maxTopLoad=null,float $minimumSupportRatio=0.0,?string $group=null,array $tags=[],array $incompatibleTags=[],int $priority=0,array $metadata=[],?int $maxStackedItems=null,array $eligibleContainerTags=[],?string $groundContactRule=null,?Length $nestingHeight=null,?int $stopIndex=null,?int $value=null,ShapeType $shapeType=ShapeType::RIGID_CUBOID,?array $hullVertices=null,?int $compressionRatioPpm=null,?int $maxCompressionPressureKpa=null,?string $stackingGroup=null,array $acceptsStackingGroups=[]) { if($id==='')throw new InvalidArgumentException('Item id is required');if($quantity<=0)throw new InvalidArgumentException('Item quantity must be positive');if($minimumSupportRatio<0||$minimumSupportRatio>1)throw new InvalidArgumentException('Minimum support ratio must be between 0 and 1');if($maxStackedItems!==null&&$maxStackedItems<1)throw new InvalidArgumentException('max_stacked_items must be at least 1');if($groundContactRule!==null&&!in_array($groundContactRule,self::GROUND_CONTACT_RULES,true))throw new InvalidArgumentException('ground_contact_rule must be one of '.implode(', ',self::GROUND_CONTACT_RULES)); if($nestingHeight!==null&&!($nestingHeight->ticks>=0&&$nestingHeight->ticks<$dimensions->height->ticks))throw new InvalidArgumentException("nesting_height must be at least zero and strictly less than the item's own height"); @@ -51,8 +59,10 @@ public function __construct(string $id,Dimensions $dimensions,?Weight $weight=nu $this->shapeType=$shapeType; $this->hullVertices=self::admitShape($shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa,$dimensions,$nestingHeight); $this->compressionRatioPpm=$compressionRatioPpm;$this->maxCompressionPressureKpa=$maxCompressionPressureKpa; + $this->stackingGroup=$stackingGroup;$this->acceptsStackingGroups=array_values(array_unique($acceptsStackingGroups)); + $this->acceptedStackingGroups=array_fill_keys($this->acceptsStackingGroups,true); } - public static function create(string $id,Dimensions $dimensions,Weight|int|string|array $weight=0,int $quantity=1,array $allowedRotations=[Rotation::LWH,Rotation::LHW,Rotation::WLH,Rotation::WHL,Rotation::HLW,Rotation::HWL],bool $keepUpright=false,bool $stackable=true,bool $mustBeOnFloor=false,Weight|int|string|array|null $maxTopLoad=null,float $minimumSupportRatio=0.0,?string $group=null,array $tags=[],array $incompatibleTags=[],int $priority=0,array $metadata=[],?int $maxStackedItems=null,array $eligibleContainerTags=[],?string $groundContactRule=null,?Length $nestingHeight=null,?int $stopIndex=null,?int $value=null,ShapeType $shapeType=ShapeType::RIGID_CUBOID,?array $hullVertices=null,?int $compressionRatioPpm=null,?int $maxCompressionPressureKpa=null):self{return new self($id,$dimensions,Weight::parse($weight),$quantity,$allowedRotations,$keepUpright,$stackable,$mustBeOnFloor,$maxTopLoad===null?null:Weight::parse($maxTopLoad),$minimumSupportRatio,$group,$tags,$incompatibleTags,$priority,$metadata,$maxStackedItems,$eligibleContainerTags,$groundContactRule,$nestingHeight,$stopIndex,$value,$shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa);} + public static function create(string $id,Dimensions $dimensions,Weight|int|string|array $weight=0,int $quantity=1,array $allowedRotations=[Rotation::LWH,Rotation::LHW,Rotation::WLH,Rotation::WHL,Rotation::HLW,Rotation::HWL],bool $keepUpright=false,bool $stackable=true,bool $mustBeOnFloor=false,Weight|int|string|array|null $maxTopLoad=null,float $minimumSupportRatio=0.0,?string $group=null,array $tags=[],array $incompatibleTags=[],int $priority=0,array $metadata=[],?int $maxStackedItems=null,array $eligibleContainerTags=[],?string $groundContactRule=null,?Length $nestingHeight=null,?int $stopIndex=null,?int $value=null,ShapeType $shapeType=ShapeType::RIGID_CUBOID,?array $hullVertices=null,?int $compressionRatioPpm=null,?int $maxCompressionPressureKpa=null,?string $stackingGroup=null,array $acceptsStackingGroups=[]):self{return new self($id,$dimensions,Weight::parse($weight),$quantity,$allowedRotations,$keepUpright,$stackable,$mustBeOnFloor,$maxTopLoad===null?null:Weight::parse($maxTopLoad),$minimumSupportRatio,$group,$tags,$incompatibleTags,$priority,$metadata,$maxStackedItems,$eligibleContainerTags,$groundContactRule,$nestingHeight,$stopIndex,$value,$shapeType,$hullVertices,$compressionRatioPpm,$maxCompressionPressureKpa,$stackingGroup,$acceptsStackingGroups);} /** * Admit this item's shape, or refuse it with the reason. * @@ -108,7 +118,21 @@ private static function admitShape(ShapeType $shapeType,?array $hullVertices,?in */ public function isStackSensitive():bool { - return !$this->stackable||$this->maxTopLoad!==null||$this->maxStackedItems!==null||$this->maxCompressionPressureKpa!==null; + // A stacking group alone does not count: such an item is refused only by a + // constrained item beneath it, which already switched the graph on. + return !$this->stackable||$this->acceptsStackingGroups!==[]||$this->maxTopLoad!==null||$this->maxStackedItems!==null||$this->maxCompressionPressureKpa!==null; + } + + /** Whether an item of `$group` may rest directly on this one, ignoring `stackable`. O(1). */ + public function acceptsStackingGroup(?string $group):bool + { + return $this->acceptsStackingGroups===[]||($group!==null&&isset($this->acceptedStackingGroups[$group])); + } + + /** Whether a column of this one item type passes every stacking edge. */ + public function carriesItself():bool + { + return $this->stackable&&$this->acceptsStackingGroup($this->stackingGroup); } /** @return list */ public function instances():array{$out=[];for($i=1;$i<=$this->quantity;$i++)$out[]=new ItemInstance($this,$i);return $out;} diff --git a/src/Domain/MadeToMeasure.php b/src/Domain/MadeToMeasure.php new file mode 100644 index 0000000..2bd303a --- /dev/null +++ b/src/Domain/MadeToMeasure.php @@ -0,0 +1,159 @@ +$name){ + if($this->minimum[$axis]>$maximum[$axis])throw new InvalidArgumentException("made_to_measure minimum {$name} exceeds inner_dimensions"); + if(($maximum[$axis]-$this->minimum[$axis])%$this->increment[$axis]!==0)throw new InvalidArgumentException("made_to_measure increment {$name} does not divide inner_dimensions minus minimum"); + } + } + + /** The smallest cuttable size on `$axis` that is at least `$value`. */ + public function grid(int $axis,int $value):int + { + $minimum=$this->minimum[$axis];$step=$this->increment[$axis]; + return $minimum+intdiv(max($value,$minimum)-$minimum+$step-1,$step)*$step; + } + + /** `grid`, capped at the machine maximum: sizes a solving envelope, never a box. */ + public function clamp(int $axis,int $value,int $maximum):int{return min($maximum,$this->grid($axis,$value));} + + /** The inner surface of a closed box, 2(LW + LH + WH), in square ticks. @param array{0:int,1:int,2:int} $sides */ + public static function surfaceArea(array $sides):string + { + [$l,$w,$h]=$sides; + return BigInt::multiply('2',BigInt::add(BigInt::add(BigInt::multiply($l,$w),BigInt::multiply($l,$h)),BigInt::multiply($w,$h))); + } + + /** + * ceil(rate * area / 1 m^2), as `p*q + ceil(p*r / T^2)` with `q, r = divmod(area, T^2)` -- + * the split Rust needs to stay inside i128, kept here so the engines share one formula. + */ + public static function perSquareMetre(int $rate,string $area):string + { + $whole=BigInt::divide($area,self::SQUARE_METRE_TICKS2); + $fraction=BigInt::subtract($area,BigInt::multiply($whole,self::SQUARE_METRE_TICKS2)); + $numerator=BigInt::multiply($rate,$fraction); + $part=BigInt::divide($numerator,self::SQUARE_METRE_TICKS2); + if(BigInt::compare(BigInt::multiply($part,self::SQUARE_METRE_TICKS2),$numerator)<0)$part=BigInt::add($part,'1'); + return BigInt::add(BigInt::multiply($rate,$whole),$part); + } + + /** + * A box's price: the container's own fee plus its material at `$priceMinor` per square + * metre, rounded up. Cost grows with every side, so the machine maximum bounds them all. + * + * @param array{0:int,1:int,2:int} $sides + */ + public static function boxCostFor(int $priceMinor,int $feeMinor,array $sides):string + { + return BigInt::add((string)$feeMinor,self::perSquareMetre($priceMinor,self::surfaceArea($sides))); + } + + /** @param array{0:int,1:int,2:int} $sides */ + public function boxCostMinor(int $feeMinor,array $sides):int{return (int)self::boxCostFor($this->costPerSquareMetreMinor,$feeMinor,$sides);} + + /** The fabricated box's weight: the declared tare plus its board, rounded up. @param array{0:int,1:int,2:int} $sides */ + public function boxTareTicks(int $declaredTare,array $sides):int + { + return (int)BigInt::add((string)$declaredTare,self::perSquareMetre($this->tarePerSquareMetre,self::surfaceArea($sides))); + } + + /** The smallest non-negative c with c^3 >= value: doubling, then bisection, O(log value) steps. */ + public static function icbrtCeil(string $value):string + { + $cube=static fn(string $x):string=>BigInt::multiply(BigInt::multiply($x,$x),$x); + $high='1'; + while(BigInt::compare($cube($high),$value)<0)$high=BigInt::multiply($high,'2'); + $low='0'; + while(BigInt::compare($low,$high)<0){ + $middle=BigInt::divide(BigInt::add($low,$high),'2'); + if(BigInt::compare($cube($middle),$value)>=0)$high=$middle;else $low=BigInt::add($middle,'1'); + } + return $low; + } + + /** + * The rungs one trial tries, ascending on every axis, the machine maximum last. + * + * `$edges` are each remaining instance's envelope edges (nominal plus twice the clearance). + * O(r) over the r instances plus the cube root; the list depends only on their multiset. + * + * @param array{0:int,1:int,2:int} $maximum @param list $edges + * @return list + */ + public function solvingEnvelopes(array $maximum,array $edges):array + { + $volume='0';$floors=[0,0,0]; + foreach($edges as $instance){ + $volume=BigInt::add($volume,BigInt::multiply(BigInt::multiply($instance[0],$instance[1]),$instance[2])); + $ranked=$instance;rsort($ranked); + for($rank=0;$rank<3;$rank++)$floors[$rank]=max($floors[$rank],$ranked[$rank]); + } + $side=self::icbrtCeil($volume); + $rungs=[]; + foreach(self::RUNG_FACTORS as [$numerator,$denominator]){ + $scaled=(int)BigInt::divide(BigInt::add(BigInt::multiply($side,$numerator),(string)($denominator-1)),(string)$denominator); + $rung=[]; + for($axis=0;$axis<3;$axis++)$rung[]=$this->clamp($axis,max($scaled,$floors[$axis]),$maximum[$axis]); + if(BigInt::compare(BigInt::multiply(BigInt::multiply($rung[0],$rung[1]),$rung[2]),$volume)<0||in_array($rung,$rungs,true))continue; + $rungs[]=$rung; + } + if(!in_array($maximum,$rungs,true))$rungs[]=$maximum; + return $rungs; + } + + /** + * Each instance's envelope edges, the input `solvingEnvelopes` sizes rungs from. + * + * @param list $items @return list + */ + public static function instanceEdges(array $items,int $clearanceTicks):array + { + $grow=2*$clearanceTicks; + return array_map(static function(ItemInstance $item)use($grow):array{$d=$item->dimensions();return [$d->length->ticks+$grow,$d->width->ticks+$grow,$d->height->ticks+$grow];},$items); + } +} diff --git a/src/Domain/Nesting.php b/src/Domain/Nesting.php index 309e7b5..f1266ee 100644 --- a/src/Domain/Nesting.php +++ b/src/Domain/Nesting.php @@ -101,6 +101,23 @@ public static function occupiedVolume(Placement $placement): string return BigInt::multiply((string)$footprint, (string)$height); } + /** + * The volume `occupiedVolume` counts for this item before it is placed, in any orientation. + * + * A hull occupies its authored solid and a proper rotation keeps that volume, so one + * orientation answers for all six through the memoised shape. A compressible item keeps + * its declared box: collision and support use the uncompressed box, so placed boxes never + * share space and their declared volumes stay additive. + */ + public static function itemOccupiedVolume(ItemInstance $instance): string + { + $item = $instance->item; + if ($item->shapeType === ShapeType::CONVEX_HULL) { + return HullShape::shapeFor($item->hullVertices, Rotation::LWH)->volume; + } + return $instance->dimensions()->volumeString(); + } + /** * Physical volume actually occupied by `$placements`, nesting overlap removed. * diff --git a/src/Domain/PackedContainer.php b/src/Domain/PackedContainer.php index ffbad3e..8cbfc82 100644 --- a/src/Domain/PackedContainer.php +++ b/src/Domain/PackedContainer.php @@ -72,11 +72,29 @@ public function expandPlacements(): array return $this->latticeSummary !== null ? $this->latticeSummary->expand($this->latticeItems) : $this->placements; } + /** + * The largest envelope x2, y2 and z2 of its placements: a flat bag's conformed package + *, or a made-to-measure box's extent before it is rounded onto the machine grid + *; null for any other container. O(p). + */ + public function achievedDimensions():?Dimensions + { + if(!$this->container->isFlatBag()&&$this->container->madeToMeasure===null)return null; + return FlatBag::asDimensions(FlatBag::extentOf($this->placements)); + } + + /** What a carrier measures: a bag's achieved package, else the declared outer size. */ + public function billedDimensions():Dimensions + { + $achieved=$this->container->isFlatBag()?$this->achievedDimensions():null; + return $achieved??$this->container->outerDimensions??$this->container->innerDimensions; + } + public function asItem(?string $id=null,bool $keepUpright=true,?Weight $maxTopLoad=null):Item { return Item::create( $id??$this->id(), - $this->container->outerDimensions??$this->container->innerDimensions, + $this->billedDimensions(), $this->grossWeight(), 1, Rotation::all(), diff --git a/src/Explain/Explain.php b/src/Explain/Explain.php index 2fad217..fcb30ed 100644 --- a/src/Explain/Explain.php +++ b/src/Explain/Explain.php @@ -58,6 +58,8 @@ final class Explain 'was not placed because the exact search ended before proving a final answer', 'container_inventory_exhausted' => 'requires another compatible container, but the declared inventory is exhausted', + 'axle_overloaded' => + 'would overload an axle wherever it stood alone in any container that otherwise admits it', ]; /** diff --git a/src/Objective/LandedCostSolutionScorer.php b/src/Objective/LandedCostSolutionScorer.php index 889ac74..1e65866 100644 --- a/src/Objective/LandedCostSolutionScorer.php +++ b/src/Objective/LandedCostSolutionScorer.php @@ -51,7 +51,7 @@ public function score(RawSolution $solution): ObjectiveScore . "'{$container->container->id}' has none", ); } - $dimensions = $container->container->outerDimensions ?? $container->container->innerDimensions; + $dimensions = $container->billedDimensions(); $dimensionalWeight = $dimensions->dimensionalWeight($this->divisor, $this->lengthUnit, $this->weightUnit); $billedTicks = max($container->grossWeight()->ticks, $dimensionalWeight->ticks); $charge = $table->chargeMinorOrNull(self::grams($billedTicks)); @@ -82,7 +82,7 @@ public static function unpriceableContainer(array $containers, PackingConfig $co return null; } foreach ($containers as $container) { - $dimensions = $container->container->outerDimensions ?? $container->container->innerDimensions; + $dimensions = $container->billedDimensions(); $dimensional = $dimensions->dimensionalWeight( $config->dimensionalWeightDivisor, $config->dimensionalWeightLengthUnit, diff --git a/src/Objective/MaximumVolumeSolutionScorer.php b/src/Objective/MaximumVolumeSolutionScorer.php new file mode 100644 index 0000000..65b53d0 --- /dev/null +++ b/src/Objective/MaximumVolumeSolutionScorer.php @@ -0,0 +1,55 @@ +score($solution)->components; + $unpackedVolume = '0'; + foreach ($solution->unpacked as $item) { + $unpackedVolume = BigInt::add($unpackedVolume, $item->instance->dimensions()->volumeString()); + } + $requested = $unpackedVolume; + foreach ($solution->containers as $container) { + $instances = $container->latticeItems !== [] + ? $container->latticeItems + : array_map(static fn($placement) => $placement->instance, $container->placements); + foreach ($instances as $instance) { + $requested = BigInt::add($requested, $instance->dimensions()->volumeString()); + } + } + return new ObjectiveScore([self::ceilingPpm($unpackedVolume, $requested), $unpacked, $containers, $cost, $unused]); + } + + private static function ceilingPpm(string $part, string $whole): int + { + if (BigInt::compare($whole, '0') === 0) { + return 0; + } + $rounded = BigInt::add(BigInt::multiply($part, (string)self::SCALE), BigInt::subtract($whole, '1')); + return (int)BigInt::divide($rounded, $whole); + } +} diff --git a/src/Objective/ObjectiveRegistry.php b/src/Objective/ObjectiveRegistry.php index 11c1ac9..4a39e35 100644 --- a/src/Objective/ObjectiveRegistry.php +++ b/src/Objective/ObjectiveRegistry.php @@ -28,6 +28,7 @@ public static function resolve(string $name, ?PackingConfig $config = null): Sol 'lowest_landed_cost' => LandedCostSolutionScorer::fromConfig(...), '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(), ]; $factory = self::$factories[$name] ?? null; if ($factory === null) { diff --git a/src/Objective/ShippingCostSolutionScorer.php b/src/Objective/ShippingCostSolutionScorer.php index cfd897f..5fce2e4 100644 --- a/src/Objective/ShippingCostSolutionScorer.php +++ b/src/Objective/ShippingCostSolutionScorer.php @@ -58,7 +58,7 @@ public function score(RawSolution $solution): ObjectiveScore $billable = 0; foreach ($solution->containers as $container) { - $dimensions = $container->container->outerDimensions ?? $container->container->innerDimensions; + $dimensions = $container->billedDimensions(); $dimensionalWeight = $dimensions->dimensionalWeight($this->divisor, $this->lengthUnit, $this->weightUnit); $billable += max($container->grossWeight()->ticks, $dimensionalWeight->ticks); } diff --git a/src/Packer.php b/src/Packer.php index 8d83832..608e8f7 100644 --- a/src/Packer.php +++ b/src/Packer.php @@ -4,7 +4,7 @@ namespace Packvium; use Packvium\Algorithm\{Deadline, FixedPlacementAdmission, SolverOrchestrator}; -use Packvium\Support\StableSorter; +use Packvium\Support\{StableSorter, UnsupportedPlacements}; use Packvium\Config\PackingConfig; use Packvium\Domain\{Container, FixedPlacement, Item, PackingRequest, UnratedWeightException}; use Packvium\Extension\ExtensionRegistry; @@ -117,6 +117,10 @@ public function pack(array $items, array $containers, array $fixedPlacements = [ } } } + $unsupported = UnsupportedPlacements::warning($raw->containers, $this->config->minimumSupportRatio); + if ($unsupported !== null) { + $warnings[] = $unsupported; + } $starts = []; $winnerMarked = false; foreach ($portfolio->starts as $record) { diff --git a/src/Result/PackingResult.php b/src/Result/PackingResult.php index d06ea0f..d18d2cf 100644 --- a/src/Result/PackingResult.php +++ b/src/Result/PackingResult.php @@ -4,7 +4,8 @@ namespace Packvium\Result; use Packvium\Constraint\{AxleLoad, LoadCalculator, VolumeReserve}; -use Packvium\Domain\{PackedContainer, UnpackedItem}; +use Packvium\Domain\{Dimensions, PackedContainer, Point, UnpackedItem}; +use Packvium\Unit\Length; final readonly class PackingResult { @@ -88,6 +89,15 @@ public function toArray( string $weightUnit = 'g', bool $includeAlternatives = true, ): array { + // Equal quantities share one array: placements repeat a type's dimensions, a lattice + // coordinate and a zero top load, and a shared array serializes to the same bytes. + $shared = ['length' => [], 'weight' => [], 'dimensions' => []]; + return $this->serialized($lengthUnit, $weightUnit, $includeAlternatives, $shared); + } + + /** @param array{length:array,weight:array,dimensions:array>>} $shared */ + private function serialized(string $lengthUnit, string $weightUnit, bool $includeAlternatives, array &$shared): array + { $containers = []; foreach ($this->containers as $container) { $placements = []; @@ -95,11 +105,11 @@ public function toArray( $placements[] = [ 'item_id' => $placement->instance->id(), 'item_type' => $placement->instance->item->id, - 'position' => $placement->position->toArray($lengthUnit), - 'dimensions' => $placement->dimensions->toArray($lengthUnit), + 'position' => self::point($placement->position, $lengthUnit, $shared), + 'dimensions' => self::dimensions($placement->dimensions, $lengthUnit, $shared), 'orientation' => $placement->rotation->value, 'support_ratio' => sprintf('%.6f', $placement->supportRatio), - 'top_load' => $placement->topLoad->toArray($weightUnit), + 'top_load' => $shared['weight'][$placement->topLoad->ticks] ??= $placement->topLoad->toArray($weightUnit), ]; // Absent unless true, so a request without fixed placements keeps its bytes. if ($placement->fixed) { @@ -120,6 +130,20 @@ public function toArray( 'void_fill_reserve_ticks3' => VolumeReserve::reserved($container->container), 'placements' => $placements, ]; + // Present exactly when the container conforms to its contents, so a + // rigid container's bytes are unchanged. + $achieved = $container->achievedDimensions(); + if ($achieved !== null) { + $serialized['achieved_dimensions'] = $achieved->toArray($lengthUnit); + } + // A packed made-to-measure container is the fabricated box, so its own price and + // tare are the box's; absent for every other container. + if ($container->container->madeToMeasure !== null) { + $serialized['made_to_measure'] = [ + 'cost_minor' => $container->container->costMinor, + 'tare_weight' => $container->container->tareWeight->toArray($weightUnit), + ]; + } if ($container->latticeSummary !== null) { // Compact form: when `configuration.require_placement_coordinates` // was false and GridSolver's lattice fast path applied, `placements` stays @@ -168,6 +192,13 @@ public function toArray( ]; } + $alternatives = []; + if ($includeAlternatives) { + foreach ($this->alternatives as $alternative) { + $alternatives[] = $alternative->serialized($lengthUnit, $weightUnit, false, $shared); + } + } + return [ 'status' => $this->status->value, 'feasibility' => $this->feasibility->toArray(), @@ -196,9 +227,23 @@ public function toArray( 'unpacked_items' => $unpacked, 'catalog_versions_used' => [], 'warnings' => $this->warnings, - 'alternatives' => $includeAlternatives - ? array_map(fn(self $alternative) => $alternative->toArray($lengthUnit, $weightUnit, false), $this->alternatives) - : [], + 'alternatives' => $alternatives, ]; } + + /** `Point::toArray`, from shared length arrays. */ + private static function point(Point $point, string $unit, array &$shared): array + { + return [ + 'x' => $shared['length'][$point->x] ??= (new Length($point->x))->toArray($unit), + 'y' => $shared['length'][$point->y] ??= (new Length($point->y))->toArray($unit), + 'z' => $shared['length'][$point->z] ??= (new Length($point->z))->toArray($unit), + ]; + } + + /** `Dimensions::toArray`, one shared array per distinct size. */ + private static function dimensions(Dimensions $dimensions, string $unit, array &$shared): array + { + return $shared['dimensions'][$dimensions->length->ticks][$dimensions->width->ticks][$dimensions->height->ticks] ??= $dimensions->toArray($unit); + } } diff --git a/src/Sequence/LoadingDependencyGraph.php b/src/Sequence/LoadingDependencyGraph.php index f8b5af3..2276bc2 100644 --- a/src/Sequence/LoadingDependencyGraph.php +++ b/src/Sequence/LoadingDependencyGraph.php @@ -207,6 +207,13 @@ public static function verifyLoadingPrefixBusinessRules(array $placements, array throw new SequenceReplayError(-1, -1, 'order is not a permutation of every placement index exactly once'); } $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; + foreach ($placements as $placement) { + $grouped = $grouped || $placement->instance->item->acceptsStackingGroups !== []; + } $present = []; foreach ($order as $step => $index) { $present[] = $placements[$index]; @@ -223,6 +230,10 @@ public static function verifyLoadingPrefixBusinessRules(array $placements, array } } } + if ($problem === null && $grouped) { + $last = count($present) - 1; + $problem = (new LoadSupportGraph($units))->nonStackableFailure($present, $present[$last]->instance, $last); + } if ($problem === null) { $candidate = $present[count($present) - 1]; $rule = $candidate->instance->item->groundContactRule; diff --git a/src/Sequence/UnloadingDependencyGraph.php b/src/Sequence/UnloadingDependencyGraph.php index a67e9fa..1dc4f7a 100644 --- a/src/Sequence/UnloadingDependencyGraph.php +++ b/src/Sequence/UnloadingDependencyGraph.php @@ -88,24 +88,28 @@ public static function safeRemovalOrder(array $boxes, Dimensions $container, arr $present = array_fill_keys(array_keys($boxes), true); $order = []; while ($present !== []) { - $removable = []; + $unblocked = []; foreach (array_keys($present) as $index) { $blockedBySupport = false; foreach (array_keys($dependsOn[$index] ?? []) as $dependency) { if (isset($present[$dependency])) { $blockedBySupport = true; break; } } if ($blockedBySupport) { continue; } + $unblocked[] = $index; + } + sort($unblocked); + $chosen = null; + foreach ($unblocked as $index) { if (SequenceGeometry::clearDirection($index, $boxes[$index], $boxes, $present, $container, $directions) !== null) { - $removable[] = $index; + $chosen = $index; + break; } } - if ($removable === []) { + if ($chosen === null) { throw new SequenceError(array_keys($present)); } // Deterministic: the lowest index among this step's candidates, not // arbitrary array iteration order. - sort($removable); - $chosen = $removable[0]; $order[] = $chosen; unset($present[$chosen]); } @@ -158,24 +162,28 @@ public static function safeRouteRemovalOrder(array $boxes, array $stops, Dimensi if ($stops[$index] === $stop) { $due[$index] = true; } } while ($due !== []) { - $removable = []; + $unblocked = []; foreach (array_keys($due) as $index) { $blockedBySupport = false; foreach (array_keys($dependsOn[$index] ?? []) as $dependency) { if (isset($remaining[$dependency])) { $blockedBySupport = true; break; } } if ($blockedBySupport) { continue; } + $unblocked[] = $index; + } + sort($unblocked); + $chosen = null; + foreach ($unblocked as $index) { if (SequenceGeometry::clearDirection($index, $boxes[$index], $boxes, $remaining, $container, $directions) !== null) { - $removable[] = $index; + $chosen = $index; + break; } } - if ($removable === []) { + if ($chosen === null) { throw new RouteSequenceError($stop, array_keys($due)); } // Deterministic: the lowest index among this step's candidates, not // arbitrary array iteration order. - sort($removable); - $chosen = $removable[0]; $order[] = $chosen; unset($remaining[$chosen]); unset($due[$chosen]); diff --git a/src/Serialization/ArrayCodec.php b/src/Serialization/ArrayCodec.php index 74f8567..96c15cf 100644 --- a/src/Serialization/ArrayCodec.php +++ b/src/Serialization/ArrayCodec.php @@ -5,11 +5,11 @@ use InvalidArgumentException; use Packvium\Algorithm\EffortBudget; use Packvium\Config\{PackingConfig,SolverProfile}; -use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,Item,Obstacle,Point,RateTable,Rotation,ShapeType}; +use Packvium\Domain\{Axle,AxisAlignedBox,Compression,Container,Dimensions,FixedPlacement,Item,MadeToMeasure,Obstacle,Point,RateTable,Rotation,ShapeType}; use Packvium\Extension\ExtensionRegistry; use Packvium\Packer; use Packvium\Policy\PolicyRuleSet; -use Packvium\Support\{FixedPlacementShape,JsonValue,RequestRules}; +use Packvium\Support\{FixedPlacementShape,JsonValue,MeasureReading,RequestRules}; use Packvium\Unit\{Length,Weight}; use Throwable; use TypeError; @@ -103,6 +103,7 @@ public static function rejectUnsupported(array $data,?array $unsupported=null,?a } } } + foreach(self::madeToMeasureCombinations($data) as $name)$found[$name]=true; foreach(self::entries($data,'items') as $entry){ if(!is_array($entry))continue; $shape=$entry['shape_type']??null; @@ -118,6 +119,36 @@ public static function rejectUnsupported(array $data,?array $unsupported=null,?a ); } + /** + * The made-to-measure combinations 1.6 refuses (D10, docs/MADE-TO-MEASURE-CONTAINERS.md). + * Each reads a container dimension or position the fabricated box does not keep. Checked on + * the raw request, before any request error. O(containers + fixed placements). + * + * @param array $data + * @return list + */ + public static function madeToMeasureCombinations(array $data):array + { + $found=[];$measured=[]; + foreach(self::entries($data,'containers') as $entry){ + if(!is_array($entry)||($entry['made_to_measure']??null)===null)continue; + if(is_string($entry['id']??null))$measured[$entry['id']]=true; + if(($entry['axles']??null)!==null)$found['container.made_to_measure+axles']=true; + $obstacles=$entry['obstacles']??null; + if(JsonValue::isList($obstacles)&&$obstacles!==[])$found['container.made_to_measure+obstacles']=true; + $reserve=$entry['void_fill_reserve_ratio']??null; + if((is_int($reserve)||is_float($reserve))&&$reserve>0)$found['container.made_to_measure+void_fill_reserve_ratio']=true; + } + $fixed=$data['fixed_placements']??null; + if($measured!==[]&&is_array($fixed)){ + foreach($fixed as $entry){ + $type=is_array($entry)?($entry['container_type']??null):null; + if(is_string($type)&&isset($measured[$type])){$found['fixed_placements+container.made_to_measure']=true;break;} + } + } + return array_keys($found); + } + /** @return array a collection to scan, or nothing when it is not one */ private static function entries(array $data,string $collection):array{$entries=$data[$collection]??[];return is_array($entries)?$entries:[];} @@ -218,7 +249,8 @@ private static function catalogVersionsUsed(mixed $raw):array private static function item(array $r,string $unit):Item{$rot=array_map(fn($v)=>Rotation::from($v),$r['allowed_rotations']??array_map(fn($x)=>$x->value,Rotation::all()));return new Item((string)$r['id'],Dimensions::fromArray($r['dimensions'],$unit),Weight::parse($r['weight']??0), (int)($r['quantity']??1),$rot,(bool)($r['keep_upright']??false),(bool)($r['stackable']??true),(bool)($r['must_be_on_floor']??false),isset($r['max_top_load'])?Weight::parse($r['max_top_load']):null,(float)($r['minimum_support_ratio']??0),$r['group']??null,$r['tags']??[],$r['incompatible_tags']??[],(int)($r['priority']??0),$r['metadata']??[],isset($r['max_stacked_items'])?(int)$r['max_stacked_items']:null,$r['eligible_container_tags']??[],$r['ground_contact_rule']??null,isset($r['nesting_height'])?Length::parse($r['nesting_height'],$unit):null,isset($r['stop_index'])?(int)$r['stop_index']:null,isset($r['value'])?(int)$r['value']:null, ShapeType::from((string)($r['shape_type']??ShapeType::RIGID_CUBOID->value)),self::hullVertices($r['hull_vertices']??null,$unit), isset($r['compression_ratio'])?Compression::ratioToPpm((float)$r['compression_ratio']):null, - isset($r['max_compression_pressure_kpa'])?(int)$r['max_compression_pressure_kpa']:null);} + isset($r['max_compression_pressure_kpa'])?(int)$r['max_compression_pressure_kpa']:null, + $r['stacking_group']??null,$r['accepts_stacking_groups']??[]);} /** * Parse `hull_vertices` into the integer tick frame before any geometry runs. @@ -251,6 +283,17 @@ private static function box(array $r,string $unit):AxisAlignedBox{return new Axi * @param array $r */ private static function fixedPlacement(array $r,string $unit):FixedPlacement{return new FixedPlacement($r['item_type'],$r['container_type'],self::point($r['position']??[],$unit),Rotation::from($r['orientation']),array_key_exists('container_instance',$r)?(int)JsonValue::integer($r['container_instance']):1);} - private static function container(array $r,string $unit):Container{$obs=[];foreach($r['obstacles']??[] as $o){$additional=array_map(fn($b)=>self::box($b,$unit),$o['additional_boxes']??[]);$obs[]=new Obstacle((string)$o['id'],self::box($o,$unit),$additional);}return new Container((string)$r['id'],Dimensions::fromArray($r['inner_dimensions'],$unit),isset($r['outer_dimensions'])?Dimensions::fromArray($r['outer_dimensions'],$unit):null,Weight::parse($r['tare_weight']??0),isset($r['max_payload'])?Weight::parse($r['max_payload']):null,(int)($r['cost_minor']??0),isset($r['quantity'])?(int)$r['quantity']:null,$obs,$r['tags']??[],isset($r['max_items'])?(int)$r['max_items']:null,$r['metadata']??[],(float)($r['void_fill_reserve_ratio']??0),array_map(static fn($v)=>(int)$v,$r['tag_limits']??[]),isset($r['max_stack_density'])?Weight::parse($r['max_stack_density']):null,self::axles($r['axles']??null,$unit),self::rateTable($r['rate_table']??null),array_map(static fn($d)=>(string)$d,$r['access_directions']??[]));} + private static function container(array $r,string $unit):Container{$obs=[];foreach($r['obstacles']??[] as $o){$additional=array_map(fn($b)=>self::box($b,$unit),$o['additional_boxes']??[]);$obs[]=new Obstacle((string)$o['id'],self::box($o,$unit),$additional);}return new Container((string)$r['id'],Dimensions::fromArray($r['inner_dimensions'],$unit),isset($r['outer_dimensions'])?Dimensions::fromArray($r['outer_dimensions'],$unit):null,Weight::parse($r['tare_weight']??0),isset($r['max_payload'])?Weight::parse($r['max_payload']):null,(int)($r['cost_minor']??0),isset($r['quantity'])?(int)$r['quantity']:null,$obs,$r['tags']??[],isset($r['max_items'])?(int)$r['max_items']:null,$r['metadata']??[],(float)($r['void_fill_reserve_ratio']??0),array_map(static fn($v)=>(int)$v,$r['tag_limits']??[]),isset($r['max_stack_density'])?Weight::parse($r['max_stack_density']):null,self::axles($r['axles']??null,$unit),self::rateTable($r['rate_table']??null),array_map(static fn($d)=>(string)$d,$r['access_directions']??[]),[],isset($r['deformable_boundary'])?(string)$r['deformable_boundary']['kind']:null,self::madeToMeasure($r['made_to_measure']??null,$unit));} + /** @param array|null $r */ + private static function madeToMeasure(?array $r,string $unit):?MadeToMeasure + { + if($r===null)return null; + $sides=static function($value)use($unit):array{ + if($value===null)return [0,0,0]; + return array_map(static fn(string $axis):int=>MeasureReading::ticks($value[$axis],Length::class,$unit),['length','width','height']); + }; + $tare=$r['tare_per_square_metre']??null; + return new MadeToMeasure($sides($r['minimum']??null),$sides($r['increment']??null),(int)($r['cost_per_square_metre_minor']??0),$tare===null?0:MeasureReading::ticks($tare,Weight::class,'g'),$sides($r['outer_allowance']??null)); + } private static function rateTable(?array $r):?RateTable{if($r===null)return null;return new RateTable(array_map('intval',$r['weight_brackets_g']),array_map('intval',$r['prices_minor']),(int)($r['minimum_charge_minor']??0),(int)($r['fuel_surcharge_permille']??0));} } diff --git a/src/Support/BigInt.php b/src/Support/BigInt.php index 0049c0e..d8fd689 100644 --- a/src/Support/BigInt.php +++ b/src/Support/BigInt.php @@ -11,14 +11,23 @@ */ final class BigInt { + /** Decimal digits of one limb: a limb product plus two limbs stays below PHP_INT_MAX. */ + private const LIMB_DIGITS=9; + private const LIMB=1_000_000_000; + /** Digits of the largest value whose sum or product with another of its size is a native integer. */ + private const NATIVE_DIGITS=18; + public static function add(string $a, string $b): string { - $i = strlen($a) - 1; $j = strlen($b) - 1; $carry = 0; $out = ''; - while ($i >= 0 || $j >= 0 || $carry > 0) { - $sum = ($i >= 0 ? ord($a[$i--]) - 48 : 0) + ($j >= 0 ? ord($b[$j--]) - 48 : 0) + $carry; - $out = (string)($sum % 10) . $out; $carry = intdiv($sum, 10); + if (strlen($a) <= self::NATIVE_DIGITS && strlen($b) <= self::NATIVE_DIGITS) { return (string)((int)$a + (int)$b); } + $x = self::limbs($a); $y = self::limbs($b); $sum = []; $carry = 0; + for ($i = 0, $n = max(count($x), count($y)); $i < $n; ++$i) { + $limb = ($x[$i] ?? 0) + ($y[$i] ?? 0) + $carry; + $carry = $limb >= self::LIMB ? 1 : 0; + $sum[] = $limb - $carry * self::LIMB; } - return ltrim($out, '0') ?: '0'; + if ($carry > 0) { $sum[] = $carry; } + return self::fromLimbs($sum); } /** @@ -43,16 +52,21 @@ public static function chunks(string $value, int $groups = 6, int $width = 15): public static function multiply(string|int $a, string|int $b): string { - $a = ltrim((string)$a, '0') ?: '0'; $b = ltrim((string)$b, '0') ?: '0'; - if ($a === '0' || $b === '0') { return '0'; } - $digits = array_fill(0, strlen($a) + strlen($b), 0); - for ($i = strlen($a)-1; $i >= 0; --$i) { - for ($j = strlen($b)-1; $j >= 0; --$j) { - $p = (ord($a[$i])-48) * (ord($b[$j])-48) + $digits[$i+$j+1]; - $digits[$i+$j+1] = $p % 10; $digits[$i+$j] += intdiv($p,10); + $a = (string)$a; $b = (string)$b; + if (strlen($a) + strlen($b) <= self::NATIVE_DIGITS) { return (string)((int)$a * (int)$b); } + $x = self::limbs($a); $y = self::limbs($b); + $product = array_fill(0, count($x) + count($y), 0); + foreach ($x as $i => $left) { + if ($left === 0) { continue; } + $carry = 0; + foreach ($y as $j => $right) { + $limb = $product[$i + $j] + $left * $right + $carry; + $carry = intdiv($limb, self::LIMB); + $product[$i + $j] = $limb - $carry * self::LIMB; } + $product[$i + count($y)] += $carry; } - return ltrim(implode('', $digits), '0') ?: '0'; + return self::fromLimbs($product); } /** Compare two non-negative decimal strings: -1, 0 or 1. */ @@ -74,13 +88,14 @@ public static function subtract(string|int $a, string|int $b): string if (self::compare($a, $b) < 0) { throw new \InvalidArgumentException("BigInt::subtract would be negative: {$a} - {$b}"); } - $i = strlen($a) - 1; $j = strlen($b) - 1; $borrow = 0; $out = ''; - while ($i >= 0) { - $digit = (ord($a[$i--]) - 48) - $borrow - ($j >= 0 ? ord($b[$j--]) - 48 : 0); - if ($digit < 0) { $digit += 10; $borrow = 1; } else { $borrow = 0; } - $out = (string)$digit . $out; + if (strlen($a) <= self::NATIVE_DIGITS) { return (string)((int)$a - (int)$b); } + $x = self::limbs($a); $y = self::limbs($b); $difference = []; $borrow = 0; + foreach ($x as $i => $limb) { + $limb -= ($y[$i] ?? 0) + $borrow; + $borrow = $limb < 0 ? 1 : 0; + $difference[] = $limb + $borrow * self::LIMB; } - return ltrim($out, '0') ?: '0'; + return self::fromLimbs($difference); } /** @@ -93,6 +108,42 @@ public static function divide(string|int $a, string|int $b): string $a = self::normalize($a); $b = self::normalize($b); if ($b === '0') { throw new \DivisionByZeroError('BigInt::divide by zero'); } if (self::compare($a, $b) < 0) { return '0'; } + if (strlen($a) <= self::NATIVE_DIGITS) { return (string)intdiv((int)$a, (int)$b); } + if (strlen($b) <= self::LIMB_DIGITS) { return self::divideByLimb($a, (int)$b); } + return self::divideByEstimate($a, $b); + } + + /** Short division by a divisor below one limb: each step divides a value below LIMB^2. */ + private static function divideByLimb(string $a, int $b): string + { + $quotient = []; $remainder = 0; + foreach (array_reverse(self::limbs($a)) as $limb) { + $remainder = $remainder * self::LIMB + $limb; + $quotient[] = intdiv($remainder, $b); + $remainder %= $b; + } + return self::fromLimbs(array_reverse($quotient)); + } + + /** + * A float quotient corrected until q * b <= a < (q + 1) * b, which only the floor meets. + * + * Below 2^50 the float estimate is within a few units of the floor, so the correction + * takes a step or two; a larger quotient falls back to digit-by-digit long division. + */ + private static function divideByEstimate(string $a, string $b): string + { + $estimate = floor((float)$a / (float)$b); + if (!($estimate < 2 ** 50)) { return self::longDivide($a, $b); } + $quotient = (int)$estimate; + $product = self::multiply($quotient, $b); + while (self::compare($product, $a) > 0) { --$quotient; $product = self::subtract($product, $b); } + while (self::compare($next = self::add($product, $b), $a) <= 0) { ++$quotient; $product = $next; } + return (string)$quotient; + } + + private static function longDivide(string $a, string $b): string + { $quotient = ''; $remainder = '0'; for ($i = 0, $n = strlen($a); $i < $n; ++$i) { // Schoolbook long division: shift the next digit in, then find the largest @@ -109,6 +160,27 @@ public static function divide(string|int $a, string|int $b): string return ltrim($quotient, '0') ?: '0'; } + /** @return list The value's base-LIMB digits, least significant first. */ + private static function limbs(string $digits): array + { + $limbs = []; + for ($end = strlen($digits); $end > 0; $end -= self::LIMB_DIGITS) { + $start = $end > self::LIMB_DIGITS ? $end - self::LIMB_DIGITS : 0; + $limbs[] = (int)substr($digits, $start, $end - $start); + } + return $limbs; + } + + /** @param non-empty-list $limbs Least significant first. */ + private static function fromLimbs(array $limbs): string + { + $top = count($limbs) - 1; + while ($top > 0 && $limbs[$top] === 0) { --$top; } + $out = (string)$limbs[$top]; + for ($i = $top - 1; $i >= 0; --$i) { $out .= str_pad((string)$limbs[$i], self::LIMB_DIGITS, '0', STR_PAD_LEFT); } + return $out; + } + private static function normalize(string|int $value): string { $value = ltrim((string)$value, '0'); diff --git a/src/Support/MeasureReading.php b/src/Support/MeasureReading.php index eb5054b..b78650c 100644 --- a/src/Support/MeasureReading.php +++ b/src/Support/MeasureReading.php @@ -45,6 +45,18 @@ public static function verdict($value, string $kind, string $unit): string return self::READABLE; } + /** + * 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`. + * + * @param mixed $value + * @param class-string|class-string $kind + */ + public static function ticks($value, string $kind, string $unit): int + { + return $kind::parse(self::normalised($value), $unit)->ticks; + } + /** @param class-string|class-string $kind */ public static function knowsUnit(string $kind, string $unit): bool { diff --git a/src/Support/PrettyJsonStream.php b/src/Support/PrettyJsonStream.php new file mode 100644 index 0000000..1af591e --- /dev/null +++ b/src/Support/PrettyJsonStream.php @@ -0,0 +1,103 @@ +stream = $stream; + } + + /** + * @param mixed $value + * @param resource $stream + * @throws \JsonException + */ + public static function write($value, $stream): void + { + $writer = new self($stream); + $writer->value($value, 0); + $writer->flush(); + } + + /** @param mixed $value */ + private function value($value, int $depth): void + { + if (!\is_array($value) || \count($value, \COUNT_RECURSIVE) <= self::WHOLE_ELEMENTS) { + $this->append(self::encoded($value, $depth)); + return; + } + $list = JsonValue::isList($value); + $separator = "\n" . \str_repeat(self::INDENT, $depth + 1); + $this->append($list ? '[' : '{'); + $first = true; + foreach ($value as $key => $member) { + $this->append(($first ? '' : ',') . $separator); + $first = false; + if (!$list) { + $this->append(\json_encode((string) $key, self::FLAGS) . ': '); + } + $this->value($member, $depth + 1); + } + $this->append("\n" . \str_repeat(self::INDENT, $depth) . ($list ? ']' : '}')); + } + + /** @param mixed $value */ + private static function encoded($value, int $depth): string + { + $json = \json_encode($value, self::FLAGS); + return $depth === 0 ? $json : \str_replace("\n", "\n" . \str_repeat(self::INDENT, $depth), $json); + } + + private function append(string $text): void + { + $this->buffer .= $text; + if (\strlen($this->buffer) >= self::FLUSH_BYTES) { + $this->flush(); + } + } + + private function flush(): void + { + if (\fwrite($this->stream, $this->buffer) !== \strlen($this->buffer)) { + throw new \RuntimeException('could not write the result to the output stream'); + } + $this->buffer = ''; + } +} diff --git a/src/Support/RequestRules.php b/src/Support/RequestRules.php index 77ecc60..3100b3f 100644 --- a/src/Support/RequestRules.php +++ b/src/Support/RequestRules.php @@ -2,6 +2,8 @@ declare(strict_types=1); namespace Packvium\Support; +use Packvium\Domain\FlatBag; +use Packvium\Domain\MadeToMeasure; use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\Length; use Packvium\Unit\Weight; @@ -21,7 +23,7 @@ final class RequestRules { public const SOLVER_PROFILES = ['fast', 'balanced', 'quality', 'exact_small']; - public const OBJECTIVES = ['default', 'lowest_cost', 'shipping_cost', 'lowest_landed_cost', 'open_dimension_height', 'maximum_value']; + public const OBJECTIVES = ['default', 'lowest_cost', 'shipping_cost', 'lowest_landed_cost', 'open_dimension_height', 'maximum_value', 'maximum_volume']; public const ACCESS_DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z']; private const CONFIGURATION_INTEGERS = [ @@ -39,6 +41,12 @@ final class RequestRules 'solver_profile', 'solvers', 'time_limit_ms', ]; private const SIDES = ['length', 'width', 'height']; + /** Container fields a flat bag refuses, in reporting order (docs/DEFORMABLE-CONTAINERS.md). */ + private const BAG_EXCLUSIONS = ['obstacles', 'axles', 'access_directions', 'max_stack_density', + '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'; /** @@ -138,6 +146,27 @@ private static function item($raw, string $where, string $unit): void self::optionalInteger($item, 'max_compression_pressure_kpa', $where, 0); self::optionalRatio($item, 'minimum_support_ratio', $where, 1); self::optionalRatio($item, 'compression_ratio', $where, null); + $stackingGroup = JsonValue::get($item, 'stacking_group'); + if ($stackingGroup !== null) { + self::stackingGroupName($stackingGroup, "{$where}/stacking_group"); + } + $accepts = JsonValue::get($item, 'accepts_stacking_groups'); + if ($accepts !== null) { + foreach (self::listAt($accepts, "{$where}/accepts_stacking_groups") as $index => $name) { + self::stackingGroupName($name, "{$where}/accepts_stacking_groups/{$index}"); + } + } + } + + /** @param mixed $value */ + private static function stackingGroupName($value, string $field): void + { + if (!\is_string($value)) { + throw self::refuse('wrong_type', $field, 'must be a string'); + } + if ($value === '') { + throw self::refuse('invalid_value', $field, 'must not be empty'); + } } /** @param mixed $raw */ @@ -173,6 +202,116 @@ private static function container($raw, string $where, string $unit): void if ($obstacles !== null) { self::obstacles($obstacles, "{$where}/obstacles", $unit); } + $boundary = JsonValue::get($container, 'deformable_boundary'); + if ($boundary !== null) { + self::deformableBoundary($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); + } + } + + /** + * @param stdClass|array $sides + * @return array{0:int,1:int,2:int} + */ + private static function sideTicks($sides, string $unit): array + { + $ticks = []; + foreach (self::SIDES as $side) { + $ticks[] = MeasureReading::ticks(JsonValue::get($sides, $side), Length::class, $unit); + } + 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. + * + * @param mixed $value + */ + private static function setBesideABag(string $name, $value): bool + { + if ($name === 'obstacles') { + return $value !== null && $value !== []; + } + if ($name === 'void_fill_reserve_ratio') { + return $value !== null && $value > 0; + } + return $value !== null; } /** @param mixed $raw */ diff --git a/src/Support/UnsupportedPlacements.php b/src/Support/UnsupportedPlacements.php new file mode 100644 index 0000000..d0cc89a --- /dev/null +++ b/src/Support/UnsupportedPlacements.php @@ -0,0 +1,39 @@ + $containers */ + public static function warning(array $containers, float $minimumSupportRatio): ?string + { + if ($minimumSupportRatio !== 0.0) { + return null; + } + $count = 0; + foreach ($containers as $container) { + foreach ($container->placements as $placement) { + if ($placement->supportRatio === 0.0 && $placement->position->z > 0) { + $count++; + } + } + } + if ($count === 0) { + return null; + } + return "unsupported_placements: {$count} placement(s) rest on nothing above the container floor; " + . 'set configuration.minimum_support_ratio above 0 to require support'; + } +} diff --git a/src/Validation/IndependentSolutionValidator.php b/src/Validation/IndependentSolutionValidator.php index 694ac37..4787642 100644 --- a/src/Validation/IndependentSolutionValidator.php +++ b/src/Validation/IndependentSolutionValidator.php @@ -3,7 +3,7 @@ namespace Packvium\Validation; use Packvium\Constraint\{AxleLoad,CompatibilityConstraint,ConstraintContext,LoadCalculator,SupportConstraint,TagCountConstraint}; use Packvium\Constraint\Internal\LoadSupportGraph; -use Packvium\Domain\{AxisAlignedBox,Nesting,PackedContainer,PackingRequest,Placement,Point,UnpackedItem}; +use Packvium\Domain\{AxisAlignedBox,FlatBag,Nesting,PackedContainer,PackingRequest,Placement,Point,UnpackedItem}; use Packvium\Sequence\{RouteSequenceError,UnloadingDependencyGraph}; use Packvium\Unit\Length; /** @@ -30,7 +30,8 @@ public function validate(PackingRequest $request,array $containers,float $minimu $item=$placement->instance->item; if($item->tags!==[]||$item->incompatibleTags!==[])$compatibilitySensitive=true; if($item->minimumSupportRatio>0||($item->groundContactRule!==null&&$item->groundContactRule!=='free'))$supportSensitive=true; - if(!$item->stackable)$stackSensitive=true; + // A stacking-group list refuses load on the same edges `stackable` does. + if(!$item->stackable||$item->acceptsStackingGroups!==[])$stackSensitive=true; } $stackGraph=$stackSensitive?new LoadSupportGraph(LoadCalculator::units($placements)):null; foreach(self::collisionPairs($placements) as [$left,$right]) @@ -88,6 +89,11 @@ public function validate(PackingRequest $request,array $containers,float $minimu ); if($axleFailure!==null)$issues[]=new ValidationIssue($axleFailure[0],$packed->id().': '.$axleFailure[1]); } + if($packed->container->isFlatBag()){ + // The girth rule over the envelopes alone; the frame is checked above. + [$a,$b,$c]=FlatBag::extentOf($packed->placements); + if(!FlatBag::girthAdmits($packed->container->innerDimensions,$a,$b,$c))$issues[]=new ValidationIssue('bag_girth_exceeded',$packed->id()); + } $onRoute=false;foreach($placements as $p)if($p->instance->item->stopIndex!==null){$onRoute=true;break;} if($onRoute){ $routeIssue=self::unloadingOrderViolation($packed); @@ -115,12 +121,38 @@ public function validate(PackingRequest $request,array $containers,float $minimu sort($unknown); foreach($unknown as $id)$issues[]=new ValidationIssue('unknown_item',$id); foreach(self::splitGroups($containers) as $detail)$issues[]=new ValidationIssue('group_split',$detail); + array_push($issues,...self::madeToMeasureIssues($request,$containers)); array_push($issues,...self::fixedPlacementIssues($request,$containers)); if($unpacked!==null) foreach(self::partialGroups($request,$containers) as $detail)$issues[]=new ValidationIssue('group_partial',$detail); return new ValidationReport($issues===[],$issues); } + /** + * Every made-to-measure box is the one its placements call for. Containment in + * the box was checked above like any container's; this re-cuts it from the declared + * machine and the achieved extent, so a trial committed with a stale or mixed-up box is + * caught. O(p) per container. + * + * @param list $containers @return list + */ + private static function madeToMeasureIssues(PackingRequest $request,array $containers):array + { + $declared=[];foreach($request->containers as $container)$declared[$container->id]=$container; + $issues=[]; + foreach($containers as $packed){ + $machine=$declared[$packed->container->id]??null; + if($machine===null||$machine->madeToMeasure===null||$packed->container->madeToMeasure===null)continue; + $expected=$machine->fabricate(FlatBag::extentOf($packed->placements)); + $box=$packed->container; + if($box->innerDimensions!=$expected->innerDimensions)$issues[]=new ValidationIssue('fabricated_dimensions_mismatch',$packed->id()); + if($box->outerDimensions!=$expected->outerDimensions)$issues[]=new ValidationIssue('outer_dimensions_mismatch',$packed->id()); + if($box->costMinor!==$expected->costMinor)$issues[]=new ValidationIssue('made_to_measure_cost_mismatch',$packed->id()); + if($box->tareWeight->ticks!==$expected->tareWeight->ticks)$issues[]=new ValidationIssue('made_to_measure_tare_mismatch',$packed->id()); + } + return $issues; + } + /** * @param list $placements @return list * diff --git a/tests/AxleLoadTest.php b/tests/AxleLoadTest.php index 9c06df2..fdeb8f5 100644 --- a/tests/AxleLoadTest.php +++ b/tests/AxleLoadTest.php @@ -120,4 +120,20 @@ public static function testTheBalancedOriginsAccountForTheLoadAlreadyAboard(): v self::assertNull(AxleLoad::exceeded($axles, [...$aboard, $atFront])); self::assertNull(AxleLoad::exceeded($axles, [...$aboard, $atRear])); } + + public static function testAnItemAloneIsAdmittedExactlyWhereBothAxlesHold(): void + { + // Axles at 0 and 100, limits 400 front / 700 rear, a 1000-tick item centred at c: + // the front needs c >= 60 and the rear c <= 70. A 10-long box holds at origins + // 55..65; a 100-long one has the single centre 50, outside that window. + $axles = [new Axle(new Length(0), new Weight(400)), new Axle(new Length(100), new Weight(700))]; + self::assertTrue(AxleLoad::admitsAlone($axles, 0, 100, 1000, 10)); + self::assertFalse(AxleLoad::admitsAlone($axles, 0, 100, 1000, 100)); + $weak = [new Axle(new Length(0), new Weight(400)), new Axle(new Length(100), new Weight(400))]; + self::assertFalse(AxleLoad::admitsAlone($weak, 0, 100, 1000, 10)); + self::assertFalse(AxleLoad::admitsAlone([new Axle(new Length(0), null), new Axle(new Length(100), null)], 0, 100, 1, 101)); + // Tare 800 at the centre puts 400 on each axle. + self::assertTrue(AxleLoad::admitsAlone([new Axle(new Length(0), new Weight(400)), new Axle(new Length(100), null)], 800, 100, 0, 10)); + self::assertFalse(AxleLoad::admitsAlone([new Axle(new Length(0), new Weight(399)), new Axle(new Length(100), null)], 800, 100, 0, 10)); + } } diff --git a/tests/BigIntTest.php b/tests/BigIntTest.php index ec10b40..4949e3a 100644 --- a/tests/BigIntTest.php +++ b/tests/BigIntTest.php @@ -49,5 +49,89 @@ public static function run(): void $divideByZero = true; } self::assertTrue($divideByZero, 'divide must reject a zero divisor'); + + self::agreesWithDigitByDigitArithmetic(); + } + + /** + * The native, limb and float-estimate paths against the digit-by-digit arithmetic they + * replace, on every length pair across each path's boundary (18 digits native, 9 a + * limb, a 2^50 quotient for the estimate) and on carries, borrows and zero limbs. + */ + private static function agreesWithDigitByDigitArithmetic(): void + { + mt_srand(1606); + $values = ['0', '1', '9', '10', '999999999', '1000000000', '999999999999999999', '1000000000000000000', + '4096000000000000000000', '1000000000000000000000000000', str_repeat('9', 40)]; + for ($digits = 1; $digits <= 40; $digits++) { + for ($sample = 0; $sample < 2; $sample++) { $values[] = self::randomDigits($digits); } + } + foreach ($values as $a) { + foreach ($values as $b) { + self::assertSame(self::slowAdd($a, $b), BigInt::add($a, $b), "{$a} + {$b}"); + self::assertSame(self::slowMultiply($a, $b), BigInt::multiply($a, $b), "{$a} * {$b}"); + if (BigInt::compare($a, $b) >= 0) { self::assertSame(self::slowSubtract($a, $b), BigInt::subtract($a, $b), "{$a} - {$b}"); } + if ($b !== '0') { self::assertSame(self::slowDivide($a, $b), BigInt::divide($a, $b), "{$a} / {$b}"); } + } + } + self::assertSame('7', BigInt::add('0007', '000')); + self::assertSame('0', BigInt::multiply('000', '12345678901234567890')); + self::assertSame('12', BigInt::divide('0000000000000000000144', '000012')); + } + + private static function randomDigits(int $digits): string + { + $out = (string)mt_rand(1, 9); + for ($i = 1; $i < $digits; $i++) { $out .= mt_rand(0, 9) < 3 ? (mt_rand(0, 1) ? '0' : '9') : (string)mt_rand(0, 9); } + return $out; + } + + private static function slowAdd(string $a, string $b): string + { + $i = strlen($a) - 1; $j = strlen($b) - 1; $carry = 0; $out = ''; + while ($i >= 0 || $j >= 0 || $carry > 0) { + $sum = ($i >= 0 ? ord($a[$i--]) - 48 : 0) + ($j >= 0 ? ord($b[$j--]) - 48 : 0) + $carry; + $out = (string)($sum % 10) . $out; $carry = intdiv($sum, 10); + } + return ltrim($out, '0') ?: '0'; + } + + private static function slowMultiply(string $a, string $b): string + { + $a = ltrim($a, '0') ?: '0'; $b = ltrim($b, '0') ?: '0'; + if ($a === '0' || $b === '0') { return '0'; } + $digits = array_fill(0, strlen($a) + strlen($b), 0); + for ($i = strlen($a) - 1; $i >= 0; --$i) { + for ($j = strlen($b) - 1; $j >= 0; --$j) { + $p = (ord($a[$i]) - 48) * (ord($b[$j]) - 48) + $digits[$i + $j + 1]; + $digits[$i + $j + 1] = $p % 10; $digits[$i + $j] += intdiv($p, 10); + } + } + return ltrim(implode('', $digits), '0') ?: '0'; + } + + private static function slowSubtract(string $a, string $b): string + { + $a = ltrim($a, '0') ?: '0'; $b = ltrim($b, '0') ?: '0'; + $i = strlen($a) - 1; $j = strlen($b) - 1; $borrow = 0; $out = ''; + while ($i >= 0) { + $digit = (ord($a[$i--]) - 48) - $borrow - ($j >= 0 ? ord($b[$j--]) - 48 : 0); + if ($digit < 0) { $digit += 10; $borrow = 1; } else { $borrow = 0; } + $out = (string)$digit . $out; + } + return ltrim($out, '0') ?: '0'; + } + + private static function slowDivide(string $a, string $b): string + { + $a = ltrim($a, '0') ?: '0'; $b = ltrim($b, '0') ?: '0'; + $quotient = ''; $remainder = '0'; + for ($i = 0, $n = strlen($a); $i < $n; ++$i) { + $remainder = ltrim($remainder . $a[$i], '0') ?: '0'; + $digit = 0; + while (BigInt::compare($remainder, $b) >= 0) { $remainder = self::slowSubtract($remainder, $b); ++$digit; } + $quotient .= (string)$digit; + } + return ltrim($quotient, '0') ?: '0'; } } diff --git a/tests/ConstraintTest.php b/tests/ConstraintTest.php index 9c87aca..8efdb23 100644 --- a/tests/ConstraintTest.php +++ b/tests/ConstraintTest.php @@ -1406,6 +1406,92 @@ public static function testANonStackableItemBesideAnotherIsFine(): void self::assertTrue((new TopLoadConstraint())->evaluate(self::context($candidate, 0, [$beside]))->allowed); } + // ------------------------------------------------------ stacking groups + + /** + * @param array $lower + * @param array $upper + */ + private static function stackingVerdict(array $lower, array $upper): \Packvium\Constraint\ConstraintResult + { + $base = self::placed(self::instance('lower', options: $lower)); + return (new TopLoadConstraint())->evaluate(self::context(self::instance('upper', options: $upper), 10 * self::MM, [$base])); + } + + public static function testAnItemWhoseGroupTheLowerItemAcceptsMayRestOnIt(): void + { + $lower = ['stackingGroup' => 'A', 'acceptsStackingGroups' => ['A', 'B']]; + self::assertTrue(self::stackingVerdict($lower, ['stackingGroup' => 'B'])->allowed); + $refused = self::stackingVerdict($lower, ['stackingGroup' => 'C']); + self::assertSame(['stacking_group_incompatible', 'lower'], [$refused->code, $refused->detail]); + } + + public static function testAnEmptyListIsUnconstrainedAndANonEmptyOneIsClosed(): void + { + self::assertTrue(self::stackingVerdict(['stackingGroup' => 'A'], ['stackingGroup' => 'C'])->allowed); + self::assertTrue(self::stackingVerdict(['acceptsStackingGroups' => []], [])->allowed); + self::assertSame('stacking_group_incompatible', + self::stackingVerdict(['acceptsStackingGroups' => ['A']], [])->code); + self::assertSame('stacking_group_incompatible', + self::stackingVerdict(['acceptsStackingGroups' => ['B']], ['stackingGroup' => 'b'])->code); + } + + public static function testAnItemNeedNotAcceptItsOwnGroup(): void + { + $lower = ['stackingGroup' => 'A', 'acceptsStackingGroups' => ['B']]; + self::assertSame('stacking_group_incompatible', self::stackingVerdict($lower, ['stackingGroup' => 'A'])->code); + self::assertTrue(self::stackingVerdict($lower, ['stackingGroup' => 'B'])->allowed); + } + + public static function testEverySupporterOfABridgingItemMustAccept(): void + { + $left = self::placed(self::instance('left', 50, 100, 10, ['acceptsStackingGroups' => ['A']])); + $right = self::placed(self::instance('right', 50, 100, 10), 50 * self::MM); + $bridge = self::instance('bridge', 100, 100, 10, ['stackingGroup' => 'B']); + $result = (new TopLoadConstraint())->evaluate(self::context($bridge, 10 * self::MM, [$right, $left])); + self::assertSame(['stacking_group_incompatible', 'left'], [$result->code, $result->detail]); + } + + public static function testTheStackingRuleIsDirectNotTransitive(): void + { + $a = self::placed(self::instance('a', options: ['acceptsStackingGroups' => ['B']])); + $b = self::placed(self::instance('b', options: ['stackingGroup' => 'B']), 0, 0, 10 * self::MM); + $c = self::instance('c', options: ['stackingGroup' => 'C']); + self::assertTrue((new TopLoadConstraint())->evaluate(self::context($c, 20 * self::MM, [$a, $b]))->allowed); + } + + public static function testACandidateSlidUnderAnItemIsJudgedByItsOwnList(): void + { + $above = self::placed(self::instance('above', options: ['stackingGroup' => 'C']), 0, 0, 10 * self::MM); + $refusing = self::instance('under', options: ['acceptsStackingGroups' => ['A']]); + $result = (new TopLoadConstraint())->evaluate(self::context($refusing, 0, [$above])); + self::assertSame(['stacking_group_incompatible', 'under'], [$result->code, $result->detail]); + $accepting = self::instance('under', options: ['acceptsStackingGroups' => ['C']]); + self::assertTrue((new TopLoadConstraint())->evaluate(self::context($accepting, 0, [$above]))->allowed); + } + + public static function testNonStackableDominatesAListNamingTheUpperGroup(): void + { + $lower = ['stackable' => false, 'acceptsStackingGroups' => ['B']]; + self::assertSame('non_stackable', self::stackingVerdict($lower, ['stackingGroup' => 'B'])->code); + } + + public static function testANestedColumnIsRefusedWhenTheListOmitsItsOwnGroup(): void + { + $crate = Item::create('crate', Dimensions::mm(100, 100, 50), quantity: 2, + nestingHeight: Length::mm(25), stackingGroup: 'A', acceptsStackingGroups: ['B']); + [$lower, $upper] = $crate->instances(); + $result = (new TopLoadConstraint())->evaluate(self::context($upper, 25 * self::MM, [self::placed($lower)])); + self::assertSame('stacking_group_incompatible', $result->code); + } + + public static function testOnlyANonEmptyListMakesAnItemStackSensitive(): void + { + self::assertTrue(self::instance('a', options: ['acceptsStackingGroups' => ['A']])->item->isStackSensitive()); + self::assertFalse(self::instance('a', options: ['stackingGroup' => 'A'])->item->isStackSensitive()); + self::assertFalse(self::instance('a', options: ['acceptsStackingGroups' => []])->item->isStackSensitive()); + } + public static function testACandidateThatWouldCrushTheStackBelowIsRefused(): void { $base = self::placed(self::instance('base', options: ['weight' => '1 kg', 'maxTopLoad' => '1.5 kg'])); diff --git a/tests/ExplainTest.php b/tests/ExplainTest.php index d6a9fd9..0927eab 100644 --- a/tests/ExplainTest.php +++ b/tests/ExplainTest.php @@ -36,7 +36,8 @@ public static function testEveryReasonThisLibraryCanProduceHasARegisteredMessage $produced = [ 'no_compatible_container_dimensions', 'rotation_restricted', 'payload_exceeded', 'no_eligible_container', 'time_limit', 'effort_limit', 'group_cannot_fit_together', - 'insufficient_support', 'no_feasible_placement', + 'insufficient_support', 'no_feasible_placement', 'container_inventory_exhausted', + 'axle_overloaded', ]; foreach ($produced as $reason) { self::assertTrue(array_key_exists($reason, Explain::REASON_MESSAGES), "missing message for {$reason}"); diff --git a/tests/FixedPlacementTest.php b/tests/FixedPlacementTest.php index 0cd8068..4ca1be5 100644 --- a/tests/FixedPlacementTest.php +++ b/tests/FixedPlacementTest.php @@ -131,6 +131,20 @@ public static function testAFixedSetThatCannotHoldIsRefusedBeforeSearch(): void } } + public static function testAFixedSetThatBreaksTheStackingGroupRuleIsRefusedBeforeSearch(): void + { + // Admission runs the validator over the fixed set alone, so the new code arrives + // with no admission code of its own. + $pallet = self::cube(1) + ['accepts_stacking_groups' => ['A']]; + $drum = ['id' => 'drum', 'quantity' => 1, 'stacking_group' => 'C', + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]; + $onTop = ['item_type' => 'drum'] + self::fixed('0', '0', '100'); + $message = self::refusal(self::request([$pallet, $drum], null, [self::fixed(), $onTop])); + self::assertSame('invalid_fixed_placement: stacking_group_incompatible: cube#1: cube', $message); + $drum['stacking_group'] = 'A'; + self::assertNull(self::refusal(self::request([$pallet, $drum], null, [self::fixed(), $onTop]))); + } + public static function testAFixedPlacementOutOfShapeIsRefusedBeforeAnythingIsCoerced(): void { $entry = self::fixed('100'); diff --git a/tests/FlatBagTest.php b/tests/FlatBagTest.php new file mode 100644 index 0000000..957c268 --- /dev/null +++ b/tests/FlatBagTest.php @@ -0,0 +1,217 @@ + ['kind' => 'flat_bag']]; + + public static function testTheWorkedExamplesOfTheOracle(): void + { + $inner = Dimensions::mm(240, 140, 100); + self::assertTrue(FlatBag::girthAdmits($inner, self::ticks(200), self::ticks(100), self::ticks(40))); + self::assertFalse(FlatBag::girthAdmits($inner, self::ticks(200), self::ticks(100), self::ticks(40) + 1)); + self::assertFalse(FlatBag::girthAdmits(Dimensions::mm(1000, 480, 300), self::ticks(1000), self::ticks(10), self::ticks(10))); + self::assertFalse(FlatBag::fitsAlone(Dimensions::mm(300, 300, 100), Dimensions::mm(250, 150, 80))); + self::assertTrue(FlatBag::fitsAlone(Dimensions::mm(300, 300, 100), Dimensions::mm(220, 150, 80))); + self::assertSame([0, 0, 0], FlatBag::extentOf([])); + } + + public static function testTheRunningExtentEqualsTheExtentFromScratch(): void + { + $book = self::book(3); + $state = new ContainerState(self::bag(), 1); + $placements = []; + foreach ([[0, 0, 0], [0, 0, 20], [30, 10, 0]] as $index => [$x, $y, $z]) { + $placement = self::placed($book, $index + 1, $x, $y, $z); + $placements[] = $placement; + $state->add($placement); + self::assertSame(FlatBag::extentOf($placements), [$state->maxX, $state->maxY, $state->maxZ]); + } + } + + public static function testABagRefusesEveryWallAnchoredField(): void + { + self::assertTrue(self::bag()->isFlatBag()); + $refusals = [ + fn() => new Container('m', Dimensions::mm(240, 140, 100), Dimensions::mm(250, 150, 110), deformableBoundary: 'flat_bag'), + fn() => Container::create('m', Dimensions::mm(240, 140, 100), 0, null, null, 0, null, [], [], null, [], 0.1, [], null, null, null, [], 'flat_bag'), + fn() => Container::create('m', Dimensions::mm(240, 140, 100), 0, null, null, 0, null, [], [], null, [], 0.0, [], 5, null, null, [], 'flat_bag'), + fn() => Container::create('m', Dimensions::mm(240, 140, 100), 0, null, null, 0, null, [], [], null, [], 0.0, [], null, null, null, ['+x'], 'flat_bag'), + fn() => Container::create('m', Dimensions::mm(1, 1, 1), 0, null, null, 0, null, [], [], null, [], 0.0, [], null, null, null, [], 'gusseted'), + ]; + foreach ($refusals as $refusal) { + self::assertThrows(InvalidArgumentException::class, $refusal); + } + } + + public static function testAMalformedBagIsRefusedWithItsPointer(): void + { + $cases = [ + [['deformable_boundary' => 'flat_bag'], '/deformable_boundary', 'wrong_type', 'must be an object'], + [['deformable_boundary' => []], '/deformable_boundary/kind', 'missing_field', 'is required'], + [['deformable_boundary' => ['kind' => 'pouch']], '/deformable_boundary/kind', 'not_allowed', 'must be one of ["flat_bag"]'], + [['deformable_boundary' => ['kind' => 'flat_bag', 'seam' => 1]], '/deformable_boundary/seam', 'not_allowed', 'is not a known field'], + [self::BAG + ['made_to_measure' => []], '/made_to_measure', 'not_allowed', 'cannot be combined with deformable_boundary'], + [self::BAG + ['obstacles' => [['id' => 'o', 'dimensions' => ['length' => '1', 'width' => '1', 'height' => '1']]]], '/obstacles', 'not_allowed', 'cannot be combined with deformable_boundary'], + [self::BAG + ['void_fill_reserve_ratio' => 0.5], '/void_fill_reserve_ratio', 'not_allowed', 'cannot be combined with deformable_boundary'], + ]; + foreach ($cases as [$fields, $field, $reason, $detail]) { + try { + ArrayCodec::pack(self::request([self::books(1)], [['id' => 'mailer', 'inner_dimensions' => ['length' => '300', 'width' => '200', 'height' => '100']] + $fields])); + throw new \RuntimeException("{$field} was not refused"); + } catch (InvalidRequestException $error) { + self::assertSame(["/containers/0{$field}", $reason, $detail], [$error->field(), $error->reason(), $error->detail()]); + } + } + $inert = self::mailer() + ['obstacles' => [], 'void_fill_reserve_ratio' => 0]; + self::assertCount(1, ArrayCodec::pack(self::request([self::books(1)], [$inert]))['containers']); + } + + public static function testGirthNotTheFrameDecidesHowHighABagStacks(): void + { + $result = ArrayCodec::pack(self::request([self::books(3)], [self::mailer() + ['quantity' => 1]])); + self::assertSame([[200, 100, 40]], array_map([self::class, 'extentMm'], $result['containers'])); + self::assertSame('container_inventory_exhausted', $result['unpacked_items'][0]['reason']); + $opened = ArrayCodec::pack(self::request([self::books(3)], [self::mailer()])); + self::assertCount(2, $opened['containers']); + } + + public static function testAnItemNoRotationAdmitsIsProvenUnplaceable(): void + { + $carton = ['id' => 'carton', 'dimensions' => ['length' => '250', 'width' => '150', 'height' => '80']]; + $result = ArrayCodec::pack(self::request([$carton], [self::mailer('300', '300')])); + self::assertSame('no_compatible_container_dimensions', $result['unpacked_items'][0]['reason']); + $restricted = ArrayCodec::pack(self::request([$carton + ['allowed_rotations' => ['LHW']]], [self::mailer('330', '300')])); + self::assertSame('rotation_restricted', $restricted['unpacked_items'][0]['reason']); + } + + public static function testTheLatticeAndBlockSolversDeferToTheCandidateCheck(): void + { + $items = self::book(3)->instances(); + $config = new PackingConfig(); + $solution = (new GridSolver())->packOne(self::bag(), 1, $items, $config, new SearchStats(), Deadline::ofMilliseconds(60_000)); + self::assertFalse($solution->dominantLattice); + self::assertCount(2, $solution->state->placements); + self::assertFalse((new HomogeneousBlockSolver())->supports(self::bag(), $items, $config)); + } + + public static function testABagIsBilledOnItsAchievedPackage(): void + { + $packed = new PackedContainer(self::bag(300, 250), 1, [self::placed(self::book(1), 1, 0, 0, 0)]); + self::assertEquals(Dimensions::mm(200, 100, 20), $packed->billedDimensions()); + self::assertEquals(Dimensions::mm(200, 100, 20), $packed->asItem()->dimensions); + $rigid = new PackedContainer(Container::create('box', Dimensions::mm(300, 250, 100)), 1, []); + self::assertNull($rigid->achievedDimensions()); + $config = new PackingConfig(dimensionalWeightDivisor: 5000, dimensionalWeightLengthUnit: 'cm', dimensionalWeightWeightUnit: 'kg'); + $state = new ContainerState(self::bag(), 1); + self::assertSame(0, $state->billedDimensionalWeight($config)); + $state->add(self::placed(self::book(1), 1, 0, 0, 0)); + self::assertSame(Weight::parse('80 g')->ticks, $state->billedDimensionalWeight($config)); + foreach (['lowest_landed_cost' => 400, 'shipping_cost' => Weight::parse('300 g')->ticks] as $objective => $expected) { + foreach (['fast', 'exact_small'] as $profile) { + $rate = ['weight_brackets_g' => [500, 1000, 2000], 'prices_minor' => [400, 700, 1100]]; + $carton = ['id' => 'carton', 'inner_dimensions' => ['length' => '300', 'width' => '200', 'height' => '150'], 'rate_table' => $rate]; + $result = ArrayCodec::pack(self::request([self::books(1)], [$carton, self::mailer('300', '250') + ['rate_table' => $rate]], [ + 'objective' => $objective, 'solver_profile' => $profile, 'dimensional_weight_divisor' => 5000, + 'dimensional_weight_length_unit' => 'cm', 'dimensional_weight_weight_unit' => 'kg', + ])); + self::assertSame('mailer', $result['containers'][0]['container_type']); + self::assertSame($expected, $result['score'][1]); + } + } + } + + public static function testTheValidatorAndFixedAdmissionReportABagPastItsGirth(): void + { + $book = self::book(3); + $packed = new PackedContainer(self::bag(), 1, [self::placed($book, 1, 0, 0, 0), self::placed($book, 2, 0, 0, 20), self::placed($book, 3, 0, 0, 40)]); + $report = (new IndependentSolutionValidator())->validate(new PackingRequest([$book], [self::bag()]), [$packed]); + self::assertSame('bag_girth_exceeded', $report->issues[0]->code); + self::assertSame('mailer#1', $report->issues[0]->detail); + $fixed = []; + foreach ([0, 20, 40] as $z) { + $fixed[] = ['item_type' => 'book', 'container_type' => 'mailer', 'orientation' => 'LWH', 'position' => ['x' => '0', 'y' => '0', 'z' => (string) $z]]; + } + try { + ArrayCodec::pack(self::request([self::books(3)], [self::mailer()]) + ['fixed_placements' => $fixed]); + throw new \RuntimeException('the fixed set was admitted'); + } catch (FixedPlacementException $error) { + self::assertSame('invalid_fixed_placement: bag_girth_exceeded: mailer#1', $error->getMessage()); + } + } + + public static function testABagInheritsNoDoors(): void + { + $item = Item::create('parcel', Dimensions::mm(100, 100, 20), 0, 2, [Rotation::LWH], stopIndex: 1); + $context = new ConstraintContext(self::bag(), [], $item->instances()[0], new Point(0, 0, 0), Rotation::LWH, + $item->dimensions, $item->dimensions, true, true); + self::assertTrue((new StopAccessibilityConstraint(['+x']))->evaluate($context)->allowed); + $packer = new \Packvium\Packer(new PackingConfig(accessDirections: ['+x'])); + self::assertCount(2, $packer->pack([$item], [self::bag()])->containers[0]->placements); + } + + private static function ticks(int $millimetres): int + { + return Length::mm($millimetres)->ticks; + } + + private static function bag(int $length = 240, int $width = 140): Container + { + return Container::create('mailer', Dimensions::mm($length, $width, 100), 0, null, null, 0, null, [], [], null, [], 0.0, [], null, null, null, [], 'flat_bag'); + } + + private static function book(int $quantity): Item + { + return Item::create('book', Dimensions::mm(200, 100, 20), '300 g', $quantity, [Rotation::LWH]); + } + + private static function placed(Item $item, int $sequence, int $x, int $y, int $z): Placement + { + $origin = new Point(self::ticks($x), self::ticks($y), self::ticks($z)); + return new Placement(new ItemInstance($item, $sequence), $origin, Rotation::LWH, $item->dimensions, $origin, $item->dimensions); + } + + /** @return array */ + private static function books(int $quantity): array + { + return ['id' => 'book', 'quantity' => $quantity, 'weight' => '300 g', 'allowed_rotations' => ['LWH'], + 'dimensions' => ['length' => '200', 'width' => '100', 'height' => '20']]; + } + + /** @return array */ + private static function mailer(string $length = '240', string $width = '140'): array + { + return ['id' => 'mailer', 'inner_dimensions' => ['length' => $length, 'width' => $width, 'height' => '100']] + self::BAG; + } + + /** + * @param list> $items @param list> $containers @param array $configuration + * @return array + */ + private static function request(array $items, array $containers, array $configuration = []): array + { + return ['items' => $items, 'containers' => $containers, + 'configuration' => $configuration + ['solver_profile' => 'fast', 'time_limit_ms' => 60000, 'effort_budget' => ['max_search_nodes' => 100000]]]; + } + + /** @param array $container @return list */ + private static function extentMm(array $container): array + { + return array_map(static fn(string $side): int => (int) $container['achieved_dimensions'][$side]['value'], ['length', 'width', 'height']); + } +} diff --git a/tests/InvariantTest.php b/tests/InvariantTest.php index 8bc53a4..67c8b07 100644 --- a/tests/InvariantTest.php +++ b/tests/InvariantTest.php @@ -120,7 +120,8 @@ public static function testEveryUnpackedItemCarriesARecognisedReason(): void { // A caller acts on these strings, so an unexplained failure is a failure. $known = ['no_compatible_container_dimensions', 'payload_exceeded', 'no_feasible_placement', - 'group_cannot_fit_together', 'time_limit', 'insufficient_support']; + 'group_cannot_fit_together', 'time_limit', 'insufficient_support', + 'container_inventory_exhausted', 'axle_overloaded']; for ($seed = 0; $seed < self::TRIALS; $seed++) { [$items, $containers] = self::generate($seed); foreach (Support::pack($items, $containers, self::budget())->unpacked as $unpacked) { diff --git a/tests/IrregularItemsTest.php b/tests/IrregularItemsTest.php index a8e7682..534f110 100644 --- a/tests/IrregularItemsTest.php +++ b/tests/IrregularItemsTest.php @@ -2,8 +2,10 @@ declare(strict_types=1); namespace Packvium\Tests; +use Packvium\Algorithm\{BeamPacker, ContainerState, SolverOrchestrator}; use Packvium\Constraint\LoadCalculator; -use Packvium\Domain\{AxisAlignedBox, Compression, Dimensions, HullShape, Item, Nesting, Placement, Point, Rotation, ShapeType}; +use Packvium\Domain\{AxisAlignedBox, Compression, Container, Dimensions, HullShape, Item, Nesting, Placement, Point, Rotation, ShapeType}; +use ReflectionMethod; use Packvium\Serialization\ArrayCodec; use Packvium\Unit\{Length, Weight}; use Packvium\Support\SignedBigInt; @@ -229,6 +231,34 @@ public static function testTouchingWedgesAreContactAndNotCollision(): void self::assertTrue(Placement::collide($lower, self::placedWedge('other', self::lowerWedge(), 0, 0, 0))); } + public static function testTheBeamOrderingBoundLetsTheSecondWedgeFit(): void + { + // With one wedge placed, half the crate is free and the other wedge occupies + // exactly that half. Its declared box is the whole crate, and counting that against + // occupied free space claimed it could never fit. + $state = new ContainerState(new Container('cube', Dimensions::mm(100, 100, 100)), 1); + $state->add(self::placedWedge('lower', self::lowerWedge(), 0, 0, 0)); + [$upper] = self::hullItem('upper', self::upperWedge())->instances(); + $precompute = new ReflectionMethod(BeamPacker::class, 'precomputeFuture'); + $precompute->setAccessible(true); + $bound = new ReflectionMethod(BeamPacker::class, 'unpackedLowerBoundPrecomputed'); + $bound->setAccessible(true); + self::assertSame(0, $bound->invoke(null, $state, 0, $precompute->invoke(null, [$upper], null))); + } + + public static function testTheContainerPlanBoundCountsAWedgePairAsOneCrate(): void + { + // Two wedges that fill one crate between them have boxes worth two crates. + // Counted by box, the plan bound said a second crate was unavoidable. + $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->setAccessible(true); + $plan = ['remaining' => [$lower, $upper], 'inventory' => ['cube' => 2]]; + self::assertSame(1, $bound->invoke(null, $plan, [$crate])); + } + public static function testARouteBoundHullFallsBackToItsBox(): void { // `packing_sequence` reasons with box sweeps, so a hull on a route is deliberately diff --git a/tests/LimitReasonTest.php b/tests/LimitReasonTest.php new file mode 100644 index 0000000..6fc7588 --- /dev/null +++ b/tests/LimitReasonTest.php @@ -0,0 +1,97 @@ + [[self::cube('cube', 2)], [self::box('10', '10', '10', ['quantity' => 1])], []], + 'max_containers' => [[self::cube('cube', 2)], [self::box('10', '10', '10')], ['max_containers' => 1]], + 'max_items' => [[self::cube('cube', 2)], [self::box('20', '20', '20', ['quantity' => 1, 'max_items' => 1])], []], + 'max_payload' => [[self::cube('cube', 2, '10', ['weight' => self::grams('600')])], [self::box('20', '20', '20', ['quantity' => 1, 'max_payload' => self::grams('1000')])], []], + 'tag_limits' => [[self::cube('hazmat', 2, '10', ['tags' => ['hazmat']])], [self::box('20', '20', '20', ['quantity' => 1, 'tag_limits' => ['hazmat' => 1]])], []], + 'stop_access' => [[self::cube('early', 1, '100', ['stop_index' => 0]), self::cube('late', 1, '100', ['stop_index' => 1, 'stackable' => false])], [self::box('100', '100', '200', ['quantity' => 1, 'access_directions' => ['+z']])], []], + 'axle_share' => [[self::cube('payload', 2, '10', ['weight' => self::grams('500'), 'allowed_rotations' => ['LWH']])], [self::box('100', '10', '10', ['quantity' => 1, 'axles' => self::axles('600', '350')])], []], + ]; + foreach ($cases as $name => [$items, $containers, $configuration]) { + self::assertSame(self::INVENTORY, self::reasons($items, $containers, $configuration), $name); + } + self::assertSame([], self::reasons([self::cube('cube', 2)], [self::box('20', '20', '20', ['max_items' => 1])])); + } + + public static function testAnAxleThatRefusesTheItemAloneIsNamed(): void + { + foreach ([['10', '400', '400'], ['100', '400', '700']] as [$length, $front, $rear]) { + $item = ['id' => 'load', 'quantity' => 1, 'weight' => self::grams('1000'), 'allowed_rotations' => ['LWH'], + 'dimensions' => ['length' => $length, 'width' => '10', 'height' => '10']]; + $vehicle = self::box('100', '10', '10', ['axles' => self::axles($front, $rear)]); + self::assertSame([['axle_overloaded', 'inferred']], self::reasons([$item], [$vehicle]), $length); + } + $item = self::cube('load', 2, '10', ['weight' => self::grams('1000'), 'allowed_rotations' => ['LWH']]); + $crate = ['id' => 'crate'] + self::box('10', '10', '10', ['quantity' => 1]); + $vehicle = self::box('100', '10', '10', ['axles' => self::axles('400', '400')]); + self::assertSame(self::INVENTORY, self::reasons([$item], [$vehicle, $crate])); + } + + public static function testASingleRestartPacksWorseThanTheFullPortfolio(): void + { + // The shared conformance scene feature-effort-restarts-first-start-loses. + $items = [ + ['id' => 'panel', 'quantity' => 4, 'dimensions' => ['length' => '20', 'width' => '25', 'height' => '50']], + ['id' => 'crate', 'quantity' => 4, 'dimensions' => ['length' => '60', 'width' => '40', 'height' => '40']], + ]; + $budget = ['max_candidates_evaluated' => 1000000, 'max_placement_attempts' => 1000000, 'max_search_nodes' => 1000000]; + foreach ([[1, 4], [null, 3]] as [$restarts, $unpacked]) { + $effort = $restarts === null ? $budget : $budget + ['max_restarts' => $restarts]; + $found = self::reasons($items, [self::box('50', '100', '60', ['quantity' => 1])], ['solver_profile' => 'balanced', 'effort_budget' => $effort]); + self::assertSame($unpacked, count($found), (string)$restarts); + } + } + + /** @return list */ + private static function reasons(array $items, array $containers, array $configuration = []): array + { + $result = ArrayCodec::pack([ + 'units' => ['length' => 'mm'], + 'configuration' => ['solver_profile' => 'fast', 'time_limit_ms' => 300000] + $configuration, + 'items' => $items, + 'containers' => $containers, + ]); + $reasons = array_map(static fn(array $item): array => [$item['reason'], $item['proof']['level']], $result['unpacked_items']); + sort($reasons); + return $reasons; + } + + private static function cube(string $id, int $quantity, string $side = '10', array $fields = []): array + { + return ['id' => $id, 'quantity' => $quantity, 'dimensions' => ['length' => $side, 'width' => $side, 'height' => $side]] + $fields; + } + + private static function box(string $length, string $width, string $height, array $fields = []): array + { + return ['id' => 'box', 'inner_dimensions' => ['length' => $length, 'width' => $width, 'height' => $height]] + $fields; + } + + private static function grams(string $value): array + { + return ['value' => $value, 'unit' => 'g']; + } + + private static function axles(string $front, string $rear): array + { + return [['position' => '0', 'max_load' => self::grams($front)], ['position' => '100', 'max_load' => self::grams($rear)]]; + } +} diff --git a/tests/MadeToMeasureTest.php b/tests/MadeToMeasureTest.php new file mode 100644 index 0000000..59c0351 --- /dev/null +++ b/tests/MadeToMeasureTest.php @@ -0,0 +1,279 @@ +grid(0, 200 * self::MM)); + self::assertSame(210 * self::MM, $machine->grid(0, 210 * self::MM)); + self::assertSame(60 * self::MM, $machine->grid(0, 1)); + self::assertSame(1510 * self::MM, $machine->clamp(0, 2000 * self::MM, 1510 * self::MM)); + } + + public static function testTheSplitCostEqualsTheDirectCeiling(): void + { + $generator = 2702; + for ($case = 0; $case < 50; $case++) { + $generator = ($generator * 1103515245 + 12345) % 2147483648; + $rate = $generator * 4194304 + $case; + $area = (string) ($generator * 977 + $case) . '000000000000000000'; + $numerator = \Packvium\Support\BigInt::multiply($rate, $area); + $direct = \Packvium\Support\BigInt::divide(\Packvium\Support\BigInt::add($numerator, '255999999999999'), MadeToMeasure::SQUARE_METRE_TICKS2); + self::assertSame($direct, MadeToMeasure::perSquareMetre($rate, $area)); + } + self::assertSame('1', MadeToMeasure::perSquareMetre(1, '1')); + self::assertSame(305, self::machine(costPerSquareMetreMinor: 1000)->boxCostMinor(40, self::ticks(210, 210, 210))); + } + + public static function testTheIntegerCubeRootIsTheLeastCubeAtOrAbove(): void + { + foreach (['0' => '0', '1' => '1', '7' => '2', '8' => '2', '9' => '3', + '1000000000000000000000' => '10000000', '1000000000000000000001' => '10000001'] as $value => $root) { + self::assertSame($root, MadeToMeasure::icbrtCeil((string) $value)); + } + } + + public static function testTheWorkedRungListsMatchTheContract(): void + { + self::assertSame( + [self::ticks(260, 260, 260), self::ticks(310, 310, 310), self::ticks(410, 410, 410), self::ticks(1510, 1510, 1510)], + self::machine()->solvingEnvelopes(self::ticks(1510, 1510, 1510), array_fill(0, 8, self::ticks(100, 100, 100))), + ); + $pinned = new MadeToMeasure(self::ticks(200, 100, 100), self::ticks(70, 10, 10)); + self::assertSame([self::ticks(1950, 100, 100)], + $pinned->solvingEnvelopes(self::ticks(1950, 100, 100), array_fill(0, 5, self::ticks(100, 100, 100)))); + self::assertSame( + [self::ticks(190, 190, 190), self::ticks(220, 220, 220), self::ticks(290, 290, 290), self::ticks(300, 300, 300)], + self::machine(50, 10)->solvingEnvelopes(self::ticks(300, 300, 300), array_fill(0, 3, self::ticks(100, 100, 100))), + ); + $rod = self::machine()->solvingEnvelopes(self::ticks(1510, 1510, 1510), [self::ticks(1000, 50, 50), self::ticks(100, 100, 100)])[0]; + self::assertTrue($rod[0] >= 1000 * self::MM && $rod[1] < 1000 * self::MM && $rod[2] < 1000 * self::MM); + } + + public static function testAMachineOffItsOwnGridIsRefused(): void + { + self::assertThrows(InvalidArgumentException::class, static fn() => new Container('odd', Dimensions::mm(1500, 1510, 1510), madeToMeasure: self::machine())); + self::assertThrows(InvalidArgumentException::class, static fn() => new MadeToMeasure([0, 1, 1], [1, 1, 1])); + } + + public static function testTheFirstCompleteRungIsKeptWithoutTryingALargerOne(): void + { + $solver = new ScriptedRungSolver([[3, 100], [3, 100], [3, 100], [3, 100]]); + [$one, $trials] = self::chain($solver); + self::assertSame(1, $trials); + self::assertCount(1, $solver->envelopes); + self::assertEquals(Dimensions::mm(310, 110, 110), $one->state->container->innerDimensions); + self::assertFalse($one->exhaustive); + } + + public static function testAnIncompleteChainKeepsTheRoundKeyChoiceAndTheSmallerRungOnATie(): void + { + [$one, $trials] = self::chain(new ScriptedRungSolver([[1, 100], [2, 100], [1, 100], [2, 105]])); + self::assertSame(4, $trials); + self::assertSame([0, 100 * self::MM], array_map(static fn(Placement $p): int => $p->position->x, $one->state->placements)); + } + + public static function testAChainThatPlacesNothingStaysAZeroPlacementTrial(): void + { + [$one, $trials] = self::chain(new ScriptedRungSolver(array_fill(0, 4, [0, 100]))); + self::assertSame(4, $trials); + self::assertSame(0, $one->state->placementCount()); + } + + public static function testACountedLimitReachedMidChainStopsItWithTheBestSoFar(): void + { + $stats = new SearchStats(); + $solver = new ScriptedRungSolver(array_fill(0, 4, [1, 100]), $stats); + [$one, $trials] = self::chain($solver, new Deadline(60_000_000_000, null, new \Packvium\Algorithm\EffortBudget(maxSearchNodes: 1), $stats)); + self::assertSame(1, $trials); + self::assertTrue($one->timeLimitReached); + } + + public static function testTheWorkedOrderIsCutToA210MillimetreBox(): void + { + $packed = ArrayCodec::pack(self::request())['containers'][0]; + self::assertSame('210', $packed['inner_dimensions']['length']['value']); + self::assertSame('213', $packed['outer_dimensions']['height']['value']); + self::assertSame('200', $packed['achieved_dimensions']['width']['value']); + self::assertSame(305, $packed['made_to_measure']['cost_minor']); + } + + public static function testTheBoardWeightGrowsTheTare(): void + { + $request = self::request(); + $request['containers'][0]['made_to_measure']['tare_per_square_metre'] = '500'; + $packed = ArrayCodec::pack($request)['containers'][0]; + self::assertSame('132.3', $packed['made_to_measure']['tare_weight']['value']); + self::assertSame('932.3', $packed['gross_weight']['value']); + } + + public static function testTheRoundKeyReadsTheFabricatedPriceAndTheLatticeStandsDown(): void + { + $request = self::request(); + $request['containers'][] = ['id' => 'stock', 'cost_minor' => 300, 'inner_dimensions' => self::mm(210, 210, 210)]; + self::assertSame('stock', ArrayCodec::pack($request)['containers'][0]['container_type']); + $compact = self::request(); + $compact['configuration']['require_placement_coordinates'] = false; + $packed = ArrayCodec::pack($compact)['containers'][0]; + self::assertFalse(array_key_exists('lattice_summary', $packed)); + self::assertCount(8, $packed['placements']); + $exact = self::request(); + $exact['configuration']['solver_profile'] = 'exact_small'; + $exact['items'][0]['quantity'] = 2; + self::assertSame('not_proven', ArrayCodec::pack($exact)['optimality']['code']); + } + + public static function testEachRefusedCombinationIsNamed(): void + { + $cases = [ + 'container.made_to_measure+axles' => ['axles' => [['position' => '0'], ['position' => '1510']]], + 'container.made_to_measure+obstacles' => ['obstacles' => [['id' => 'post', 'dimensions' => self::mm(10, 10, 10)]]], + 'container.made_to_measure+void_fill_reserve_ratio' => ['void_fill_reserve_ratio' => 0.5], + ]; + foreach ($cases as $name => $fields) { + $request = self::request(); + $request['containers'][0] = array_merge($request['containers'][0], $fields); + self::assertRefusedWith(UnsupportedFeatureException::class, $name, $request); + } + $request = self::request(); + $request['fixed_placements'] = [['item_type' => 'cube', 'container_type' => 'machine', 'orientation' => 'LWH']]; + self::assertRefusedWith(UnsupportedFeatureException::class, 'fixed_placements+container.made_to_measure', $request); + } + + public static function testEachRequestErrorNamesItsRule(): void + { + $cases = [ + ['/containers/0/made_to_measure/extra: is not a known field', ['extra' => 1]], + ['/containers/0/made_to_measure/minimum/width: must be positive', ['minimum' => self::mm(60, 0, 60)]], + ['/containers/0/made_to_measure/increment/height: must be positive', ['increment' => self::mm(25, 25, 0)]], + ['/containers/0/made_to_measure/minimum/length: exceeds inner_dimensions', ['minimum' => self::mm(1600, 60, 60)]], + ['/containers/0/made_to_measure/increment/width: does not divide inner_dimensions minus minimum', ['increment' => self::mm(25, 30, 25)]], + ['/containers/0/made_to_measure/cost_per_square_metre_minor: prices the largest box above 9007199254740991', ['cost_per_square_metre_minor' => 9007199254740991]], + ]; + foreach ($cases as [$message, $fields]) { + $request = self::request(); + $request['containers'][0]['made_to_measure'] = array_merge($request['containers'][0]['made_to_measure'], $fields); + self::assertRefusedWith(InvalidRequestException::class, 'invalid_request: ' . $message, $request); + } + $request = self::request(); + $request['containers'][0]['outer_dimensions'] = self::mm(1600, 1600, 1600); + self::assertRefusedWith(InvalidRequestException::class, '/containers/0/outer_dimensions: cannot be combined with made_to_measure', $request); + } + + public static function testTheValidatorRecutsTheBoxFromTheDeclaredMachine(): void + { + $declared = new Container('machine', Dimensions::mm(1510, 1510, 1510), costMinor: 40, madeToMeasure: self::machine(costPerSquareMetreMinor: 1000)); + $item = Item::create('cube', Dimensions::mm(100, 100, 100)); + $instance = $item->instances()[0]; + $placement = new Placement($instance, new Point(0, 0, 0), Rotation::LWH, $instance->dimensions(), new Point(0, 0, 0), $instance->dimensions()); + $request = new PackingRequest([$item], [$declared]); + $good = $declared->fabricate(self::ticks(100, 100, 100)); + $validator = new IndependentSolutionValidator(); + self::assertTrue($validator->validate($request, [new PackedContainer($good, 1, [$placement])])->valid); + $stale = new Container('machine', $good->innerDimensions, $good->outerDimensions, costMinor: 40, madeToMeasure: $declared->madeToMeasure); + $codes = array_map(static fn($issue) => $issue->code, $validator->validate($request, [new PackedContainer($stale, 1, [$placement])])->issues); + self::assertSame(['made_to_measure_cost_mismatch'], $codes); + } + + /** @return array{0:SingleContainerSolution,1:int} */ + private static function chain(ScriptedRungSolver $solver, ?Deadline $deadline = null): array + { + $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)); + } + + private static function assertRefusedWith(string $class, string $fragment, array $request): void + { + try { + ArrayCodec::pack($request); + } catch (\Throwable $error) { + self::assertTrue($error instanceof $class, get_class($error) . ': ' . $error->getMessage()); + self::assertTrue(str_contains($error->getMessage(), $fragment), $error->getMessage()); + return; + } + self::assertTrue(false, "expected a refusal naming {$fragment}"); + } + + private static function machine(int $minimum = 60, int $increment = 25, int $costPerSquareMetreMinor = 0): MadeToMeasure + { + return new MadeToMeasure(self::ticks($minimum, $minimum, $minimum), self::ticks($increment, $increment, $increment), $costPerSquareMetreMinor); + } + + /** @return array{0:int,1:int,2:int} */ + private static function ticks(int $length, int $width, int $height): array + { + return [$length * self::MM, $width * self::MM, $height * self::MM]; + } + + /** @return array{length:string,width:string,height:string} */ + private static function mm(int $length, int $width, int $height): array + { + return ['length' => (string) $length, 'width' => (string) $width, 'height' => (string) $height]; + } + + /** @return array */ + private static function request(): array + { + return [ + 'units' => ['length' => 'mm'], + 'configuration' => ['solver_profile' => 'fast', 'minimum_support_ratio' => 1, 'time_limit_ms' => 300000, + 'effort_budget' => ['max_search_nodes' => 1000000]], + 'items' => [['id' => 'cube', 'quantity' => 8, 'weight' => '100', 'dimensions' => self::mm(100, 100, 100)]], + 'containers' => [['id' => 'machine', 'cost_minor' => 40, 'inner_dimensions' => self::mm(1510, 1510, 1510), + 'made_to_measure' => ['minimum' => self::mm(60, 60, 60), 'increment' => self::mm(25, 25, 25), + 'cost_per_square_metre_minor' => 1000, 'outer_allowance' => self::mm(3, 3, 3)]]], + ]; + } +} + +/** Places a scripted number of items per rung, along x at the scripted pitch in millimetres. */ +final class ScriptedRungSolver implements SingleContainerSolver +{ + /** @var list */ + public array $envelopes = []; + + /** @param list $script */ + public function __construct(private array $script, public ?SearchStats $stats = null) + { + } + + public function name(): string + { + return 'scripted'; + } + + public function packOne(Container $container, int $sequence, array $items, PackingConfig $config, SearchStats $stats, Deadline $deadline): SingleContainerSolution + { + [$count, $pitch] = $this->script[count($this->envelopes)]; + $this->envelopes[] = $container->innerDimensions; + $stats->searchNodesExpanded++; + $state = new ContainerState($container, $sequence); + foreach (array_slice($items, 0, $count) as $index => $instance) { + $origin = new Point($index * $pitch * Length::TICKS_PER_MM, 0, 0); + $state->addDirect(new Placement($instance, $origin, Rotation::LWH, $instance->dimensions(), $origin, $instance->dimensions())); + } + return new SingleContainerSolution($state, array_slice($items, $count)); + } +} diff --git a/tests/ObjectiveTest.php b/tests/ObjectiveTest.php index c6c5255..00ec690 100644 --- a/tests/ObjectiveTest.php +++ b/tests/ObjectiveTest.php @@ -854,4 +854,94 @@ public static function testANegativeValueFailsAdmissionInsteadOfBeingIgnored(): self::assertThrows(\InvalidArgumentException::class, static fn() => Item::create('a', Dimensions::mm(10, 10, 10), value: -1)); } + + // --------------------------------------------------------- maximum volume + + /** @param list $items @return list */ + private static function volumeScoreOfLeavingBehind(array $items): array + { + $unpacked = []; + foreach ($items as $item) { + foreach ($item->instances() as $instance) { + $unpacked[] = new UnpackedItem($instance, 'no_feasible_placement'); + } + } + return (new \Packvium\Objective\MaximumVolumeSolutionScorer()) + ->score(new RawSolution('test', [], $unpacked, new SearchStats()))->components; + } + + /** @return list */ + private static function keptItemTypes(\Packvium\Result\PackingResult $result): array + { + return array_values(array_unique(array_map( + static fn($p) => $p->instance->item->id, + array_merge([], ...array_map(static fn($c) => $c->placements, $result->containers)), + ))); + } + + /** @return list */ + private static function fiveSmallAndOneLarge(): array + { + return [Support::item('small', 40, 40, 40, ['quantity' => 5]), Support::item('large', 100, 100, 90)]; + } + + public static function testMaximumVolumeRanksTheVolumeLeftBehindAheadOfThePieceCount(): void + { + self::assertSame([1_000_000, 1, 0, 0, 0], self::volumeScoreOfLeavingBehind([Support::item('large', 100, 100, 90)])); + self::assertSame([1_000_000, 5, 0, 0, 0], self::volumeScoreOfLeavingBehind([Support::item('small', 40, 40, 40, ['quantity' => 5])])); + self::assertSame([0, 0, 0, 0, 0], self::volumeScoreOfLeavingBehind([])); + } + + public static function testMaximumVolumeRoundsTheShareUpSoAnIncompleteAnswerNeverScoresZero(): void + { + $result = Support::pack( + [Support::item('freight', 12000, 2300, 2400), Support::item('speck', 1, 1, 1)], + [Support::box('c', 12000, 2300, 2400, ['quantity' => 1])], + new PackingConfig(objective: 'maximum_volume'), + ); + self::assertSame(['speck'], array_map(static fn($u) => $u->instance->item->id, $result->unpacked)); + self::assertSame([1, 1], array_slice($result->score, 0, 2)); + } + + public static function testMaximumVolumeCountsACompactLatticesItemsAsRequested(): void + { + // The compact path carries no per-item placements; the packed volume must still + // come from the instances the lattice consumed. + $result = Support::pack( + [Support::item('cube', 100, 100, 100, ['quantity' => 3])], + [Support::box('tower', 100, 100, 200, ['quantity' => 1])], + new PackingConfig(profile: SolverProfile::Fast, multiStartOrders: 1, objective: 'maximum_volume', requirePlacementCoordinates: false), + ); + self::assertNotNull($result->containers[0]->latticeSummary); + self::assertSame([333_334, 1], array_slice($result->score, 0, 2)); + } + + public static function testMaximumVolumeKeepsTheOneLargeItemInEveryProfile(): void + { + $box = [Support::box('c', 100, 100, 100, ['quantity' => 1])]; + foreach ([ + new PackingConfig(profile: SolverProfile::Fast, multiStartOrders: 1, objective: 'maximum_volume'), + new PackingConfig(objective: 'maximum_volume'), + new PackingConfig(profile: SolverProfile::Quality, multiStartOrders: 24, maxCandidatesPerItem: 16, objective: 'maximum_volume', containerPlanBeamWidth: 16, containerPlanNodeLimit: 100_000), + ] as $config) { + $result = Support::pack(self::fiveSmallAndOneLarge(), $box, $config); + self::assertSame(['large'], self::keptItemTypes($result)); + self::assertSame([262_296, 5], array_slice($result->score, 0, 2)); + } + } + + public static function testDefaultKeepsMorePiecesOnTheSceneMaximumVolumeFills(): void + { + $result = Support::pack(self::fiveSmallAndOneLarge(), [Support::box('c', 100, 100, 100, ['quantity' => 1])], PackingConfig::quality()); + self::assertSame(['small'], self::keptItemTypes($result)); + } + + public static function testMaximumVolumeOpensTheContainerThatLoadsTheMostVolume(): void + { + $containers = [Support::box('snug', 90, 90, 90, ['quantity' => 1]), Support::box('tall', 100, 100, 95, ['quantity' => 1])]; + $byVolume = Support::pack(self::fiveSmallAndOneLarge(), $containers, new PackingConfig(maxContainers: 1, objective: 'maximum_volume')); + $byCount = Support::pack(self::fiveSmallAndOneLarge(), $containers, new PackingConfig(maxContainers: 1)); + self::assertSame(['tall'], array_map(static fn($c) => $c->container->id, $byVolume->containers)); + self::assertSame(['snug'], array_map(static fn($c) => $c->container->id, $byCount->containers)); + } } diff --git a/tests/OperationalArtifactTest.php b/tests/OperationalArtifactTest.php index fa78a37..5105b69 100644 --- a/tests/OperationalArtifactTest.php +++ b/tests/OperationalArtifactTest.php @@ -230,6 +230,24 @@ public static function testAResultThatDoesNotSayHowItWasSolvedIsNotPromisedOneEi self::assertSame(['level' => 'not_guaranteed', 'because' => 'provenance.solver'], $provenance['replay']); } + public static function testReplayLevelAnswersWhatTheArtifactWouldRecordWithoutBuildingIt(): void + { + foreach ([self::result(), self::result(['time_limit_reached' => true] + self::algorithm()), self::result(null)] as $result) { + self::assertSame( + OperationalArtifact::build(self::REQUEST, $result)['provenance']['replay']['level'], + OperationalArtifact::replayLevel($result) + ); + } + $effortStopped = '{"algorithm": {"profile": "fast", "solver": "x", "seed": 1, ' + . '"time_limit_reached": false, "effort_limit_reached": true}}'; + self::assertSame('exact', OperationalArtifact::replayLevel(OperationalArtifact::parse($effortStopped))); + foreach (['text', [1, 2], ['algorithm' => ['profile' => 'fast']]] as $malformed) { + self::assertSame('invalid_result', self::code(static function () use ($malformed): void { + OperationalArtifact::replayLevel($malformed); + })); + } + } + // ---------------------------------------------------------------------------- refusals public static function testARequestOrResultThatIsNotAnObjectIsRefused(): void diff --git a/tests/PackingSequenceTest.php b/tests/PackingSequenceTest.php index c593659..43712d7 100644 --- a/tests/PackingSequenceTest.php +++ b/tests/PackingSequenceTest.php @@ -893,6 +893,26 @@ public static function testALoadingPrefixThatStacksOntoANonStackableItemIsCaught } } + public static function testALoadingPrefixThatBreaksTheStackingGroupRuleIsCaught(): void + { + $base = Item::create('base', Dimensions::mm(10, 10, 5), acceptsStackingGroups: ['A']); + $rider = Item::create('rider', Dimensions::mm(10, 10, 5), stackingGroup: 'C'); + $placements = [self::stackedPlacement($base, 0, 0, 0), self::stackedPlacement($rider, 0, 0, 5)]; + $container = Container::create('c', Dimensions::mm(10, 10, 20)); + foreach ([[0, 1], [1, 0]] as $order) { + try { + LoadingDependencyGraph::verifyLoadingPrefixBusinessRules($placements, $order, $container); + self::assertTrue(false, 'expected SequenceReplayError'); + } catch (SequenceReplayError $error) { + self::assertSame(1, $error->step); + self::assertSame('stacking_group_incompatible: base', $error->reason); + } + } + $accepted = Item::create('rider', Dimensions::mm(10, 10, 5), stackingGroup: 'A'); + LoadingDependencyGraph::verifyLoadingPrefixBusinessRules( + [self::stackedPlacement($base, 0, 0, 0), self::stackedPlacement($accepted, 0, 0, 5)], [0, 1], $container); + } + public static function testALoadingPrefixThatViolatesAGroundContactRuleIsCaught(): void { // "single" requires resting on exactly one supporter; two half-width bases @@ -1029,4 +1049,38 @@ public static function testSequenceReplayErrorToArrayMatchesTheCrossLanguageShap $error->toArray(), ); } + + public static function testSafeRemovalOrderTieBreaksByLowestIndexAmongUnblocked(): void + { + $container = Dimensions::mm(40, 20, 20); + $b0 = self::box(0, 0, 0, 10, 10, 10); + $b1 = self::box(10, 0, 0, 10, 10, 10); + $b2 = self::box(20, 0, 0, 10, 10, 10); + $order = UnloadingDependencyGraph::safeRemovalOrder([$b0, $b1, $b2], $container, ['+z']); + self::assertSame([0, 1, 2], $order); + } + + public static function testSafeRouteRemovalOrderMultipleUnblockedAtSameStop(): void + { + $container = Dimensions::mm(40, 20, 20); + $b0 = self::box(0, 0, 0, 10, 10, 10); + $b1 = self::box(10, 0, 0, 10, 10, 10); + $b2 = self::box(20, 0, 0, 10, 10, 10); + $order = UnloadingDependencyGraph::safeRouteRemovalOrder([$b0, $b1, $b2], [0, 0, 0], $container, ['+z']); + self::assertSame([0, 1, 2], $order); + } + + public static function testSafeRouteRemovalOrderDeadlockReportsStuckBoxes(): void + { + $container = Dimensions::mm(20, 10, 10); + $b0 = self::box(0, 0, 0, 10, 10, 10); + $b1 = self::box(10, 0, 0, 10, 10, 10); + try { + UnloadingDependencyGraph::safeRouteRemovalOrder([$b0, $b1], [1, 0], $container, ['-x']); + self::fail('expected RouteSequenceError'); + } catch (\Packvium\Sequence\RouteSequenceError $e) { + self::assertSame(0, $e->stop); + self::assertContains(1, $e->stuck); + } + } } diff --git a/tests/PackingTest.php b/tests/PackingTest.php index d92a28b..c73b03c 100644 --- a/tests/PackingTest.php +++ b/tests/PackingTest.php @@ -87,6 +87,19 @@ public static function testEveryProfileFillsAnExactlyDivisibleContainer(): void } } + public static function testThePublicEffortBudgetIsTheSolversOwnTypeAndBoundsTheSearch(): void + { + $public = new \Packvium\Config\EffortBudget(maxSearchNodes: 5); + self::assertTrue($public instanceof EffortBudget); + self::assertTrue(new EffortBudget() instanceof \Packvium\Config\EffortBudget); + + $items = [Support::item('cube', 20, 20, 20, ['quantity' => 20])]; + $config = new PackingConfig(timeLimitMs: 60_000, solvers: ['grid'], effortBudget: $public); + $result = Support::pack($items, [Support::box('box', 200, 200, 200)], $config); + self::assertSame(5, $result->packedItemCount()); + self::assertSame('effort_limit', $result->termination->code); + } + public static function testAnItemLargerThanEveryContainerIsReportedWithAReason(): void { $items = [Support::item('slab', 200, 200, 200)]; diff --git a/tests/PrettyJsonStreamTest.php b/tests/PrettyJsonStreamTest.php new file mode 100644 index 0000000..f760c1f --- /dev/null +++ b/tests/PrettyJsonStreamTest.php @@ -0,0 +1,102 @@ + '{"items":[{"id":"a","dimensions":{"length":"40","width":"30","height":"20"},"quantity":5},{"id":"b","dimensions":{"length":"60","width":"50","height":"40"},"quantity":3}],"containers":[{"id":"c","inner_dimensions":{"length":"150","width":"150","height":"150"},"quantity":3}],"configuration":{"solver_profile":"balanced","alternatives":1,"time_limit_ms":300000,"effort_budget":{"max_candidates_evaluated":1000000,"max_placement_attempts":1000000,"max_search_nodes":1000000}}}', + 'gen-alternatives-03' => '{"items":[{"id":"a","dimensions":{"length":"40","width":"30","height":"20"},"quantity":5},{"id":"b","dimensions":{"length":"60","width":"50","height":"40"},"quantity":3}],"containers":[{"id":"c","inner_dimensions":{"length":"150","width":"150","height":"150"},"quantity":3}],"configuration":{"solver_profile":"balanced","alternatives":4,"time_limit_ms":300000,"effort_budget":{"max_candidates_evaluated":1000000,"max_placement_attempts":1000000,"max_search_nodes":1000000}}}', + 'feature-made-to-measure-multi-box' => '{"units":{"length":"mm"},"configuration":{"solver_profile":"balanced","time_limit_ms":300000,"minimum_support_ratio":1,"effort_budget":{"max_candidates_evaluated":1000000,"max_placement_attempts":1000000,"max_search_nodes":1000000}},"items":[{"id":"cube","quantity":30,"weight":"100","dimensions":{"length":"100","width":"100","height":"100"}}],"containers":[{"id":"machine","cost_minor":40,"inner_dimensions":{"length":"300","width":"300","height":"300"},"made_to_measure":{"minimum":{"length":"50","width":"50","height":"50"},"increment":{"length":"10","width":"10","height":"10"},"cost_per_square_metre_minor":1000,"outer_allowance":{"length":"3","width":"3","height":"3"}}}]}', + 'feature-axle-gross' => '{"units":{"length":"mm"},"configuration":{"solver_profile":"fast","time_limit_ms":300000,"effort_budget":{"max_candidates_evaluated":1000000,"max_placement_attempts":1000000,"max_search_nodes":1000000}},"items":[{"id":"payload","quantity":1,"dimensions":{"length":"10","width":"10","height":"10"},"weight":{"value":"1000","unit":"g"},"allowed_rotations":["LWH"]}],"containers":[{"id":"vehicle","inner_dimensions":{"length":"100","width":"10","height":"10"},"tare_weight":{"value":"1000","unit":"g"},"axles":[{"position":"0","max_load":{"value":"2000","unit":"g"}},{"position":"100","max_load":{"value":"2000","unit":"g"}}]}]}', + ]; + + /** @param mixed $value */ + private static function assertStreamsAsEncoded($value, string $message = ''): void + { + self::assertSame(\json_encode($value, self::FLAGS), self::streamed($value), $message); + } + + public static function testAResultWithAlternativesStreamsAsItEncodes(): void + { + foreach (self::RESULT_SHAPE_REQUESTS as $name => $json) { + $request = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR); + self::assertStreamsAsEncoded(ArrayCodec::pack($request), $name); + } + } + + public static function testEveryShapeJsonEncodeDistinguishesIsKept(): void + { + $leaf = ['path' => 'a/b', 'text' => "line\nbreak \u{2028} \u{e9}", 'float' => 0.1, 'whole' => 1.0, 'none' => null, 'yes' => true]; + $value = [ + 'empty_list' => [], + 'empty_object' => new stdClass(), + 'object' => (object) ['k' => [1, 2]], + 'integer_keys' => [3 => 'c', 1 => 'a'], + 'numeric_string_key' => ['7' => ['x' => 1]], + 'gapped_list' => [0 => 'a', 2 => 'b'], + 'nested' => [[[], [[]]], \array_fill(0, 80, [])], + 'long' => \array_fill(0, 100, $leaf), + 'list_of_lists' => \array_fill(0, 30, \array_fill(0, 5, $leaf)), + 'unicode_key_é/' => \range(1, 70), + ]; + self::assertStreamsAsEncoded($value); + self::assertStreamsAsEncoded([]); + self::assertStreamsAsEncoded('scalar/text'); + self::assertStreamsAsEncoded(\range(1, 65)); + } + + 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::assertSame(\json_encode($value, self::FLAGS), $streamed); + } + + public static function testAStreamThatRefusesTheWriteIsAnError(): void + { + $path = (string) \tempnam(\sys_get_temp_dir(), 'packvium-json'); + $readOnly = \fopen($path, 'rb'); + try { + self::assertThrows(\RuntimeException::class, static function () use ($readOnly): void { + @PrettyJsonStream::write(['a' => 1], $readOnly); + }); + } finally { + \fclose($readOnly); + \unlink($path); + } + } + + public static function testAValueJsonCannotHoldIsRefused(): void + { + self::assertThrows(\JsonException::class, static function (): void { + self::streamed(['rows' => \array_fill(0, 70, 1.0), 'bad' => \NAN]); + }); + } +} diff --git a/tests/RequestErrorTest.php b/tests/RequestErrorTest.php index fc5342e..bf7eb2d 100644 --- a/tests/RequestErrorTest.php +++ b/tests/RequestErrorTest.php @@ -68,7 +68,7 @@ public static function testEachRuleNamesTheValueItBroke(): void 'unknown profile' => [static function (array &$r): void { $r['configuration']['solver_profile'] = 7; }, 'not_allowed', '/configuration/solver_profile', 'must be one of ["fast","balanced","quality","exact_small"]'], 'unknown objective' => [static function (array &$r): void { $r['configuration']['objective'] = 'cheapest'; }, - 'not_allowed', '/configuration/objective', 'must be one of ["default","lowest_cost","shipping_cost","lowest_landed_cost","open_dimension_height","maximum_value"]'], + 'not_allowed', '/configuration/objective', 'must be one of ["default","lowest_cost","shipping_cost","lowest_landed_cost","open_dimension_height","maximum_value","maximum_volume"]'], 'unknown access direction' => [static function (array &$r): void { $r['containers'][0]['access_directions'] = ['upwards']; }, 'not_allowed', '/containers/0/access_directions/0', 'must be one of ["+x","-x","+y","-y","+z","-z"]'], 'unknown configuration key' => [static function (array &$r): void { $r['configuration']['top_k'] = 2; $r['configuration']['profile'] = 'balanced'; }, @@ -89,6 +89,16 @@ public static function testEachRuleNamesTheValueItBroke(): void 'wrong_type', '/items', 'must be a list'], 'id a number' => [static function (array &$r): void { $r['items'][0]['id'] = 7; }, 'wrong_type', '/items/0/id', 'must be a string'], + 'stacking group a number' => [static function (array &$r): void { $r['items'][0]['stacking_group'] = 7; }, + 'wrong_type', '/items/0/stacking_group', 'must be a string'], + 'stacking group empty' => [static function (array &$r): void { $r['items'][0]['stacking_group'] = ''; }, + 'invalid_value', '/items/0/stacking_group', 'must not be empty'], + 'accepted groups not a list' => [static function (array &$r): void { $r['items'][0]['accepts_stacking_groups'] = 'A'; }, + 'wrong_type', '/items/0/accepts_stacking_groups', 'must be a list'], + 'accepted group a number' => [static function (array &$r): void { $r['items'][0]['accepts_stacking_groups'] = ['A', 3]; }, + 'wrong_type', '/items/0/accepts_stacking_groups/1', 'must be a string'], + 'accepted group empty' => [static function (array &$r): void { $r['items'][0]['accepts_stacking_groups'] = ['A', '']; }, + 'invalid_value', '/items/0/accepts_stacking_groups/1', 'must not be empty'], 'huge negative stop' => [static function (array &$r): void { $r['items'][0]['stop_index'] = -1.0e19; }, 'below_minimum', '/items/0/stop_index', 'must be at least 0'], 'ratio as text' => [static function (array &$r): void { $r['items'][0]['compression_ratio'] = '0.5'; }, diff --git a/tests/SerializationTest.php b/tests/SerializationTest.php index 5025697..3068f5e 100644 --- a/tests/SerializationTest.php +++ b/tests/SerializationTest.php @@ -3,7 +3,10 @@ namespace Packvium\Tests; +use Packvium\Config\PackingConfig; +use Packvium\Domain\{Container, Dimensions, Item}; use Packvium\Domain\ReasonProof; +use Packvium\Packer; use Packvium\Serialization\ArrayCodec; use Packvium\Serialization\InvalidRequestException; use Packvium\Unit\Length; @@ -59,6 +62,35 @@ public static function testTheResultIsPlainData(): void self::assertEquals($result, json_decode(json_encode($result), true)); } + public static function testEveryPlacementReadsAsItsOwnQuantitiesSerialize(): void + { + // Equal lengths, sizes and top loads share one array in the result; each must still + // read exactly as that placement's own Point, Dimensions and Weight serialize, in the + // winner and in every alternative, in whatever units were asked for. + $items = [ + Item::create('a', Dimensions::mm(30, 20, 10), 5, 9), + Item::create('b', Dimensions::mm(25, 25, 15), 7, 6), + ]; + $box = Container::create('c', Dimensions::mm(100, 60, 40)); + $result = (new Packer(new PackingConfig(topK: 3)))->pack($items, [$box]); + $serialized = $result->toArray('in', 'kg'); + self::assertTrue($result->alternatives !== []); + $placements = 0; + foreach ([[$result, $serialized], ...array_map(null, $result->alternatives, $serialized['alternatives'])] as [$answer, $array]) { + foreach ($answer->containers as $c => $container) { + self::assertSame($container->container->innerDimensions->toArray('in'), $array['containers'][$c]['inner_dimensions']); + foreach ($container->placements as $p => $placement) { + $row = $array['containers'][$c]['placements'][$p]; + self::assertSame($placement->position->toArray('in'), $row['position']); + self::assertSame($placement->dimensions->toArray('in'), $row['dimensions']); + self::assertSame($placement->topLoad->toArray('kg'), $row['top_load']); + $placements++; + } + } + } + self::assertTrue($placements > 15); + } + public static function testTheDocumentedTopLevelKeysAreAllPresent(): void { $result = ArrayCodec::pack(self::request([self::cube('a', 50)], [self::box('c')])); diff --git a/tests/SolverTest.php b/tests/SolverTest.php index 414ce25..ceff652 100644 --- a/tests/SolverTest.php +++ b/tests/SolverTest.php @@ -210,12 +210,13 @@ private static function threeTypeOrderScenario(): array ]; } - public static function testThePortfolioDropsFromSixteenStartsToNineOnAThreeTypeOrder(): void + public static function testThePortfolioDropsFromSixteenStartsToNineAndAddsOneBlockStart(): void { // The acceptance criterion, made executable rather than only claimed in prose: // this scene naively runs 2 solvers (extreme_points, layer) x 8 orders = 16 // starts; declaring LayerSolver order-insensitive collapses its eight down to - // one, leaving 8 + 1 = 9. + // one, leaving 8 + 1 = 9. The block start `balanced` adds where the lattice can + // express the request is the tenth, and the last. $items=self::threeTypeOrderScenario(); $container=Container::create('box',Dimensions::mm(100,100,100)); $config=PackingConfig::balanced(); @@ -223,14 +224,15 @@ public static function testThePortfolioDropsFromSixteenStartsToNineOnAThreeTypeO $run=(new SolverOrchestrator())->solvePortfolio($items,[$container],$config,self::generous()); - self::assertCount(9,$run->starts); - $bySolver=['extreme_points'=>0,'layer'=>0]; + self::assertCount(10,$run->starts); + $bySolver=['extreme_points'=>0,'layer'=>0,'homogeneous_blocks'=>0]; foreach($run->starts as $start){ [$solverName]=explode(':',$start->id,2); self::assertTrue(array_key_exists($solverName,$bySolver),"unexpected solver in start id: {$start->id}"); $bySolver[$solverName]++; } - self::assertSame(['extreme_points'=>8,'layer'=>1],$bySolver); + self::assertSame(['extreme_points'=>8,'layer'=>1,'homogeneous_blocks'=>1],$bySolver); + self::assertTrue(str_starts_with($run->starts[9]->id,'homogeneous_blocks:')); } public static function testALayerSolverProducesTheIdenticalPackingRegardlessOfTheOrderItIsHanded(): void @@ -404,6 +406,140 @@ public static function testBlockSearchFallsBackForCompressibleItems(): void self::assertPhysicallySound($solution->state); } + // ------------------------------------------- the block start of `fast` and `balanced` + + /** @return list */ + private static function fourSimilarCartons(): array + { + return [...self::instances('b1',350,250,140),...self::instances('b2',350,250,140),...self::instances('b3',350,230,130),...self::instances('b4',350,250,140)]; + } + + /** @return array{0:list,1:\Packvium\Algorithm\PortfolioRun} */ + private static function startSolvers(array $items,array $containers,PackingConfig $config): array + { + $run=(new SolverOrchestrator())->solvePortfolio($items,$containers,$config,self::generous()); + return [array_map(static fn($start):string=>explode(':',$start->id,2)[0],$run->starts),$run]; + } + + private static function blockStart(array $items,PackingConfig $config,array $containers): ?HomogeneousBlockSolver + { + return (new ReflectionMethod(SolverOrchestrator::class,'blockStart'))->invoke(new SolverOrchestrator(),$items,$config,$containers); + } + + public static function testFastAndBalancedEndWithABlockStartWhereTheLatticeCanExpressTheRequest(): void + { + $containers=[Container::create('box',Dimensions::mm(600,400,250))]; + foreach([PackingConfig::fast(),PackingConfig::balanced()] as $config){ + [$solvers]=self::startSolvers(self::fourSimilarCartons(),$containers,$config); + self::assertSame('homogeneous_blocks',$solvers[count($solvers)-1]); + self::assertCount(1,array_keys($solvers,'homogeneous_blocks',true)); + } + } + + public static function testTheBlockStartWinsOnlyByAStrictlyBetterScore(): void + { + // The per-item search needs a second box for these four cartons; the lattice does not. + $containers=[Container::create('box',Dimensions::mm(600,400,250))]; + [,$improved]=self::startSolvers(self::fourSimilarCartons(),$containers,PackingConfig::balanced()); + self::assertSame(1,min(array_map(static fn($solution):int=>count($solution->containers),$improved->solutions))); + $inOneBox=array_values(array_filter($improved->solutions,static fn($solution):bool=>count($solution->containers)===1)); + self::assertSame(['homogeneous_blocks:volume'],array_map(static fn($solution):string=>$solution->solverName,$inOneBox)); + + // Two cubes that any start stacks into one box: the lattice ties, so its answer is dropped. + $cubes=[...self::instances('light',100,100,100,['weight'=>1]),...self::instances('heavy',100,100,100,['weight'=>3])]; + $tower=[Container::create('box',Dimensions::mm(100,100,200))]; + [$solvers,$tied]=self::startSolvers($cubes,$tower,PackingConfig::fast()); + self::assertSame('homogeneous_blocks',$solvers[count($solvers)-1]); + foreach($tied->solutions as $solution)self::assertFalse(str_starts_with($solution->solverName,'homogeneous_blocks')); + } + + public static function testTheBlockStartStaysOutWhereTheLatticeCannotHonourTheRequest(): void + { + $box=[Container::create('box',Dimensions::mm(600,400,250))]; + $cartons=self::fourSimilarCartons(); + $oneType=self::instances('only',100,100,100,['quantity'=>4]); + $prioritised=[...self::instances('first',350,250,140,['priority'=>5]),...self::instances('rest',350,230,130,['quantity'=>3])]; + $floorOnly=[...self::instances('floor',350,250,140,['mustBeOnFloor'=>true]),...self::instances('free',350,230,130)]; + $starts=new ReflectionMethod(SolverOrchestrator::class,'starts'); + foreach([ + [$cartons,PackingConfig::quality()], + [$cartons,new PackingConfig(solvers:['extreme_points'])], + [$oneType,PackingConfig::balanced()], + [$prioritised,PackingConfig::balanced()], + [$floorOnly,PackingConfig::balanced()], + ] as [$items,$config]){ + $added=array_filter( + $starts->invoke(new SolverOrchestrator(),$items,$config,$box), + static fn(array $start):bool=>$start[0] instanceof HomogeneousBlockSolver&&$start[0]->nodeLimit!==null, + ); + self::assertSame([],$added); + } + } + + public static function testACountedLimitStopsTheBlockSolverOnTheNodeThePerNodeWalkStoppedAt(): void + { + // The solver counts a whole lattice group in one step and ranks only groups that can + // lead. Each row is [limit, placements, stopped]: the limit from which that outcome + // holds, pinned from the per-node walk over every limit from 1 to 7000, so a stop + // must land on the same node, in a node limit and in an effort budget alike. + $items=[...self::instances('a',108,76,30,['quantity'=>40]),...self::instances('b',110,43,25,['quantity'=>33]), + ...self::instances('c',92,81,55,['quantity'=>39]),...self::instances('d',61,47,33,['quantity'=>12])]; + $box=Container::create('box',Dimensions::mm(587,233,220)); + $steps=[ + 'count'=>[[1,0,true],[727,40,true],[1580,73,true],[2120,87,true],[2723,99,true],[3065,105,true],[3397,108,true],[3721,108,false]], + 'volume'=>[[1,0,true],[727,36,true],[1578,54,true],[2809,86,true],[3642,94,true],[4508,101,true],[5271,105,true],[5829,106,true],[6350,107,true],[6837,107,false]], + ]; + foreach($steps as $mode=>$rows){ + $total=$rows[count($rows)-1][0]; + foreach($rows as $row=>[$from,$placed,$stopped]){ + foreach(array_unique([$from-1,$from,$from+1]) as $limit){ + if($limit<1)continue; + [$expectedPlaced,$expectedStopped]=$limit<$from?[$rows[$row-1][1],$rows[$row-1][2]]:[$placed,$stopped]; + if($limit>$from&&isset($rows[$row+1])&&$limit>=$rows[$row+1][0])continue; + $stats=new SearchStats(); + $solution=(new HomogeneousBlockSolver([],null,[$mode],$limit))->packOne($box,1,$items,PackingConfig::fast(),$stats,self::generous()); + self::assertSame(min($limit,$total),$stats->searchNodesExpanded,"{$mode} node limit {$limit}"); + self::assertSame($expectedPlaced,count($solution->state->placements),"{$mode} node limit {$limit}"); + self::assertSame($expectedStopped,$solution->timeLimitReached,"{$mode} node limit {$limit}"); + $effort=new SearchStats(); + $budget=self::generous()->withEffort(new EffortBudget(maxSearchNodes:$limit),$effort); + $limited=(new HomogeneousBlockSolver([],null,[$mode],1_000_000))->packOne($box,1,$items,PackingConfig::fast(),$effort,$budget); + self::assertSame(min($limit,$total),$effort->searchNodesExpanded,"{$mode} effort budget {$limit}"); + self::assertSame($expectedPlaced,count($limited->state->placements),"{$mode} effort budget {$limit}"); + } + } + } + } + + public static function testLatticeNodeCountsAndLargestBlocksMatchTheWalk(): void + { + // The closed-form node count and the early-stopping largest block, against the + // per-node walk they replace: every (X, Y, Z, capacity) up to 9, 9, 6 and 120. + $nodes=new ReflectionMethod(HomogeneousBlockSolver::class,'latticeNodes'); + $largest=new ReflectionMethod(HomogeneousBlockSolver::class,'largestBlock'); + for($x=1;$x<=9;$x++)for($y=1;$y<=9;$y++)for($z=1;$z<=6;$z++)for($capacity=1;$capacity<=120;$capacity++){ + $walked=0;$best=[0,0,0,0]; + for($nx=1;$nx<=min($x,$capacity);$nx++)for($ny=1;$ny<=min($y,intdiv($capacity,$nx));$ny++){ + $walked++; + $nz=min($z,intdiv($capacity,$nx*$ny)); + if($nx*$ny*$nz>$best[0])$best=[$nx*$ny*$nz,$nx,$ny,$nz]; + } + self::assertSame($walked,$nodes->invoke(null,$x,$y,$capacity)); + $expected=$capacity>=$x*$y*$z?[$x*$y*$z,$x,$y,$z]:$largest->invoke(null,$x,$y,$z,$capacity); + self::assertSame($best,$expected,"{$x} {$y} {$z} {$capacity}"); + } + } + + public static function testTheFastBlockStartEnumeratesOneModeAndBalancedBoth(): void + { + $box=[Container::create('box',Dimensions::mm(600,400,250))]; + $cartons=self::fourSimilarCartons(); + $fastByVolume=new PackingConfig(profile:SolverProfile::Fast,timeLimitMs:200,topK:1,multiStartOrders:1,objective:'maximum_volume'); + self::assertSame(['count'],self::blockStart($cartons,PackingConfig::fast(),$box)->modes); + self::assertSame(['volume'],self::blockStart($cartons,$fastByVolume,$box)->modes); + self::assertSame(['count','volume'],self::blockStart($cartons,PackingConfig::balanced(),$box)->modes); + } + public static function testBeamPackerPrecomputedFutureMatchesStandardEvaluation(): void { $box = Container::create('box', Dimensions::mm(300, 200, 200), quantity: 1); @@ -976,6 +1112,29 @@ public static function testTheFreeSpaceListNeverExceedsTheBudget(): void } } + public static function testTheFreeSpaceOrderIsPinned(): void + { + // Both solvers that carve read spaces in this order, so a faster carve must keep it + // exactly: origin z, y, x, then largest first among spaces sharing an origin, then + // first seen, with the budget cut applied. The digest is of the order the + // per-object implementation produced on 90 two-box carves that reach the budget and + // share origins 7011 times. + $spaces = [self::space(0, 0, 0, 3000, 2000, 1500)]; + $trace = ''; + $stats = new SearchStats(); + 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); + 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};"; + } + $trace .= '|'; + } + self::assertSame('c31307d3e1c0344553ca30788d4fe779', md5($trace)); + self::assertSame(50816, $stats->spacePartitions); + } + public static function testAnAdversarialItemMixStillPlacesCompletelyWithinTheSpaceBudget(): void { // The same growth pattern, driven through the real solver: varied item sizes @@ -1188,6 +1347,35 @@ public static function testTheLatticeFallsBackRatherThanPlacingMixedTypesAtTheWr } } + public static function testTheLatticeKeepsAnItemThatRefusesItsOwnGroupOnTheFloor(): void + { + // Every lattice edge joins two items of one type, so a type whose list omits its + // own group caps the lattice at one layer; accepting it restores the column. + $box = Container::create('c', Dimensions::mm(100, 100, 100)); + $refusing = self::instances('a', 40, 40, 40, ['quantity' => 8, 'stackingGroup' => 'A', 'acceptsStackingGroups' => ['B']]); + $solution = (new GridSolver())->packOne($box, 1, $refusing, PackingConfig::fast(), new SearchStats(), self::generous()); + foreach ($solution->state->placements as $placement) { + self::assertSame(0, $placement->envelopeOrigin->z); + } + self::assertPhysicallySound($solution->state); + $accepting = self::instances('a', 40, 40, 40, ['quantity' => 8, 'stackingGroup' => 'A', 'acceptsStackingGroups' => ['A']]); + $stacked = (new GridSolver())->packOne($box, 1, $accepting, PackingConfig::fast(), new SearchStats(), self::generous()); + self::assertTrue(max(array_map(static fn($p) => $p->envelopeOrigin->z, $stacked->state->placements)) > 0); + $other = self::instances('b', 40, 40, 40, ['stackingGroup' => 'B']); + self::assertFalse((new GridSolver())->supports([...self::instances('a', 40, 40, 40, ['stackingGroup' => 'A']), ...$other])); + } + + public static function testBlockSearchDelegatesWhenAnItemDeclaresAStackingGroupList(): void + { + $box = Container::create('box', Dimensions::mm(100, 100, 200), quantity: 1); + $items = [...self::instances('a', 100, 100, 100, ['acceptsStackingGroups' => ['A']]), + ...self::instances('b', 100, 100, 100, ['stackingGroup' => 'B'])]; + $solution = (new HomogeneousBlockSolver())->packOne($box, 1, $items, PackingConfig::quality(), new SearchStats(), self::generous()); + self::assertSame(1, count($solution->state->placements)); + self::assertSame(1, count($solution->unpacked)); + self::assertPhysicallySound($solution->state); + } + public static function testTheLatticeKeepsNonStackableItemsOnTheFloor(): void { // A regular stack cannot express a per-item rule, so the rule is folded into the @@ -1477,6 +1665,22 @@ public static function testExactEqualCountBoundKeepsALargerRemainingItemReachabl )); } + public static function testTheExactSolverRanksVolumeFirstWhenTheObjectiveDoes(): void + { + $box = Container::create('c', Dimensions::mm(10, 10, 10)); + $items = [...self::instances('small', 3, 10, 10, ['quantity' => 2]), ...self::instances('large', 8, 10, 10)]; + + foreach (['default' => ['small', 'small'], 'maximum_volume' => ['large']] as $objective => $kept) { + $solution = (new ExactSmallSolver())->packOne( + $box, 1, $items, new PackingConfig(profile: SolverProfile::ExactSmall, objective: $objective), + new SearchStats(), self::generous(), + ); + $ids = array_map(static fn(Placement $placement): string => $placement->instance->item->id, $solution->state->placements); + sort($ids); + self::assertSame($kept, $ids, $objective); + } + } + public static function testIsBetterStateComparesPlacedPhysicalVolumeExactlyBeyondFloatPrecision(): void { $twoToThe53 = 9_007_199_254_740_992; @@ -1545,4 +1749,62 @@ public static function testAGreedyGroupBatchForfeitsTheExhaustivenessClaim(): vo ->packOne($box, 1, $items, PackingConfig::exactSmall(), new SearchStats(), self::generous()); self::assertFalse($solution->exhaustive); } + + public static function testContainerStateIncrementalPlacementSignature(): void + { + $box = Container::create('c', Dimensions::mm(300, 300, 300)); + $state = new ContainerState($box, 1); + self::assertSame('', $state->placementSignature()); + + $items = self::instances('item', 100, 100, 100, ['quantity' => 2]); + $p1 = new Placement( + $items[0], + new Point(0, 0, 0), + Rotation::LWH, + $items[0]->item->dimensions, + new Point(0, 0, 0), + $items[0]->item->dimensions, + 1.0 + ); + $state->add($p1); + $expected1 = $items[0]->id() . '@0,0,0'; + self::assertSame($expected1, $state->placementSignature()); + + $p2 = new Placement( + $items[1], + new Point(100 * 16000, 0, 0), + Rotation::LWH, + $items[1]->item->dimensions, + new Point(100 * 16000, 0, 0), + $items[1]->item->dimensions, + 1.0 + ); + $state->add($p2); + $expected2 = $expected1 . '|' . $items[1]->id() . '@1600000,0,0'; + self::assertSame($expected2, $state->placementSignature()); + + // Cloning preserves signature and branches independently + $clone = $state->copy(); + self::assertSame($expected2, $clone->placementSignature()); + + // Reflection test for BeamPacker::signature + $sigMethod = new ReflectionMethod(BeamPacker::class, 'signature'); + self::assertSame($expected2, $sigMethod->invoke(null, $state)); + } + + public static function testDirectPlacementsBuildSignatureOnlyWhenRequested(): void + { + $box = Container::create('c', Dimensions::mm(300, 100, 100)); + $items = self::instances('item', 100, 100, 100, ['quantity' => 2]); + $state = new ContainerState($box, 1); + foreach ($items as $index => $item) { + $origin = new Point($index * 1600000, 0, 0); + $state->addDirect(new Placement( + $item, $origin, Rotation::LWH, $item->dimensions(), $origin, $item->dimensions() + )); + } + $expected = $items[0]->id() . '@0,0,0|' . $items[1]->id() . '@1600000,0,0'; + self::assertSame($expected, $state->placementSignature()); + self::assertSame($expected, $state->copy()->placementSignature()); + } } diff --git a/tests/UnsupportedPlacementTest.php b/tests/UnsupportedPlacementTest.php new file mode 100644 index 0000000..b6dcb7c --- /dev/null +++ b/tests/UnsupportedPlacementTest.php @@ -0,0 +1,118 @@ + 0.5])); + self::assertSame([], $result['warnings']); + } + + public static function testANonzeroRatioNeverCountsEvenAnUnsupportedPlacement(): void + { + $items = [Item::create('cube', Dimensions::mm(100, 100, 100), '1000g', 1)]; + $containers = [Container::create('box', Dimensions::mm(100, 100, 300), 0, null, null, 0, 1)]; + $lifted = new FixedPlacement('cube', 'box', new Point(0, 0, Length::mm(100)->ticks), Rotation::LWH, 1); + $packed = (new Packer(new PackingConfig()))->pack($items, $containers, [$lifted])->containers; + self::assertSame(sprintf(self::WARNING, 1), UnsupportedPlacements::warning($packed, 0.0)); + self::assertNull(UnsupportedPlacements::warning($packed, 0.25)); + } + + public static function testNoContainersMeansNoWarning(): void + { + self::assertNull(UnsupportedPlacements::warning([], 0.0)); + } + + /** + * Two stacked bases, plus a slab in mid-air and a slab on an obstacle when floating. + * + * @param array $configuration + * @return array + */ + private static function scene(bool $floating = true, array $configuration = []): array + { + $placements = [self::fixed('base', '0', '0', '0'), self::fixed('base', '0', '0', '100')]; + $items = [self::cube('base', 2), self::cube('loose', 4)]; + if ($floating) { + $placements[] = self::fixed('slab', '100', '100', '300'); + $placements[] = self::fixed('slab', '200', '0', '100'); + $items[] = self::cube('slab', 2, '50'); + } + return [ + 'items' => $items, + 'containers' => [[ + 'id' => 'crate', 'quantity' => 1, + 'inner_dimensions' => ['length' => '400', 'width' => '200', 'height' => '400'], + 'obstacles' => [['id' => 'shelf', 'origin' => ['x' => '200', 'y' => '0', 'z' => '0'], + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => '100']]], + ]], + 'fixed_placements' => $placements, + 'configuration' => ['solver_profile' => 'quality', 'alternatives' => 3, + 'effort_budget' => ['max_search_nodes' => 20000], 'time_limit_ms' => 60000] + $configuration, + ]; + } + + /** @return array */ + private static function cube(string $id, int $quantity, string $height = '100'): array + { + return ['id' => $id, 'quantity' => $quantity, 'weight' => '500', + 'dimensions' => ['length' => '100', 'width' => '100', 'height' => $height]]; + } + + /** @return array */ + private static function fixed(string $itemType, string $x, string $y, string $z): array + { + return ['item_type' => $itemType, 'container_type' => 'crate', + 'position' => ['x' => $x, 'y' => $y, 'z' => $z], 'orientation' => 'LWH']; + } + + /** + * @param array $result + * @return list + */ + private static function unsupportedWarnings(array $result): array + { + return array_values(array_filter( + $result['warnings'], + static fn(string $line): bool => str_starts_with($line, 'unsupported_placements:'), + )); + } +} diff --git a/tests/ValidationTest.php b/tests/ValidationTest.php index 5d97f66..f218b7e 100644 --- a/tests/ValidationTest.php +++ b/tests/ValidationTest.php @@ -579,6 +579,37 @@ public static function testTheStackingRuleIsCheckedAgainstLaterPlacementsToo(): self::assertContains('non_stackable', Support::issues([$base, $load], [$box], [$reversed])); } + public static function testAnItemOnOneThatDoesNotAcceptItsStackingGroupIsCaught(): void + { + $base = self::item('base', 100, 100, 50, ['stackingGroup' => 'A', 'acceptsStackingGroups' => ['A', 'B']]); + $drum = self::item('load', 100, 100, 50, ['stackingGroup' => 'C']); + $carton = self::item('load', 100, 100, 50, ['stackingGroup' => 'B']); + $box = self::shelf(); + [$baseInstance] = $base->instances(); + foreach ([$drum, $carton] as $load) { + [$loadInstance] = $load->instances(); + foreach ([false, true] as $loadFirst) { + $placements = [self::place($baseInstance), self::place($loadInstance, z: 50 * self::MM)]; + $packed = new PackedContainer($box, 1, $loadFirst ? array_reverse($placements) : $placements); + $issues = Support::issues([$base, $load], [$box], [$packed]); + self::assertSame($load === $drum, in_array('stacking_group_incompatible', $issues, true)); + } + } + } + + public static function testANonStackableItemWithAListReportsOnlyNonStackable(): void + { + $base = self::item('base', 100, 100, 50, ['stackable' => false, 'acceptsStackingGroups' => ['B']]); + $load = self::item('load', 100, 100, 50, ['stackingGroup' => 'C']); + $box = self::shelf(); + [$baseInstance] = $base->instances(); + [$loadInstance] = $load->instances(); + $packed = new PackedContainer($box, 1, [self::place($baseInstance), self::place($loadInstance, z: 50 * self::MM)]); + $issues = Support::issues([$base, $load], [$box], [$packed]); + self::assertContains('non_stackable', $issues); + self::assertFalse(in_array('stacking_group_incompatible', $issues, true)); + } + // --------------------------------------------------------- ground contact public static function testARatioThatWouldPassIsStillCaughtByTheCornerRule(): void