diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml index 1c94bf5..ee0cb51 100644 --- a/.github/DISCUSSION_TEMPLATE/q-a.yml +++ b/.github/DISCUSSION_TEMPLATE/q-a.yml @@ -10,7 +10,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium 1.10.0 (Python)" + placeholder: "packvium 1.11.0 (Python)" validations: required: true - type: textarea diff --git a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml index 5b71630..26cb55f 100644 --- a/.github/DISCUSSION_TEMPLATE/show-and-tell.yml +++ b/.github/DISCUSSION_TEMPLATE/show-and-tell.yml @@ -16,7 +16,7 @@ body: id: package-version attributes: label: Package and version - placeholder: "packvium 1.10.0 (Python)" + placeholder: "packvium 1.11.0 (Python)" validations: required: false - type: textarea diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 1bad155..e177e5f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -33,8 +33,8 @@ body: id: version attributes: label: Package version - description: The exact version installed, for example 1.10.0. - placeholder: "1.10.0" + description: The exact version installed, for example 1.11.0. + placeholder: "1.11.0" validations: required: true - type: input @@ -101,5 +101,5 @@ body: options: - label: I searched the existing issues and did not find this one. required: true - - label: I read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-python/blob/HEAD/docs/GUARANTEES.md) and this is not something it says the library does not guarantee. + - label: I read [docs/GUARANTEES.md](https://github.com/packvium/packvium-python/blob/HEAD/docs/GUARANTEES.md) and this is not something it says the library does not guarantee. required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 4c80f76..187be71 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,10 +1,10 @@ blank_issues_enabled: false contact_links: - name: Question or help with a request - url: https://github.com/toxakara/packvium-python/discussions/categories/q-a + url: https://github.com/packvium/packvium-python/discussions/categories/q-a about: Ask in Discussions → Q&A. Answers there help the next person too. - name: Report a security vulnerability - url: https://github.com/toxakara/packvium-python/security/advisories/new + url: https://github.com/packvium/packvium-python/security/advisories/new about: Report privately. Do not open a public issue for a security problem. - name: Documentation url: https://packvium.com/docs diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index def1855..ecd0ecc 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -29,7 +29,7 @@ body: id: version attributes: label: Package version - placeholder: "1.10.0" + placeholder: "1.11.0" validations: required: true - type: textarea diff --git a/.github/workflows/rc.yml b/.github/workflows/rc.yml index a0275d6..9eaa551 100644 --- a/.github/workflows/rc.yml +++ b/.github/workflows/rc.yml @@ -6,7 +6,7 @@ name: rc # # Before the first RC, once (the owner): # 1. Create an account on https://test.pypi.org (separate from the PyPI one) and enable 2FA. -# 2. Add a pending Trusted Publisher for project `packvium`: owner `toxakara`, repository +# 2. Add a pending Trusted Publisher for project `packvium`: owner `packvium`, repository # `packvium-python`, workflow `rc.yml`, environment `testpypi`. # 3. In this repository, create a GitHub environment named `testpypi` with the same # reviewers as `pypi`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 70cbf8d..3717ea9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,41 @@ What changed in `packvium` on PyPI, release by release. The format follows [Keep a Changelog](https://keepachangelog.com/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.11.0] + +Bottom gussets and standing pouches, a certified bound for the shipping objectives, one money +ceiling, one measure grammar, and request objects that own their mappings. + +### Added + +- **`deformable_boundary.bottom_gusset_depth` and `orientation: "standing"`** on a + `gusseted_bag`. A bottom gusset lengthens the girth along the bag; a standing pouch is packed + upright in a `W x H x L` frame. `Container` gains `bottom_gusset_depth`, `bag_orientation` and + `girth`. +- **`optimality.lower_bound` and the gap under `shipping_cost` and `lowest_landed_cost`**; + `validate` checks them. +- **`examples/checkout.py` and `examples/fulfilment.py`.** + +### Changed + +- **A `rate_table` priced above 9007199254740991 minor units** at its top bracket, surcharge + included, is `invalid_request` / `above_maximum`. A commerce quote refuses an amount above it + instead of answering, and a revision refuses a stock box priced above it. +- **Measures are ASCII decimals and fractions only:** `1e2`, `1_00`, `.5`, `5.`, `nan` and + non-ASCII digits are `wrong_type`, as in the other engines. +- **`hull_vertices` holds at most 32 points**; a non-list is `wrong_type` / `must be a list` on + the object path too. +- **`Container.tag_limits` is read-only**, `metadata` is a copy of the caller's dicts and lists, + a `CatalogSnapshot` holds tuples and a `Tariff`'s mappings are read-only. Pickling, `copy` and + `dataclasses.replace` work as before. +- **The "why unpacked" reason no longer depends on a 2 s clock.** + +### Fixed + +- **A very long measure took time quadratic in its length** (48 s for a 1 MB weight); it is + refused in milliseconds. +- **`effort_budget` limits written as `1000.0`** crashed the solver; they now read as integers. + ## [1.10.0] New request fields, a bound under three more objectives, and the intelligence modules join the diff --git a/CITATION.cff b/CITATION.cff index 42f9c9a..e0a615f 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,10 +5,10 @@ type: software authors: - name: "Packvium contributors" website: "https://packvium.com" -version: "1.10.0" +version: "1.11.0" license: MIT url: "https://packvium.com" -repository-code: "https://github.com/toxakara/packvium-python" +repository-code: "https://github.com/packvium/packvium-python" repository-artifact: "https://pypi.org/project/packvium/" abstract: >- Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results. diff --git a/README.md b/README.md index 2b4bec6..c22e697 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,25 @@ # Packvium for Python -Deterministic 3D cartonization and rectangular bin packing. Pure Python, **no runtime -dependencies**, exact integer geometry. +Deterministic 3D bin packing and cartonization in pure Python. No runtime dependencies, +and exact integer geometry instead of floats. Use it to pick the smallest carton for an order, build a pallet, load a shipping container, or load a truck within its axle ratings and delivery-stop order. Every answer comes back as coordinates and rotations for each item, with a reason for anything that did not fit. -Full documentation, the constraint reference and benchmarks live at -[packvium.com](https://packvium.com). - -> **Version 1.10.0 — the public API is frozen.** Field names, status codes and the +> **Version 1.11.0 — the public API is frozen.** Field names, status codes and the > objective vector do not change without a major version, so any `1.x` is a safe upgrade > from any earlier `1.x`. -> Read [docs/GUARANTEES.md](https://github.com/toxakara/packvium-python/blob/main/docs/GUARANTEES.md) before relying on a result. +> Read [docs/GUARANTEES.md](https://github.com/packvium/packvium-python/blob/main/docs/GUARANTEES.md) before relying on a result. + +## Install ```bash pip install packvium ``` +Python 3.9 or newer. Nothing else is installed with it. + ## Quick start ```python @@ -53,11 +54,83 @@ echo '{"items":[{"id":"box","quantity":8,"dimensions":{"length":"50","width":"50 | python -m 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 — `PackingConfig.balanced(minimum_support_ratio=0.75)`, -or `"configuration": {"minimum_support_ratio": 0.75}` in JSON. +The result is the same in both forms: `status`, the containers that were opened with a +placement for every unit, and `unpacked_items` with a reason for each item left out. + +## Using it in your project + +Two examples are written the way application code is written, with your own product and +order records on one side and the library call in the middle. Start from the one closer to +what you are building. + +| You are building | Start from | What it does | +| --- | --- | --- | +| A checkout or cart page | [`checkout.py`](https://github.com/packvium/packvium-python/blob/main/examples/checkout.py) | Maps a cart onto a request, picks the cheapest cartons, and reads the parcels back for the page. Two functions hold everything Packvium-specific. | +| A warehouse or fulfilment job | [`fulfilment.py`](https://github.com/packvium/packvium-python/blob/main/examples/fulfilment.py) | Runs an order from paid to labelled: a shipping rule picks the carrier service, the order is packed under its constraints, `validate` checks the plan, and every parcel is priced from a pinned tariff. | +| An HTTP endpoint that packs | [`errors.py`](https://github.com/packvium/packvium-python/blob/main/examples/errors.py) | Turns each kind of refused request into a 422 that names the item and the value. | +| A dock or driver screen | [`execution.py`](https://github.com/packvium/packvium-python/blob/main/examples/execution.py), [`trucking.py`](https://github.com/packvium/packvium-python/blob/main/examples/trucking.py) | Turns a result into numbered loading steps, and loads a van by stop and axle rating. | + +Rules that most projects need on day one: + +- An item that does not fit is not an error. The result lists it in `unpacked_items` with a + reason, and everything else is still packed. +- Support is not required by default: `minimum_support_ratio` is 0, so an item may rest on + nothing above the container floor, and the result then says so in `warnings` + (`unsupported_placements: N placement(s) rest on nothing above the container floor; ...`). + To require support, set it above 0: `PackingConfig.balanced(minimum_support_ratio=0.75)`, + or `"configuration": {"minimum_support_ratio": 0.75}` in JSON. +- Set an `effort_budget` for any answer you store or show twice. See + [Getting the same answer every time](#getting-the-same-answer-every-time). + +## Errors + +A request that no engine may answer raises `packvium.InvalidRequestError`, a `ValueError`, +before anything is solved. It names the problem instead of describing it: + +```python +from packvium import InvalidRequestError, pack_from_dict + +try: + result = pack_from_dict(request) +except InvalidRequestError as error: + error.code # "invalid_request" + error.reason # "below_minimum" + error.field # "/items/0/quantity" -- a JSON Pointer into your request + str(error) # "invalid_request: /items/0/quantity: must be at least 1" +``` + +`reason` is one of `missing_field`, `wrong_type`, `below_minimum`, `above_maximum`, +`negative_measure`, `invalid_unit`, `duplicate_id`, `not_allowed` or `invalid_value`. +`FixedPlacementError` is a subclass, with code `invalid_fixed_placement` and reason +`malformed` or `cannot_hold`. The message is the same in every Packvium engine. Branch on +`reason` and `field`; show the message to a person. + +An unknown `objective` or `access_directions` value in a request is refused with +reason `not_allowed` and the JSON Pointer of the bad value (direct domain model constructors +raise `UnknownObjectiveError` or `InvalidDirectionError`). A request that is +valid but does not fit completely is not an error: the result lists what was left out, and +why, in `unpacked_items`. `errors.py` turns all of these into HTTP responses. + +## Checking a result + +*New in 1.7.0.* + +`packvium.validate` checks a result against the request it answers, from the JSON documents +alone: geometry, support and load, accounting, the result's facts and its score. It is the +reference validator every Packvium package exports a port of, so they all return the same +issues, code and detail: + +```python +from packvium import MalformedResult, pack_from_dict, validate + +issues = validate(request, pack_from_dict(request)) # [] -- valid +for issue in issues: + print(issue.code, issue.detail) # e.g. collision cube#1 with cube#2 in box#1 +``` + +It shares no code with the engine, so it judges any engine's result, not only this package's. A +result without the documented shape raises `MalformedResult`, whose `kind` is `contract` or +`shape`. ## Units @@ -73,7 +146,7 @@ Item.create("mug", Dimensions.mm("100", "100", "120"), "12 oz") A JSON request refuses a float measure rather than rounding it: send `"160.5"`, not `160.5`. Its `units` sets only the length unit; a weight takes its unit from the measure or is grams; any other `units` key, `weight` included, is refused. See -[docs/UNITS-AND-NUMERICS.md](https://github.com/toxakara/packvium-python/blob/main/docs/UNITS-AND-NUMERICS.md). +[docs/UNITS-AND-NUMERICS.md](https://github.com/packvium/packvium-python/blob/main/docs/UNITS-AND-NUMERICS.md). ## Getting the same answer every time @@ -145,89 +218,41 @@ After the solve, `safe_route_removal_order` gives an unloading order stop by sto says what can be reached when the doors open. An item the axle ratings cannot carry even alone in the vehicle is reported as `axle_overloaded`. See `trucking.py`. -## Errors - -A request that no engine may answer raises `packvium.InvalidRequestError`, a `ValueError`, -before anything is solved. It names the problem instead of describing it: - -```python -from packvium import InvalidRequestError, pack_from_dict - -try: - result = pack_from_dict(request) -except InvalidRequestError as error: - error.code # "invalid_request" - error.reason # "below_minimum" - error.field # "/items/0/quantity" -- a JSON Pointer into your request - str(error) # "invalid_request: /items/0/quantity: must be at least 1" -``` - -`reason` is one of `missing_field`, `wrong_type`, `below_minimum`, `above_maximum`, -`negative_measure`, `invalid_unit`, `duplicate_id`, `not_allowed` or `invalid_value`. -`FixedPlacementError` is a subclass, with code `invalid_fixed_placement` and reason -`malformed` or `cannot_hold`. The message is the same in every Packvium engine. Branch on -`reason` and `field`; show the message to a person. - -An unknown `objective` or `access_directions` value in a request is refused with -reason `not_allowed` and the JSON Pointer of the bad value (direct domain model constructors -raise `UnknownObjectiveError` or `InvalidDirectionError`). A request that is -valid but does not fit completely is not an error: the result lists what was left out, and -why, in `unpacked_items`. `errors.py` turns all of these into HTTP responses. - -## Checking a result - -*New in 1.7.0.* - -`packvium.validate` checks a result against the request it answers, from the JSON documents -alone: geometry, support and load, accounting, the result's facts and its score. It is the -reference validator every Packvium package exports a port of, so they all return the same -issues, code and detail: - -```python -from packvium import MalformedResult, pack_from_dict, validate - -issues = validate(request, pack_from_dict(request)) # [] -- valid -for issue in issues: - print(issue.code, issue.detail) # e.g. collision cube#1 with cube#2 in box#1 -``` - -It shares no code with the engine, so it judges any engine's result, not only this package's. A -result without the documented shape raises `MalformedResult`, whose `kind` is `contract` or -`shape`. - ## Examples -Runnable, in [`examples/`](https://github.com/toxakara/packvium-python/tree/main/examples), +Runnable, in [`examples/`](https://github.com/packvium/packvium-python/tree/main/examples), and included in the source distribution. Each one is a single file you can read top to bottom. Every one of them is executed by the test suite on each release, so none of them can quietly stop working. -New here? Read `basic.py`, then `objectives.py` — between them they cover what most -callers need. `units.py` and `serialization.py` explain the two design choices that +New here? Read `basic.py`, then `objectives.py`. Between them they cover what most +callers need, and `checkout.py` shows the same call inside a project. `units.py` and `serialization.py` explain the two design choices that surprise people. `extensions.py` is last on purpose: reach for it only after the fields in `constraints.py` and `limits.py` have failed you. | File | What it shows | | --- | --- | -| [`basic.py`](https://github.com/toxakara/packvium-python/blob/main/examples/basic.py) | The smallest useful call: items in, placements out — and the three details in it that are easy to miss. | -| [`objectives.py`](https://github.com/toxakara/packvium-python/blob/main/examples/objectives.py) | Six of the seven objectives (all but `maximum_volume`) on scenes where they genuinely disagree, including the rate card that makes the heavier shipment the cheaper one, a rate card's `currency`, and the lower bound that proves the value left behind is the least possible. | -| [`constraints.py`](https://github.com/toxakara/packvium-python/blob/main/examples/constraints.py) | Upright-only, floor-only, non-stackable, top-load limits, and tags that keep two items out of the same box — plus how to read the reason an item was refused, and a crate allowed past the pallet deck by `pallet_overhang_limit`. | -| [`limits.py`](https://github.com/toxakara/packvium-python/blob/main/examples/limits.py) | A courier fleet: a van with a fridge unit and wheel arches as obstacles, an item cap per bike, one dangerous-goods item per van, frozen goods only in a refrigerated vehicle, and a cap on vehicles. | -| [`units.py`](https://github.com/toxakara/packvium-python/blob/main/examples/units.py) | Why there are no floats anywhere: fractional inches, exact ticks, and the one-tick difference between a fit and a refusal. | -| [`serialization.py`](https://github.com/toxakara/packvium-python/blob/main/examples/serialization.py) | The same request as JSON, the result in full, and exactly which mistakes are refused and which are silently ignored. | -| [`errors.py`](https://github.com/toxakara/packvium-python/blob/main/examples/errors.py) | A web handler: refused requests turned into a 422 with a pointer and a message a person can act on, fixed placements that cannot hold, and a partial fit that is not an error. | -| [`reproducibility.py`](https://github.com/toxakara/packvium-python/blob/main/examples/reproducibility.py) | Why a clock-limited search answers differently on a busy machine, how an effort budget fixes it, and how to read `termination`. | -| [`trucking.py`](https://github.com/toxakara/packvium-python/blob/main/examples/trucking.py) | A three-stop delivery van within its axle ratings: loading and unloading order, what the driver can reach at each stop, and the same goods packed without a route. | -| [`fixed_placements.py`](https://github.com/toxakara/packvium-python/blob/main/examples/fixed_placements.py) | A trailer that arrives partly loaded: new pallets packed around the ones already on board, a record of what is on board that cannot be true, and a loaded pallet fixed by quoting its `placement_id`. | -| [`rebalancing.py`](https://github.com/toxakara/packvium-python/blob/main/examples/rebalancing.py) | Two pallets of very different weight evened out after packing, one validated move at a time. | -| [`shapes.py`](https://github.com/toxakara/packvium-python/blob/main/examples/shapes.py) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, two copies of one wedge that need a signed rotation such as `-L-W+H`, a cushion that compresses under load until the crush limit refuses it, and a gusseted bag that holds a layer more than a flat one. | -| [`nested.py`](https://github.com/toxakara/packvium-python/blob/main/examples/nested.py) | Units into cartons, cartons onto a pallet, in one call, and `level_beam_width` letting the pallet pick a dearer carton set that packs better. | -| [`commerce.py`](https://github.com/toxakara/packvium-python/blob/main/examples/commerce.py) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | -| [`execution.py`](https://github.com/toxakara/packvium-python/blob/main/examples/execution.py) | Turn a result into dock instructions: solver facts kept apart from screen text, a step order that is injected or honestly absent, and an operator lock that yields a second plan rather than editing the approved one. | -| [`artifacts.py`](https://github.com/toxakara/packvium-python/blob/main/examples/artifacts.py) | Hand a result to a system with no engine: one document with the plan, geometry and the request that produced it, exported as CSV and a printable work order, with an honest replay level. | -| [`revisions.py`](https://github.com/toxakara/packvium-python/blob/main/examples/revisions.py) | Replan a half-loaded job: a missing item and a locked placement recorded against the approved plan, a replan that keeps the locked item in place, a hash-chained record that notices an edit, and a box already cut to measure (with a void-fill reserve) stocked for the replan. | -| [`intelligence.py`](https://github.com/toxakara/packvium-python/blob/main/examples/intelligence.py) | Prove a carton change is worth publishing: two scenarios compared order by order, a proposal that refuses to exist on thin evidence, and a replay against held-out history where a cheaper packing your validator rejects still counts as a regression. | -| [`extensions.py`](https://github.com/toxakara/packvium-python/blob/main/examples/extensions.py) | A rule the schema has no field for — and an honest account of what you give up by writing one. | +| [`checkout.py`](https://github.com/packvium/packvium-python/blob/main/examples/checkout.py) | A shop's checkout: a cart mapped onto a request and the parcels read back, with the cheapest cartons chosen. | +| [`fulfilment.py`](https://github.com/packvium/packvium-python/blob/main/examples/fulfilment.py) | An order from paid to labelled: a policy rule picks the service, the order is packed under its constraints, `validate` checks the plan, and each parcel is priced from a pinned tariff. | +| [`basic.py`](https://github.com/packvium/packvium-python/blob/main/examples/basic.py) | The smallest useful call: items in, placements out, and the three details in it that are easy to miss. | +| [`objectives.py`](https://github.com/packvium/packvium-python/blob/main/examples/objectives.py) | Six of the seven objectives (all but `maximum_volume`) on scenes where they disagree, including the rate card that makes the heavier shipment the cheaper one, a rate card's `currency`, and the lower bound that proves the value left behind is the least possible. | +| [`constraints.py`](https://github.com/packvium/packvium-python/blob/main/examples/constraints.py) | Upright-only, floor-only, non-stackable, top-load limits, and tags that keep two items out of the same box, plus how to read the reason an item was refused, and a crate allowed past the pallet deck by `pallet_overhang_limit`. | +| [`limits.py`](https://github.com/packvium/packvium-python/blob/main/examples/limits.py) | A courier fleet: a van with a fridge unit and wheel arches as obstacles, an item cap per bike, one dangerous-goods item per van, frozen goods only in a refrigerated vehicle, and a cap on vehicles. | +| [`units.py`](https://github.com/packvium/packvium-python/blob/main/examples/units.py) | Why there are no floats anywhere: fractional inches, exact ticks, and the one-tick difference between a fit and a refusal. | +| [`serialization.py`](https://github.com/packvium/packvium-python/blob/main/examples/serialization.py) | The same request as JSON, the result in full, and exactly which mistakes are refused and which are silently ignored. | +| [`errors.py`](https://github.com/packvium/packvium-python/blob/main/examples/errors.py) | A web handler: refused requests turned into a 422 with a pointer and a message a person can act on, fixed placements that cannot hold, and a partial fit that is not an error. | +| [`reproducibility.py`](https://github.com/packvium/packvium-python/blob/main/examples/reproducibility.py) | Why a clock-limited search answers differently on a busy machine, how an effort budget fixes it, and how to read `termination`. | +| [`trucking.py`](https://github.com/packvium/packvium-python/blob/main/examples/trucking.py) | A three-stop delivery van within its axle ratings: loading and unloading order, what the driver can reach at each stop, and the same goods packed without a route. | +| [`fixed_placements.py`](https://github.com/packvium/packvium-python/blob/main/examples/fixed_placements.py) | A trailer that arrives partly loaded: new pallets packed around the ones already on board, a record of what is on board that cannot be true, and a loaded pallet fixed by quoting its `placement_id`. | +| [`rebalancing.py`](https://github.com/packvium/packvium-python/blob/main/examples/rebalancing.py) | Two pallets of very different weight evened out after packing, one validated move at a time. | +| [`shapes.py`](https://github.com/packvium/packvium-python/blob/main/examples/shapes.py) | Items that are not their box: complementary wedges sharing one crate as `convex_hull`, two copies of one wedge that need a signed rotation such as `-L-W+H`, a cushion that compresses under load until the crush limit refuses it, and a gusseted bag that holds a layer more than a flat one. | +| [`nested.py`](https://github.com/packvium/packvium-python/blob/main/examples/nested.py) | Units into cartons, cartons onto a pallet, in one call, and `level_beam_width` letting the pallet pick a dearer carton set that packs better. | +| [`commerce.py`](https://github.com/packvium/packvium-python/blob/main/examples/commerce.py) | Rate a shipment, apply an eligibility rule, and pin a catalog version. | +| [`execution.py`](https://github.com/packvium/packvium-python/blob/main/examples/execution.py) | Turn a result into dock instructions: solver facts kept apart from screen text, a step order that is injected or absent, and an operator lock that yields a second plan rather than editing the approved one. | +| [`artifacts.py`](https://github.com/packvium/packvium-python/blob/main/examples/artifacts.py) | Hand a result to a system with no engine: one document with the plan, geometry and the request that produced it, exported as CSV and a printable work order, with its replay level. | +| [`revisions.py`](https://github.com/packvium/packvium-python/blob/main/examples/revisions.py) | Replan a half-loaded job: a missing item and a locked placement recorded against the approved plan, a replan that keeps the locked item in place, a hash-chained record that notices an edit, and a box already cut to measure (with a void-fill reserve) stocked for the replan. | +| [`intelligence.py`](https://github.com/packvium/packvium-python/blob/main/examples/intelligence.py) | Prove a carton change is worth publishing: two scenarios compared order by order, a proposal that refuses to exist on thin evidence, and a replay against held-out history where a cheaper packing your validator rejects still counts as a regression. | +| [`extensions.py`](https://github.com/packvium/packvium-python/blob/main/examples/extensions.py) | A rule the schema has no field for, and an account of what you give up by writing one. | With `packvium` installed, run any of them from a copy of the `examples/` directory: @@ -238,66 +263,63 @@ python3 examples/trucking.py From a checkout of the repository without installing, point Python at the source tree instead: `PYTHONPATH=src python3 examples/trucking.py`. -## What it does - -- **Exact arithmetic.** Length is measured in ticks of 1/16000 mm and weight in 1/8 µg. - No coordinate is ever a float, so no placement decision depends on rounding. -- **Real constraints.** Weight and payload limits, permitted rotations, keep-upright, - floor-only, non-stackable, top-load limits, minimum support ratio, tag incompatibility, - eligible container tags, per-container item and tag limits, clearance, obstacles, two-axle - load limits, multi-stop route order, pallet overhang past the deck, and flat or gusseted - bags. -- **A solver portfolio, not one algorithm.** Regular-grid, layer, extreme-point, - maximal-space and bounded exact search, selected by problem shape and profile. -- **Answers you can check.** Every solution is re-validated by logic independent of the - search. Unplaced items come back with a reason code, not silently missing. Every placement - carries a `placement_id` that a fixed placement, a revision or a lock can quote. -- **A proof, or the distance to one.** Under the `default`, `lowest_cost`, `maximum_value`, +## What it covers + +- Exact arithmetic. Length is measured in ticks of 1/16000 mm and weight in 1/8 µg, so no + coordinate is a float and no placement depends on rounding. +- Constraints: weight and payload limits, permitted rotations, keep-upright, floor-only, + non-stackable, top-load limits, minimum support ratio, tag incompatibility, eligible + container tags, per-container item and tag limits, clearance, obstacles, two-axle load + limits, multi-stop route order, pallet overhang past the deck, and flat or gusseted bags. +- Several solvers, chosen by problem shape and profile: regular-grid, layer, extreme-point, + maximal-space and bounded exact search. +- Every solution is re-validated by logic independent of the search. Unplaced items come + back with a reason code. Every placement carries a `placement_id` that a fixed placement, + a revision or a lock can quote. +- A proof, or the distance to one. Under the `default`, `lowest_cost`, `maximum_value`, `open_dimension_height` and `maximum_volume` objectives every result states - `optimality.lower_bound`. A complete result that attains it reports `optimal`, - which proves no packing obeying the request's rules scores better; any other carries the gap - to the bound (`gap_key`, `absolute_gap`, `relative_gap`). -- **Deterministic when you ask for it.** The same request with an `effort_budget` gives the + `optimality.lower_bound`. A complete result that attains it reports `optimal`, which + proves no packing obeying the request's rules scores better; any other carries the gap to + the bound (`gap_key`, `absolute_gap`, `relative_gap`). +- Deterministic when you ask for it. The same request with an `effort_budget` gives the same result on every run and machine. A search stopped by `time_limit_ms` keeps what it reached, which can differ between runs; `termination` says which happened. -- **Multi-container and nested.** Split across containers, or pack containers into - containers; `NestedPacker(level_beam_width=K)` carries the K best carton sets up a level, - so the pallet decides between them. `rebalance_weight` evens out the payload across containers afterwards. -- **Extensible.** Register your own constraints, item orderings, candidate scorers, - container selectors or complete solvers. -- **Work orders, not just coordinates.** `packvium.execution` turns a validated result - into a plan: solver facts kept apart from the text that cites them, an injected loading - order or an honest `unavailable`, and a canonical form four engines emit byte for byte. - `packvium.locks` lets an operator pin a placement and get a *second* plan beside the - approved one — never an edit of it, and never a placement the engine would refuse. -- **Artifacts a warehouse system can use without an engine.** `packvium.artifacts` wraps the - plan with geometry, display values and provenance, including the request itself and an - honest replay level. `packvium.artifact_exports` writes it as RFC 8785 JSON, CSV or a +- Multi-container and nested packing. `NestedPacker(level_beam_width=K)` carries the K best + carton sets up a level, so the pallet decides between them, and `rebalance_weight` evens + out the payload across containers afterwards. +- Your own constraints, item orderings, candidate scorers, container selectors or complete + solvers, registered in process. +- Work orders. `packvium.execution` turns a validated result into a plan: solver facts kept + apart from the text that cites them, an injected loading order or a plain + `unavailable`, and a canonical form four engines emit byte for byte. `packvium.locks` + lets an operator pin a placement and get a second plan beside the approved one. +- Artifacts a warehouse system can use without an engine. `packvium.artifacts` wraps the + plan with geometry, display values and provenance, including the request itself and its + replay level. `packvium.artifact_exports` writes it as RFC 8785 JSON, CSV or a self-contained HTML work order, byte for byte what the other engines write. -- **Items already in place, and replanning around them.** `fixed_placements` pins items to - known positions before the solve: they keep their place, carry weight and support, and come - back marked `fixed: true`. `packvium.revisions` records what changed on the dock — a missing - item, a substituted container, a lock, a verification — as an append-only chain linked by - SHA-256, and derives the request the next plan solves. `packvium.revision_outcomes` feeds - those events to the historical evaluation (Python only). -- **Decide before you publish.** `packvium.simulation` and `packvium.recommendations` - compare two catalog scenarios order by order and propose a change only when the paired - cohort supports it; `packvium.holdout` replays that proposal against history it has not - seen. Python-only, and signature-frozen since 1.10.0 like the packing surface — see - [PUBLIC-API.md](https://github.com/toxakara/packvium-python/blob/main/docs/PUBLIC-API.md). +- Items already in place, and replanning around them. `fixed_placements` pins items to + known positions before the solve: they keep their place, carry weight and support, and + come back marked `fixed: true`. `packvium.revisions` records what changed on the dock (a + missing item, a substituted container, a lock, a verification) as an append-only chain + linked by SHA-256, and derives the request the next plan solves. + `packvium.revision_outcomes` feeds those events to the historical evaluation (Python + only). +- Deciding before you publish a catalog change. `packvium.simulation` and + `packvium.recommendations` compare two catalog scenarios order by order and propose a + change only when the paired cohort supports it; `packvium.holdout` replays that proposal + against history it has not seen. Python only, and signature-frozen since 1.10.0 like the + packing surface. See [PUBLIC-API.md](https://github.com/packvium/packvium-python/blob/main/docs/PUBLIC-API.md). ## Documentation | Document | Covers | | --- | --- | -| [docs/GUARANTEES.md](https://github.com/toxakara/packvium-python/blob/main/docs/GUARANTEES.md) | What is promised and what is not. Start here. | -| [docs/PUBLIC-API.md](https://github.com/toxakara/packvium-python/blob/main/docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | -| [docs/COMMERCE-API.md](https://github.com/toxakara/packvium-python/blob/main/docs/COMMERCE-API.md) | Carrier rating, eligibility rules and catalog versions. | -| [docs/UNITS-AND-NUMERICS.md](https://github.com/toxakara/packvium-python/blob/main/docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | - -## Requirements +| [docs/GUARANTEES.md](https://github.com/packvium/packvium-python/blob/main/docs/GUARANTEES.md) | What is promised and what is not. Start here. | +| [docs/PUBLIC-API.md](https://github.com/packvium/packvium-python/blob/main/docs/PUBLIC-API.md) | Inputs, outputs and status semantics. | +| [docs/COMMERCE-API.md](https://github.com/packvium/packvium-python/blob/main/docs/COMMERCE-API.md) | Carrier rating, eligibility rules and catalog versions. | +| [docs/UNITS-AND-NUMERICS.md](https://github.com/packvium/packvium-python/blob/main/docs/UNITS-AND-NUMERICS.md) | Units, accepted input forms, rounding policy. | -Python 3.9 or newer. No dependencies. +The constraint reference and the benchmarks are at [packvium.com](https://packvium.com). ## The Packvium family @@ -307,36 +329,33 @@ PHP are held to byte-identical canonical results; Rust and the JavaScript fallba to independent validity and a per-fixture objective floor. Pick the package for your stack; mixing them in one system is safe. -Documentation, the constraint reference and the benchmarks are at -[packvium.com](https://packvium.com). - | Package | Install | Source | | --- | --- | --- | -| Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/toxakara/packvium-python) | -| PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/toxakara/packvium-php) | -| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.10"` | [packvium-rust](https://github.com/toxakara/packvium-rust) | -| Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/toxakara/packvium-node) | -| Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/toxakara/packvium-wasm) | -| PHP FFI bridge — [`packvium/native-bridge`](https://packagist.org/packages/packvium/native-bridge) | `composer require packvium/native-bridge` | [packvium-php-bridge](https://github.com/toxakara/packvium-php-bridge) | -| Python native selector — `packvium-native` | from source until the native wheels ship | [packvium-python-adapter](https://github.com/toxakara/packvium-python-adapter) | +| Python — [`packvium`](https://pypi.org/project/packvium/) | `pip install packvium` | [packvium-python](https://github.com/packvium/packvium-python) | +| PHP — [`packvium/packvium`](https://packagist.org/packages/packvium/packvium) | `composer require packvium/packvium` | [packvium-php](https://github.com/packvium/packvium-php) | +| Rust — [`packvium`](https://crates.io/crates/packvium) | `packvium = "1.11"` | [packvium-rust](https://github.com/packvium/packvium-rust) | +| Node.js — [`@packvium/engine`](https://www.npmjs.com/package/@packvium/engine) | `npm install @packvium/engine` | [packvium-node](https://github.com/packvium/packvium-node) | +| Browser / WebAssembly — [`@packvium/browser`](https://www.npmjs.com/package/@packvium/browser) | `npm install @packvium/browser` | [packvium-wasm](https://github.com/packvium/packvium-wasm) | +| PHP FFI bridge — [`packvium/native-bridge`](https://packagist.org/packages/packvium/native-bridge) | `composer require packvium/native-bridge` | [packvium-php-bridge](https://github.com/packvium/packvium-php-bridge) | +| Python native selector — `packvium-native` | from source until the native wheels ship | [packvium-python-adapter](https://github.com/packvium/packvium-python-adapter) | ## Contributing -See [CONTRIBUTING.md](https://github.com/toxakara/packvium-python/blob/main/CONTRIBUTING.md). Security reports go through the process in -[SECURITY.md](https://github.com/toxakara/packvium-python/blob/main/SECURITY.md), not public issues. +See [CONTRIBUTING.md](https://github.com/packvium/packvium-python/blob/main/CONTRIBUTING.md). Security reports go through the process in +[SECURITY.md](https://github.com/packvium/packvium-python/blob/main/SECURITY.md), not public issues. ## Citation If Packvium supports your research, cite it as software. GitHub's **Cite this repository** -button reads [`CITATION.cff`](https://github.com/toxakara/packvium-python/blob/main/CITATION.cff), and -[`codemeta.json`](https://github.com/toxakara/packvium-python/blob/main/codemeta.json) carries the same record in +button reads [`CITATION.cff`](https://github.com/packvium/packvium-python/blob/main/CITATION.cff), and +[`codemeta.json`](https://github.com/packvium/packvium-python/blob/main/codemeta.json) carries the same record in CodeMeta form. ```bibtex @software{packvium_python, author = {{Packvium contributors}}, title = {Packvium for Python}, - version = {1.10.0}, + version = {1.11.0}, license = {MIT}, url = {https://packvium.com} } @@ -344,4 +363,4 @@ CodeMeta form. ## License -MIT. See [LICENSE](https://github.com/toxakara/packvium-python/blob/main/LICENSE). +MIT. See [LICENSE](https://github.com/packvium/packvium-python/blob/main/LICENSE). diff --git a/codemeta.json b/codemeta.json index ee02588..15a8837 100644 --- a/codemeta.json +++ b/codemeta.json @@ -3,7 +3,7 @@ "@type": "SoftwareSourceCode", "name": "Packvium for Python", "description": "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results.", - "version": "1.10.0", + "version": "1.11.0", "license": "https://spdx.org/licenses/MIT", "author": [ { @@ -13,8 +13,8 @@ } ], "url": "https://packvium.com", - "codeRepository": "https://github.com/toxakara/packvium-python", - "issueTracker": "https://github.com/toxakara/packvium-python/issues", + "codeRepository": "https://github.com/packvium/packvium-python", + "issueTracker": "https://github.com/packvium/packvium-python/issues", "programmingLanguage": "Python", "keywords": [ "3d-bin-packing", diff --git a/docs/COMMERCE-API.md b/docs/COMMERCE-API.md index 6f4e4b7..44a835e 100644 --- a/docs/COMMERCE-API.md +++ b/docs/COMMERCE-API.md @@ -417,9 +417,19 @@ existing rule-pool storage. difference — `JSON.parse` gives the same `Number` for `1` and `1.0` — so this is the one shape where the four implementations cannot be made to agree, and the contract resolves it by requiring callers not to emit it. No fixture uses one. -- JavaScript refuses, rather than rounds, a quote whose components exceed - `Number.MAX_SAFE_INTEGER`. The arithmetic itself runs in `BigInt`, so nothing drifts - through a double; what cannot be done is *reporting* a value a JSON number cannot hold - exactly. Python has no such ceiling, Rust takes every product in `i128`, and PHP falls - back to decimal-string arithmetic. The bound is far above any real tariff — nine - quadrillion minor currency units. +- Every engine refuses, rather than rounds, a quote that reports an amount above + `2^53 - 1` (`9007199254740991`): `dimensional_weight_g`, `billed_weight_g`, + `base_charge_minor`, `fuel_surcharge_minor`, any accessorial charge, or `total_minor`, + checked in that order. The arithmetic itself is exact in all four -- unbounded integers + in Python, `BigInt` in JavaScript, `i128` in Rust, decimal strings in PHP -- so nothing + drifts or wraps on the way; what cannot be done is *reporting* a value a JSON number + cannot hold exactly. The refusal is the input error of the language, with the message + `quote amount {value} is above 9007199254740991 and cannot be represented exactly`. + Until 1.11 only JavaScript refused; Python answered without a ceiling, and Rust and PHP + answered up to `2^63 - 1`. The bound is far above any real tariff — nine quadrillion + minor currency units. +- JavaScript refuses an input integer above `2^53 - 1` with `expected an exact integer`: + `JSON.parse` has already rounded it, so no exact arithmetic after that can recover the + value the caller sent. Python computes from such an input exactly and PHP and Rust read it + up to `2^63 - 1`, so an engine may answer a quote JavaScript refuses; callers should not + send one. No fixture does. diff --git a/docs/GUARANTEES.md b/docs/GUARANTEES.md index f0b05e9..929e28f 100644 --- a/docs/GUARANTEES.md +++ b/docs/GUARANTEES.md @@ -61,7 +61,7 @@ silently — if you need them, they belong in your own layer above this library. ## Status of this release -Version `1.10.0` freezes the public API. Field names, status codes, the objective +Version `1.11.0` freezes the public API. Field names, status codes, the objective vector, the numeric policy and the validation rules do not change without a major version, so any `1.x` is a safe upgrade from any earlier `1.x`. A caret or tilde constraint on `1.0` is enough; an exact pin is no longer required. diff --git a/docs/UNITS-AND-NUMERICS.md b/docs/UNITS-AND-NUMERICS.md index c09c8e8..624c9d0 100644 --- a/docs/UNITS-AND-NUMERICS.md +++ b/docs/UNITS-AND-NUMERICS.md @@ -10,6 +10,8 @@ One internal length tick is `1/16000 mm`. Accepted inputs include integers, decimal strings, fractions (`3/16`) and mixed fractions (`12 3/8`), with `mm`, `cm`, `m`, `in`, `ft`, and ticks. A binary float with a fractional part is intentionally rejected by the Python API, by `Length` and `Weight` alike (`TypeError`); an integral float such as `100.0` is exact, and is what JavaScript sends for `100`, so it is accepted as that integer. PHP type declarations accept only integer/string/structured values. +The written grammar is one and the same in all four engines (1.11): an optional sign, ASCII digits, and an optional fraction part with at least one digit on each side of the point and at most 18 after it; or a fraction `n/d`; or a mixed fraction `w n/d`. A unit suffix is matched ignoring ASCII case (`100 MM`, `1 KG`). Nothing else is a measure -- not `100.`, `.5`, `0x64`, `1e2`, `1_0`, nor digits outside ASCII -- and each is refused as `wrong_type`, `must be a measure`. Until 1.11 each language's own number parser decided the edge cases, and they disagreed. + ## Weight One weight tick is `1/8 microgram`, allowing exact common metric units and exact international avoirdupois conversions used by the package. diff --git a/examples/checkout.py b/examples/checkout.py new file mode 100644 index 0000000..4973f12 --- /dev/null +++ b/examples/checkout.py @@ -0,0 +1,105 @@ +"""A shop's checkout: turn a cart into parcels. + +Run it: + + PYTHONPATH=src python3 examples/checkout.py + +This is the shape most projects start from. You already have product rows and cart lines +in your own format; the library wants a request. So there are two small functions between +them: `to_request` maps your records onto the request, and `parcels` reads the result +back into something your checkout page can render. Everything Packvium-specific lives in +those two functions, and the rest of the shop never sees a tick or a placement. + +The request is a plain dict, the same JSON every Packvium engine reads, so the mapping +below works unchanged if you later move the solve to another language or a queue worker. +""" + +from __future__ import annotations + +from packvium import pack_from_dict + +# Your product table. Sizes in centimetres and weights in grams, as a shop usually has them. +PRODUCTS = { + "kettle": {"size_cm": (24, 22, 26), "weight_g": 1300, "this_side_up": True}, + "mug": {"size_cm": (12, 9, 10), "weight_g": 350, "this_side_up": False}, + "cookbook": {"size_cm": (28, 22, 3), "weight_g": 900, "this_side_up": False}, + "floor-lamp": {"size_cm": (150, 30, 30), "weight_g": 4200, "this_side_up": False}, +} + +# The cartons on your packing bench, with what each one costs you in cents. +BOXES = [ + {"id": "small", "inner_cm": (30, 25, 15), "max_kg": 5, "cost_cents": 45}, + {"id": "medium", "inner_cm": (40, 30, 30), "max_kg": 12, "cost_cents": 80}, + {"id": "large", "inner_cm": (60, 40, 40), "max_kg": 20, "cost_cents": 140}, +] + + +def to_request(cart: dict[str, int]) -> dict: + """Your cart (`{sku: quantity}`) as a Packvium request.""" + return { + "units": {"length": "cm"}, + "configuration": { + # Pay as little as possible for cartons, after packing everything that fits. + "objective": "lowest_cost", + # Counted work decides where the search stops, so the same cart always gets + # the same parcels. The time limit is a fuse against a hang, not a search limit. + "effort_budget": {"max_candidates_evaluated": 200_000}, + "time_limit_ms": 60_000, + }, + "items": [ + { + "id": sku, + "quantity": quantity, + "weight": f"{PRODUCTS[sku]['weight_g']} g", + "keep_upright": PRODUCTS[sku]["this_side_up"], + "dimensions": dict(zip(("length", "width", "height"), map(str, PRODUCTS[sku]["size_cm"]))), + } + for sku, quantity in cart.items() + ], + "containers": [ + { + "id": box["id"], + "max_payload": f"{box['max_kg']} kg", + "cost_minor": box["cost_cents"], + "inner_dimensions": dict(zip(("length", "width", "height"), map(str, box["inner_cm"]))), + } + for box in BOXES + ], + } + + +def parcels(cart: dict[str, int]) -> tuple[list[dict], list[str]]: + """The parcels to ship, and the SKUs that fit no carton you stock.""" + result = pack_from_dict(to_request(cart)) + shipped = [] + for container in result["containers"]: + contents: dict[str, int] = {} + for placement in container["placements"]: + contents[placement["item_type"]] = contents.get(placement["item_type"], 0) + 1 + shipped.append({ + "box": container["container_type"], + "contents": contents, + # `value` is the exact weight rendered in `unit`; here that is whole grams. + "weight": f"{container['gross_weight']['value']} {container['gross_weight']['unit']}", + }) + # An item that fits nowhere is not an error. It comes back with a reason, and the rest + # of the cart is still packed. + left_out = sorted({entry["item_type"] for entry in result["unpacked_items"]}) + return shipped, left_out + + +def show(title: str, cart: dict[str, int]) -> None: + shipped, left_out = parcels(cart) + print(f"\n{title}") + for number, parcel in enumerate(shipped, start=1): + contents = ", ".join(f"{count} x {sku}" for sku, count in sorted(parcel["contents"].items())) + print(f" parcel {number}: {parcel['box']:6s} {parcel['weight']:>7s} {contents}") + box_cost = sum(box["cost_cents"] for parcel in shipped for box in BOXES if box["id"] == parcel["box"]) + print(f" cartons cost {box_cost} cents") + for sku in left_out: + print(f" {sku} fits none of our cartons: ship it in its own packaging") + + +show("a small order", {"mug": 2, "cookbook": 1}) +show("a bigger order", {"kettle": 4, "mug": 6, "cookbook": 4}) +show("an order with something oversized", {"floor-lamp": 1, "mug": 4}) diff --git a/examples/fulfilment.py b/examples/fulfilment.py new file mode 100644 index 0000000..c5eb906 --- /dev/null +++ b/examples/fulfilment.py @@ -0,0 +1,204 @@ +"""From a paid order to labelled parcels: eligibility, packing, a second opinion, a price. + +Run it: + + PYTHONPATH=src python3 examples/fulfilment.py + +checkout.py maps a cart onto a request and reads the parcels back. A warehouse needs more +around that call, and this example wires the pieces in the order a fulfilment job runs them: + +1. `evaluate_policy` decides which carrier service the order may use at all. +2. `pack_from_dict` packs it, under the rules the goods come with. +3. `validate` checks the plan against the request with code that shares nothing with the + solver, so a parcel is never labelled on the solver's word alone. +4. `quote` prices every parcel from the tariff version you pinned. + +Two kinds of trouble are kept apart on purpose. A request that is wrong (a quantity of +zero from a bad import) raises `InvalidRequestError`, and the job puts the order on hold. +An item that fits no carton is not an error: the rest of the order ships and the item is +handed to freight. +""" + +from __future__ import annotations + +from packvium import InvalidRequestError, pack_from_dict, validate +from packvium.commerce import evaluate_policy, quote + +#: Results carry exact integers: 16 000 length ticks to the millimetre, 8 000 000 weight +#: ticks to the gram. A carrier bills whole millimetres and grams, rounded up. +TICKS_PER_MM = 16_000 +TICKS_PER_GRAM = 8_000_000 + +# What you publish: one tariff per carrier service, and the rules that say what may ship +# how. You would load this from your own storage; a version's number is its position in +# the list, so `tariff_version: 1` below always means the same prices. +COMMERCE = { + "tariffs": [ + { + "carrier_id": "postway", "service_id": "air", + "versions": [{ + "effective_at": 0, + "dimensional_weight_divisor": 5000, + "cost_per_dimensional_kg_minor": {"domestic": 520, "eu": 890}, + "minimum_charge_minor": 950, + "fuel_surcharge_permille": 140, + "accessorials": [], + }], + }, + { + "carrier_id": "postway", "service_id": "ground", + "versions": [{ + "effective_at": 0, + "dimensional_weight_divisor": 6000, + "cost_per_dimensional_kg_minor": {"domestic": 210, "eu": 380}, + "minimum_charge_minor": 590, + "fuel_surcharge_permille": 90, + "accessorials": [], + }], + }, + ], + "policy_rules": [ + { + "rule_id": "lithium-stays-on-the-ground", + "versions": [{ + "scope": "service", "action": "reject", "priority": 10, "effective_at": 0, + "reason": "lithium batteries do not fly with this carrier", + "predicates": [ + {"scope": "service", "field": "service", "operator": "equals", "value": "air"}, + {"scope": "service", "field": "battery", "operator": "equals", "value": "lithium"}, + ], + }], + }, + ], + "catalogs": [], +} + +PRODUCTS = { + "laptop": {"mm": (360, 250, 30), "g": 2100, "battery": "lithium"}, + "monitor": {"mm": (680, 430, 140), "g": 5400, "keep_upright": True, "stackable": False}, + "bleach": {"mm": (90, 90, 280), "g": 1100, "keep_upright": True, + "tags": ["chemical"], "incompatible_tags": ["food"]}, + "coffee": {"mm": (120, 80, 220), "g": 1000, "tags": ["food"]}, + "desk": {"mm": (1600, 800, 60), "g": 28000}, +} + +BOXES = [ + {"id": "S", "mm": (300, 200, 300), "tare_g": 180, "max_kg": 8, "cost_minor": 50}, + {"id": "M", "mm": (400, 300, 300), "tare_g": 260, "max_kg": 15, "cost_minor": 85}, + {"id": "L", "mm": (700, 450, 450), "tare_g": 520, "max_kg": 25, "cost_minor": 160}, +] + + +def measures(edges: tuple[int, int, int]) -> dict[str, str]: + return dict(zip(("length", "width", "height"), map(str, edges))) + + +def allowed_service(order: dict) -> tuple[str, str | None]: + """The service the customer chose, or ground when a rule forbids it, and why.""" + for sku in order["lines"]: + decision = evaluate_policy(COMMERCE, { + "scope": "service", + "context": {"service": order["service"], "battery": PRODUCTS[sku].get("battery", "none")}, + "as_of": 0, + })["decision"] + if not decision["allowed"]: + return "ground", f"{sku}: {decision['citation']['reason']}" + return order["service"], None + + +def packing_request(order: dict) -> dict: + items = [] + for sku, quantity in order["lines"].items(): + product = PRODUCTS[sku] + item = {"id": sku, "quantity": quantity, "weight": f"{product['g']} g", + "dimensions": measures(product["mm"])} + # Only the rules a product actually has are sent; an absent field means "no rule". + for rule in ("keep_upright", "stackable", "tags", "incompatible_tags"): + if rule in product: + item[rule] = product[rule] + items.append(item) + return { + "units": {"length": "mm"}, + "configuration": { + "objective": "lowest_cost", + # Nothing may hang in the air: three quarters of every base must rest on something. + "minimum_support_ratio": 0.75, + "effort_budget": {"max_candidates_evaluated": 200_000}, + "time_limit_ms": 60_000, + }, + "items": items, + "containers": [ + {"id": box["id"], "inner_dimensions": measures(box["mm"]), "cost_minor": box["cost_minor"], + "tare_weight": f"{box['tare_g']} g", "max_payload": f"{box['max_kg']} kg"} + for box in BOXES + ], + } + + +def price(container: dict, service: str, zone: str) -> dict: + """One parcel through the pinned tariff. Whole grams and millimetres, rounded up. + + The answer is either a quote or a rejection with a code: a zone the tariff does not + price is never a zero. + """ + grams = -(-container["gross_weight"]["ticks"] // TICKS_PER_GRAM) + volume = 1 + for edge in ("length", "width", "height"): + volume *= -(-container["outer_dimensions"][edge]["ticks"] // TICKS_PER_MM) + return quote(COMMERCE, { + "carrier_id": "postway", "service_id": service, "tariff_version": 1, + "zone": zone, "actual_weight_g": grams, "volume_mm3": volume, + }) + + +def fulfil(order: dict) -> None: + print(f"\norder {order['id']} to zone {order['zone']}, customer chose {order['service']}") + service, why = allowed_service(order) + if why: + print(f" moved to {service}: {why}") + + request = packing_request(order) + try: + result = pack_from_dict(request) + except InvalidRequestError as error: + # `field` is a JSON Pointer into the request, `reason` one of a closed set. + print(f" on hold: {error.reason} at {error.field} ({error.detail})") + return + + issues = validate(request, result) + if issues: + print(" on hold: the plan failed its check: " + "; ".join(f"{i.code}: {i.detail}" for i in issues)) + return + print(f" plan checked: {len(result['containers'])} parcel(s), no issues") + + answers = [price(container, service, order["zone"]) for container in result["containers"]] + refused = [answer["error"]["code"] for answer in answers if answer["status"] != "ok"] + if refused: + print(f" on hold: no {service} price for zone {order['zone']} ({refused[0]})") + return + + total = 0 + for container, answer in zip(result["containers"], answers): + contents: dict[str, int] = {} + for placement in container["placements"]: + contents[placement["item_type"]] = contents.get(placement["item_type"], 0) + 1 + quoted = answer["quote"] + total += quoted["total_minor"] + listing = ", ".join(f"{count} x {sku}" for sku, count in sorted(contents.items())) + print(f" {container['id']:4s} {listing}") + print(f" {quoted['actual_weight_g']} g on the scale, billed as " + f"{quoted['billed_weight_g']} g, {quoted['total_minor']} minor units") + print(f" shipping by {service}: {total} minor units") + + for entry in result["unpacked_items"]: + print(f" {entry['item_id']} goes to freight: {entry['reason']}") + + +fulfil({"id": "A-1001", "zone": "domestic", "service": "air", + "lines": {"coffee": 6, "bleach": 2}}) +fulfil({"id": "A-1002", "zone": "eu", "service": "air", + "lines": {"laptop": 1, "monitor": 1, "desk": 1}}) +fulfil({"id": "A-1003", "zone": "domestic", "service": "ground", + "lines": {"coffee": 0}}) +fulfil({"id": "A-1004", "zone": "overseas", "service": "ground", + "lines": {"coffee": 1}}) diff --git a/pyproject.toml b/pyproject.toml index 0b768eb..3a79ec1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "packvium" -version = "1.10.0" +version = "1.11.0" description = "Deterministic 3D bin-packing and cartonization engine for pallets, containers, trucks and shipping cartons. Exact integer geometry, reproducible results." readme = "README.md" requires-python = ">=3.9" @@ -31,11 +31,11 @@ classifiers = [ [project.urls] Homepage = "https://packvium.com" -Source = "https://github.com/toxakara/packvium-python" +Source = "https://github.com/packvium/packvium-python" Documentation = "https://packvium.com/docs" -"Quick start" = "https://github.com/toxakara/packvium-python#quick-start" -Changelog = "https://github.com/toxakara/packvium-python/blob/main/CHANGELOG.md" -Issues = "https://github.com/toxakara/packvium-python/issues" +"Quick start" = "https://github.com/packvium/packvium-python#quick-start" +Changelog = "https://github.com/packvium/packvium-python/blob/main/CHANGELOG.md" +Issues = "https://github.com/packvium/packvium-python/issues" [project.scripts] packvium = "packvium.__main__:main" diff --git a/src/packvium/artifacts.py b/src/packvium/artifacts.py index 2291e23..d523369 100644 --- a/src/packvium/artifacts.py +++ b/src/packvium/artifacts.py @@ -33,7 +33,7 @@ #: The suite version of this builder, the same string in all four engines of one release. #: The engine's own name is deliberately not recorded: four correct builders naming themselves #: would emit four different documents. `make version-set` rewrites this line. -SUITE_VERSION = "1.10.0" +SUITE_VERSION = "1.11.0" #: The deterministic part of `result.algorithm`. `duration_ms` is wall-clock time and never #: enters an artifact. diff --git a/src/packvium/axle_load.py b/src/packvium/axle_load.py index 4f54de6..53439b5 100644 --- a/src/packvium/axle_load.py +++ b/src/packvium/axle_load.py @@ -3,7 +3,7 @@ from typing import TYPE_CHECKING, Sequence if TYPE_CHECKING: - from .constraints import LoadUnit + from .loads import LoadUnit from .models import Axle diff --git a/src/packvium/bounds.py b/src/packvium/bounds.py index 7c5b6ea..e72c025 100644 --- a/src/packvium/bounds.py +++ b/src/packvium/bounds.py @@ -45,8 +45,8 @@ `for_request` returns them in the order of the objective a result is scored with: `lowest_cost` reads `(L0, L2, L1, L3, L4)`, which the document shows is still a bound; `maximum_value`, `open_dimension_height` and `maximum_volume` each add one term for the key -only they rank by; `shipping_cost` and `lowest_landed_cost` get none, because a -vector compared against a score that ranks other quantities means nothing. +only they rank by, and `shipping_cost` and `lowest_landed_cost` one each for what a +carrier bills, read from the configuration's dimensional-weight divisor. Which instances. The bound is a property of the request, so it is taken over every instance the request declares, fixed placements included. A bound over the free instances @@ -60,13 +60,19 @@ from __future__ import annotations +import bisect +import functools import heapq -from typing import Dict, Iterable, Sequence, Tuple +from typing import TYPE_CHECKING, Dict, Iterable, Sequence, Tuple from ._compat import dataclass from .constraints import usable_volume -from .geometry import ShapeType +from .geometry import ShapeType, dimensional_weight from .models import Container, Item, ItemInstance +from .units import Weight + +if TYPE_CHECKING: + from .config import PackingConfig #: Parts per million, the fixed-point scale keys 3 and 4 of the objective are carried at. PPM = 1_000_000 @@ -100,8 +106,34 @@ "maximum_value": (0, "value_forgone", 1, 2, 3), "open_dimension_height": (0, "achieved_height", 1, 2, 3), "maximum_volume": ("unpacked_volume_ppm", 0, 1, 2, 3), + "shipping_cost": (0, "billed_weight", 1, 3, 4), + "lowest_landed_cost": (0, "landed_charge", 1, 3, 4), } +#: The objectives whose own key is what a carrier bills, which needs the configuration's +#: dimensional-weight divisor and units as well as the request. +BILLED_OBJECTIVES = ("shipping_cost", "lowest_landed_cost") + + +@dataclass(frozen=True, slots=True) +class Billing: + """What a carrier can bill one container of a type, at the least. + + `tare` and `dimensional` are weight ticks: an opened container is billed + `max(tare + payload, dimensional)`, so `max(tare, dimensional)` is its floor whatever it + carries. `brackets` is its rate table as `(upper bound in weight ticks, charge in minor + units)`, the charge already floored at the minimum and surcharged, or empty where the + objective prices nothing. + """ + + tare: int + dimensional: int + brackets: Tuple[Tuple[int, int], ...] = () + + @property + def floor(self) -> int: + return max(self.tare, self.dimensional) + class BoundOverflowError(ValueError): """A sum in the bound path exceeded the declared ceiling. @@ -262,12 +294,13 @@ def _occupies_less_than_its_box(item: Item) -> bool: def for_request(instances: Sequence[ItemInstance], containers: Sequence[Container], - objective: str) -> "Tuple[int, ...] | None": + objective: str, config: "PackingConfig | None" = None) -> "Tuple[int, ...] | None": """The request's bound in `objective`'s own score order, or `None` where none is stated. `instances` is every instance the request declares, fixed placements included, and - `containers` every type it may open. `None` for an objective with no bound, for a - request with a `made_to_measure` container (D13: the unused-volume key would be + `containers` every type it may open. `None` for an objective with no bound, for a billed objective whose inventory cannot + carry a packing that attains `L0` at a price, for a request with a + `made_to_measure` container (D13: the unused-volume key would be taken from the machine maximum while the score uses the fabricated box), and for a request past a declared ceiling. The last withholds the bound and nothing else: the pack is still answered, as it was before any bound existed (OPTIMALITY-GAP.md § 1.5). @@ -280,23 +313,61 @@ def for_request(instances: Sequence[ItemInstance], containers: Sequence[Containe if any(container.made_to_measure is not None for container in containers): return None try: - return objective_vector(instances, containers, objective) - except BoundOverflowError: + billings = billing_for(containers, config) if objective in BILLED_OBJECTIVES else () + return objective_vector(instances, containers, objective, billings) + except (BoundOverflowError, BoundWithheld): return None +class BoundWithheld(ValueError): + """A billed objective's inventory cannot carry, at any price it lists, a packing that + attains `L0`; no answer is compared against a bound then, so none is stated.""" + + +def billing_for(containers: Sequence[Container], config: "PackingConfig | None") -> Tuple[Billing, ...]: + """Each type's `Billing`, from the objective's divisor and units. + + A rigid container is billed on its declared outer size, else its declared inner one; a + pallet whose load overhangs is billed larger per side, never smaller, and dimensional + weight only grows with each side, so the declared size is a floor. A bag is billed on the + package its contents make, which can be smaller than declared, so its floor is 0. + """ + if config is None or config.dimensional_weight_divisor is None: + raise BoundWithheld("a billed objective needs configuration.dimensional_weight_divisor") + landed = config.objective == "lowest_landed_cost" + return tuple(Billing( + tare=container.tare_weight.ticks, + dimensional=0 if container.is_flat_bag else dimensional_weight( + container.outer_dimensions or container.declared_inner, + config.dimensional_weight_divisor, config.dimensional_weight_length_unit, + config.dimensional_weight_weight_unit).ticks, + brackets=_brackets(container) if landed else (), + ) for container in containers) + + +def _brackets(container: Container) -> Tuple[Tuple[int, int], ...]: + """The rate table as `(bound in weight ticks, charge)`; the charge at a bracket's bound is + that bracket's charge, since the bound is the heaviest weight it prices.""" + table = container.rate_table + if table is None: + return () + return tuple((bound * Weight.TICKS_PER_G, table.charge_minor_or_none(bound)) + for bound in table.weight_brackets_g) + + def objective_vector(instances: Sequence[ItemInstance], containers: Sequence[Container], - objective: str) -> Tuple[int, ...]: + objective: str, billings: Sequence[Billing] = ()) -> Tuple[int, ...]: """The bound in a covered `objective`'s score order, raising `BoundOverflowError` where a - ceiling withholds it -- the predicate's or the objective's own term's.""" + ceiling withholds it -- the predicate's or the objective's own term's -- and + `BoundWithheld` where a billed objective has no priceable answer to bound.""" vector = compute(instances, containers).as_tuple() return tuple(vector[position] if isinstance(position, int) - else _objective_term(position, instances, containers, vector[0]) + else _objective_term(position, instances, containers, vector, billings) for position in OBJECTIVE_ORDERS[objective]) def _objective_term(name: str, instances: Sequence[ItemInstance], containers: Sequence[Container], - unpacked: int) -> int: + vector: Tuple[int, ...], billings: Sequence[Billing]) -> int: """The bound on the one key an objective ranks by and the default does not. Each is conditional on the keys before it, as `compute`'s are: the value and height terms @@ -308,8 +379,19 @@ def _objective_term(name: str, instances: Sequence[ItemInstance], containers: Se `O(n log L0)`. With `O(c)` over the container types, the request bound stays `O(n log n + c log c)`. """ + unpacked, opened = vector[0], vector[1] if name == "value_forgone": return _value_forgone_bound(instances, unpacked) + if name in ("billed_weight", "landed_charge"): + weights = sorted(instance.weight.ticks for instance in instances) + quantities = [container.quantity for container in containers] + if name == "billed_weight": + return _billed_weight_bound(weights, billings, quantities, unpacked, opened) + volumes = sorted(instance.item.dimensions.volume for instance in instances) + nests = any(_occupies_less_than_its_box(instance.item) for instance in instances) + limits = [(usable_volume(c), None if c.max_payload is None else c.max_payload.ticks, + c.max_items, c.quantity) for c in containers] + return _landed_charge_bound(weights, volumes, nests, billings, limits, unpacked, opened) volumes = [instance.item.dimensions.volume for instance in instances] nests = any(_occupies_less_than_its_box(instance.item) for instance in instances) if name == "achieved_height": @@ -319,6 +401,127 @@ def _objective_term(name: str, instances: Sequence[ItemInstance], containers: Se return _unpacked_volume_bound(volumes, nests, usable, [c.quantity for c in containers]) +def _smallest_from_inventory(values: Sequence[int], quantities: Sequence["int | None"], + count: int) -> "int | None": + """The sum of the `count` smallest of `{value repeated quantity}`, or `None` when the + inventory holds fewer. Sorting the types and taking `min(quantity, still needed)` of each + is `L2`'s rule, `O(c log c)`, without building the multiset.""" + total, needed = 0, count + for value, quantity in sorted(zip(values, quantities), key=lambda pair: pair[0]): + if needed == 0: + break + taken = needed if quantity is None else min(quantity, needed) + total += value * taken + needed -= taken + return None if needed else total + + +def _billed_weight_bound(weights: Sequence[int], billings: Sequence[Billing], + quantities: Sequence["int | None"], unpacked: int, opened: int) -> int: + """`shipping_cost`'s second key, summed billed weight in ticks. + + A packing that leaves exactly `unpacked` behind opens at least `opened` containers and + carries at least the lightest `n - unpacked` instances. Each opened container is billed + `max(tare + payload, dimensional)`, at least its floor, and a sum of maxima is at least + either sum on its own, so the two can be taken over different types. Every term is + non-negative, so opening more only adds. `weights` is ascending. + """ + if opened == 0: + return 0 + floors = _smallest_from_inventory([b.floor for b in billings], quantities, opened) + tares = _smallest_from_inventory([b.tare for b in billings], quantities, opened) + if floors is None or tares is None: + raise BoundWithheld("the inventory holds fewer containers than must be opened") + payload = sum(weights[:len(weights) - unpacked]) + return _guard_output(max(floors, tares + payload), "billed weight") + + +def _landed_charge_bound(weights: Sequence[int], volumes: Sequence[int], nests: bool, + billings: Sequence[Billing], + limits: Sequence[Tuple[int, "int | None", "int | None", "int | None"]], + unpacked: int, opened: int) -> int: + """`lowest_landed_cost`'s second key, the summed carrier charge in minor units. + + Every opened container is billed in exactly one bracket and pays its charge. A container + in bracket `(bound, charge)` weighs at most `bound`, so it is reachable only when its floor + is within it, carries at most `bound - tare` of payload (and its `max_payload`), and at + most as many instances as the lightest-first count under that payload, its usable volume + and `max_items`. Three relaxations of that assignment hold, and the largest is the bound: + the cheapest reachable charge per container over `opened` containers; the least cost + covering the placed weight; the least cost covering the placed count. Prices need not rise + with weight, which is why a bracket is chosen rather than read off the floor. A type no + bracket prices offers nothing: a packing that opens one is refused, never returned. + `weights` and `volumes` are ascending; `limits` is `(usable, max_payload, max_items, + quantity)` per type. `O(c b log n + c b log(c b))` for `b` brackets per type. + """ + placed = len(weights) - unpacked + if opened == 0 or placed == 0: + return 0 + payload_prefix = _prefix_sums(weights) + volume_prefix = None if nests else _prefix_sums(volumes) + cheapest, quantities, offers = [], [], [] + for billing, (usable, max_payload, max_items, quantity) in zip(billings, limits): + reachable = [(bound, charge) for bound, charge in billing.brackets + if charge is not None and billing.floor <= bound] + if not reachable: + continue + cheapest.append(min(charge for _, charge in reachable)) + quantities.append(quantity) + for bound, charge in reachable: + carried = bound - billing.tare + if max_payload is not None: + carried = min(carried, max_payload) + count = _fit_prefix(payload_prefix, carried) + if volume_prefix is not None: + count = min(count, _fit_prefix(volume_prefix, usable)) + if max_items is not None: + count = min(count, max_items) + offers.append((charge, carried, count, quantity)) + by_count = _smallest_from_inventory(cheapest, quantities, opened) + by_weight = _cover([(charge, carried, quantity) for charge, carried, _, quantity in offers], + payload_prefix[placed - 1]) + by_items = _cover([(charge, count, quantity) for charge, _, count, quantity in offers], placed) + if by_count is None or by_weight is None or by_items is None: + raise BoundWithheld("no priceable inventory carries a packing that attains L0") + return _guard_output(max(by_count, by_weight, by_items), "landed charge") + + +def _prefix_sums(ascending: Sequence[int]) -> list: + totals, running = [], 0 + for value in ascending: + running += value + totals.append(running) + return totals + + +def _fit_prefix(prefix: Sequence[int], capacity: int) -> int: + """`_fit` by binary search over prefix sums, `O(log n)` per question.""" + return bisect.bisect_right(prefix, capacity) + + +def _cover(offers: Sequence[Tuple[int, int, "int | None"]], need: int) -> "int | None": + """The least cost covering `need` units from `(cost, capacity, quantity)` offers, taken + fractionally and rounded up, or `None` when the offers cannot cover it. + + A fractional covering problem with one constraint is solved exactly by taking offers in + order of cost per unit. Only the last offer is taken in part, so the cost is an integer + plus one ceiling and no fraction is carried. Offers of equal cost per unit give the same + total in either order, so the order needs no tie-break. Each offer is limited by its + type's whole inventory, which only weakens the bound. + """ + if need <= 0: + return 0 + ranked = sorted((offer for offer in offers if offer[1] > 0), + key=functools.cmp_to_key(lambda a, b: a[0] * b[1] - b[0] * a[1])) + total = 0 + for cost, capacity, quantity in ranked: + if quantity is None or quantity * capacity >= need: + return total + _ceil_div(cost * need, capacity) + total += cost * quantity + need -= capacity * quantity + return None + + def _value_forgone_bound(instances: Sequence[ItemInstance], unpacked: int) -> int: """`maximum_value`'s second key: whichever `unpacked` instances are left behind, their value is at least that of the `unpacked` least valuable. Values are non-negative, so the diff --git a/src/packvium/commerce/catalog.py b/src/packvium/commerce/catalog.py index 9cca0f9..9fbb6bc 100644 --- a/src/packvium/commerce/catalog.py +++ b/src/packvium/commerce/catalog.py @@ -108,6 +108,7 @@ class ItemMaster: def __post_init__(self) -> None: _require_id("item", self.id) + object.__setattr__(self, "dimensions_mm", tuple(self.dimensions_mm)) if len(self.dimensions_mm) != 3: raise ValueError("item dimensions must have exactly three axes") _require_positive_dimensions("item", self.dimensions_mm) @@ -126,6 +127,7 @@ class CartonMaster: def __post_init__(self) -> None: _require_id("carton", self.id) + object.__setattr__(self, "inner_dimensions_mm", tuple(self.inner_dimensions_mm)) if len(self.inner_dimensions_mm) != 3: raise ValueError("carton dimensions must have exactly three axes") _require_positive_dimensions("carton", self.inner_dimensions_mm) @@ -146,6 +148,7 @@ class PalletMaster: def __post_init__(self) -> None: _require_id("pallet", self.id) + object.__setattr__(self, "deck_dimensions_mm", tuple(self.deck_dimensions_mm)) if len(self.deck_dimensions_mm) != 2: raise ValueError("pallet deck dimensions must have exactly two axes") _require_positive_dimensions("pallet", self.deck_dimensions_mm) @@ -244,6 +247,9 @@ class CatalogSnapshot(_SnapshotLookupCache): overrides: tuple[FacilityOverride, ...] = () def __post_init__(self) -> None: + # Tuples detached from the caller's lists, so published history cannot be edited later. + for name in ("items", "cartons", "pallets", "exclusions", "overrides"): + object.__setattr__(self, name, tuple(getattr(self, name))) _require_unique_ids("item", self.items) _require_unique_ids("carton", self.cartons) _require_unique_ids("pallet", self.pallets) @@ -261,8 +267,6 @@ def pallet(self, id: str) -> PalletMaster: def _lookup(self, entries, id, kind, entry_type): - if type(entries) is not tuple: - return _find(entries, id, kind) indexes = getattr(self, "_entry_indexes", {}) index = indexes.get(kind) if index is None: @@ -283,8 +287,10 @@ def __getstate__(self): def __setstate__(self, state): # Also accept the dictionary state produced by older non-slotted runtimes. + # Tuples again, as __post_init__ makes them: a snapshot pickled before 1.11 holds lists. for index, field in enumerate(fields(self)): - object.__setattr__(self, field.name, state[field.name] if isinstance(state, dict) else state[index]) + value = state[field.name] if isinstance(state, dict) else state[index] + object.__setattr__(self, field.name, tuple(value)) # ------------------------------------------------------------------------------- version diff --git a/src/packvium/commerce/document.py b/src/packvium/commerce/document.py index aa84695..4fe4d6a 100644 --- a/src/packvium/commerce/document.py +++ b/src/packvium/commerce/document.py @@ -191,11 +191,12 @@ def _publish_tariff_versions( ("minimum_charge_minor", "fuel_surcharge_permille", "accessorials"), ) zones = _mapping(fields["cost_per_dimensional_kg_minor"], path + ".cost_per_dimensional_kg_minor") - costs = { - _text(zone, path + ".cost_per_dimensional_kg_minor key"): - _integer(cost, "{0}.cost_per_dimensional_kg_minor[{1!r}]".format(path, zone)) - for zone, cost in zones.items() - } + # Validated in code-point order of the zone key so the first error never depends on + # the order a language happens to iterate the mapping in. + for zone in sorted(zones, key=str): + _text(zone, path + ".cost_per_dimensional_kg_minor key") + _integer(zones[zone], "{0}.cost_per_dimensional_kg_minor[{1!r}]".format(path, zone)) + costs = dict(zones) accessorials = _load_accessorials(_default(fields, "accessorials", ()), path + ".accessorials") _model(path, lambda: registry.publish( carrier_id, service_id, diff --git a/src/packvium/commerce/rating.py b/src/packvium/commerce/rating.py index cd0e770..8a31455 100644 --- a/src/packvium/commerce/rating.py +++ b/src/packvium/commerce/rating.py @@ -41,6 +41,10 @@ from __future__ import annotations from .._compat import dataclass +from .._canonical_json import MAX_EXACT_MAGNITUDE +from .errors import CommerceInputError +from dataclasses import fields +from types import MappingProxyType from typing import Mapping, Optional @@ -109,6 +113,9 @@ def charge_minor(self, base_charge_minor: int) -> int: return _ceil_div(base_charge_minor * self.permille_of_base, 1000) +_TARIFF_MAPPINGS = ("cost_per_dimensional_kg_minor", "accessorials") + + @dataclass(frozen=True, slots=True) class Tariff: """One immutable, numbered version of one `(carrier_id, service_id)` pair's rate @@ -126,6 +133,7 @@ class Tariff: accessorials: Mapping[str, AccessorialCharge] def __post_init__(self) -> None: + self._read_only_copy_of_mappings() if not self.carrier_id: raise ValueError("carrier_id is required") if not self.service_id: @@ -146,6 +154,23 @@ def __post_init__(self) -> None: if mismatched: raise ValueError(f"accessorials dict key must match its own accessorial_id: {mismatched}") + def _read_only_copy_of_mappings(self) -> None: + # Published history must replay identically: a read-only copy, so neither the caller's + # dict nor the tariff the registry hands back can change a pinned version's rates. + for name in _TARIFF_MAPPINGS: + object.__setattr__(self, name, MappingProxyType(dict(getattr(self, name)))) + + def __getstate__(self): + # A mappingproxy cannot be pickled; the read-only view is rebuilt on restore. + return [dict(value) if isinstance(value, MappingProxyType) else value + for value in (getattr(self, field.name) for field in fields(self))] + + def __setstate__(self, state): + # Also accept the dictionary state produced by older non-slotted runtimes. + for index, field in enumerate(fields(self)): + object.__setattr__(self, field.name, state[field.name] if isinstance(state, dict) else state[index]) + self._read_only_copy_of_mappings() + # ---------------------------------------------------------------------------- breakdown @@ -194,6 +219,15 @@ def __post_init__(self) -> None: raise ValueError("requested accessorial ids must be unique") +def _refuse_unrepresentable(*amounts: int) -> None: + """M2: a quote reports exact integers, so the first amount, in reporting order, that a + double could not hold exactly refuses the whole quote. O(accessorials).""" + for amount in amounts: + if amount > MAX_EXACT_MAGNITUDE: + raise CommerceInputError( + f"quote amount {amount} is above {MAX_EXACT_MAGNITUDE} and cannot be represented exactly") + + def rate_tariff(tariff: Tariff, request: RatingRequest) -> RateBreakdown: """Rate a request against one already-resolved immutable tariff version.""" if request.zone not in tariff.cost_per_dimensional_kg_minor: @@ -231,6 +265,11 @@ def rate_tariff(tariff: Tariff, request: RatingRequest) -> RateBreakdown: amount for _, amount in accessorial_charges ) + _refuse_unrepresentable( + dimensional_weight_g, billed_weight_g, base_charge_minor, fuel_surcharge_minor, + *(amount for _, amount in accessorial_charges), total_minor, + ) + return RateBreakdown( carrier_id=tariff.carrier_id, service_id=tariff.service_id, diff --git a/src/packvium/constraints.py b/src/packvium/constraints.py index 8f407d4..15809ef 100644 --- a/src/packvium/constraints.py +++ b/src/packvium/constraints.py @@ -5,6 +5,8 @@ from .axle_load import axle_load_exceeded from .contact import ContactEdge, ContactGraph +from .loads import LoadUnit, load_units # noqa: F401 (re-exported: the names predate the move) +from .ratios import SUPPORT_SCALE, required_area, reserved_volume, scaled_ratio # noqa: F401 (re-exported likewise) from .geometry import (ALL_DIRECTIONS, AxisAlignedBox, Dimensions, InvalidDirectionError, Point, Rotation, sweep_intersects, swept_volume) from .models import Container, Item, ItemInstance, Placement @@ -13,31 +15,6 @@ from .compression import applied_pressure from .units import Length, Weight -# Support ratios arrive as floats from the public API but must never decide feasibility -# in floating point. They are converted once to a scaled integer and every comparison -# below is exact. See docs/UNITS-AND-NUMERICS.md. -SUPPORT_SCALE = 1_000_000 - - -def scaled_ratio(ratio: float) -> int: - return int(ratio * SUPPORT_SCALE + 0.5) - - -def required_area(base_area: int, scaled: int) -> int: - """Exact floor(base_area * scaled / SUPPORT_SCALE) without an overflowing product.""" - whole, remainder = divmod(base_area, SUPPORT_SCALE) - return whole * scaled + (remainder * scaled) // SUPPORT_SCALE - - -def reserved_volume(container: Container) -> int: - """Volume set aside for packing material, exact even for a metre-scale container. - - Not floating-point `ratio * volume`: that is exactly the double-precision loss - this codebase's fixed-point design exists to avoid for a feasibility number. - """ - return required_area(container.inner_dimensions.volume, scaled_ratio(container.void_fill_reserve_ratio)) - - def usable_volume(container: Container) -> int: return container.inner_dimensions.volume - reserved_volume(container) @@ -153,26 +130,6 @@ def proves_unplaceable( ) -> tuple[str, str] | None: ... -@dataclass(frozen=True, slots=True) -class LoadUnit: - """The only facts load propagation needs about a box, real or hypothetical.""" - box: AxisAlignedBox - weight_ticks: int - max_top_load_ticks: int | None - max_stacked_items: int | None - label: str - nesting_item_id: str | None = None - nesting_height_ticks: int | None = None - # Set only for a `compressible` item. Load propagation already computes the - # cumulative mass above every unit, which is exactly the numerator the pressure model - # needs, so the crush check rides the graph that is built anyway rather than a second one. - compression_ratio_ppm: int | None = None - max_compression_pressure_kpa: int | None = None - # The item's own footprint, which the load presses on; `box` is its envelope, grown by the - # clearance, and it carries the support graph. - footprint_ticks2: int | None = None - - @dataclass(frozen=True, slots=True) class DirectSupport: index: int @@ -470,23 +427,6 @@ def stacking_refusal(lower: Item, upper_group: str | None) -> str | None: return None -def load_units(placements: Sequence[Placement], extra: LoadUnit | None = None) -> tuple[LoadUnit, ...]: - units = [ - LoadUnit(p.envelope_box, p.instance.weight.ticks, - None if p.instance.item.max_top_load is None else p.instance.item.max_top_load.ticks, - p.instance.item.max_stacked_items, - p.instance.id, - None if p.instance.item.nesting_height is None else p.instance.item.id, - None if p.instance.item.nesting_height is None else p.instance.item.nesting_height.ticks, - p.instance.item.compression_ratio_ppm, - p.instance.item.max_compression_pressure_kpa, - p.dimensions.length.ticks * p.dimensions.width.ticks) - for p in placements - ] - if extra is not None: units.append(extra) - return tuple(units) - - def top_loads(units: Sequence[LoadUnit], graph: LoadSupportGraph | None = None) -> list[int]: """Weight borne by each unit, propagated down the whole stack. diff --git a/src/packvium/flat_bag.py b/src/packvium/flat_bag.py index b2cb7ac..a2866c3 100644 --- a/src/packvium/flat_bag.py +++ b/src/packvium/flat_bag.py @@ -12,14 +12,21 @@ A `gusseted_bag` (1.10) has side gussets of depth `G` folded into each long edge: the tube round the package's `y-z` section is `2(W + G)` long instead of `2W`, so the width sum becomes -`b + c <= W + G`. The length sum is unchanged (no bottom gusset in 1.10), and `G = 0` is the -flat bag. Every function here takes the gusset depth in ticks, `0` for a flat bag. +`b + c <= W + G`, and `G = 0` is the flat bag. + +A bottom gusset (1.11) is one panel of depth `K` folded into the closed end: the loop +along the bag runs front, bottom, back, `2L + K`, so the length sum becomes +`2(a + c) <= 2L + K`, doubled to stay in integers. A gusseted bag with a bottom gusset may +stand on it (`orientation: standing`): the solving frame is then `W x H x L`, the floor is the +opened bottom, and the same two loops go round other axes -- `a + b <= W + G` across, +`2(b + c) <= 2L + K` along. `Girth` holds the two loops for either frame. """ from __future__ import annotations from typing import Iterable +from ._compat import dataclass from .geometry import Dimensions from .units import Length @@ -27,16 +34,47 @@ GUSSETED_BAG = "gusseted_bag" DEFORMABLE_BOUNDARY_KINDS = (FLAT_BAG, GUSSETED_BAG) +FLAT = "flat" +STANDING = "standing" +BAG_ORIENTATIONS = (FLAT, STANDING) + Extent = tuple[int, int, int] -def girth_admits(inner: Dimensions, a: int, b: int, c: int, gusset: int = 0) -> bool: - """Whether a package of extents `(a, b, c)` passes both girth inequalities. +@dataclass(frozen=True, slots=True) +class Girth: + """The two loops of film round a bag's package, as axis pairs of the solving frame. - The rigid boundary (`a <= L`, `b <= W`, `c <= H`) is the caller's own check and stays - where it already is; only the two sums are new. + `along` is the loop down the length (`2L + K`, compared against the doubled sum of its two + extents), `across` the loop round the width (`W + G`, against their plain sum). Lying flat + they are `(x, z)` and `(y, z)`; standing, `(y, z)` and `(x, y)`. """ - return a + c <= inner.length.ticks and b + c <= inner.width.ticks + gusset + + along: tuple[int, int] + along_limit: int + across: tuple[int, int] + across_limit: int + + def admits(self, extent: Extent) -> bool: + """Whether a package of extents `(a, b, c)` passes both loops. The rigid boundary is + the caller's own check and stays where it already is; only the two sums are new.""" + i, j = self.along + p, q = self.across + return (2 * (extent[i] + extent[j]) <= self.along_limit + and extent[p] + extent[q] <= self.across_limit) + + +def girth_for(length: int, width: int, side_gusset: int, bottom_gusset: int, standing: bool) -> Girth: + """The loops of a bag declared `length x width` with the two gusset depths, `0` where none + is declared, in its flat or standing frame.""" + if standing: + return Girth((1, 2), 2 * length + bottom_gusset, (0, 1), width + side_gusset) + return Girth((0, 2), 2 * length + bottom_gusset, (1, 2), width + side_gusset) + + +def standing_dimensions(declared: Dimensions) -> Dimensions: + """The `W x H x L` frame a bag declared `L x W x H` stands in.""" + return Dimensions(declared.width, declared.height, declared.length) def grown_extent(extent: Extent, x2: int, y2: int, z2: int) -> Extent: @@ -52,10 +90,22 @@ def extent_of(boxes: Iterable[tuple[int, int, int]]) -> Extent: return extent -def fits_alone(inner: Dimensions, dimensions: Dimensions, gusset: int = 0) -> bool: - """Whether one box of these dimensions, alone at the origin, fits a bag.""" - a, b, c = dimensions.length.ticks, dimensions.width.ticks, dimensions.height.ticks - return dimensions.fits_inside(inner) and girth_admits(inner, a, b, c, gusset) +def girth_admits(inner: Dimensions, a: int, b: int, c: int, gusset: int = 0, bottom: int = 0) -> bool: + """Whether a flat-lying bag declared `inner` admits a package of extents `(a, b, c)`, with a + side gusset `gusset` and a bottom gusset `bottom` in ticks. The 1.10 signature, widened by a + trailing `bottom`; the rigid boundary stays the caller's own check.""" + return girth_for(inner.length.ticks, inner.width.ticks, gusset, bottom, False).admits((a, b, c)) + + +def fits_alone(inner: Dimensions, dimensions: Dimensions, girth: "Girth | int" = 0) -> bool: + """Whether one box of these dimensions, alone at the origin of the frame `inner`, fits a bag. + + `girth` is the bag's two loops; a plain integer is the 1.10 form, a flat-lying bag's side + gusset depth in ticks.""" + if isinstance(girth, int): + girth = girth_for(inner.length.ticks, inner.width.ticks, girth, 0, False) + extent = (dimensions.length.ticks, dimensions.width.ticks, dimensions.height.ticks) + return dimensions.fits_inside(inner) and girth.admits(extent) def as_dimensions(extent: Extent) -> Dimensions: diff --git a/src/packvium/hull.py b/src/packvium/hull.py index 7da53eb..553f144 100644 --- a/src/packvium/hull.py +++ b/src/packvium/hull.py @@ -59,6 +59,10 @@ #: Smallest number of vertices that can enclose a volume. MINIMUM_HULL_VERTICES = 4 +#: Most vertices an item's hull may list (the corpus maximum is 16). Refused at admission, before +#: any per-vertex work, so a request cannot make the hull checks cost what it chooses. +MAXIMUM_HULL_VERTICES = 32 + #: Largest absolute vertex coordinate a hull may carry, in ticks (6.25 m). #: #: Shared verbatim with PHP, Rust and JavaScript. Besides keeping admission identical across diff --git a/src/packvium/loads.py b/src/packvium/loads.py new file mode 100644 index 0000000..3049641 --- /dev/null +++ b/src/packvium/loads.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import Sequence + +from ._compat import dataclass +from .geometry import AxisAlignedBox +from .models import Placement + + +@dataclass(frozen=True, slots=True) +class LoadUnit: + """The only facts load propagation needs about a box, real or hypothetical.""" + box: AxisAlignedBox + weight_ticks: int + max_top_load_ticks: int | None + max_stacked_items: int | None + label: str + nesting_item_id: str | None = None + nesting_height_ticks: int | None = None + # Set only for a `compressible` item. Load propagation already computes the + # cumulative mass above every unit, which is exactly the numerator the pressure model + # needs, so the crush check rides the graph that is built anyway rather than a second one. + compression_ratio_ppm: int | None = None + max_compression_pressure_kpa: int | None = None + # The item's own footprint, which the load presses on; `box` is its envelope, grown by the + # clearance, and it carries the support graph. + footprint_ticks2: int | None = None + + +def load_units(placements: Sequence[Placement], extra: LoadUnit | None = None) -> tuple[LoadUnit, ...]: + units = [ + LoadUnit(p.envelope_box, p.instance.weight.ticks, + None if p.instance.item.max_top_load is None else p.instance.item.max_top_load.ticks, + p.instance.item.max_stacked_items, + p.instance.id, + None if p.instance.item.nesting_height is None else p.instance.item.id, + None if p.instance.item.nesting_height is None else p.instance.item.nesting_height.ticks, + p.instance.item.compression_ratio_ppm, + p.instance.item.max_compression_pressure_kpa, + p.dimensions.length.ticks * p.dimensions.width.ticks) + for p in placements + ] + if extra is not None: units.append(extra) + return tuple(units) diff --git a/src/packvium/models.py b/src/packvium/models.py index 3ad4066..6ea76c8 100644 --- a/src/packvium/models.py +++ b/src/packvium/models.py @@ -1,6 +1,7 @@ from __future__ import annotations -from dataclasses import field +from dataclasses import field, fields +from types import MappingProxyType from ._compat import dataclass from typing import Any, Iterable, Mapping @@ -8,7 +9,8 @@ from ._canonical_json import canonical_identifier from .centre_of_mass import centre_of_mass_offset_ppm from . import compression, hull -from .flat_bag import DEFORMABLE_BOUNDARY_KINDS, GUSSETED_BAG, as_dimensions, extent_of +from .flat_bag import (BAG_ORIENTATIONS, DEFORMABLE_BOUNDARY_KINDS, FLAT, GUSSETED_BAG, STANDING, Girth, + as_dimensions, extent_of, girth_for) from .pallet_overhang import Deck, OverhangLimit from .pallet_overhang import achieved_dimensions as pallet_achieved, billed_dimensions as pallet_billed from .geometry import (ALL_DIRECTIONS, AxisAlignedBox, Dimensions, InvalidDirectionError, @@ -33,6 +35,21 @@ def _ratio_between_zero_and_one(value: float, name: str) -> None: reason = "below_minimum" if value < 0 else "above_maximum" if value > 1 else "invalid_value" raise refused(reason, f"{name} must be between 0 and 1") +def _detached(value: Any) -> Any: + """A copy of the dicts, lists and tuples in `value`, sharing every other object. + + Enough to keep a caller's later edits out of an admitted request without the deep copy + that clones, or fails on, objects a caller keeps in metadata. O(size of the structure). + """ + if isinstance(value, Mapping): + return {key: _detached(item) for key, item in value.items()} + if type(value) is list: + return [_detached(item) for item in value] + if type(value) is tuple: + return tuple(_detached(item) for item in value) + return value + + @dataclass(frozen=True, slots=True) class Obstacle: """An excluded zone. `additional_boxes` expresses a non-rectangular shape (a @@ -163,6 +180,10 @@ def __post_init__(self) -> None: object.__setattr__(self, "incompatible_tags", frozenset(self.incompatible_tags)) object.__setattr__(self, "eligible_container_tags", frozenset(self.eligible_container_tags)) object.__setattr__(self, "accepts_stacking_groups", frozenset(self.accepts_stacking_groups)) + # Detached from the caller's dict (nested values too), so mutating it afterwards cannot + # change a request that was already admitted. A copy rather than a read-only view, + # since metadata is echoed into results as an ordinary dict. + object.__setattr__(self, "metadata", _detached(self.metadata)) # Coerce here rather than in `create`, so every construction path is covered. An # unparsed weight used to travel all the way into the solver before failing. object.__setattr__(self, "weight", Weight.parse(self.weight)) @@ -176,6 +197,11 @@ def _validate_shape(self) -> None: at once: which of them are required, which are forbidden, and what the survivors have to be consistent with. """ + # First, so an oversized hull is refused before any per-vertex work runs. + if self.hull_vertices is not None and not isinstance(self.hull_vertices, (list, tuple)): + raise refused_type("hull_vertices must be a list") + if self.hull_vertices is not None and len(self.hull_vertices) > hull.MAXIMUM_HULL_VERTICES: + raise refused("above_maximum", f"hull_vertices must have at most {hull.MAXIMUM_HULL_VERTICES} vertices") object.__setattr__(self, "shape_type", ShapeType(self.shape_type)) # The value's own floor first, as the JSON rules check it before the shape. if self.max_compression_pressure_kpa is not None and self.max_compression_pressure_kpa < 0: @@ -379,14 +405,21 @@ class Container: # `inner_dimensions` to the frame and drops the limit, so a frame is never widened twice. deck: Deck | None = None # A `"gusseted_bag"`'s side gusset depth G: its width girth is W + G (1.10, `flat_bag.py`). - # Required for that kind and refused for every other container. Last, as above. + # A gusseted bag declares it, `bottom_gusset_depth`, or both; every other container + # refuses it. Last, as above. side_gusset_depth: Length | None = None + # A gusseted bag's bottom gusset depth K: its length girth is 2L + K (1.11). + bottom_gusset_depth: Length | None = None + # `"flat"` or `"standing"` (1.11): a gusseted bag with a bottom gusset may stand on it. + bag_orientation: str = FLAT + # Set only by `solving_frame`: `inner_dimensions` is the standing `W x H x L` frame, and + # `declared_inner` turns it back. A frame is never turned twice. + upright_frame: bool = False def __post_init__(self) -> None: if not self.id: raise refused("invalid_value", "container id is required") if self.deformable_boundary is not None: self._require_bag_fields() - elif self.side_gusset_depth is not None: - raise refused("not_allowed", "side_gusset_depth requires deformable_boundary gusseted_bag") + else: self._refuse_gusset_fields() if self.pallet_overhang_limit is not None: self._require_pallet_fields() if self.made_to_measure is not None: self.made_to_measure.admits(as_triple(self.inner_dimensions)) if self.quantity is not None and self.quantity <= 0: raise refused("below_minimum", "container quantity must be positive") @@ -398,6 +431,10 @@ def __post_init__(self) -> None: raise refused("invalid_value", "the front axle must be strictly nearer the origin than the rear axle") if front.position.ticks < 0 or rear.position.ticks > self.inner_dimensions.length.ticks: raise refused("invalid_value", "axle positions must lie within the container's length") + # Read-only before the check below, so the admitted limits cannot be edited afterwards; + # pickling, which the concurrent portfolio needs, goes through __getstate__. + object.__setattr__(self, "tag_limits", MappingProxyType(dict(self.tag_limits))) + object.__setattr__(self, "metadata", _detached(self.metadata)) if any(limit < 1 for limit in self.tag_limits.values()): raise refused("below_minimum", "tag_limits must be at least 1") if self.max_items is not None and self.max_items < 1: raise refused("below_minimum", "container max_items must be at least 1") # Deduplicated into the canonical order rather than kept as given: two callers @@ -417,6 +454,17 @@ def __post_init__(self) -> None: if self.max_stack_density is not None: object.__setattr__(self, "max_stack_density", Weight.parse(self.max_stack_density)) + def __getstate__(self) -> list[Any]: + # A mappingproxy cannot be pickled; the read-only view is rebuilt on restore. + return [dict(value) if isinstance(value, MappingProxyType) else value + for value in (getattr(self, name.name) for name in fields(self))] + + def __setstate__(self, state: Any) -> None: + # Also accepts the dictionary state of a runtime without slots (Python 3.9). + for index, name in enumerate(fields(self)): + object.__setattr__(self, name.name, state[name.name] if isinstance(state, dict) else state[index]) + object.__setattr__(self, "tag_limits", MappingProxyType(dict(self.tag_limits))) + def _require_bag_fields(self) -> None: """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 @@ -434,26 +482,58 @@ def _require_bag_fields(self) -> None: if fields: raise refused("not_allowed", f"{fields[0]} cannot be combined with deformable_boundary") + def _refuse_gusset_fields(self) -> None: + """Gusset depths and a standing orientation describe a gusseted bag and nothing else.""" + for name, present in (("side_gusset_depth", self.side_gusset_depth is not None), + ("bottom_gusset_depth", self.bottom_gusset_depth is not None), + ("orientation", self.bag_orientation != FLAT)): + if present: + raise refused("not_allowed", f"{name} requires deformable_boundary gusseted_bag") + def _require_gusset_rule(self) -> None: - """A gusseted bag's side gusset is required, positive and no deeper than the bag is - wide: a deeper fold would have no flat sheet left to fold from. A flat bag takes - none. O(1).""" - gusseted = self.deformable_boundary == GUSSETED_BAG - if self.side_gusset_depth is None: - if gusseted: raise refused("missing_field", "a gusseted_bag requires side_gusset_depth") + """A gusseted bag declares a side gusset, a bottom gusset or both, each positive. A + side gusset is no deeper than the bag is wide and a bottom one no deeper than twice its + length: a deeper fold would have no flat sheet left to fold from. Standing needs a + bottom gusset to stand on. A flat bag takes none of them. O(1).""" + if self.deformable_boundary != GUSSETED_BAG: + self._refuse_gusset_fields() return - if not gusseted: - raise refused("not_allowed", "side_gusset_depth requires deformable_boundary gusseted_bag") - depth = self.side_gusset_depth.ticks - if depth <= 0: raise refused("invalid_value", "side_gusset_depth must be positive") - if depth > self.inner_dimensions.width.ticks: - raise refused("invalid_value", "side_gusset_depth exceeds inner_dimensions width") + declared = self.declared_inner + if self.side_gusset_depth is None and self.bottom_gusset_depth is None: + raise refused("missing_field", "a gusseted_bag requires side_gusset_depth") + for name, depth, limit, what in ( + ("side_gusset_depth", self.side_gusset_depth, declared.width.ticks, + "inner_dimensions width"), + ("bottom_gusset_depth", self.bottom_gusset_depth, 2 * declared.length.ticks, + "twice inner_dimensions length")): + if depth is None: + continue + if depth.ticks <= 0: raise refused("invalid_value", f"{name} must be positive") + if depth.ticks > limit: raise refused("invalid_value", f"{name} exceeds {what}") + if self.bag_orientation not in BAG_ORIENTATIONS: + raise refused("not_allowed", f"orientation must be one of {list(BAG_ORIENTATIONS)}") + if self.bag_orientation == STANDING and self.bottom_gusset_depth is None: + raise refused("missing_field", "bottom_gusset_depth is required when orientation is standing") @property def side_gusset_ticks(self) -> int: - """The gusset depth G in ticks; 0 for a flat bag and every rigid container.""" + """The side gusset depth G in ticks; 0 for a flat bag and every rigid container.""" return 0 if self.side_gusset_depth is None else self.side_gusset_depth.ticks + @property + def bottom_gusset_ticks(self) -> int: + """The bottom gusset depth K in ticks; 0 where none is declared.""" + return 0 if self.bottom_gusset_depth is None else self.bottom_gusset_depth.ticks + + @property + def girth(self) -> "Girth | None": + """A bag's two loops in the frame it is packed in; `None` for a rigid container.""" + if self.deformable_boundary is None: + return None + declared = self.declared_inner + return girth_for(declared.length.ticks, declared.width.ticks, self.side_gusset_ticks, + self.bottom_gusset_ticks, self.upright_frame) + def _require_pallet_fields(self) -> None: """The fields a pallet with an overhang limit refuses: each reads the declared frame or a wall the widened frame moves (docs/PALLET-AND-ROBOT-RULES.md ""). The JSON @@ -468,7 +548,11 @@ def _require_pallet_fields(self) -> None: @property def declared_inner(self) -> Dimensions: - """The inner size the caller declared: a solving frame's deck, else `inner_dimensions`.""" + """The inner size the caller declared: a solving frame's deck, a standing bag's frame + turned back to `L x W x H`, else `inner_dimensions`.""" + if self.upright_frame: + inner = self.inner_dimensions + return Dimensions(inner.height, inner.length, inner.width) if self.deck is None: return self.inner_dimensions return Dimensions(Length(self.deck.length), Length(self.deck.width), self.inner_dimensions.height) diff --git a/src/packvium/packer.py b/src/packvium/packer.py index d726721..4b6be27 100644 --- a/src/packvium/packer.py +++ b/src/packvium/packer.py @@ -44,7 +44,8 @@ def _objective_bound(self, request: PackingRequest) -> "tuple[int, ...] | None": """ if self.solution_scorer is not None: return None - return bounds.for_request(request.instances, request.containers, self.config.objective) + return bounds.for_request(request.instances, request.containers, self.config.objective, + self.config) def pack(self, items, containers, fixed_placements=(), currency: str | None = None) -> PackingResult: items, containers, fixed_placements = tuple(items), tuple(containers), tuple(fixed_placements) diff --git a/src/packvium/pallet_overhang.py b/src/packvium/pallet_overhang.py index f10cb6b..54f6a1b 100644 --- a/src/packvium/pallet_overhang.py +++ b/src/packvium/pallet_overhang.py @@ -19,6 +19,7 @@ from typing import TYPE_CHECKING from ._compat import dataclass +from .flat_bag import STANDING, standing_dimensions from .geometry import AxisAlignedBox, Dimensions, Point from .units import Length @@ -55,8 +56,12 @@ def as_box(self) -> AxisAlignedBox: def solving_frame(container: "Container") -> "Container": - """The container every solver packs: itself without a limit, else the widened frame - carrying its deck. The frame states no limit, so a second call returns it unchanged.""" + """The container every solver packs: a standing bag turned to its `W x H x L` frame +, a pallet with a limit widened to the frame carrying its deck, else itself. A + frame is marked as one, so a second call returns it unchanged.""" + if container.bag_orientation == STANDING and not container.upright_frame: + return replace(container, inner_dimensions=standing_dimensions(container.inner_dimensions), + upright_frame=True) limit = container.pallet_overhang_limit if limit is None: return container diff --git a/src/packvium/ratios.py b/src/packvium/ratios.py new file mode 100644 index 0000000..d86a512 --- /dev/null +++ b/src/packvium/ratios.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .models import Container + +# Support ratios arrive as floats from the public API but must never decide feasibility +# in floating point. They are converted once to a scaled integer and every comparison +# below is exact. See docs/UNITS-AND-NUMERICS.md. +SUPPORT_SCALE = 1_000_000 + + +def scaled_ratio(ratio: float) -> int: + return int(ratio * SUPPORT_SCALE + 0.5) + + +def required_area(base_area: int, scaled: int) -> int: + """Exact floor(base_area * scaled / SUPPORT_SCALE) without an overflowing product.""" + whole, remainder = divmod(base_area, SUPPORT_SCALE) + return whole * scaled + (remainder * scaled) // SUPPORT_SCALE + + +def reserved_volume(container: Container) -> int: + """Volume set aside for packing material, exact even for a metre-scale container. + + Not floating-point `ratio * volume`: that is exactly the double-precision loss + this codebase's fixed-point design exists to avoid for a feasibility number. + """ + return required_area(container.inner_dimensions.volume, scaled_ratio(container.void_fill_reserve_ratio)) diff --git a/src/packvium/request_errors.py b/src/packvium/request_errors.py index 2b710f1..c2fbcce 100644 --- a/src/packvium/request_errors.py +++ b/src/packvium/request_errors.py @@ -23,11 +23,12 @@ from ._canonical_json import MAX_EXACT_MAGNITUDE, json_integer, json_spelling from ._request_error import InvalidRequestError -from .flat_bag import DEFORMABLE_BOUNDARY_KINDS, GUSSETED_BAG +from .flat_bag import BAG_ORIENTATIONS, DEFORMABLE_BOUNDARY_KINDS, GUSSETED_BAG, STANDING from .units import LENGTH_UNIT_CODES, WEIGHT_UNIT_CODES, Length, ParsedMeasures, Weight from .made_to_measure import box_cost_minor_for from .orientations import CODES, UPRIGHT_CODES, SIGNED_CODE_NEEDS_A_HULL, refusal_reason, vocabulary from .bounds import MAX_BOUND_SUM +from .hull import MAXIMUM_HULL_VERTICES REASONS = ("missing_field", "wrong_type", "below_minimum", "above_maximum", "negative_measure", "invalid_unit", "duplicate_id", "not_allowed", "invalid_value") @@ -282,6 +283,7 @@ def _check_item(raw: Any, where: str, unit: str, measures: ParsedMeasures) -> No _optional(item, "allowed_rotations", where, lambda v, f: _allowed_rotations(v, f, item)) _optional(item, "ground_contact_rule", where, lambda v, f: _one_of(v, f, GROUND_CONTACT_RULES)) _optional(item, "shape_type", where, lambda v, f: _one_of(v, f, SHAPE_TYPES)) + _optional(item, "hull_vertices", where, _hull_vertex_count) for name in ITEM_BOOLEANS: _optional(item, name, where, _boolean) listed = item.get("allowed_rotations") @@ -290,6 +292,13 @@ def _check_item(raw: Any, where: str, unit: str, measures: ParsedMeasures) -> No "must allow at least one rotation after keep_upright") +def _hull_vertex_count(raw: Any, field: str) -> None: + """Only the count: the cap exists so no per-vertex work runs on an oversized hull. O(1).""" + if len(_list(raw, field)) > MAXIMUM_HULL_VERTICES: + raise InvalidRequestError("above_maximum", field, + f"must have at most {MAXIMUM_HULL_VERTICES} vertices") + + def _allowed_rotations(raw: Any, where: str, item: Mapping[str, Any]) -> None: """Each code from the item's vocabulary (1.10): all 24 for a hull, the six legacy codes for anything else, where a signed code is a rule broken rather than an unknown word. The @@ -378,31 +387,59 @@ def pallet_frame(inner: Tuple[int, int, int], overhang_x: int, overhang_y: int, def _deformable_boundary(container: Mapping[str, Any], raw: Any, field: str, where: str, unit: str, measures: ParsedMeasures) -> None: - """The boundary object top to bottom -- kind, unknown keys, the gusset -- then the - container fields a bag refuses. O(1).""" + """The boundary object top to bottom -- kind, unknown keys, the gussets, the orientation -- + then the container fields a bag refuses. O(1).""" boundary = _object(raw, field) kind = _required(boundary, "kind", field) _one_of(kind, pointer_join(field, "kind"), DEFORMABLE_BOUNDARY_KINDS) gusseted = kind == GUSSETED_BAG - _known_fields(boundary, field, ("kind", "side_gusset_depth") if gusseted else ("kind",)) + _known_fields(boundary, field, GUSSETED_BAG_FIELDS if gusseted else ("kind",)) if gusseted: - _side_gusset_depth(container, _required(boundary, "side_gusset_depth", field), - pointer_join(field, "side_gusset_depth"), unit, measures) + _gusseted_bag(container, boundary, field, unit, measures) for name in BAG_EXCLUSIONS: if _set_beside_a_bag(name, container.get(name)): raise InvalidRequestError("not_allowed", pointer_join(where, name), "cannot be combined with deformable_boundary") -def _side_gusset_depth(container: Mapping[str, Any], value: Any, field: str, unit: str, - measures: ParsedMeasures) -> None: - """A length, positive once read in ticks, and no deeper than the bag's inner width.""" +#: The keys a gusseted bag's boundary may carry (1.10 side gusset; 1.11 bottom gusset and +#: orientation). +GUSSETED_BAG_FIELDS = ("bottom_gusset_depth", "kind", "orientation", "side_gusset_depth") + + +def _gusseted_bag(container: Mapping[str, Any], boundary: Mapping[str, Any], field: str, unit: str, + measures: ParsedMeasures) -> None: + """The side gusset, then the bottom one, each a positive length within its fold; with + neither, the side gusset is reported missing as in 1.10. Then the orientation, and a + standing bag's bottom gusset. O(1).""" + side, bottom = boundary.get("side_gusset_depth"), boundary.get("bottom_gusset_depth") + if side is None and bottom is None: + _required(boundary, "side_gusset_depth", field) + inner = _ticks(container["inner_dimensions"], unit, measures) + if side is not None: + _gusset_depth(side, pointer_join(field, "side_gusset_depth"), inner[1], + "exceeds inner_dimensions width", unit, measures) + if bottom is not None: + _gusset_depth(bottom, pointer_join(field, "bottom_gusset_depth"), 2 * inner[0], + "exceeds twice inner_dimensions length", unit, measures) + orientation = boundary.get("orientation") + if orientation is None: + return + _one_of(orientation, pointer_join(field, "orientation"), BAG_ORIENTATIONS) + if orientation == STANDING and bottom is None: + raise InvalidRequestError("missing_field", pointer_join(field, "bottom_gusset_depth"), + "is required when orientation is standing") + + +def _gusset_depth(value: Any, field: str, deepest: int, too_deep: str, unit: str, + measures: ParsedMeasures) -> None: + """A length, positive once read in ticks, and no deeper than its fold allows.""" _measure(value, field, Length, unit, measures) depth = measures.read(Length, value, unit).ticks if depth == 0: raise InvalidRequestError("invalid_value", field, "must be positive") - if depth > _ticks(container["inner_dimensions"], unit, measures)[1]: - raise InvalidRequestError("invalid_value", field, "exceeds inner_dimensions width") + if depth > deepest: + raise InvalidRequestError("invalid_value", field, too_deep) #: Every key the request schema's `made_to_measure` declares; it sets `additionalProperties: false`. @@ -557,6 +594,25 @@ def _rate_table(raw: Any, where: str, currency: Optional[str]) -> None: _optional(table, "minimum_charge_minor", where, lambda v, f: _integer(v, f, 0)) _optional(table, "fuel_surcharge_permille", where, lambda v, f: _integer(v, f, 0)) _optional(table, "currency", where, lambda v, f: rate_table_currency(v, f, currency)) + top_bracket_landed( + [json_integer(price) for price in table.get("prices_minor") or ()], + json_integer(table.get("minimum_charge_minor") or 0), + json_integer(table.get("fuel_surcharge_permille") or 0), where) + + +def top_bracket_landed(prices: Sequence[int], minimum_charge: int, surcharge_permille: int, + where: str) -> None: + """M1: the dearest bracket's landed cost, fuel surcharge included, against + `MAX_EXACT_MAGNITUDE`. The same arithmetic as `RateTable.charge_minor_or_none`, so no + bracket the table can bill passes it. A table with no prices is left to the other rules. + Shared with `request_objects`. O(prices).""" + if not prices: + return + base = max(max(prices), minimum_charge) + if base + -(-base * surcharge_permille // 1000) > MAX_EXACT_MAGNITUDE: + raise InvalidRequestError( + "above_maximum", where, + f"must price its top bracket at most {MAX_EXACT_MAGNITUDE} minor units with the fuel surcharge") def currency_code(value: Any, field: str) -> None: diff --git a/src/packvium/request_objects.py b/src/packvium/request_objects.py index e69f9d4..75506c4 100644 --- a/src/packvium/request_objects.py +++ b/src/packvium/request_objects.py @@ -26,7 +26,7 @@ from .request_errors import (BAG_EXCLUSIONS, InvalidRequestError, _integer, _one_of, _ratio, _set_beside_a_bag, _stacking_group_name, box_ticks, currency_code, length_ticks, pallet_frame, pointer, pointer_join, - rate_table_currency, total_weight_ticks, weight_ticks) + rate_table_currency, top_bracket_landed, total_weight_ticks, weight_ticks) #: (JSON name, PackingConfig attribute, floor), in `check_request`'s order. _CONFIGURATION_INTEGERS = (("time_limit_ms", "time_limit_ms", 1), ("alternatives", "top_k", 1), @@ -149,6 +149,7 @@ def _check_rate_table(table: RateTable, where: str, currency: Optional[str]) -> _integer(table.fuel_surcharge_permille, pointer_join(where, "fuel_surcharge_permille"), 0) if table.currency is not None: rate_table_currency(table.currency, pointer_join(where, "currency"), currency) + top_bracket_landed(table.prices_minor, table.minimum_charge_minor, table.fuel_surcharge_permille, where) def _check_flat_bag(container: Container, where: str) -> None: diff --git a/src/packvium/result.py b/src/packvium/result.py index cc2b4c7..e6589dc 100644 --- a/src/packvium/result.py +++ b/src/packvium/result.py @@ -7,8 +7,9 @@ from typing import Iterable, Mapping from .axle_load import axle_reactions -from .constraints import load_units, reserved_volume +from .loads import load_units from .models import PackedContainer, UnpackedItem, placement_id +from .ratios import reserved_volume from .units import Length diff --git a/src/packvium/result_validation.py b/src/packvium/result_validation.py index 5136203..a070d33 100644 --- a/src/packvium/result_validation.py +++ b/src/packvium/result_validation.py @@ -275,6 +275,12 @@ class ContainerSpec: #: 1.10: a gusseted bag's side gusset depth G in ticks, which widens the width girth to #: b + c <= W + G; 0 for a flat bag and every rigid container. side_gusset: int = 0 + #: 1.11: a gusseted bag's bottom gusset depth K in ticks, which lengthens the + #: length girth to 2(a + c) <= 2L + K; 0 where none is declared. + bottom_gusset: int = 0 + #: A bag standing on its bottom gusset, whose `inner` is then the `W x H x L` + #: frame it is packed in. + standing: bool = False #: Whether a packed instance must report `achieved_dimensions`: a flat bag or a #: made-to-measure box. Either way it is the tight extent of the placements. reports_achieved_extent: bool = False @@ -409,8 +415,12 @@ def _parse_containers(request: dict, unit: str) -> dict[str, ContainerSpec]: ) for axle in raw_axles ) - inner, deck = _frame_and_deck(dimensions_to_ticks(raw["inner_dimensions"], unit), - raw.get("pallet_overhang_limit"), unit) + boundary = raw.get("deformable_boundary") + standing = boundary is not None and boundary.get("orientation") == "standing" + declared = dimensions_to_ticks(raw["inner_dimensions"], unit) + if standing: + declared = (declared[1], declared[2], declared[0]) + inner, deck = _frame_and_deck(declared, raw.get("pallet_overhang_limit"), unit) containers[raw["id"]] = ContainerSpec( id=raw["id"], inner=inner, @@ -441,7 +451,9 @@ def _parse_containers(request: dict, unit: str) -> dict[str, ContainerSpec]: ), rate_table=raw.get("rate_table"), flat_bag=raw.get("deformable_boundary") is not None, - side_gusset=_side_gusset(raw.get("deformable_boundary"), unit), + side_gusset=_gusset(boundary, "side_gusset_depth", unit), + bottom_gusset=_gusset(boundary, "bottom_gusset_depth", unit), + standing=standing, reports_achieved_extent=(raw.get("deformable_boundary") is not None or raw.get("made_to_measure") is not None or deck is not None), @@ -451,11 +463,11 @@ def _parse_containers(request: dict, unit: str) -> dict[str, ContainerSpec]: return containers -def _side_gusset(boundary: dict | None, unit: str) -> int: - """A gusseted bag's side gusset depth in ticks, else 0.""" - if boundary is None or boundary.get("side_gusset_depth") is None: +def _gusset(boundary: dict | None, name: str, unit: str) -> int: + """A gusseted bag's side or bottom gusset depth in ticks, else 0.""" + if boundary is None or boundary.get(name) is None: return 0 - return to_ticks(boundary["side_gusset_depth"], unit, LENGTH_TICKS) + return to_ticks(boundary[name], unit, LENGTH_TICKS) def _frame_and_deck(declared: tuple[int, int, int], limit: dict | None, @@ -798,8 +810,30 @@ def _fits_empty(container: ContainerSpec, size: tuple[int, int, int]) -> bool: bag, both girth sums with the envelope alone at the origin.""" if any(size[index] > container.inner[index] for index in range(3)): return False - return not container.flat_bag or (size[0] + size[2] <= container.inner[0] - and size[1] + size[2] <= container.inner[1] + container.side_gusset) + return not container.flat_bag or _girth_breach(container, *size) is None + + +def _girth_breach(spec: ContainerSpec, a: int, b: int, c: int) -> str | None: + """How a bag's package of extents `(a, b, c)` breaks a loop of film, or `None`. + + Lying flat on an `L x W` bag: `2(a + c) <= 2L + K` and `b + c <= W + G`. Standing in its + `W x H x L` frame: `2(b + c) <= 2L + K` and `a + b <= W + G` (1.10). `G` + and `K` are the side and bottom gussets, 0 where none is declared. + """ + if spec.standing: + width, length = spec.inner[0], spec.inner[2] + along, across = (b, c), (a, b) + else: + length, width = spec.inner[0], spec.inner[1] + along, across = (a, c), (b, c) + if 2 * sum(along) <= 2 * length + spec.bottom_gusset and sum(across) <= width + spec.side_gusset: + return None + if spec.standing: + sums = f"b + c = {b + c}, a + b = {a + b}, standing, length {length}, width {width}" + else: + sums = f"a + c = {a + c}, b + c = {b + c}, flat size {length} x {width}" + return (sums + (f", side gusset {spec.side_gusset}" if spec.side_gusset else "") + + (f", bottom gusset {spec.bottom_gusset}" if spec.bottom_gusset else "")) def _achieved_extent(packed: dict, clearance: int) -> tuple[int, int, int]: @@ -828,11 +862,9 @@ def _check_achieved_extent(packed: dict, spec: ContainerSpec, clearance: int, if stated != (a, b, c): issues.append(Issue("achieved_dimensions_mismatch", f"{packed['id']}: reported {stated}, computed {(a, b, c)}")) - if spec.flat_bag and (a + c > spec.inner[0] or b + c > spec.inner[1] + spec.side_gusset): - issues.append(Issue("bag_girth_exceeded", - f"{packed['id']}: a + c = {a + c}, b + c = {b + c}, " - f"flat size {spec.inner[0]} x {spec.inner[1]}" - + (f", side gusset {spec.side_gusset}" if spec.side_gusset else ""))) + breach = _girth_breach(spec, a, b, c) if spec.flat_bag else None + if breach is not None: + issues.append(Issue("bag_girth_exceeded", f"{packed['id']}: {breach}")) def _fabricated_side(achieved: int, minimum: int, increment: int) -> int: @@ -2710,8 +2742,13 @@ def _check_groups(request: dict, result: dict, issues: list[Issue]) -> None: "maximum_value": (0, "value_forgone", 1, 2, 3), "open_dimension_height": (0, "achieved_height", 1, 2, 3), "maximum_volume": ("unpacked_volume_ppm", 0, 1, 2, 3), + "shipping_cost": (0, "billed_weight", 1, 3, 4), + "lowest_landed_cost": (0, "landed_charge", 1, 3, 4), } +#: The objectives whose own key is what a carrier bills. +BILLED_BOUND_OBJECTIVES = ("shipping_cost", "lowest_landed_cost") + #: The one refusal predicate's two ceilings. MAX_BOUND_SUM = 10 ** 30 MAX_BOUND_VALUE = 2 ** 53 - 1 @@ -2942,7 +2979,13 @@ def _stated_bound(request: dict, status: Any, items: dict[str, ItemSpec], bound = lower_bound(volumes, weights, shrinks, bound_containers) if bound is None: return None, "the request is past a declared ceiling" + if objective_name in BILLED_BOUND_OBJECTIVES: + billed = _billed_term(objective_name, request.get("configuration", {}), containers, + volumes, weights, shrinks, bound) + if billed is None: + return None, "no priceable inventory carries a packing that attains the count bound" stated = tuple(bound[position] if isinstance(position, int) + else billed if position in ("billed_weight", "landed_charge") else _objective_term(position, items, volumes, shrinks, bound_containers, bound[0]) for position in order) if any(value > MAX_BOUND_VALUE for value in stated): @@ -2972,6 +3015,109 @@ def _objective_term(name: str, items: dict[str, ItemSpec], volumes: Runs, shrink return _ceil_div(max(0, requested - capacity) * SCORE_SCALE, requested) +def _least_of_inventory(values: Sequence[tuple[int, int | None]], count: int) -> int | None: + """The `count` smallest of `{value repeated quantity}`, summed; `None` if fewer exist.""" + total = 0 + for value, quantity in sorted(values, key=lambda pair: pair[0]): + if count <= 0: + break + taken = count if quantity is None else min(quantity, count) + total += value * taken + count -= taken + return None if count > 0 else total + + +def _fractional_cover(offers: Sequence[tuple[int, int, int | None]], need: int) -> int | None: + """Least cost covering `need` from `(cost, capacity, quantity)` offers taken fractionally, + rounded up; greedy by cost per unit is optimal for one covering constraint.""" + if need <= 0: + return 0 + remaining, total = Fraction(need), Fraction(0) + for cost, capacity, quantity in sorted((o for o in offers if o[1] > 0), + key=lambda o: Fraction(o[0], o[1])): + share = remaining / capacity if quantity is None else min(remaining / capacity, Fraction(quantity)) + total += share * cost + remaining -= share * capacity + if remaining <= 0: + return -(-total.numerator // total.denominator) + return None + + +def _billed_term(objective: str, configuration: dict, containers: dict[str, ContainerSpec], + volumes: Runs, weights: Runs, shrinks: bool, bound: Sequence[int]) -> int | None: + """The billed key of `shipping_cost` or `lowest_landed_cost`, or `None` when no + priceable inventory carries a packing that leaves exactly `L0` behind. + + Recomputed from the request alone. Each opened container bills at least + `max(tare, dimensional)` -- the dimensional weight of its declared outer size, else its + declared floor and height, and 0 for a bag, whose billed package can be smaller -- and at + least its tare plus what it carries. A rate-table bracket is reachable from a floor within + it; there a container carries at most the bracket's bound less its tare (and its + `max_payload`), so at most the lightest-first count under that, its usable volume and + `max_items`. The cheapest reachable charge over the `L1` containers, the cheapest cover of + the placed weight and of the placed count each bound the charge; the largest is stated. + O(c b t + c b log(c b)) for `t` runs and `b` brackets per type: `_fit` walks the runs per offer. + """ + divisor = configuration.get("dimensional_weight_divisor") + if divisor is None: + return None + length_unit = configuration.get("dimensional_weight_length_unit", "in") + weight_unit = configuration.get("dimensional_weight_weight_unit", "lb") + unpacked, opened = bound[0], bound[1] + placed = _run_count(volumes) - unpacked + specs = list(containers.values()) + floors = [] + for spec in specs: + size = (spec.outer if spec.outer is not None else spec.inner if spec.deck is None + else (spec.deck[2], spec.deck[3], spec.inner[2])) + dimensional = 0 if spec.flat_bag else _dimensional_weight_ticks( + size, int(divisor), length_unit, weight_unit) + floors.append(max(spec.tare_weight, dimensional)) + if objective == "shipping_cost": + if opened == 0: + return 0 + by_floor = _least_of_inventory([(f, s.quantity) for f, s in zip(floors, specs)], opened) + by_tare = _least_of_inventory([(s.tare_weight, s.quantity) for s in specs], opened) + if by_floor is None or by_tare is None: + return None + return max(by_floor, by_tare + _smallest(weights, placed)) + if opened == 0 or placed == 0: + return 0 + cheapest, by_weight, by_items = [], [], [] + for floor, spec in zip(floors, specs): + table = spec.rate_table or {"weight_brackets_g": [], "prices_minor": []} + minimum = int(table.get("minimum_charge_minor", 0)) + permille = int(table.get("fuel_surcharge_permille", 0)) + charges = [] + for grams, price in zip(table["weight_brackets_g"], table["prices_minor"]): + limit = int(grams) * WEIGHT_TICKS["g"] + if floor > limit: + continue + base = max(int(price), minimum) + charge = base + -(-base * permille // 1000) + carried = limit - spec.tare_weight + if spec.max_payload is not None: + carried = min(carried, spec.max_payload) + count = _fit(weights, carried) + if not shrinks: + volume = spec.inner[0] * spec.inner[1] * spec.inner[2] + scaled = _ratio_ppm(spec.void_fill_reserve_ratio) + usable = volume - ((volume // SCORE_SCALE) * scaled + + ((volume % SCORE_SCALE) * scaled) // SCORE_SCALE) + count = min(count, _fit(volumes, usable)) + if spec.max_items is not None: + count = min(count, spec.max_items) + charges.append(charge) + by_weight.append((charge, carried, spec.quantity)) + by_items.append((charge, count, spec.quantity)) + if charges: + cheapest.append((min(charges), spec.quantity)) + terms = (_least_of_inventory(cheapest, opened), + _fractional_cover(by_weight, _smallest(weights, placed)), + _fractional_cover(by_items, placed)) + return None if any(term is None for term in terms) else max(terms) + + def _departure(score: Sequence[int], bound: Sequence[int]) -> tuple[int, int] | None: """The first position where `score` leaves `bound`, with the sign of the difference. diff --git a/src/packvium/revisions.py b/src/packvium/revisions.py index b0904af..c63c07e 100644 --- a/src/packvium/revisions.py +++ b/src/packvium/revisions.py @@ -15,7 +15,7 @@ import hashlib from typing import Any, Dict, List, Mapping, Optional, Sequence -from ._canonical_json import CanonicalJsonError, canonical_json, json_integer, json_spelling +from ._canonical_json import CanonicalJsonError, MAX_EXACT_MAGNITUDE, canonical_json, json_integer, json_spelling from ._compat import dataclass from .artifacts import FORMAT as ARTIFACT_FORMAT from .artifacts import SUITE_VERSION @@ -276,12 +276,22 @@ def weight(value: Any, name: str) -> int: "quantity": 1, "inner_dimensions": _tick_box(inner), "outer_dimensions": _tick_box(outer), - "cost_minor": _stock_integer(machine.get("cost_minor"), "cost_minor") + per_square_metre(price, area), + "cost_minor": _safe_cost(_stock_integer(machine.get("cost_minor"), "cost_minor") + per_square_metre(price, area)), "tare_weight": {"value": str(declared_tare + per_square_metre(tare_rate, area)), "unit": "ticks"}, }) return box +def _safe_cost(cost: int) -> int: + """The exact cost, or a refusal in the wording of the admission rule (C-13): a cut box larger + than its machine's own declared size can pass 2^53 - 1, which JavaScript cannot hold exactly.""" + if cost > MAX_EXACT_MAGNITUDE: + raise PlanRevisionError( + "invalid_revision", + f"a made-to-measure container's cost_per_square_metre_minor prices the largest box above {MAX_EXACT_MAGNITUDE}") + return cost + + def _stock_object(value: Any, name: str, optional: bool = False) -> Mapping[str, Any]: if value is None and optional: return {} diff --git a/src/packvium/serialization.py b/src/packvium/serialization.py index 7837ffa..baa3892 100644 --- a/src/packvium/serialization.py +++ b/src/packvium/serialization.py @@ -8,6 +8,7 @@ from .config import PackingConfig, SolverProfile from .effort import EffortBudget from .compression import ratio_to_ppm +from .flat_bag import FLAT from .geometry import AxisAlignedBox, Dimensions, Point, Rotation, ShapeType from .models import Axle, Container, FixedPlacement, Item, Obstacle, RateTable from .made_to_measure import MadeToMeasure @@ -33,12 +34,15 @@ def _axles(raw: list | None, unit: str) -> tuple[Axle, Axle] | None: def _effort_budget(raw: dict | None) -> EffortBudget | None: if raw is None: return None - return EffortBudget( - max_candidates_evaluated=raw.get("max_candidates_evaluated"), - max_placement_attempts=raw.get("max_placement_attempts"), - max_search_nodes=raw.get("max_search_nodes"), - max_restarts=raw.get("max_restarts"), - ) + return EffortBudget(**{name: _admitted_integer(raw.get(name)) for name in ( + "max_candidates_evaluated", "max_placement_attempts", "max_search_nodes", "max_restarts")}) + + +def _admitted_integer(value: Any) -> Any: + """An admitted JSON integer as an `int`: admission reads `1.0` as `1`, as JavaScript must, + so the value has to reach the solver as one too. Anything else is passed on unchanged.""" + number = json_integer(value) + return value if number is None else number def _hull_vertices(raw, unit: str) -> "tuple[tuple[int, int, int], ...] | None": @@ -168,14 +172,16 @@ def _container(raw: dict, unit: str, measures: Optional[ParsedMeasures] = None) deformable_boundary=None if raw.get("deformable_boundary") is None else raw["deformable_boundary"]["kind"], made_to_measure=_made_to_measure(raw.get("made_to_measure"), unit, measures), pallet_overhang_limit=_pallet_overhang_limit(raw.get("pallet_overhang_limit"), unit, measures), - side_gusset_depth=_side_gusset_depth(raw.get("deformable_boundary"), unit, measures), + side_gusset_depth=_gusset_depth(raw.get("deformable_boundary"), "side_gusset_depth", unit, measures), + bottom_gusset_depth=_gusset_depth(raw.get("deformable_boundary"), "bottom_gusset_depth", unit, measures), + bag_orientation=(raw.get("deformable_boundary") or {}).get("orientation") or FLAT, ) -def _side_gusset_depth(raw: dict | None, unit: str, measures: ParsedMeasures) -> Length | None: - if raw is None or raw.get("side_gusset_depth") is None: +def _gusset_depth(raw: dict | None, name: str, unit: str, measures: ParsedMeasures) -> Length | None: + if raw is None or raw.get(name) is None: return None - return measures.read(Length, raw["side_gusset_depth"], unit) + return measures.read(Length, raw[name], unit) def _pallet_overhang_limit(raw: dict | None, unit: str, measures: ParsedMeasures) -> OverhangLimit | None: diff --git a/src/packvium/solvers.py b/src/packvium/solvers.py index 3949282..34de450 100644 --- a/src/packvium/solvers.py +++ b/src/packvium/solvers.py @@ -657,12 +657,16 @@ def _prepare_candidate_search( return None inner = container.inner_dimensions limit_x, limit_y, limit_z = inner.length.ticks, inner.width.ticks, inner.height.ticks - # A bag also needs a + c <= L and b + c <= W + G over the running extents grown by the - # candidate (G is a gusseted bag's side gusset, 0 for a flat one): O(1), and - # the extents only grow, so no admitted verdict flips. W + G is summed once per call. - bag = container.is_flat_bag + # A bag also needs both loops of film round the running extents grown by the candidate: + # lying flat 2(a + c) <= 2L + K and b + c <= W + G, standing 2(b + c) <= 2L + K and + # a + b <= W + G (1.10 side gussets, bottom gussets; `flat_bag.Girth`). + # O(1), and the extents only grow, so no admitted verdict flips. Both limits are summed + # once per call. + girth = container.girth + bag = girth is not None bag_x, bag_y, bag_z = state.max_x, state.max_y, state.max_z - girth_y = limit_y + container.side_gusset_ticks + along, across = (girth.along_limit, girth.across_limit) if bag else (0, 0) + standing = bag and container.upright_frame clearance = config.clearance.ticks # Envelope and extents depend only on the rotation, so they are built once instead # of once per (point, rotation) pair. @@ -717,7 +721,7 @@ def _prepare_candidate_search( state, container, item, config, forms, placed, stack_sensitive, route_sensitive, bounds, hull_shapes, index, nesting, placement_offset, reserve_check, usable, compression_sensitive, active, inert_chain, inert_support_checks, tracing, - limit_x, limit_y, limit_z, bag, bag_x, bag_y, bag_z, girth_y, clearance, + limit_x, limit_y, limit_z, bag, bag_x, bag_y, bag_z, along, across, standing, clearance, ) @@ -732,7 +736,7 @@ def _scan_candidate_points( state, container, item, config, forms, placed, stack_sensitive, route_sensitive, bounds, hull_shapes, index, nesting, placement_offset, reserve_check, usable, compression_sensitive, active, inert_chain, inert_support_checks, tracing, - limit_x, limit_y, limit_z, bag, bag_x, bag_y, bag_z, girth_y, clearance, + limit_x, limit_y, limit_z, bag, bag_x, bag_y, bag_z, along, across, standing, clearance, ) = prepared candidates: list[Candidate] = [] best: Candidate | None = None @@ -769,11 +773,14 @@ def _scan_candidate_points( x1, y1, z1 = point.x, point.y, point.z for rotation, physical, envelope, dx, dy, dz, shape in point_forms: x2, y2, z2 = x1 + dx, y1 + dy, z1 + dz - # Conditional expressions rather than `max()`: the builtin call made this test - # four times dearer per bag candidate (75 ns against 309 ns, CPython 3.11). - if x2 > limit_x or y2 > limit_y or z2 > limit_z or ( - bag and ((x2 if x2 > bag_x else bag_x) + (thickness := z2 if z2 > bag_z else bag_z) > limit_x - or (y2 if y2 > bag_y else bag_y) + thickness > girth_y)): + # Conditional expressions rather than `max()` or a helper call: either made this + # test several times dearer per bag candidate (75 ns against 309 ns for `max()`, + # CPython 3.11). + if x2 > limit_x or y2 > limit_y or z2 > limit_z or (bag and ( + (2 * ((grown_y := y2 if y2 > bag_y else bag_y) + (grown_z := z2 if z2 > bag_z else bag_z)) > along + or (x2 if x2 > bag_x else bag_x) + grown_y > across) if standing else + (2 * ((x2 if x2 > bag_x else bag_x) + (grown_z := z2 if z2 > bag_z else bag_z)) > along + or (y2 if y2 > bag_y else bag_y) + grown_z > across))): if tracing: trace.emit({"type": "filter", "item_id": item.id, "point": {"x": x1, "y": y1, "z": z1}, "rotation": rotation.value, "reason": "boundary"}) continue @@ -1932,20 +1939,43 @@ def _solution_key(solution: SingleContainerSolution, by_volume: bool = False) -> return (len(solution.unpacked), -state.used_volume_ticks, state.max_z, signature) @staticmethod - def _block(mode, space, space_volume, item_id, rotation, physical, envelope, - nx, ny, nz, count): - """A group's winning block with the key the mode ranks it by, smaller first.""" - used_volume = count * physical.volume + def _score(mode, space, space_volume, item_id, rotation, used_volume, nx, ny, nz, count): + """The key the mode ranks a group's winning block by, smaller first.""" space_fill_ppm = used_volume * 1_000_000 // space_volume if mode == "count": lead = (-count, -space_fill_ppm, -used_volume) else: lead = (-used_volume, -space_fill_ppm, -count) - score = (*lead, space.origin.z, space.origin.y, space.origin.x, item_id, rotation.value, - nx, ny, nz) + return (*lead, space.origin.z, space.origin.y, space.origin.x, item_id, rotation.value, + nx, ny, nz) + + @classmethod + def _block(cls, mode, space, space_volume, item_id, rotation, physical, envelope, + nx, ny, nz, count): + """A group's winning block with the key the mode ranks it by, smaller first.""" + used_volume = count * physical.volume + score = cls._score(mode, space, space_volume, item_id, rotation, used_volume, nx, ny, nz, count) return _HomogeneousBlock(space, item_id, rotation, physical, envelope, nx, ny, nz, count, used_volume, score) + @classmethod + def _can_lead(cls, mode, last, space, space_volume, item_id, rotation, count, volume, + nx, ny, nz): + """Whether a group's block would rank before `last`, the last kept block's key. + + The same answer as comparing the built block's key, reached field by field so the + common loser is decided by its first or second field and never has a block or a key + built: `-count` or `-used_volume` first, then the space fill, then the whole key.""" + used_volume = count * volume + first = -count if mode == "count" else -used_volume + if first != last[0]: + return first < last[0] + fill = -(used_volume * 1_000_000 // space_volume) + if fill != last[1]: + return fill < last[1] + return cls._score(mode, space, space_volume, item_id, rotation, used_volume, + nx, ny, nz, count) < last + @staticmethod def _forms(prototype: ItemInstance, config: PackingConfig) -> tuple[tuple, ...]: """Each unique rotation of a type with its envelope extents and physical volume.""" @@ -2084,7 +2114,6 @@ def _leading_blocks(self, container, state, spaces, remaining, forms, config, st and whether a limit stopped the round (which then commits nothing).""" node_limit = config.container_plan_node_limit node_ceiling = deadline._search_node_ceiling(stats) - by_count = mode == "count" leading: list[_HomogeneousBlock] = [] # Capacity reads only the committed state, so it is fixed for the whole round. types = [] @@ -2127,20 +2156,20 @@ def _leading_blocks(self, container, state, spaces, remaining, forms, config, st return leading, nodes + budget, True nodes += group_nodes stats.search_nodes_expanded += group_nodes - # The key's first field is `-count` or `-used_volume`; a group that - # loses on it to the last kept block loses on the key, so its key is - # never built. - full = len(leading) == leaders - if count and (not full - or (-count if by_count else -count * volume) <= leading[-1].score[0]): - block = self._block( - mode, space, space_volume, item_id, rotation, physical, - envelope, nx, ny, nz, count, - ) - if not full or block.score < leading[-1].score: - leading.append(block) - leading.sort(key=lambda kept: kept.score) - del leading[leaders:] + if not count: + continue + if len(leading) == leaders and not self._can_lead( + mode, leading[-1].score, space, space_volume, item_id, rotation, + count, volume, nx, ny, nz, + ): + continue + block = self._block( + mode, space, space_volume, item_id, rotation, physical, + envelope, nx, ny, nz, count, + ) + leading.append(block) + leading.sort(key=lambda kept: kept.score) + del leading[leaders:] return leading, nodes, False def _commit(self, state, best, remaining, config, stats, deadline) -> bool: @@ -2438,9 +2467,10 @@ def _with_top_loads(placements: Sequence[Placement]) -> tuple[Placement, ...]: def _fits_alone(container: Container, dimensions: Dimensions) -> bool: """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.""" - if container.is_flat_bag: - return fits_alone(container.inner_dimensions, dimensions, container.side_gusset_ticks) + bag the girth rule too, so a bag too thin for an item proves it unplaceable.""" + girth = container.girth + if girth is not None: + return fits_alone(container.inner_dimensions, dimensions, girth) return dimensions.fits_inside(container.inner_dimensions) @@ -2693,10 +2723,39 @@ def _effort_limited(unpacked: tuple[UnpackedItem, ...], effort_reached: bool) -> ) +def _frozen_clock() -> int: + return 0 + + +class _SupportDiagnostic: + """The verdicts and replayed container states of one final layout. + + Scoped to the layout it was built for: a different `packed` or `config` starts a fresh one. + """ + + __slots__ = ("config", "packed", "verdicts", "_states") + + def __init__(self, config: PackingConfig, packed: Sequence[PackedContainer]): + self.config = config + self.packed = packed + self.verdicts: dict[str, bool] = {} + self._states: dict[int, ContainerState] = {} + + def state(self, index: int, packed_container: PackedContainer) -> ContainerState: + state = self._states.get(index) + if state is None: + state = ContainerState(packed_container.container, packed_container.sequence) + for placement in packed_container.placements: + state.add(placement) + self._states[index] = state + return state + + class SolverOrchestrator: def __init__(self, custom_constraints=(), custom_orders=(), custom_solvers=(), container_selector=None): self.custom_constraints = tuple(custom_constraints); self.custom_orders = tuple(custom_orders); self.custom_solvers = tuple(custom_solvers) self.container_selector = container_selector or DefaultContainerSelector() + self._support_diagnostic: "_SupportDiagnostic | None" = None def _solvers(self, items, config): if config.solvers: @@ -3218,6 +3277,21 @@ def _support_is_the_blocker(self, instance, packed, config): `ReasonProof.for_reason`'s `observed` level and `docs/PUBLIC-API.md`'s rejection proof section. """ + # The answer is a function of the item's declared attributes and the final layout, + # so every instance of a type shares one verdict -- unless a caller's own constraint + # may read the instance itself, in which case each instance is asked. The replayed + # container states are likewise built once per layout, not once per unpacked item. + diagnostic = self._support_diagnostic + if diagnostic is None or diagnostic.config is not config or diagnostic.packed is not packed: + diagnostic = self._support_diagnostic = _SupportDiagnostic(config, packed) + key = instance.id if self.custom_constraints else instance.item.id + verdict = diagnostic.verdicts.get(key) + if verdict is None: + verdict = diagnostic.verdicts[key] = self._observe_support_blocker(instance, diagnostic) + return verdict + + def _observe_support_blocker(self, instance, diagnostic): + config = diagnostic.config constraints = default_constraints(config, self.custom_constraints) support_constraints = tuple(c for c in constraints if isinstance(c, SupportConstraint)) # The built-in support specification is a strict no-op for this item when it @@ -3229,16 +3303,13 @@ def _support_is_the_blocker(self, instance, packed, config): for c in support_constraints): return False without_support = tuple(c for c in constraints if not isinstance(c, SupportConstraint)) - # A small, fixed local budget -- independent of the caller's own deadline, - # which may already be exhausted -- so this diagnostic can never itself hang - # the solve; it is a best-effort explanation, not a required step. - budget = Deadline(2_000) - for packed_container in packed: - if budget.expired: - return False - state = ContainerState(packed_container.container, packed_container.sequence) - for placement in packed_container.placements: - state.add(placement) + # No wall clock: the reason an item is reported unpacked must be a function of the + # request and the layout, never of machine load. A frozen clock leaves nothing to + # expire; each search is bounded by the layout's own candidate points (one + # candidate wanted) and the verdict is memoised per item type. + budget = Deadline(0, limit_ns=1, clock=_frozen_clock) + for index, packed_container in enumerate(diagnostic.packed): + state = diagnostic.state(index, packed_container) if not find_candidates(state, instance, config, without_support, SearchStats(), budget, 1): continue if not find_candidates(state, instance, config, constraints, SearchStats(), budget, 1): @@ -3361,8 +3432,8 @@ def _additional_container_lower_bound(plan, containers) -> int: lower = max(lower, (total_weight + maximum_payload - 1) // maximum_payload) return lower - def _plan_bound_key(self, plan, containers, config) -> tuple: - partial = list(self._score_plan(plan.packed, (), config)) + def _plan_bound_key(self, plan, containers, config, partial_score) -> tuple: + partial = list(partial_score) count_index = 1 if config.objective == "default" else 2 partial[count_index] += self._additional_container_lower_bound(plan, containers) remaining_signature = tuple(item.id for item in plan.remaining) @@ -3461,10 +3532,12 @@ def _across_containers_beam(self, solver, items, containers, config, stats, dead previous = dominant.get(signature) if previous is None or partial_score < previous[0]: dominant[signature] = (partial_score, plan) - beam = sorted( - (pair[1] for pair in dominant.values()), - key=lambda plan: self._plan_bound_key(plan, containers, config), - )[:config.container_plan_beam_width] + beam = [ + plan for _, plan in sorted( + dominant.values(), + key=lambda pair: self._plan_bound_key(pair[1], containers, config, pair[0]), + )[:config.container_plan_beam_width] + ] unpacked = [] opened = self._opened_by_type(incumbent.packed) diff --git a/src/packvium/units.py b/src/packvium/units.py index 741f2f6..94c8ae3 100644 --- a/src/packvium/units.py +++ b/src/packvium/units.py @@ -2,7 +2,7 @@ from ._compat import dataclass from ._request_error import refused, refused_type -from decimal import Decimal, InvalidOperation +from decimal import Decimal from enum import Enum from fractions import Fraction import re @@ -30,26 +30,50 @@ def _fraction(value: int | str | Decimal | Fraction) -> Fraction: if isinstance(value, Decimal): return Fraction(value) text = str(value).strip().replace("\u00a0", " ") - mixed = re.fullmatch(r"([+-]?\d+)\s+(\d+)\s*/\s*(\d+)", text) + negative = text.startswith("-") + mixed = re.fullmatch(r"[+-]?([0-9]+)\s+([0-9]+)\s*/\s*([0-9]+)", text, re.ASCII) if mixed: - whole, numerator, denominator = map(int, mixed.groups()) + whole, numerator, denominator = map(_digits, mixed.groups()) # The sign comes from the written text, not from the value of the whole part, so # "-0 1/2" is minus one half rather than plus one half. - magnitude = abs(whole) * denominator + numerator - return Fraction(-magnitude if text.startswith("-") else magnitude, denominator) - simple = re.fullmatch(r"([+-]?\d+)\s*/\s*(\d+)", text) + magnitude = whole * denominator + numerator + return Fraction(-magnitude if negative else magnitude, denominator) + simple = re.fullmatch(r"[+-]?([0-9]+)\s*/\s*([0-9]+)", text, re.ASCII) if simple: - return Fraction(int(simple.group(1)), int(simple.group(2))) - decimal = re.fullmatch(r"[+-]?\d+(?:\.(\d+))?", text) + numerator, denominator = map(_digits, simple.groups()) + return Fraction(-numerator if negative else numerator, denominator) + # ASCII digits only: `\d` alone also matches fullwidth and Arabic-Indic digits, which the + # other engines refuse. No exponent form (`1e3000000` would cost seconds before any range + # check), no underscores, no bare ".5" or "5.". + decimal = re.fullmatch(r"[+-]?([0-9]+)(?:\.([0-9]+))?", text, re.ASCII) + if decimal is None: + raise refused("wrong_type", f"invalid decimal or fraction: {text}") + whole, places = decimal.group(1), decimal.group(2) or "" # A shared cap, not a Python limitation: PHP cannot hold 10**19 in an integer, and a # silently different accepted range between the two is exactly the kind of divergence # this library exists to avoid. Eighteen digits is far past what a tick can express. - if decimal and decimal.group(1) and len(decimal.group(1)) > 18: + if len(places) > 18: raise refused("wrong_type", "decimal has more fractional digits than a tick can distinguish") - try: - return Fraction(Decimal(text)) - except InvalidOperation as error: - raise refused("wrong_type", f"invalid decimal or fraction: {text}") from error + scale = 10 ** len(places) + magnitude = _digits(whole) * scale + int(places or "0") + return Fraction(-magnitude if negative else magnitude, scale) + + +#: Past this many significant digits a measure is far above every admitted maximum (2^53 - 1 +#: ticks is sixteen digits), so its exact value cannot change the verdict. +_SIGNIFICANT_DIGITS = 64 + + +def _digits(text: str) -> int: + """ASCII digits as an integer, saturated past `_SIGNIFICANT_DIGITS` significant digits. + + Reading the full number costs time quadratic in its length (a 1 MB weight took 48 s), and + `int` refuses past 4300 digits, which counted leading zeros too. O(len(text)). + """ + significant = text.lstrip("0") + if len(significant) > _SIGNIFICANT_DIGITS: + return 10 ** _SIGNIFICANT_DIGITS + return int(significant or "0") def _unit_key(unit: object) -> str | None: diff --git a/src/packvium/validation.py b/src/packvium/validation.py index 43fc6f9..5baf164 100644 --- a/src/packvium/validation.py +++ b/src/packvium/validation.py @@ -7,7 +7,7 @@ SupportConstraint, TagCountConstraint, load_units, crushed, non_stackable_failure, overloaded, stack_density_exceeded, stack_limit_exceeded, usable_volume) -from .flat_bag import extent_of, girth_admits +from .flat_bag import extent_of from .geometry import AxisAlignedBox, Point from . import made_to_measure from .models import (Container, PackedContainer, PackingRequest, UnpackedItem, is_stack_sensitive, @@ -256,10 +256,12 @@ def _collision_pairs(placements) -> list[tuple[int, int]]: @staticmethod def _bag_admits(packed: PackedContainer) -> bool: - """The girth rule over the envelopes alone, widened by a side gusset (1.10); - the frame is checked above.""" - a, b, c = extent_of((box.x2, box.y2, box.z2) for box in (p.envelope_box for p in packed.placements)) - return girth_admits(packed.container.inner_dimensions, a, b, c, packed.container.side_gusset_ticks) + """The girth rule over the envelopes alone, widened by a side gusset (1.10) + and lengthened by a bottom one, flat or standing; the frame is checked above.""" + girth = packed.container.girth + assert girth is not None + return girth.admits(extent_of((box.x2, box.y2, box.z2) + for box in (p.envelope_box for p in packed.placements))) @staticmethod def _unloading_order_violation(packed: PackedContainer) -> "ValidationIssue | None": diff --git a/tests/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json b/tests/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json new file mode 100644 index 0000000..8a42fc7 --- /dev/null +++ b/tests/fixtures/feature-made-to-measure-dimensional-weight-on-outer.json @@ -0,0 +1,60 @@ +{ + "units": { + "length": "mm" + }, + "configuration": { + "solver_profile": "balanced", + "time_limit_ms": 300000, + "minimum_support_ratio": 1, + "effort_budget": { + "max_candidates_evaluated": 1000000, + "max_placement_attempts": 1000000, + "max_search_nodes": 1000000 + }, + "objective": "shipping_cost", + "dimensional_weight_divisor": 5000, + "dimensional_weight_length_unit": "cm", + "dimensional_weight_weight_unit": "kg" + }, + "items": [ + { + "id": "cube", + "quantity": 8, + "weight": "1", + "dimensions": { + "length": "100", + "width": "100", + "height": "100" + } + } + ], + "containers": [ + { + "id": "machine", + "cost_minor": 40, + "inner_dimensions": { + "length": "1510", + "width": "1510", + "height": "1510" + }, + "made_to_measure": { + "minimum": { + "length": "60", + "width": "60", + "height": "60" + }, + "increment": { + "length": "25", + "width": "25", + "height": "25" + }, + "cost_per_square_metre_minor": 1000, + "outer_allowance": { + "length": "3", + "width": "3", + "height": "3" + } + } + } + ] +} diff --git a/tests/test_bottom_gusset.py b/tests/test_bottom_gusset.py new file mode 100644 index 0000000..28a617c --- /dev/null +++ b/tests/test_bottom_gusset.py @@ -0,0 +1,158 @@ +"""1.11: bottom gussets, lying flat or standing, admitted by the two loops of film.""" + +from __future__ import annotations + +import random +import sys +from pathlib import Path + +import pytest + +from packvium import validate +from packvium.flat_bag import girth_for +from packvium.geometry import Dimensions +from packvium.models import Container +from packvium.pallet_overhang import solving_frame +from packvium.request_errors import InvalidRequestError +from packvium.serialization import pack_from_dict +from packvium.units import Length + +#: The independent oracle lives in the workspace's `scripts/`, not in the published package. +ORACLE = Path(__file__).resolve().parents[2] / "scripts" / "deformable_boundary_model.py" + + +def ticks(millimetres: int) -> int: + return Length.of(millimetres, "mm").ticks + + +def request(boundary: dict, item: dict, quantity: int, **container) -> dict: + return {"items": [{"id": item["id"], "quantity": quantity, "weight": "300 g", **item}], + "containers": [{"id": "pouch", "quantity": 1, "deformable_boundary": boundary, + "inner_dimensions": {"length": "300", "width": "150", "height": "100"}, + **container}], + "configuration": {"solver_profile": "fast", "time_limit_ms": 60000, + "effort_budget": {"max_search_nodes": 100000}}} + + +ROD = {"id": "rod", "allowed_rotations": ["LWH"], + "dimensions": {"length": "300", "width": "100", "height": "20"}} +BOTTLE = {"id": "bottle", "allowed_rotations": ["LWH"], + "dimensions": {"length": "50", "width": "50", "height": "150"}} + + +@pytest.mark.skipif(not ORACLE.is_file(), reason="the independent oracle lives in the workspace only") +@pytest.mark.parametrize("seed", range(60)) +def test_the_engine_loops_agree_with_the_oracle_on_every_extent(seed): + """The engine's `Girth` and the independent oracle decide every package alike, flat or + standing, over the loops alone (the rigid frame is each one's own separate check).""" + sys.path.insert(0, str(ORACLE.parent)) + from deformable_boundary_model import FlatBag, girth_violation + rng = random.Random(2604 + seed) + length, width, thickness = rng.randint(2, 40), rng.randint(2, 40), rng.randint(1, 40) + side, bottom = rng.randint(0, width), rng.randint(1, 2 * length) + standing = seed % 2 == 1 + girth = girth_for(length, width, side, bottom, standing) + bag = FlatBag(length, width, thickness, side_gusset_depth=side, bottom_gusset_depth=bottom, + standing=standing) + frame = (width, thickness, length) if standing else (length, width, thickness) + for _ in range(80): + extent = tuple(rng.randint(0, side_limit) for side_limit in frame) + assert girth.admits(extent) == (girth_violation(bag, extent) is None), (extent, standing) + + +def test_a_bottom_gusset_admits_a_rod_the_flat_length_refuses(): + """A 300 mm rod 20 mm thick fills the flat length, so a + c = 320 > 300 lying flat; a + 40 mm bottom gusset makes the loop 2L + K = 640 = 2(a + c), and equality fits.""" + flat = pack_from_dict(request({"kind": "gusseted_bag", "side_gusset_depth": "10"}, ROD, 1)) + assert flat["unpacked_items"][0]["reason"] == "no_compatible_container_dimensions" + block = pack_from_dict(request({"kind": "gusseted_bag", "bottom_gusset_depth": "40"}, ROD, 1)) + assert block["unpacked_items"] == [] + past = pack_from_dict(request({"kind": "gusseted_bag", + "bottom_gusset_depth": {"value": str(ticks(40) - 1), "unit": "ticks"}}, + ROD, 1)) + assert past["unpacked_items"][0]["reason"] == "no_compatible_container_dimensions" + + +def test_a_standing_pouch_packs_in_its_turned_frame_and_the_validator_agrees(): + """Standing, the 300 x 150 x 100 pouch is a 150 x 100 x 300 frame. Two 50 x 50 x 150 + bottles stand side by side, here front to back (a + b = 150 = W + G, b <= H); a third + beside them breaks the loop round the section and one on top breaks the loop down the + bag, 2(b + c) = 700 > 660.""" + standing = request({"kind": "gusseted_bag", "bottom_gusset_depth": "60", + "orientation": "standing"}, BOTTLE, 3) + result = pack_from_dict(standing) + packed = result["containers"][0] + assert len(packed["placements"]) == 2 and len(result["unpacked_items"]) == 1 + assert {side: packed["achieved_dimensions"][side]["value"] + for side in ("length", "width", "height")} == {"length": "50", "width": "100", "height": "150"} + assert {side: packed["inner_dimensions"][side]["value"] + for side in ("length", "width", "height")} == {"length": "300", "width": "150", "height": "100"} + assert validate(standing, result) == [] + + +def test_the_validator_refuses_a_standing_package_past_its_loop(): + """The same two bottles against a pouch 1 mm narrower: a + b = 150 > W = 149.""" + standing = request({"kind": "gusseted_bag", "bottom_gusset_depth": "60", + "orientation": "standing"}, BOTTLE, 2) + result = pack_from_dict(standing) + narrower = {**standing, "containers": [{**standing["containers"][0], "deformable_boundary": { + "kind": "gusseted_bag", "orientation": "standing", + "bottom_gusset_depth": "60"}}]} + narrower["containers"][0]["inner_dimensions"] = {"length": "300", "width": "149", "height": "100"} + codes = [issue.code for issue in validate(narrower, result)] + assert "bag_girth_exceeded" in codes + + +def test_the_standing_frame_turns_once_and_declares_the_bag_as_given(): + declared = Dimensions.mm(300, 150, 100) + bag = Container("pouch", declared, deformable_boundary="gusseted_bag", + bottom_gusset_depth=Length(ticks(60)), bag_orientation="standing") + frame = solving_frame(bag) + assert frame.inner_dimensions == Dimensions.mm(150, 100, 300) + assert frame.declared_inner == declared + assert solving_frame(frame) is frame + assert frame.girth == girth_for(ticks(300), ticks(150), 0, ticks(60), True) + + +@pytest.mark.parametrize(("fields", "reason", "detail"), [ + ({}, "missing_field", "a gusseted_bag requires side_gusset_depth"), + ({"bottom_gusset_depth": Length(ticks(600) + 1)}, "invalid_value", + "bottom_gusset_depth exceeds twice inner_dimensions length"), + ({"bottom_gusset_depth": Length(0)}, "invalid_value", "bottom_gusset_depth must be positive"), + ({"side_gusset_depth": Length(ticks(10)), "bag_orientation": "standing"}, "missing_field", + "bottom_gusset_depth is required when orientation is standing"), + ({"bottom_gusset_depth": Length(ticks(10)), "bag_orientation": "upright"}, "not_allowed", + "orientation must be one of ['flat', 'standing']"), +]) +def test_the_object_api_refuses_what_the_json_path_refuses(fields, reason, detail): + with pytest.raises(Exception) as caught: + Container("pouch", Dimensions.mm(300, 150, 100), deformable_boundary="gusseted_bag", **fields) + assert getattr(caught.value, "reason", None) == reason and detail in str(caught.value) + + +@pytest.mark.parametrize("field", ["bottom_gusset_depth", "bag_orientation"]) +def test_a_rigid_box_or_flat_bag_refuses_the_gusseted_fields(field): + value = "standing" if field == "bag_orientation" else Length(ticks(10)) + for boundary in (None, "flat_bag"): + with pytest.raises(Exception): + Container("box", Dimensions.mm(300, 150, 100), deformable_boundary=boundary, **{field: value}) + + +def test_the_json_path_refuses_a_standing_bag_without_a_bottom_gusset(): + with pytest.raises(InvalidRequestError) as caught: + pack_from_dict(request({"kind": "gusseted_bag", "side_gusset_depth": "10", + "orientation": "standing"}, BOTTLE, 1)) + assert (caught.value.reason, caught.value.field) == ( + "missing_field", "/containers/0/deformable_boundary/bottom_gusset_depth") + + +def test_the_1_10_helpers_keep_their_signatures(): + """`girth_admits` and `fits_alone` keep the 1.10 forms COMPATIBILITY.md recorded: a trailing + side gusset in ticks, now with a trailing bottom gusset beside it.""" + from packvium.flat_bag import fits_alone, girth_admits + inner = Dimensions.mm(300, 150, 100) + assert girth_admits(inner, ticks(280), ticks(100), ticks(20)) + assert not girth_admits(inner, ticks(300), ticks(100), ticks(20)) + assert girth_admits(inner, ticks(300), ticks(100), ticks(20), 0, ticks(40)) + assert fits_alone(inner, Dimensions.mm(100, 100, 60), ticks(10)) + assert not fits_alone(inner, Dimensions.mm(100, 100, 60)) diff --git a/tests/test_commerce_edge_cases.py b/tests/test_commerce_edge_cases.py index c02e5f4..466a280 100644 --- a/tests/test_commerce_edge_cases.py +++ b/tests/test_commerce_edge_cases.py @@ -167,6 +167,11 @@ def test_an_out_of_range_tariff_field_fails_admission(self, overrides, message): with pytest.raises(CommerceInputError, match=message): load_document(tariff_document(**overrides)) + @pytest.mark.parametrize("zones", [{"b": 1.5, "2": 1.5}, {"2": 1.5, "b": 1.5}]) + def test_zones_are_validated_in_code_point_order_whatever_the_insertion_order(self, zones): + with pytest.raises(CommerceInputError, match=r"cost_per_dimensional_kg_minor\['2'\]"): + load_document(tariff_document(cost_per_dimensional_kg_minor=zones)) + def test_a_zone_map_must_be_an_object(self): with pytest.raises(CommerceInputError, match="expected an object"): load_document(tariff_document(cost_per_dimensional_kg_minor=[["zone-a", 450]])) @@ -498,15 +503,15 @@ def test_a_zone_name_may_contain_anything_a_json_key_can(self): assert quote(document, dict(SHIPMENT, zone="zóna/1"))["status"] == "ok" - def test_a_quote_far_beyond_a_64_bit_product_stays_exact(self): + def test_a_quote_just_inside_the_ceiling_stays_exact(self): document = tariff_document( dimensional_weight_divisor=1, - cost_per_dimensional_kg_minor={"zone-a": 10 ** 12}, + cost_per_dimensional_kg_minor={"zone-a": 9 * 10 ** 6}, minimum_charge_minor=0, fuel_surcharge_permille=0, accessorials=[]) result = quote(document, dict(SHIPMENT, actual_weight_g=0, volume_mm3=10 ** 12)) - assert result["quote"]["total_minor"] == 10 ** 21 + assert result["quote"]["total_minor"] == 9 * 10 ** 15 assert isinstance(result["quote"]["total_minor"], int) def test_a_thousand_versions_resolve_to_the_last_effective_one(self): @@ -528,3 +533,59 @@ def test_two_documents_that_differ_only_in_key_order_price_identically(self): "service_id": "ground", "carrier_id": "acme"}]} assert canonical_json(quote(DOCUMENT, SHIPMENT)) == canonical_json(quote(shuffled, SHIPMENT)) + + +# ------------------------------------------------------------ the exact-integer ceiling (M2) + +CEILING = 2**53 - 1 + + +def ceiling_quote(rate_per_kg=450, volume_mm3=0, accessorials=(), requested=(), **tariff): + document = tariff_document(**dict( + {"minimum_charge_minor": 0, "fuel_surcharge_permille": 0}, **tariff, + cost_per_dimensional_kg_minor={"zone-a": rate_per_kg}, accessorials=list(accessorials))) + shipment = dict(SHIPMENT, actual_weight_g=1000, volume_mm3=volume_mm3, + requested_accessorials=list(requested)) + return quote(document, shipment) + + +class TestQuoteAmountsAreHeldToTheExactIntegerCeiling: + def test_a_total_exactly_at_the_ceiling_is_answered_exactly(self): + result = ceiling_quote(rate_per_kg=CEILING) + assert result["quote"]["base_charge_minor"] == CEILING + assert result["quote"]["total_minor"] == CEILING + + def test_a_base_charge_one_above_the_ceiling_is_refused(self): + with pytest.raises(CommerceInputError) as caught: + ceiling_quote(rate_per_kg=CEILING + 1) + assert str(caught.value) == ( + f"quote amount {CEILING + 1} is above {CEILING} and cannot be represented exactly") + + def test_a_fuel_surcharge_above_the_ceiling_is_refused_with_its_own_value(self): + with pytest.raises(CommerceInputError) as caught: + ceiling_quote(rate_per_kg=9 * 10**15, fuel_surcharge_permille=2000) + assert str(caught.value) == ( + f"quote amount {18 * 10**15} is above {CEILING} and cannot be represented exactly") + + def test_an_accessorial_above_the_ceiling_is_refused_with_its_own_value(self): + with pytest.raises(CommerceInputError) as caught: + ceiling_quote(accessorials=[{"accessorial_id": "liftgate", "flat_charge_minor": CEILING + 1}], + requested=["liftgate"]) + assert str(caught.value) == ( + f"quote amount {CEILING + 1} is above {CEILING} and cannot be represented exactly") + + def test_an_accessorial_exactly_at_the_ceiling_is_answered(self): + result = ceiling_quote(rate_per_kg=0, accessorials=[ + {"accessorial_id": "liftgate", "flat_charge_minor": CEILING}], requested=["liftgate"]) + assert result["quote"]["total_minor"] == CEILING + + def test_a_total_above_the_ceiling_is_refused_when_every_component_is_inside(self): + with pytest.raises(CommerceInputError) as caught: + ceiling_quote(rate_per_kg=5 * 10**15, fuel_surcharge_permille=1000) + assert str(caught.value) == ( + f"quote amount {10**16} is above {CEILING} and cannot be represented exactly") + + def test_the_dimensional_weight_is_checked_before_the_charges(self): + with pytest.raises(CommerceInputError) as caught: + ceiling_quote(rate_per_kg=CEILING + 1, volume_mm3=(CEILING + 1) * 5000) + assert str(caught.value).startswith(f"quote amount {CEILING + 1} is above") diff --git a/tests/test_commerce_lookup.py b/tests/test_commerce_lookup.py index 5df3bb9..880c7c8 100644 --- a/tests/test_commerce_lookup.py +++ b/tests/test_commerce_lookup.py @@ -56,14 +56,23 @@ def test_snapshot_lookup_indexes_do_not_change_value_copy_or_serialization(): restored = CatalogSnapshot.__new__(CatalogSnapshot) restored.__setstate__({field.name: getattr(snapshot, field.name) for field in fields(snapshot)}) assert restored.item('widget') == snapshot.items[0] + # A snapshot pickled before the fields were normalised to tuples holds lists; restoring it + # gives the tuples a new snapshot has, so the restored history cannot be edited either. + older = CatalogSnapshot.__new__(CatalogSnapshot) + older.__setstate__({field.name: list(getattr(snapshot, field.name)) for field in fields(snapshot)}) + assert older.item('widget') == snapshot.items[0] + assert older.carton('box-s') == snapshot.cartons[0] + assert all(type(getattr(older, field.name)) is tuple for field in fields(older)) -def test_snapshot_lookup_preserves_mutable_and_custom_input_behavior(): +def test_snapshot_lookup_preserves_custom_input_behavior_and_detaches_the_callers_list(): entries = [make_item('first')] snapshot = CatalogSnapshot(items=entries) assert snapshot.item('first') is entries[0] entries.append(make_item('second')) - assert snapshot.item('second') is entries[1] + assert snapshot.items == (entries[0],) + with pytest.raises(CatalogEntryNotFoundError): + snapshot.item('second') class MutableEntry: id = 'old' entry = MutableEntry() @@ -97,3 +106,30 @@ def test_pinned_and_effective_history_keep_numeric_and_date_boundaries(): assert registry.effective_tariff('acme-freight', 'ground', as_of=0).version == 63 with pytest.raises(TariffNotFoundError): registry.effective_tariff('acme-freight', 'ground', as_of=-1) + + +def test_published_history_cannot_be_edited_through_the_callers_or_the_returned_objects(): + import copy + import pickle + from packvium.commerce.rating import AccessorialCharge + dimensions = [80, 60, 40] + master = ItemMaster("widget", dimensions, 250) + dimensions[0] = 1 + assert master.dimensions_mm == (80, 60, 40) + + rates = {"zone-1": 500} + surcharges = {"liftgate": AccessorialCharge("liftgate", flat_charge_minor=900)} + registry = CarrierRegistry() + registry.publish("acme-freight", "ground", effective_at=0, dimensional_weight_divisor=5000, + cost_per_dimensional_kg_minor=rates, accessorials=surcharges) + rates["zone-1"] = 1 + pinned = registry.tariff("acme-freight", "ground", 1) + assert pinned.cost_per_dimensional_kg_minor == {"zone-1": 500} + with pytest.raises(TypeError): + pinned.cost_per_dimensional_kg_minor["zone-1"] = 1 + with pytest.raises(TypeError): + pinned.accessorials["extra"] = surcharges["liftgate"] + for restored in (copy.deepcopy(pinned), pickle.loads(pickle.dumps(pinned))): + assert restored == pinned + with pytest.raises(TypeError): + restored.cost_per_dimensional_kg_minor["zone-1"] = 1 diff --git a/tests/test_flat_bag.py b/tests/test_flat_bag.py index 00e9690..d9f2f67 100644 --- a/tests/test_flat_bag.py +++ b/tests/test_flat_bag.py @@ -11,7 +11,7 @@ from packvium.constraints import StopAccessibilityConstraint from packvium.extensions import LandedCostSolutionScorer, ShippingCostSolutionScorer from packvium.fixed_placements import FixedPlacementError -from packvium.flat_bag import (as_dimensions, extent_of, fits_alone, girth_admits, +from packvium.flat_bag import (as_dimensions, extent_of, fits_alone, girth_for, grown_extent) from packvium.geometry import Dimensions, Point, Rotation from packvium.models import (Container, Item, ItemInstance, PackedContainer, PackingRequest, @@ -27,6 +27,15 @@ BAG = {"deformable_boundary": {"kind": "flat_bag"}} + +def _girth(inner, gusset=0, bottom=0): + """The flat frame's loops for a bag declared `inner`, through the engine's own builder.""" + return girth_for(inner.length.ticks, inner.width.ticks, gusset, bottom, False) + + +def _admits(inner, a, b, c, gusset=0): + return _girth(inner, gusset).admits((a, b, c)) + def ticks(millimetres: int) -> int: return Length.of(millimetres, "mm").ticks @@ -74,11 +83,11 @@ def extent_mm(container: dict) -> tuple[int, ...]: class TestTheRule: def test_the_worked_examples_of_the_oracle(self): inner = mm(240, 140, 100) - assert girth_admits(inner, ticks(200), ticks(100), ticks(40)) - assert not girth_admits(inner, ticks(200), ticks(100), ticks(40) + 1) - assert not girth_admits(inner, ticks(200) + ticks(40) + 1, 0, 0) + assert _admits(inner, ticks(200), ticks(100), ticks(40)) + assert not _admits(inner, ticks(200), ticks(100), ticks(40) + 1) + assert not _admits(inner, ticks(200) + ticks(40) + 1, 0, 0) # A rod as long as the bag is flat passes the frame and fails the length girth. - assert not girth_admits(mm(1000, 480, 300), ticks(1000), ticks(10), ticks(10)) + assert not _admits(mm(1000, 480, 300), ticks(1000), ticks(10), ticks(10)) def test_the_running_extent_equals_the_extent_from_scratch(self): generator = random.Random(2602) @@ -89,16 +98,16 @@ def test_the_running_extent_equals_the_extent_from_scratch(self): verdicts = [] for box in boxes: running = grown_extent(running, *box) - verdicts.append(girth_admits(mm(5000, 5000, 5000), *running)) + verdicts.append(_admits(mm(5000, 5000, 5000), *running)) assert running == extent_of(boxes) # Extents only grow, so a refused prefix is never admitted again. assert verdicts == sorted(verdicts, reverse=True) def test_a_single_box_fits_only_when_both_girths_hold(self): inner = mm(300, 300, 100) - assert not fits_alone(inner, mm(250, 150, 80)) - assert fits_alone(inner, mm(220, 150, 80)) - assert not fits_alone(inner, mm(310, 10, 10)) + assert not fits_alone(inner, mm(250, 150, 80), _girth(inner)) + assert fits_alone(inner, mm(220, 150, 80), _girth(inner)) + assert not fits_alone(inner, mm(310, 10, 10), _girth(inner)) assert as_dimensions((1, 2, 3)) == Dimensions(Length(1), Length(2), Length(3)) diff --git a/tests/test_gusseted_bag.py b/tests/test_gusseted_bag.py index 16b599a..b16b237 100644 --- a/tests/test_gusseted_bag.py +++ b/tests/test_gusseted_bag.py @@ -8,7 +8,7 @@ from packvium.config import SolverProfile from packvium.extensions import LandedCostSolutionScorer from packvium.fixed_placements import FixedPlacementError -from packvium.flat_bag import fits_alone, girth_admits +from packvium.flat_bag import fits_alone, girth_for from packvium.geometry import Dimensions, Point, Rotation from packvium.models import (Container, Item, ItemInstance, PackedContainer, PackingRequest, Placement, RateTable) @@ -20,6 +20,15 @@ from packvium.validation import IndependentSolutionValidator + +def _girth(inner, gusset=0, bottom=0): + """The flat frame's loops for a bag declared `inner`, through the engine's own builder.""" + return girth_for(inner.length.ticks, inner.width.ticks, gusset, bottom, False) + + +def _admits(inner, a, b, c, gusset=0): + return _girth(inner, gusset).admits((a, b, c)) + def ticks(millimetres: int) -> int: return Length.of(millimetres, "mm").ticks @@ -58,16 +67,16 @@ def gusseted(depth: object) -> dict: class TestTheRule: def test_the_gusset_widens_only_the_width_girth(self): inner = mm(300, 150, 100) - assert not girth_admits(inner, ticks(200), ticks(100), ticks(60)) - assert girth_admits(inner, ticks(200), ticks(100), ticks(60), ticks(10)) - assert not girth_admits(inner, ticks(200), ticks(100), ticks(60) + 1, ticks(10)) - assert not girth_admits(inner, ticks(241), 0, ticks(60), ticks(150)) + assert not _admits(inner, ticks(200), ticks(100), ticks(60)) + assert _admits(inner, ticks(200), ticks(100), ticks(60), ticks(10)) + assert not _admits(inner, ticks(200), ticks(100), ticks(60) + 1, ticks(10)) + assert not _admits(inner, ticks(241), 0, ticks(60), ticks(150)) def test_a_single_box_fits_a_gusseted_bag_its_flat_twin_refuses(self): inner = mm(200, 150, 100) - assert not fits_alone(inner, mm(100, 100, 60)) - assert fits_alone(inner, mm(100, 100, 60), ticks(10)) - assert not fits_alone(inner, mm(100, 160, 10), ticks(150)) + assert not fits_alone(inner, mm(100, 100, 60), _girth(inner)) + assert fits_alone(inner, mm(100, 100, 60), _girth(inner, ticks(10))) + assert not fits_alone(inner, mm(100, 160, 10), _girth(inner, ticks(150))) class TestTheModel: diff --git a/tests/test_models.py b/tests/test_models.py index 5ff2578..9f16b2c 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -7,6 +7,11 @@ from __future__ import annotations +import copy +import dataclasses +import pickle +import threading + import pytest from packvium import (AxisAlignedBox, Axle, Container, Dimensions, FixedPlacement, FixedPlacementError, Item, @@ -286,6 +291,45 @@ def test_a_tag_limit_below_one_is_refused(): Container.create("box", Dimensions.mm(10, 10, 10), tag_limits={"fragile": 0}) +def test_mutating_the_callers_dicts_after_construction_changes_nothing(): + """The frozen objects own their mappings: a later edit cannot slip past the `>= 1` check.""" + limits = {"fragile": 2} + container_meta = {"route": {"stops": [1, 2]}} + item_meta = {"note": ["a"]} + container = Container.create("box", Dimensions.mm(10, 10, 10), tag_limits=limits, metadata=container_meta) + item = Item("cube", Dimensions.mm(1, 1, 1), metadata=item_meta) + limits["fragile"] = 0 + limits["other"] = 5 + container_meta["route"]["stops"].append(3) + item_meta["note"].append("b") + assert dict(container.tag_limits) == {"fragile": 2} + assert container.metadata == {"route": {"stops": [1, 2]}} + assert item.metadata == {"note": ["a"]} + with pytest.raises(TypeError): + container.tag_limits["fragile"] = 0 # type: ignore[index] + + +def test_admitted_tag_limits_stay_read_only_through_pickle_copy_and_replace(): + container = Container.create("box", Dimensions.mm(10, 10, 10), tag_limits={"fragile": 2}) + for copied in (pickle.loads(pickle.dumps(container)), copy.deepcopy(container), + dataclasses.replace(container, cost_minor=1)): + assert dict(copied.tag_limits) == {"fragile": 2} + with pytest.raises(TypeError): + copied.tag_limits["fragile"] = 0 # type: ignore[index] + + +def test_metadata_is_detached_without_copying_or_pickling_the_callers_objects(): + lock = threading.Lock() + item = Item("cube", Dimensions.mm(1, 1, 1), metadata={"guard": lock, "tags": ["a"]}) + assert item.metadata["guard"] is lock + + +def test_a_hull_given_as_a_number_is_a_type_refusal_on_the_object_path(): + with pytest.raises(TypeError, match="hull_vertices must be a list") as refusal: + Item("a", Dimensions.mm(10, 10, 10), shape_type="convex_hull", hull_vertices=5) # type: ignore[arg-type] + assert refusal.value.reason == "wrong_type" + + def test_a_container_max_items_below_one_is_refused(): with pytest.raises(ValueError, match="max_items"): Container.create("box", Dimensions.mm(10, 10, 10), max_items=0) diff --git a/tests/test_optimality_bounds.py b/tests/test_optimality_bounds.py index 20cd3c7..0cba954 100644 --- a/tests/test_optimality_bounds.py +++ b/tests/test_optimality_bounds.py @@ -14,6 +14,7 @@ from __future__ import annotations +import json import sys from pathlib import Path @@ -25,6 +26,7 @@ import packvium # noqa: E402 from packvium import bounds, solvers # noqa: E402 from packvium.extensions import DefaultSolutionScorer # noqa: E402 +from packvium.models import RateTable # noqa: E402 #: Four differently-shaped items. Identical items reach `GridSolver`'s quantity-compression #: fast path, which answers before most solvers are consulted -- a request that would make @@ -65,8 +67,8 @@ def _spy(monkeypatch): recorded: list = [] events: list[str] = [] - def spy_bound(instances, containers, objective): - computed = _FOR_REQUEST(instances, containers, objective) + def spy_bound(instances, containers, objective, config=None): + computed = _FOR_REQUEST(instances, containers, objective, config) recorded.append(computed) events.append("bound") return computed @@ -140,15 +142,103 @@ def test_the_height_key_abstains_where_no_volume_argument_holds(): @pytest.mark.parametrize("objective", ["shipping_cost", "lowest_landed_cost"]) -def test_an_objective_without_a_bound_gets_none(objective): - """Their second keys go through billed weight and caller-declared tariffs, for which no - bound is designed -- recording nothing is the honest answer.""" +def test_a_billed_objective_without_its_divisor_gets_none(objective): + """The billed key needs the configuration's divisor; without one there is no number to + bound, and the packer refuses such a request before it gets here.""" request = packvium.PackingRequest( tuple(packvium.Item.create(f"i{n}", packvium.Dimensions.mm(10, 10, 10)) for n in range(2)), (packvium.Container.create("box", packvium.Dimensions.mm(30, 30, 30)),)) assert bounds.for_request(request.instances, request.containers, objective) is None +def _billed(objective: str, containers: list, items: list, **configuration) -> dict: + return packvium.pack_from_dict({ + "items": items, "containers": containers, + "configuration": {"objective": objective, "dimensional_weight_divisor": 5000, + "dimensional_weight_length_unit": "cm", + "dimensional_weight_weight_unit": "kg", + "solver_profile": "exact_small", **configuration}}) + + +def _brick(quantity: int, grams: int) -> dict: + return {"id": "brick", "quantity": quantity, "weight": f"{grams} g", + "dimensions": {"length": "100", "width": "100", "height": "100"}} + + +def test_shipping_cost_bills_at_least_the_floor_and_at_least_tare_plus_payload(): + """A 200 x 100 x 100 mm box at divisor 5000 cm/kg is 0.4 kg dimensional; two 1 kg bricks + and a 300 g tare bill 2.3 kg actual, so the bound is the actual weight, and attained.""" + result = _billed("shipping_cost", + [{"id": "box", "tare_weight": "300 g", + "inner_dimensions": {"length": "200", "width": "100", "height": "100"}}], + [_brick(2, 1000)]) + ticks = packvium.Weight.TICKS_PER_G + assert result["optimality"]["lower_bound"][:2] == [0, 2300 * ticks] + assert result["status"] == "optimal" + + +def test_shipping_cost_takes_the_dimensional_floor_when_the_box_is_bulky(): + """A 400 mm cube is 12.8 kg dimensional at 5000 cm/kg, above one light brick and its tare.""" + result = _billed("shipping_cost", + [{"id": "bulky", "inner_dimensions": {"length": "400", "width": "400", "height": "400"}}], + [_brick(1, 100)]) + assert result["optimality"]["lower_bound"][1] == 12_800 * packvium.Weight.TICKS_PER_G + + +def test_landed_cost_sees_that_two_bricks_cannot_share_a_bracket(): + """Two 1000 g bricks cannot share a 1500 g bracket, so two containers pay it twice: the + item cover says 200, which the weight cover alone (134) and the count term (100) miss.""" + result = _billed("lowest_landed_cost", [ + {"id": "snug-dear", "inner_dimensions": {"length": "200", "width": "100", "height": "100"}, + "rate_table": {"weight_brackets_g": [20000], "prices_minor": [5000]}}, + {"id": "unit-cheap", "inner_dimensions": {"length": "100", "width": "100", "height": "100"}, + "rate_table": {"weight_brackets_g": [1500], "prices_minor": [100]}}], [_brick(2, 1000)]) + assert result["optimality"]["lower_bound"][:2] == [0, 200] + assert result["score"][1] == 200 + + +def test_landed_cost_reads_the_cheapest_bracket_a_floor_can_reach_not_the_floors_own(): + """A promotional dip: the 2 kg bracket is dearer than the 5 kg one. A load that could be + billed in either is bounded by the cheaper, since prices need not rise with weight.""" + bound = bounds._landed_charge_bound( + [1000 * packvium.Weight.TICKS_PER_G], [1], False, + [bounds.Billing(0, 0, ((2000 * packvium.Weight.TICKS_PER_G, 700), + (5000 * packvium.Weight.TICKS_PER_G, 400)))], + [(10, None, None, None)], 0, 1) + assert bound == 400 + + +def test_landed_cost_applies_the_minimum_charge_and_the_surcharge_to_every_bracket(): + """`max(price, minimum)` then the ceiling surcharge, the rate table's own order.""" + container = packvium.Container.create( + "c", packvium.Dimensions.mm(100, 100, 100), + rate_table=RateTable((1000, 2000), (100, 900), minimum_charge_minor=300, + fuel_surcharge_permille=85)) + assert bounds._brackets(container) == ((1000 * packvium.Weight.TICKS_PER_G, 326), + (2000 * packvium.Weight.TICKS_PER_G, 977)) + + +def test_a_type_no_bracket_can_price_is_left_out_and_none_left_withholds_the_bound(): + """A floor above every bracket cannot be priced, and a packing that opens it is refused + rather than returned, so with nothing else to open no statement is made.""" + unpriceable = bounds.Billing(0, 10, ((5, 100),)) + with pytest.raises(bounds.BoundWithheld): + bounds._landed_charge_bound([1], [1], False, [unpriceable], [(10, None, None, None)], 0, 1) + + +def test_the_fractional_cover_takes_cost_per_unit_order_and_rounds_only_once(): + """Greedy by cost per unit is exact for one covering constraint; inventory caps an offer.""" + assert bounds._cover([(10, 3, None), (4, 1, None)], 7) == 24 # 7 x 10/3, rounded up + assert bounds._cover([(10, 3, 1), (4, 1, None)], 7) == 10 + 16 # one 3-unit, then 4 x 4 + assert bounds._cover([(10, 3, 1)], 7) is None # cannot cover + assert bounds._cover([(0, 5, None)], 7) == 0 + + +def test_the_shipping_bound_is_withheld_without_enough_inventory_to_open(): + with pytest.raises(bounds.BoundWithheld): + bounds._billed_weight_bound([1, 1], [bounds.Billing(0, 5)], [1], 0, 2) + + def test_a_custom_solution_scorer_gets_no_bound(): """A caller-defined score's positions are not the bound's quantities.""" request = packvium.PackingRequest( @@ -269,12 +359,13 @@ def test_a_statement_stops_at_the_first_missed_position(): assert bounds.statement((0, 1, 99, 0, 0), bound) is None -def test_an_uncovered_objective_states_nothing(): - """§ 1.5: absence is "no statement", never "attained".""" - result = packvium.pack_from_dict({"containers": CONTAINERS, "items": ITEMS, "configuration": { - "objective": "shipping_cost", "dimensional_weight_divisor": 5000, - "dimensional_weight_length_unit": "cm", "dimensional_weight_weight_unit": "kg"}}) - assert set(result["optimality"]) == {"code"} +def test_a_withheld_bound_states_nothing(): + """§ 1.5: absence is "no statement", never "attained". Every built-in objective is covered + since, so the withheld case is a made-to-measure container (D13).""" + # A copy of the conformance fixture, so the test also runs in the published package. + request = json.loads((Path(__file__).parent / "fixtures" + / "feature-made-to-measure-dimensional-weight-on-outer.json").read_text()) + assert set(packvium.pack_from_dict(request)["optimality"]) == {"code"} def test_the_statement_does_not_depend_on_the_deadline(): @@ -486,3 +577,70 @@ def test_the_portable_gap_ceiling_is_inclusive(least): statement = bounds.statement((0, 1, least + bounds.MAX_BOUND_VALUE, 0, 0), bound) assert statement['absolute_gap'] == bounds.MAX_BOUND_VALUE assert bounds.statement((0, 1, least + bounds.MAX_BOUND_VALUE + 1, 0, 0), bound) is None + + +def _landed_request(containers: list, items: list) -> dict: + return {"items": items, "containers": containers, "configuration": { + "objective": "lowest_landed_cost", "dimensional_weight_divisor": 5000, + "dimensional_weight_length_unit": "cm", "dimensional_weight_weight_unit": "kg", + "solver_profile": "fast", "time_limit_ms": 20000}} + + +def test_the_landed_bound_reads_payload_slot_and_shrinking_limits_alike_in_engine_and_validator(): + """A type whose floor no bracket reaches offers nothing; a payload cap and a slot limit + bound what a bracket carries; a nesting item drops the volume count. The engine's stated + bound and the validator's recomputed one agree.""" + from packvium.result_validation import objective_lower_bound + request = _landed_request([ + {"id": "bulky", "inner_dimensions": {"length": "500", "width": "500", "height": "500"}, + "rate_table": {"weight_brackets_g": [1000], "prices_minor": [10]}}, + {"id": "capped", "max_payload": "1500 g", "max_items": 1, + "inner_dimensions": {"length": "200", "width": "200", "height": "200"}, + "rate_table": {"weight_brackets_g": [3000, 9000], "prices_minor": [300, 200]}}], + [{"id": "cup", "quantity": 2, "weight": "1000 g", "nesting_height": "10", + "dimensions": {"length": "100", "width": "100", "height": "50"}}]) + stated = packvium.pack_from_dict(request)["optimality"]["lower_bound"] + assert list(objective_lower_bound(request))[:len(stated)] == stated + assert stated[1] == 400 + + +def test_nothing_placeable_bounds_the_billed_keys_at_zero(): + """A payload no instance fits places nothing, opens nothing and bills nothing.""" + from packvium.result_validation import objective_lower_bound + request = _landed_request([ + {"id": "tiny", "quantity": 1, "max_payload": "1 g", + "inner_dimensions": {"length": "200", "width": "200", "height": "200"}, + "rate_table": {"weight_brackets_g": [3000], "prices_minor": [300]}}], + [{"id": "brick", "weight": "1000 g", "dimensions": {"length": "100", "width": "100", "height": "100"}}]) + assert objective_lower_bound(request)[:2] == (1, 0) + shipping = {**request, "configuration": {**request["configuration"], "objective": "shipping_cost"}} + assert objective_lower_bound(shipping)[:2] == (1, 0) + assert bounds._billed_weight_bound([1], [bounds.Billing(0, 5)], [None], 1, 0) == 0 + assert bounds._landed_charge_bound([1], [1], False, [], [], 1, 0) == 0 + + +def test_a_landed_request_nothing_can_price_states_no_bound_in_the_validator(): + from packvium import result_validation + request = _landed_request([ + {"id": "bulky", "inner_dimensions": {"length": "500", "width": "500", "height": "500"}, + "rate_table": {"weight_brackets_g": [1000], "prices_minor": [10]}}], + [{"id": "brick", "weight": "100 g", "dimensions": {"length": "100", "width": "100", "height": "100"}}]) + assert result_validation.objective_lower_bound(request) is None + unit = result_validation._length_unit(request) + items = result_validation._parse_items(request, unit) + containers = result_validation._parse_containers(request, unit) + assert result_validation._stated_bound(request, "feasible", items, containers)[1] == \ + "no priceable inventory carries a packing that attains the count bound" + custom = {**request, "configuration": {"objective": "custom"}} + assert result_validation._stated_bound(custom, "feasible", items, containers)[1] == \ + "objective 'custom' has no bound" + + +def test_the_validator_billing_helpers_cover_their_edges(): + from packvium import result_validation as rv + assert rv._fractional_cover([], 0) == 0 + assert rv._fractional_cover([(10, 3, 1)], 7) is None + assert rv._least_of_inventory([(5, 1)], 2) is None + assert rv._billed_term("shipping_cost", {}, {}, (), (), False, (0, 1, 0, 0, 0)) is None + assert bounds._brackets(packvium.Container.create("bare", packvium.Dimensions.mm(10, 10, 10))) == () + assert bounds._cover([(1, 1, None)], 0) == 0 diff --git a/tests/test_request_errors.py b/tests/test_request_errors.py index d1687eb..5aefff3 100644 --- a/tests/test_request_errors.py +++ b/tests/test_request_errors.py @@ -412,3 +412,60 @@ def test_null_obstacle_additional_boxes_packs_as_an_empty_list(): expected = pack_from_dict(defaulted) result["algorithm"]["duration_ms"] = expected["algorithm"]["duration_ms"] assert result == expected + + +def hull_item(vertices: object) -> dict: + return {"id": "hull", "dimensions": {"length": "100", "width": "100", "height": "100"}, + "shape_type": "convex_hull", "hull_vertices": vertices} + + +def hull_points(count: int) -> list[dict]: + corners = [{"x": x, "y": y, "z": z} for x in (0, 100) for y in (0, 100) for z in (0, 100)] + along_edge = [{"x": step, "y": 0, "z": 0} for step in range(1, count)] + return (corners + along_edge)[:count] + + +def test_a_hull_of_32_vertices_is_accepted(): + data = request() + data["items"] = [hull_item(hull_points(32))] + + assert isinstance(pack_from_dict(data), dict) + + +def test_a_hull_of_33_vertices_is_refused_at_admission(): + data = request() + data["items"] = [hull_item(hull_points(33))] + with pytest.raises(InvalidRequestError) as caught: + pack_from_dict(data) + + error = caught.value + assert (error.reason, error.field, error.detail) == ( + "above_maximum", "/items/0/hull_vertices", "must have at most 32 vertices") + + +def test_the_hull_cap_wins_over_a_vertex_that_would_fail_per_vertex_checks(): + vertices = hull_points(33) + vertices[0] = {"x": -1, "y": 0, "z": 0} + assert refusal(lambda d: d.update(items=[hull_item(vertices)])).reason == "above_maximum" + + +def test_a_hull_vertex_list_that_is_not_a_list_reports_its_own_type_error(): + error = refusal(lambda d: d.update(items=[hull_item(5)])) + + assert (error.reason, error.field, error.detail) == ( + "wrong_type", "/items/0/hull_vertices", "must be a list") + + +def test_a_hull_of_33_vertices_is_refused_when_the_item_is_built_directly(): + from packvium import Dimensions, Item + from packvium.geometry import ShapeType + from packvium.units import Length + + side = Length.parse("100") + vertices = tuple((x, 0, 0) for x in range(33)) + with pytest.raises(InvalidRequestError) as caught: + Item(id="hull", dimensions=Dimensions(side, side, side), shape_type=ShapeType.CONVEX_HULL, + hull_vertices=vertices) + + assert (caught.value.reason, caught.value.detail) == ( + "above_maximum", "hull_vertices must have at most 32 vertices") diff --git a/tests/test_request_objects.py b/tests/test_request_objects.py index 9faae38..366dda6 100644 --- a/tests/test_request_objects.py +++ b/tests/test_request_objects.py @@ -17,6 +17,7 @@ from packvium.geometry import Point, Rotation from packvium.made_to_measure import MadeToMeasure, as_triple from packvium.models import FixedPlacement, RateTable +from packvium.request_errors import check_request from packvium.units import Length TOO_LARGE = 2**60 @@ -199,3 +200,54 @@ def test_the_json_path_still_reports_what_its_rules_do_not_name_as_invalid_value rate_table={"weight_brackets_g": [5000, 1000], "prices_minor": [500, 900]})) assert (error.reason, error.field) == ("invalid_value", "") assert str(error) == "invalid_request: rate_table weight brackets must be strictly ascending" + + +# ------------------------------------------- a rate table's top bracket (M1) on both paths + +CEILING = 2**53 - 1 +TOP_BRACKET_MESSAGE = (f"invalid_request: /containers/0/rate_table: must price its top " + f"bracket at most {CEILING} minor units with the fuel surcharge") +OVER_THE_CEILING = [ + ("price", {"prices_minor": [CEILING], "minimum_charge_minor": 0, "fuel_surcharge_permille": 1}), + ("minimum charge", {"prices_minor": [1], "minimum_charge_minor": CEILING, "fuel_surcharge_permille": 1}), + ("fuel surcharge", {"prices_minor": [10**15], "minimum_charge_minor": 0, "fuel_surcharge_permille": 10000}), +] + + +def table(fields: Json) -> RateTable: + return RateTable((1000,) * len(fields["prices_minor"]), tuple(fields["prices_minor"]), + fields["minimum_charge_minor"], fields["fuel_surcharge_permille"]) + + +@pytest.mark.parametrize("name, fields", OVER_THE_CEILING, ids=[case[0] for case in OVER_THE_CEILING]) +def test_a_top_bracket_landing_above_the_ceiling_is_refused_on_both_paths(name: str, fields: Json) -> None: + from_objects = object_refusal(packed(containers=[box(rate_table=table(fields))])) + from_json = json_refusal(lambda r: r["containers"][0].update( + rate_table={"weight_brackets_g": [1000], **fields})) + for refusal in (from_objects, from_json): + assert (refusal.code, refusal.reason, refusal.field) == ("invalid_request", "above_maximum", + "/containers/0/rate_table") + assert str(refusal) == TOP_BRACKET_MESSAGE + assert refusal.args == from_json.args + + +@pytest.mark.parametrize("fields", [ + {"prices_minor": [CEILING], "minimum_charge_minor": 0, "fuel_surcharge_permille": 0}, + {"prices_minor": [1], "minimum_charge_minor": CEILING, "fuel_surcharge_permille": 0}, + {"prices_minor": [CEILING - 1000], "minimum_charge_minor": 0, "fuel_surcharge_permille": 0}, +]) +def test_a_top_bracket_landing_at_the_ceiling_is_admitted_on_both_paths(fields: Json) -> None: + check_request(json_request(lambda r: r["containers"][0].update( + rate_table={"weight_brackets_g": [1000], **fields}))) + packed(containers=[box(rate_table=table(fields))])() + + +def test_a_dearest_bracket_that_is_not_the_last_is_the_one_held_to_the_ceiling() -> None: + fields = {"weight_brackets_g": [500, 1000], "prices_minor": [CEILING, 1], "fuel_surcharge_permille": 1} + assert json_refusal(lambda r: r["containers"][0].update(rate_table=fields)).field == "/containers/0/rate_table" + + +def test_a_mistyped_price_still_reports_its_own_error_before_the_top_bracket() -> None: + refusal = json_refusal(lambda r: r["containers"][0].update(rate_table={ + "weight_brackets_g": [1000], "prices_minor": [CEILING, "x"], "fuel_surcharge_permille": 1000})) + assert (refusal.reason, refusal.field) == ("wrong_type", "/containers/0/rate_table/prices_minor/1") diff --git a/tests/test_request_objects_corpus.py b/tests/test_request_objects_corpus.py index be004e9..89cd5d9 100644 --- a/tests/test_request_objects_corpus.py +++ b/tests/test_request_objects_corpus.py @@ -50,6 +50,7 @@ #: Cases with no object form: the value cannot be held, or the deserializer changes it. NOT_OBJECTS: dict[str, str] = { + "item-hull-vertices-not-list": "an Item's hull_vertices is a sequence of points; a number is not one", "obstacle-origin-false": "a Point cannot hold a boolean instead of its coordinates", "obstacle-origin-zero": "a Point cannot hold a number instead of its coordinates", "obstacle-origin-nonempty-list": "a Point cannot hold a list instead of its coordinates", @@ -58,6 +59,8 @@ "obstacle-additional-origin-zero": "a Point cannot hold a number instead of its coordinates", "obstacle-additional-origin-nonempty-list": "a Point cannot hold a list instead of its coordinates", "obstacle-additional-origin-empty-string": "a Point cannot hold text instead of its coordinates", + "container-flat-bag-orientation": "`bag_orientation` defaults to flat, so a flat bag that names " + "it cannot be told apart from one that does not", "obstacle-additional-boxes-not-list": "an Obstacle holds its additional boxes as a tuple", "request-not-object": "a request that is not an object has no objects", "items-missing": "Packer.pack takes the items as an argument", @@ -136,6 +139,7 @@ "container-access-direction-unknown": "an unknown direction keeps InvalidDirectionError", "item-accepts-stacking-groups-entry-empty": "a set's index counts in code-point order", "an-item-id-before-its-quantity": _CONSTRUCTOR_FIRST, + "item-hull-33-vertices-before-a-bad-coordinate": _CONSTRUCTOR_FIRST, "item-ids-before-containers": _CONSTRUCTOR_FIRST, "container-ids-before-fixed-placements": _CONSTRUCTOR_FIRST, "currency-before-configuration": _CONSTRUCTOR_FIRST, @@ -156,7 +160,7 @@ } #: Pinned, so the skip set cannot grow without this line changing too. -SKIPPED = 105 +SKIPPED = 108 @dataclass(frozen=True) diff --git a/tests/test_result_layering.py b/tests/test_result_layering.py new file mode 100644 index 0000000..8f40e03 --- /dev/null +++ b/tests/test_result_layering.py @@ -0,0 +1,25 @@ +import ast +from pathlib import Path + +SOURCE = Path(__file__).resolve().parents[1] / "src" / "packvium" + +# The result object is Domain layer: it may read domain values and pure arithmetic, never the +# constraint, solver or validation layers above it (R-03). +RESULT_MAY_IMPORT = {"_compat", "axle_load", "loads", "models", "ratios", "units"} + + +def _packvium_imports(module: str) -> set[str]: + tree = ast.parse((SOURCE / module).read_text()) + return { + node.module for node in ast.walk(tree) + if isinstance(node, ast.ImportFrom) and node.level == 1 and node.module + } + + +def test_the_result_object_imports_nothing_above_the_domain_layer(): + assert _packvium_imports("result.py") <= RESULT_MAY_IMPORT + + +def test_the_modules_the_result_object_reads_import_no_higher_layer(): + for module in ("axle_load", "loads", "ratios"): + assert _packvium_imports(f"{module}.py") <= {"models", "geometry", "loads", "_compat"}, module diff --git a/tests/test_result_validation.py b/tests/test_result_validation.py index 92b480c..2c948f0 100644 --- a/tests/test_result_validation.py +++ b/tests/test_result_validation.py @@ -8,6 +8,7 @@ import ast import copy +import json from pathlib import Path from typing import Any @@ -188,17 +189,31 @@ def test_a_wrong_bound_value_is_an_optimality_bound_mismatch() -> None: def test_a_bound_where_none_is_stated_is_an_optimality_bound_mismatch() -> None: - request = {**GAP, "configuration": { - "objective": "shipping_cost", "dimensional_weight_divisor": 5000, - "dimensional_weight_length_unit": "cm", "dimensional_weight_weight_unit": "kg"}} + """Every built-in objective is covered since; a made-to-measure container (D13) + is where no bound is stated.""" + # A copy of the conformance fixture, so the test also runs in the published package. + request = json.loads((Path(__file__).parent / "fixtures" + / "feature-made-to-measure-dimensional-weight-on-outer.json").read_text()) result = pack_from_dict(request) result["optimality"]["lower_bound"] = [0] assert [(issue.code, issue.detail) for issue in validate(request, result)] == [( "optimality_bound_mismatch", - "lower_bound is reported where no bound is stated: objective 'shipping_cost' has no bound", + "lower_bound is reported where no bound is stated: a container is made to measure", )] +def test_a_billed_objective_states_the_bound_the_validator_recomputes() -> None: + """The validator's own billed term agrees with what the engine states, and a + bound moved by one is caught.""" + request = {**GAP, "configuration": { + "objective": "shipping_cost", "dimensional_weight_divisor": 5000, + "dimensional_weight_length_unit": "cm", "dimensional_weight_weight_unit": "kg"}} + result = pack_from_dict(request) + assert validate(request, result) == [] + result["optimality"]["lower_bound"][1] -= 1 + assert [issue.code for issue in validate(request, result)] == ["optimality_bound_mismatch"] + + def test_a_wrong_absolute_gap_is_an_optimality_gap_mismatch() -> None: result = _emitting(GAP) result["optimality"]["absolute_gap"] += 1 diff --git a/tests/test_stock_cut_errors.py b/tests/test_stock_cut_errors.py index 3481c55..e6c1fd0 100644 --- a/tests/test_stock_cut_errors.py +++ b/tests/test_stock_cut_errors.py @@ -54,3 +54,23 @@ def test_stock_costs_keep_exact_integers_and_null_defaults(cost): request["containers"][0]["cost_minor"] = cost request["fixed_placements"] = [{"container_type": "machine"}] assert stock_cut_boxes(request, artifact, 1)["containers"][1]["cost_minor"] == (0 if cost is None else cost) + + +def test_a_cut_box_priced_past_the_exact_integer_ceiling_is_refused_not_rounded(): + sides = {"length": "10", "width": "10", "height": "10"} + request = {"items": [{"id": "cube", "dimensions": sides}], "containers": [ + {"id": "machine", "inner_dimensions": sides, + "made_to_measure": {"minimum": sides, "increment": sides, "cost_per_square_metre_minor": 9007199254740991}}]} + artifact = build_operational_artifact(request, pack_from_dict(request)) + request["fixed_placements"] = [{"container_type": "machine"}] + # 600 mm^2 of surface is far below a square metre, so the price stays inside the ceiling. + assert stock_cut_boxes(request, artifact, 1)["containers"][1]["cost_minor"] <= 9007199254740991 + # The same rate on a cut box of 2000 mm per side is 24 m^2 and passes it. + cut = copy.deepcopy(artifact) + for axis in ("length", "width", "height"): + cut["geometry"]["containers"][0]["inner_dimensions"][axis] = str(2000 * 16000) + with pytest.raises(PlanRevisionError) as refusal: + stock_cut_boxes(request, cut, 1) + assert (refusal.value.code, str(refusal.value)) == ( + "invalid_revision", + "a made-to-measure container's cost_per_square_metre_minor prices the largest box above 9007199254740991") diff --git a/tests/test_units.py b/tests/test_units.py index 2a3546c..872d1a8 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -69,6 +69,22 @@ def test_mixed_fraction_takes_its_sign_from_the_text(): assert _fraction("1 1/2") == Fraction(3, 2) +@pytest.mark.parametrize( + "text", + ["1e2", "1E2", "1e3000000", "1_00", "\uff11\uff10", "\u0661\u0660", "1.\u0665", ".5", "5.", "nan", "Infinity", + "\uff11/\uff12", "1 \u0661/\u0662", "1e3 g", "1e3 mm"], +) +def test_only_ascii_decimals_and_fractions_are_measures(text): + """The grammar of docs/UNITS-AND-NUMERICS.md: exponent, underscore, non-ASCII digit and + bare-dot forms are refused before a Decimal is built, as the other engines refuse them.""" + with pytest.raises(InvalidRequestError): + _fraction(text) + with pytest.raises(InvalidRequestError): + Length.parse(text) + with pytest.raises(InvalidRequestError): + Weight.parse(text) + + def test_accepted_scalar_types(): assert Length.of(2, "mm") == Length.of("2", "mm") assert Length.of(Decimal("2.5"), "mm") == Length.of("2.5", "mm") @@ -287,3 +303,18 @@ def test_parsed_measures_refuse_a_bad_object_on_every_read(spelling, error, mess with pytest.raises(type(direct.value), match=message) as caught: measures.read(Length, spelling, "mm") assert str(caught.value) == str(direct.value) + + +# Short ids: pytest puts a test's id in PYTEST_CURRENT_TEST, and Windows caps a variable at 32767. +@pytest.mark.parametrize("text", ["9" * 1_000_000, "1" * 5000, "1" * 5000 + "/1", "1 " + "1" * 5000 + "/1"], + ids=["a-million-digits", "5000-digits", "5000-digit-numerator", "5000-digit-mixed-fraction"]) +def test_a_measure_past_every_maximum_is_read_in_linear_time_and_stays_past_it(text): + """A long measure is saturated rather than read digit by digit: `Fraction(Decimal(...))` took + 48 s on a million digits, and `int` refuses past 4300 digits.""" + assert _fraction(text) > 10 ** 60 + + +def test_leading_zeros_are_not_significant_digits(): + assert _fraction("0" * 5000 + "100") == 100 + assert _fraction("0" * 5000 + "100/1") == 100 + assert _fraction("-" + "0" * 5000 + "12.50") == Fraction(-25, 2)