Metadata-Version: 2.5
Name: designoptpy-core
Version: 0.1.0
Summary: Shared DesignOptPy algorithms, geometry, numerical methods, and data interfaces
Author: Eduardo Rodrigues Della Noce
License-Expression: MIT OR Apache-2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
License-File: NOTICE
Requires-Python: <3.15,>=3.12
Requires-Dist: matplotlib<4,>=3.11
Requires-Dist: numpy<3,>=1.26
Requires-Dist: pillow<14,>=10.1
Requires-Dist: scipy<2,>=1.12
Provides-Extra: all
Requires-Dist: cmocean<5,>=4.0.3; extra == 'all'
Requires-Dist: defusedxml<1,>=0.7.1; extra == 'all'
Requires-Dist: openpyxl<4,>=3.1; extra == 'all'
Requires-Dist: python-calamine<1,>=0.9.1; extra == 'all'
Provides-Extra: colors
Requires-Dist: cmocean<5,>=4.0.3; extra == 'colors'
Provides-Extra: io
Requires-Dist: defusedxml<1,>=0.7.1; extra == 'io'
Requires-Dist: openpyxl<4,>=3.1; extra == 'io'
Requires-Dist: python-calamine<1,>=0.9.1; extra == 'io'
Description-Content-Type: text/markdown

# designoptpy-core

`designoptpy-core` provides shared DesignOptPy algorithms and data interfaces.
An interface specifies the accepted inputs, callable methods, and returned values.
A callable is a function or object that accepts a parentheses call.
Classes can provide the required methods without a shared parent class. This is structural typing.
This component has its own installation and version. Import it through `designoptpy.core`.

Installation:

- After publication, install it with `python -m pip install designoptpy-core`.
- From the source workspace, run `uv sync --package designoptpy-core`.
- To install the complete family, install `designoptpy`.
  That distribution includes X-Ray and optional workbook and color-palette support.

See the [workspace documentation](../../README.md) for development and release procedures.

## Conventions

- Core arrays use sample-major shapes. Each row represents one sample, and each column one variable or response.
- Indices are zero-based: the first index is 0.
- `designoptpy.core.arrays` holds the shared array aliases `FloatArray`, `BoolArray`, and `IntArray` and the conversion helpers.
  `designoptpy.core.arrays.as_integer_array` checks original values before integer conversion.
  This prevents fractional truncation and integer overflow from changing indices.
- `designoptpy.core.validation.validate_integer` checks one integer control, such as a count, a work limit, or a seed.
  It accepts a Python or NumPy integer and returns a built-in `int`.
  A value of the wrong type, such as a Boolean, a float, or text, raises `TypeError`.
  An integer below the required minimum raises `ValueError`.
- Converting inputs to a required numeric representation is coercion.
  Real-valued validators reject complex data before coercion can discard imaginary components.
- A supplied function that another function invokes is a callback.
  An adapter changes the calling or result convention of a callback to match an interface.
- Unavailable or unprocessed information is `None`. Numeric zero is a processed value.
- Importing `designoptpy.core`, its geometry, or its region search loads no SciPy module.
  A function that needs SciPy, such as a hull, a distance, or the default interpolator, imports it on its first call.
  SciPy is a required dependency, so this changes only when its import cost is paid.

### Masked subsets

A Boolean mask over a full list selects a subset: its true entries, in their order.
`designoptpy.core.arrays.convert_index_base(is_in_subset, index_query, direction)` translates zero-based positions between the two lists.

- `"subset-to-full"` maps subset positions to full positions with the lookup table `numpy.flatnonzero(is_in_subset)`.
- `"full-to-subset"` maps full positions to subset positions with the running count of true entries, a prefix sum.
  A full position outside the subset has no subset position and returns `NaN`.
- On the selected entries the two maps are inverse, so a round trip returns the original positions.
- `index_query` holds positions (shape, order, and repetitions stay) or a Boolean mask over the source list.
  Each column of a two-dimensional query is one query. Boolean columns of different true counts end with `NaN` padding.
- The function also returns a Boolean destination mask per query column. A mask cannot show order or repetition.
- `IndexBaseDirection` names the two directions. Their text follows the choice-name rule of `designoptpy.core.choices`.

For the mask `[True, False, True, False, True]`, the subset positions `[0, 2]` map to the full positions `[0, 4]`,
and the full positions `[0, 1, 4]` map to the subset positions `[0, NaN, 2]`.

## Requirements, deficits, and scores

A requirement limits a measured response, such as a stress or a distance.
A deficit is a signed distance from the allowed measure limits: positive violates a limit; nonpositive satisfies it.
`measure_to_deficit` divides each limit difference by a positive normalization factor `s`:

```text
d_lower = (lower_limit - measure) / s
d_upper = (measure - upper_limit) / s
```

It applies each positive weight `w` to the corresponding normalized limit difference `d`.
It uses `w*d` when `d > 0` and `d/w` otherwise, then selects the larger weighted lower/upper difference.
For weight 2, differences -2 and 2 become -1 and 4.
Increasing a weight raises violations and moves satisfying margins toward zero.
Positive weights preserve the sign of satisfaction in exact arithmetic. Rankings and the controlling limit can change.
An absent limit is NaN, `-inf` for a lower limit, or `+inf` for an upper limit.
A lower limit of `+inf` or an upper limit of `-inf` admits no measure.
This is a configuration error, so `measure_to_deficit` raises `ValueError`.
It does not label every design as rejected by the model.

`deficit_to_label_score` turns deficit rows into labels and ranking scores.
`deficit_labels` returns only the labels, with the same rule and without weights or scorers, for a caller that discards the score.
A row is good when every deficit is at or below zero.
By default, a good row scores the negative weighted geometric mean of its margins.
A bad row scores the weighted Euclidean norm of its positive violations.
The rule names follow the choice-name rule of `designoptpy.core.choices`: `score_good` accepts `"geometric-mean"` and `"worst-case"`, and `score_bad` accepts `"euclidean-norm"` and `"worst-case"`.
None selects the default rule of the group.
The `"worst-case"` scorer uses the largest weighted active deficit.
It weights like `measure_to_deficit`: a positive deficit is multiplied by its weight, and a non-positive margin is divided by it.
A heavier requirement therefore looks closer to violation on both sides of its limit.

```python
import numpy as np
from designoptpy.core.evaluation import deficit_to_label_score

label, score = deficit_to_label_score([[-3.0, -12.0, -np.inf]], [2.0, 2.0, 200.0])
print(label, score)  # [ True] [-6.]
```

The third requirement is inactive, so only the first two margins count.
Their geometric weights normalize to one half each, and `sqrt(3 * 12) = 6`.
Scaling all geometric weights by the same positive factor leaves the score unchanged, because their relative weights stay equal.
Geometric weights are normalized over the active requirements in each row.
Edge cases of the built-in scorers:

- Every built-in good scorer returns `-1` when all requirements are inactive or the row has no requirements.
  A `(2, 0)` deficit matrix therefore gives two good labels and two scores of `-1`.
- Violation norms use absolute weights and stable reductions to preserve representable extreme magnitudes.
  The violations `[6e200, 8e200]` give a bad label and the norm `1e201`.
- Custom good and bad scorers can replace the defaults.
  Labels always come from the deficits, not from the sign of a score.

[performance_score_contour.py](../../examples/simple_examples/performance_score_contour.py) maps a grid of two measures to deficits, labels, and scores and draws the score contours.

### Infinite values and model rejection

- Requirement scoring treats negative-infinity deficits as inactive requirements.
- Raw negative infinity satisfies an upper-only requirement. A finite lower limit rejects it.
- By default, raw positive infinity satisfies a lower-only requirement, and a column without active limits gives `-inf`.
- A model can also return `+inf` to reject a design.
  `reject_positive_infinity=True` on `measure_to_deficit` or `DeficitConversionPolicy` serves this case.
  Every raw `+inf` measure then gives a `+inf` deficit, whatever the limits.
  The `designoptpy.sso` mapping evaluator and the surrogate uncertainty validators set it.
- Mapping results preserve signed infinity but reject NaN.
- Positive infinity explicitly rejects the affected requirement group.
  The group receives a false label and a positive-infinity score.
- `DesignEvaluation.model_rejected` combines explicit rejection from both deficit groups.
- Surrogate predictions remain finite.
  Numerical prediction failures cannot become structural rejection signals.
- `finite_solver_residuals` supplies a finite solver view while raw evaluations retain the original signals.
  Adapters must also keep an unweighted rejection inequality and independently qualify the returned raw model result.
  An adapter may omit the inequality only where it is the only constraint and constant near an accepted interior start,
  as the default-solver performance-score workflow of `designoptpy.point` does. The independent final qualification still applies.

### Normalization and reusable policies

`measure_normalization_factor` returns one positive factor per measure column.
The factor comes from the first available source in this order:

1. an explicit factor;
2. the finite limit span;
3. the absolute upper limit;
4. the absolute lower limit;
5. with `normalize_with_measure=True`, the observed range and then the absolute mean;
6. one.

Observed statistics ignore nonfinite response signals.
Use `normalize_with_measure=True` for a fixed data set only.
The `designoptpy.sso` evaluators do not offer it, because batch statistics would make the deficit of a design depend on the other rows of its batch.
Positive scaling changes deficit magnitude without changing its satisfaction sign.

`DeficitConversionPolicy` stores limits, normalization factors, and directional weights for `measure_to_deficit`.
`DeficitScoringPolicy` stores ranking weights, good and bad scorers, and their options for `deficit_to_label_score`.
These conversion weights are separate from the scoring weights.
Both policies store independent copies of their values.

Observed statistics change from batch to batch.
To compare batches on one scale, derive the factors once from a chosen reference batch.
Then pass those factors explicitly in a `DeficitConversionPolicy` for the later batches.

## Evaluator and mapping results

An evaluator returns requirement deficits from `evaluate(samples)`.
A mapping returns raw measures from `response(samples)` or as a plain function.
`designoptpy.core` owns one contract for these results.
Every package converts them with the same two functions, `coerce_evaluation` and `coerce_mapping_result`.

`coerce_evaluation(value, n)` accepts three forms:

- a `DesignEvaluation`;
- a tuple `(performance_deficit[, physical_feasibility_deficit[, metadata]])`;
- an object with the attributes `performance_deficit`, `physical_feasibility_deficit`, and `metadata`.

`coerce_mapping_result(value, n, *, finite=False)` accepts three forms:

- a `MappingResult`;
- a tuple `(performance[, physical_feasibility[, metadata]])`;
- a bare array, which is the performance group alone.

A `response` method and a plain mapping function return the same forms. Other values raise `TypeError`.
The protocol return types name these forms. `BottomUpMapping.response` and `FunctionalDesignMapping.response` return a `MappingResponse`: the three mapping forms.
`DesignEvaluator.evaluate` returns an `EvaluationResponse`: a `DesignEvaluation` or the tuple form. `coerce_evaluation` also accepts the attribute-object form; the protocol type does not name it.
`coerce_evaluation` rejects a bare array and a measure result, such as `MappingResult`.
`coerce_mapping_result` rejects a deficit record, such as `DesignEvaluation`.
`finite=True` also rejects infinite measures. Surrogate regression training and surrogate predictions use it.

Performance and physical feasibility each have their own matrix in a result.
Its columns are requirements for deficits and measured quantities for measures.
Both functions apply one shape rule to each returned group, implemented by `designoptpy.core.arrays.as_output_group`.
For `n` requested designs:

| Returned group | Result |
| --- | --- |
| Matrix with `n` rows | Unchanged |
| Empty vector, such as `[]` | `(n, 0)`: the group has no columns |
| Vector with `n` entries | `(n, 1)`: one column |
| Vector with `k` entries, for one design | `(1, k)` |
| Scalar, for one design | `(1, 1)` |

For example, `coerce_mapping_result(([1.0, 2.0, 3.0], []), 3)` returns a `(3, 1)` performance matrix.
Its physical feasibility matrix has shape `(3, 0)`.

Any other shape raises `ValueError`. NaN always raises `ValueError`.
A deficit group returned as `None` becomes `(n, 0)`: that group has no requirements.
A measure group returned as `None` stays `None`: the mapping did not produce it.

These rules keep each result row paired with the design that produced it.
An empty vector holds no value for any design.
Its only consistent meaning is "no columns", and the request supplies its row count.
A vector becomes a column only when its length equals the request size. It becomes a row only for one design.
A bare array is accepted for a mapping, because a mapping always has a performance group first.
It is rejected for an evaluation, because it does not state which deficit group it holds.
Measures are rejected where deficits are required, and deficits where measures are required.
A raw measure read as a deficit gives wrong satisfaction signs and scores.

`DesignEvaluator` is runtime-checkable.
`isinstance(value, DesignEvaluator)` checks only that `value` has an `evaluate` attribute.
Evaluator and mapping protocols take the input batch as a positional argument.
Caller-supplied objects can therefore name that parameter freely.

`evaluate_samples(function, samples, vectorized=..., output_shape=...)` calls a function once with all rows or once per row.
An empty per-row batch requires an explicit `output_shape`; without one it raises `ValueError`, because no output layout has been observed.
The declared trailing dimensions are preserved. `output_shape=()` declares a scalar result stored as one column.
A response vector becomes one output column for multiple samples, or one output row for a single sample.
`executor=pool` (default `None`, serial) runs the per-row calls through a `concurrent.futures.Executor` and keeps the row order.
The rows are independent, so the calls can run at the same time.
A thread pool helps only a function that waits for an external program or releases the global interpreter lock (GIL).
A process pool needs a picklable function.
Both give the serial values only for a deterministic function without state between calls.

### Mapping adapters

`CallableMapping` wraps a system function and an optional separate physical feasibility function.
Each function has its own parameter payload, and metadata from both calls is retained.
`FixedVariableMapping.from_mask` accepts a Boolean mask of the fixed variables.
`transform_design_data` converts full bounds, an initial design, and component indices to the free-variable representation.
`SurrogateMapping` presents fitted surrogate models as a mapping and retains each model's prediction details.
`performance_trusted_range` and `feasibility_trusted_range` restrict each model to a `(2, n)` design box `[lower; upper]`.

- A design outside the box never reaches that model.
  It gets `+inf` in every measure column, and `SurrogateMappingMetadata` marks it in a skipped-prediction mask.
- The class documentation gives the recipe for the box of the training rows that meet every requirement.
- The box screens the prediction range. It does not certify accuracy.

`performance_measure_index` and `feasibility_measure_index` keep selected prediction columns, zero-based and in the given order; a repeated index repeats its column.

- The mapping validates the whole prediction first, then selects. An index at or above the prediction width raises `ValueError` at the response.
  A design outside the trusted range gets `+inf` in every selected column.
- `None` (default) keeps every column. An index must be a nonempty vector of nonnegative integers; an empty, real, Boolean, or negative index raises `ValueError`, and so does an unsigned entry above the `int64` range.
- For the model `[x0, 2 * x0, 3 * x0 + x1]`, the index `[2, 0, 0]` maps the design `[1, 0]` to `[3, 1, 1]`.

A trusted range or a measure index needs the model of its group. A default row has no prediction to restrict, and it already describes the selected response.
So a range or an index without its model is an input error, raised at construction after the format checks, in this order:
`"performance_trusted_range requires a performance model"`, `"feasibility_trusted_range requires a feasibility model"`,
`"performance_measure_index requires a performance model"`, and `"feasibility_measure_index requires a feasibility model"`.
The example [`surrogate_mapping_equivalence.py`](../../examples/simple_examples/surrogate_mapping_equivalence.py) installs a fitted linear surrogate as the performance model of a `SurrogateMapping`.
The mapping response equals the direct model prediction exactly, because both run the same model arithmetic; the mapping only moves arrays.

`CallableMapping`, `FixedVariableMapping`, and `SurrogateMapping` are frozen.
A field cannot be reassigned after construction, so the construction checks hold for every call.
`FixedVariableMapping` stores read-only copies of its index and value vectors and computes its free indices once.
Pickle and `copy` restore it through its constructor, which repeats these checks and copies.
They do not copy supplied functions, models, or parameter objects.
A change to such a mutable object changes later responses.

`ContinuousVariableMapping.from_design_spaces` describes functional variables, such as a stiffness profile along a bar.
It expands functional bounds, initial values, and component indices over a configurable number of free interpolation nodes,
or over explicit node coordinates.

- Two or more free nodes are equally spaced and include both location bounds. One free node lies at the domain midpoint.
- `free_interpolation_nodes` gives one nonempty, strictly increasing, finite vector of node coordinates per functional variable, inside its location bounds (bounds included).
  It replaces the uniform grid, for example to place nodes densely where the design needs resolution. The expansion over the remaining free nodes is the same as for the grid.
  It cannot be combined with a `number_of_free_interpolation_nodes` other than one; the default count one is indistinguishable from an omitted count.
- Location bounds must be finite with lower <= upper.
  An equal-endpoint location domain accepts only one free node, which lies at that endpoint.
- Interpolation estimates values between support locations. Extrapolation evaluates beyond the outer support locations.
- The default interpolator is the shape-preserving piecewise cubic Hermite interpolating polynomial (PCHIP), with extrapolation.
  One support point gives a constant function.
  `interpolator_factory` and `interpolation_options` replace the default.

Fixed interpolation constraints:

- They replace free nodes at the same locations.
  Bounds, initial values, and component indices then describe the remaining free values.
- Repeated fixed constraints with equal values merge. Conflicting values at the same location are rejected.
- A fully fixed functional variable exposes zero free values and still produces a callable interpolation function.
  This keeps the function available while it removes independent values that cannot change.

`ContinuousVariableMapping.from_design_spaces` accepts a `FunctionalDesignMapping` or a callable that receives functional designs.
A `FunctionalDesignBatch` is a sequence of design rows.
Each row is a tuple with one real-valued interpolation function per functional variable, instead of numeric values.
Each supplied output must return one measure row per design.

## Geometry and region search

Geometry objects are constructed first and then queried.
For example, `ellipse_2d`, `circle_2d`, `ellipsoid_3d`, and `sphere_3d` return an `Ellipsoid`:

```python
from designoptpy.core.geometry import ellipse_2d

ellipse = ellipse_2d(center=[0, 0], semi_axes=[2, 1])
print(ellipse.normalized_radius_squared([[0, 0], [2, 0]]))  # [0. 1.]
```

A call with a separate parameter vector, `(samples, parameter_vector)`, is not accepted.

### Boxes

`Box.interpolate` maps unit coordinates to points between the bounds.
For opposite-sign bounds, it uses the convex combination `(1 - u) * lower + u * upper`.
This combination stays finite for any finite bounds, even when the full width `upper - lower` overflows.

`Box.unit_coordinates` is the exact inverse.
For opposite-sign bounds, it first divides the bounds and the point by `s = max(|lower|, |upper|)`: `(x/s - lower/s) / (upper/s - lower/s)`.

`grow_box` moves the faces by `growth_rate` in unit coordinates of the design space, clips them to `[0, 1]`, and maps them back.

`box_measure(box, *, factor=1.0, weights=1.0, reference_box=None)` returns `factor * prod((length / reference_length) ** weight)`.

- It splits each side length into a binary fraction and an exponent, multiplies the fractions, and adds the exponents.
- Wide and thin sides, such as 1e-200 and 1e200, then compensate without an intermediate overflow or underflow.
- For ordinary boxes with unit weights, the result equals the plain product bit for bit.
  A weight other than one changes it at about 1e-15 relative.

`box_volumes(lower, upper, factors=1.0)` measures many boxes at once, one per row, with unit weights and no reference box.
Each entry equals `box_measure` for that box bit for bit, because the same steps act on all rows together.
When every partial product `factor * length_0 * ...` of every nonzero row is a finite normal number, the function returns the plain products.
They equal the binary split results bit for bit, so this shorter path changes no value.
Factors must be real, finite, and nonnegative. They are checked before broadcasting to box rows.
An empty batch cannot hide invalid scalar factors. Complex factors fail without discarding imaginary components.

`Box.contains(samples)` returns the inclusive membership of `Box.classify` without the violation scores.

Two NumPy terms apply to these functions:

- Scaling each unit coordinate and adding its lower bound forms an affine transformation.
- Per-coordinate bounds apply across sample rows through NumPy broadcasting, which expands compatible shapes during arithmetic.
  An axis with one entry is a singleton dimension. NumPy can expand it to match a longer compatible axis.

[bounding_box_samples.py](../../examples/simple_examples/bounding_box_samples.py) fits strict and relaxed bounding boxes (`bounding_boxes`) to labeled samples and marks their boundary and shape-definition samples.

### Ellipsoids

Ellipsoid membership uses local principal-axis coordinates divided by the corresponding semi-axis lengths.
Principal axes are perpendicular directions aligned with the ellipsoid.
Each semi-axis length runs from the center to the boundary.
The method does not require the explicit quadratic-form matrix.
The section "Supported numeric domain" states the radius and `quadratic_form` signals outside the domain.
[ellipse_classification.py](../../examples/simple_examples/ellipse_classification.py) classifies Latin-hypercube samples against a rotated ellipse and a rotated ellipsoid with `normalized_radius_squared`.

### Convex hulls

A convex-hull facet is a boundary face.
Facet construction requires points that span every coordinate direction.
[convex_hull_membership.py](../../examples/simple_examples/convex_hull_membership.py) compares the facet-normal and the linear-programming membership tests, also for a segment that spans no area.

The affine rank of a point set is the dimension of the smallest affine subspace (a point, a line, a plane, and so on) that contains every point.
`compute_affine_rank(points)` returns it as an integer in `[0, d]` for `d` coordinates, or `None` when it is unavailable.

- One coordinate: the rank is 1 when `min < max` and 0 otherwise.
- More coordinates: the rank counts the singular values of the offsets `x_i - x_0` above `s_max * (max(n_points, d) * eps)`, the default tolerance of `numpy.linalg.matrix_rank`.
  Smaller singular values describe directions that the arithmetic cannot tell apart from zero.
- The coordinates are not scaled, and the tolerance grows with the row count.
  Repeated points can therefore lower the rank of a thin set.
- `convex_hull` applies the rank test to the unique rows, in the lexicographic order of `numpy.unique`.
  A rank below `d` raises `ValueError` that states the rank.

Consistency checks of `ConvexPolytope`:

- `ConvexPolytope` checks that each facet equation passes through its facet vertices and keeps every hull point inside, within a rounding allowance.
  Equations that fail a check raise `HullConsistencyError`, a `ValueError`.
- These checks are local. They do not detect a missing facet, which lets classification accept points beyond that facet.
- A caller that constructs `ConvexPolytope` directly must therefore supply the complete facet set, as `convex_hull` does.
- The measure does not take part in these checks or in classification.
  A measure above the float64 range is `+inf`, as in `box_measure`, and the facets stay valid.
  For example, the six-dimensional simplex with edges `1e60` has representable facets and the volume `1e360 / 720`.
  A negative or NaN measure raises `ValueError`.

Facet planes from `convex_hull`:

- Qhull rounds each facet normal, so a nearly coplanar point can lie slightly outside the plane through the facet vertices.
- `convex_hull` therefore keeps the Qhull normal and sets the offset to `-max(points @ normal)`.
  Each plane then passes through the outermost point, and every point satisfies every facet inequality.
- Membership changes only for points within this rounding distance of a facet.
- Above three coordinates, Qhull splits each face with more than `d` vertices into simplices of `d` points, and some of them have zero volume.
  A zero-volume facet has `d` vertices that span fewer than `d - 1` directions, so it has no unique plane.
  `convex_hull` removes these facets with the edge and rank test of `find_facet_reference_point_normal`: unit edges from the first vertex must have rank `d - 1`.
  The kept facets still cover every face, so the hull set, its measure, and its membership stay the same.
  For the 16 corners of `[0, 1]^4`, 48 of the 58 Qhull simplices remain, and `find_convex_hull_facet_normal_inside` succeeds on them.
- A plane guard checks the removal: each removed equation row must equal a kept row in every entry.
  Otherwise the kept facets would miss a supporting plane, and `convex_hull` raises `HullConsistencyError`.
- `convex_hull` also raises `HullConsistencyError` when Qhull fails.
  For nearly degenerate points, the rounded normal can also leave a facet vertex farther inside its plane than the allowance.
  A caller that computes a hull from its own points can therefore report this error as unavailable geometry.

Classification with `ConvexPolytope.classify`:

- It places each plane at the stored offset or at the outermost stored point, whichever lies farther out.
- It measures projections from a facet vertex, so a common translation of all coordinates does not change the rounding.
- Each facet deficit is the projection minus the plane position minus the facet tolerance.
- The score is the largest deficit, so a nonpositive score means inside for an inferred and an explicit tolerance alike.
- The inferred tolerance of a facet is `max(10, d + 2) * spacing(max(|q - p| @ |n|, |n| @ ptp(points)))` for `d` dimensions, the rounding bound `gamma_(d+1)` of its dot product.
  A fixed factor of ten covers only `d <= 8`; the floor 10 keeps the earlier labels there.
  Each facet uses its own projected scale, so a long facet of an anisotropic hull does not relax the test of a short facet.
- `is_in_convex_hull_with_facet_normal` uses the same tolerance.
  In place of `ptp(points)`, it uses the range of its facet reference points, or the supplied `coordinate_range`.
- Each projection adds its coordinate products in a fixed order, so a point gets the same rounded projection in every batch.
- `ConvexPolytope.facet_deficits` returns the full sample-by-facet deficit matrix.

Facet offsets and scores:

- `find_convex_hull_facet_normal_inside` also returns `facet_offsets`, which place each facet plane at the outermost input point.
  Pass them as `facet_offset` to `is_in_convex_hull_with_facet_normal`.
  Every input point then classifies inside for any nonnegative tolerance.
  These offsets are at the rounding level for a valid hull.
- `find_convex_hull_facet_normal_inside(points, face_point_preference="center")` takes each facet center as its reference point; `"vertex"` takes the first indexed vertex of the facet.
  Normals, facet indices, and the measure do not depend on the choice; offsets and the inferred tolerance use the reference point, so labels can differ only within the rounding allowance of a facet plane.
- With `compute_variant_score=True`, `is_in_convex_hull_with_facet_normal` scores the deficit matrix with `variant_score_policy`.
  This is a `DeficitScoringPolicy` with weights and named or custom scorers. `None` selects `DeficitScoringPolicy()`.
  The labels do not change. The score then combines every facet instead of the closest one.
- `coordinate_range` (default `None`) gives one finite nonnegative range per coordinate for the inferred tolerance.
  It replaces the range `ptp(facet_points)` of the facet reference points in the term `|n| @ w`.
  Pass the range of the hull points, so the allowance does not depend on which reference points the facets use.
  It applies only to the inferred tolerance; together with an explicit `tolerance` it raises `ValueError`.
- `membership_batch_size` (default `None`) is a positive maximum number of query rows per deficit batch.
  Each batch forms its own deficit matrix, and the variant policy scores each batch separately.
  A custom scorer must therefore score each row from its own deficits. `None` gives the policy every row in one call.
  Without the variant score, a batch also holds at most `max(1, 2**21 // n_facets)` rows, about 16 MiB per float64 matrix.
  Each deficit uses the fixed-order projection of its own row and facet, so labels and scores do not depend on the batch size.
- Inputs that define no half-space raise `ValueError`: no facet, no coordinate, or a normal row of zeros.
  A deficit that is not finite, for example after a large offset and tolerance overflow, also raises.

Overflow and degenerate facets:

- A facet projection or tolerance that is not finite raises `ValueError`, for example when a query-to-facet difference overflows.
- Only an omitted tolerance needs the inferred tolerance.
  An explicit `tolerance` returns labels also when the hull extent or `|q - p| @ |n|` overflows.
- `find_facet_reference_point_normal` divides each facet edge by its length before the rank test and the singular value decomposition.
  The rank test then measures the angles between the edges, so a valid facet with edge lengths 1e10 and 1e-10 is not degenerate.
- Facet centers and the hull center are computed as `sum(x / n)`, which stays finite for points near the float64 limit.

Linear-programming (LP) membership also supports segments, planes, and single-point hulls.
It tests whether nonnegative weights that sum to one can express each query as a convex combination.
LP membership scores are `-1` for feasible, `1` for infeasible, and `NaN` for another solver status.
A false membership label with `NaN` is inconclusive. It does not prove that the query is outside the hull.
With `hull_vertices_only=True`, each program uses only the hull vertices of full-dimensional generators, which describe the same convex set with fewer columns.
This option is off by default: it is faster, but a query within the solver tolerance of the boundary can change its label or its inconclusive status.

### Distances, boundary searches, and growth

Distance selection, boundary extraction, and path traversal estimate missing variances or covariance once from the pooled operation population.
Variance measures squared spread along one coordinate. Covariance measures how coordinates vary together.
Mahalanobis distance uses the inverse covariance to account for their joint variation.
Reusing those parameters keeps distance comparisons consistent across rows, blocks, and selection steps.

Validation of variance and covariance:

- A singular, nonfinite, or ill-conditioned estimate raises `ValueError` that names the metric.
  In that case, choose an explicit metric, such as `"euclidean"`.
  A singular matrix has an unresolved zero direction and no ordinary inverse.
- A covariance, and a supplied inverse covariance `VI`, must be finite and symmetric within `100 * spacing(max|matrix|)`.
- It must also have a Cholesky factorization, which exists exactly for a positive-definite matrix.
- Its reciprocal 1-norm condition number `1 / cond(matrix, 1)` must exceed `100 * eps`.
  A nonsingular but ill-conditioned covariance has an inverse with a large relative error.
  Distances along its weak direction would then be dominated by rounding.
- Supplied variance and inverse-covariance arrays must pass validation. The functions do not repair invalid parameters.

Parameter forwarding:

- Every distance function forwards the variance `V` only to `"seuclidean"` and the inverse covariance `VI` only to `"mahalanobis"`.
  Other metrics ignore them.
- A SciPy alias or `test_` form gets the preparation and the checks of its metric name.
  So `"se"`, `"s"`, and `"test_seuclidean"` use the pooled or supplied `V` of `"seuclidean"`.
  `"mahal"`, `"mah"`, and `"test_mahalanobis"` use the pooled or supplied `VI` of `"mahalanobis"`.
  The name reaches SciPy in the given spelling, because SciPy accepts `V` and `VI` under every spelling of their metric.
- `boundary_samples` can therefore accept one shared `distance_options` mapping for its default list of metrics.
- `designoptpy.core.regions.prepare_distance_metric` exposes the same pooled parameters to consumers that process one row or block at a time.

Distance functions:

- A distance function, also called a custom metric, is a callable `metric(first, second)` that follows the protocol `designoptpy.core.regions.DistanceFunction`.
  It receives two read-only float64 blocks `(n_first, d)` and `(n_second, d)` and returns their `(n_first, n_second)` finite nonnegative distances.
- `closest_points_with_different_labels`, `select_max_distance`, `sort_min_distance`, and `prepare_distance_metric` accept one as `metric`.
  `boundary_samples` accepts distance functions in `metrics`, alone or beside metric names, and returns the union of the selections.
- The selection rules do not change: nearest opposite-label rows with ties to the lower index, farthest-point picks, and the greedy path with the smallest longest segment.
- The function receives the coordinates after the optional normalization of `select_max_distance` and `sort_min_distance`.
- The selectors pass blocks of rows, and the block size is not part of the contract.
  Each entry must therefore depend only on its own two rows. A row-independent function gives the same selections for every block size.
- Bind extra settings with a closure or `functools.partial`. With a distance function, `distance_options` may hold only `V` and `VI`, which it ignores; any other key raises `ValueError`.
- A result of another shape raises `ValueError`. NaN, infinity, or a negative distance raises `DistanceMetricError`.
- A distance function covers metrics that have no SciPy name, such as a rank correlation distance.
  It also gives a metric its own meaning where the SciPy name differs, for example a `jaccard` distance over real values instead of the Boolean SciPy `"jaccard"`.
- Hit-and-run thinning (`HitAndRunOptions.thinning_distance_metric`) keeps metric names and pooled statistics; it accepts no distance function.

Distance rankings:

- Successful distance rankings use finite nonnegative distances.
- An undefined distance, such as a cosine distance to a zero vector, or an unrepresentable separation raises `DistanceMetricError`.
- The default `normalize_dimensions=True` translates and scales columns, which changes origin-sensitive geometry.
  For cosine distance, it can create a zero vector.
  Select `normalize_dimensions=False` when the original origin is meaningful.
- Rescale coordinates when their separation cannot be represented.

`sort_min_distance` builds paths by repeatedly visiting the nearest unvisited row, a greedy rule.

- It tries every row as a start by default and returns the path with the smallest maximum segment.
- `n_initial_points` tries only that many leading rows. It saves work and can give a worse path.
- The result is always a permutation of all rows, and the first segment distance is zero.
- Comparing starts improves the heuristic but does not guarantee a globally optimal path.

`region_limit_line_search` returns a sampled and refined bracket of different membership states along each bounded ray.

- The default `first_search="bracketing"` probes exponentially increasing steps before repeated interval halving, called bisection.
  The `"linear"` policy probes equally spaced steps. `"none"` probes only the box boundary before refinement.
- Bracketing starts at the box-boundary step divided by `2**min(max_iterations, 52)`.
  Smaller steps are not resolvable relative to the boundary step.
- Bisection stops early when every midpoint equals one of its endpoints, because no further halving can change a bracket.
- `initial_state` (default `None`) supplies the known criterion states of the initial points, one Boolean per ray.
  The search then makes no criterion call for them. A wrong state gives a wrong bracket.
- `batch_first_search=True` (default `False`) evaluates the whole first-search probe ladder in one criterion call.
  The probe steps and the brackets are the same; a default search makes at most 22 instead of 42 calls.
  The criterion must be row-independent. The ladder also evaluates probes after an early state change, so it evaluates more rows.
  If a ladder point is not finite, the search falls back to the sequential first search.
- A distance to a box face, a box-boundary step, or a ray point that is not finite raises `ValueError`.
  An example is a direction of 1e-320.
- The criterion receives only in-box points. Rounding can place a face point a few units in the last place outside the box,
  so the search clips each finite ray point to the inclusive box bounds before every criterion call.
  The clip changes only such rounded points. The hit-and-run sampler maps the points to physical coordinates, which rejects any
  point outside the box, so without the clip a region that reaches a box face stopped the chain.
- A nearest-boundary interpretation requires one membership transition along the ray.
  Multiple transitions or narrow intervals can fall between probes.
  No sampled change does not prove that no transition exists.

## Numerical differentiation

`designoptpy.core.numdiff.gradient` and `hessian` estimate derivatives of a sample-major callback by finite differences.
A finite difference combines responses at offset points, called a stencil, with fixed weights.
Returned tensors put output axes before derivative directions:

| Function | `values` shape |
| --- | --- |
| `gradient`, `gradient_from_function_values` | `(n_samples, n_outputs, n_dimensions)` |
| `hessian` | `(n_samples, n_outputs, n_dimensions, n_dimensions)` |

For one output, a gradient row holds the first derivatives with respect to the design coordinates.
For several outputs, these rows form a Jacobian, with one derivative row per output.
Each output's Hessian holds its second derivatives with respect to pairs of coordinates.
The `hessian` result also retains `gradient_values`.
Results also retain the evaluation points, function values, relative stencil points, and step sizes.
Set `retain_evaluation_trace=False` to return shaped empty evaluation-point and response matrices.
The derivative, step, and stencil evidence stays available.
Empty batches with a known output width keep these axes.
A design with no free dimensions has an empty derivative tensor with the required shape.
Declare an empty output width with an `(0, n_outputs)` matrix and the dimensions with an `(0, n_dimensions)` step matrix.
Every result reports `evaluations`, the number of rows sent to the function, also when the trace is not retained.

Three keyword controls decide which rows reach the function and in which calls.
Their defaults keep one call with every row and no limit.

- `max_evaluations` is a hard limit on the rows of the call, a nonnegative integer.
  The function compares the planned rows of the whole call with the limit before the first call.
  An excess raises `DerivativeBudgetExceededError`, a `ValueError` with `requested_rows` and `max_evaluations`, and no row is evaluated.
- `evaluation_batch_size` caps the rows of one call, a positive integer.
  The rows are cut in plan order into consecutive calls, so rows of different samples can share one call.
  The derivative does not change for a function that treats its rows independently.
  A function whose batch arithmetic differs at rounding level gives other last bits.
  The output groups and their widths must stay the same in every call.
- `base_value` is the known function value at the single design sample: one row, or a tuple with one row per output group.
  When the stencil has a nonzero weight at offset zero, the known value replaces the evaluation of the base row.
  For `f(x) = x0**2 + x1**2 + x2**2 + x0*x1` at `(1, 2, 3)`, the forward gradient stencil `(0, 1)` evaluates four rows without it and three with it,
  and the default Hessian evaluates nineteen rows without it and eighteen with it, with the same derivatives.
  The central gradient stencil `(-1, 0, 1)` has a zero weight at offset zero, so it lists no base row; the value is then only checked.
  The value must come from the same function at the same sample, which the function cannot verify.
  A replaced base row does not count in `max_evaluations` or `evaluations` and is not part of the trace.

A plan without rows, for example a sample whose coordinates are all fixed, still makes one call with zero rows, so the function declares its output widths.
The function or the `evaluation_adapter` can return a `FunctionEvaluation(values, metadata)`.
With the trace retained, `batch_metadata` keeps one read-only snapshot of the metadata of each call, in call order, and None for a call without metadata.
Coefficient recovery in `designoptpy.point` accepts the same record.

Both functions use relative steps by default (`use_relative_step_size=True`).
The physical step at a coordinate `x` is `h * max(abs(x), typical_x)`, the relative-step rule of Dennis and Schnabel, with `typical_x=1.0` by default.
`hessian` uses the default base step `h = 1e-4`.
`gradient` infers its default base step from its stencil as `epsilon**(1/m)`, where `epsilon` is float64 machine precision.
The degree `m` identifies the first uncancelled stencil moment beyond the reproduced polynomial degrees.
A stencil moment sums each weight times its offset raised to that degree.
For smooth functions, the truncation error of the first derivative scales as `h**(m-1)`.
Response rounding error grows roughly as `epsilon/h`.
Balancing these terms gives `h` proportional to `epsilon**(1/m)`.
The three-point centered stencil `(-1, 0, 1)` has `m=3` and a cube-root scale.
The two-point forward stencil `(0, 1)` has `m=2` and a square-root scale.
This heuristic omits unknown derivative magnitudes, response scale, and function noise.
It does not guarantee an accurate derivative or an optimal step.

A relative step keeps the perturbation proportional to the coordinate, so it stays representable at a large coordinate.
Below `typical_x`, the step stays `h * typical_x`, which can be a large relative change; set `typical_x` to the characteristic size of a small variable.
Tradeoff: for a function whose curvature does not grow with `x`, the relative step increases the truncation error at large `abs(x)`.
For example, the derivative of `sin` at `x = 1e3` has the error `3.4e-6` with the relative step and `3.6e-9` with the absolute step.
Set `typical_x` or `use_relative_step_size=False` for such coordinates.

A small absolute step can disappear or round substantially at a large coordinate.
Both functions check the stencil nodes `x + h * offsets` before they call the function:

- The nodes must be finite and distinct.
  Rounding may change each relative offset by at most `1e-6` of its size.
- The weights must satisfy their polynomial moment equations within `1e-6` of the summed term magnitudes.

The section "Supported numeric domain" states the resulting `ValueError` signals.
The checks detect loss from numeric representation.
They cannot certify derivatives from noisy or poorly scaled callbacks.
Every node with a nonzero weight is evaluated.
Only exactly zero weights are skipped, because a small weight at a far offset can carry polynomial exactness.

```python
from designoptpy.core.numdiff import gradient, hessian

linear = gradient(lambda rows: rows[:, 0] - 1e20, [[1e20]])
print(linear.values)  # [[[1.]]]

# This absolute binary step is exactly representable at the chosen large origin.
quadratic = hessian(
    lambda rows: (rows[:, 0] - 1e10) ** 2, [[1e10]], step_size=2**-10, use_relative_step_size=False
)
print(quadratic.values)  # [[[[2.]]]]
```

An absolute step fails for the first example, because `1e20 + h` rounds back to `1e20` for an ordinary `h`.
Alternatively, differentiate a function of a dimensionless coordinate and convert the derivatives with the declared physical scale.

`lower_bound` and `upper_bound` keep every evaluation point inside the domain of the callback.

- Each accepts `None` (unbounded), a scalar, or one value per dimension. The bounds must contain every design sample.
- Near a bound, the stencil of a coordinate shifts to the open side.
  Its step shrinks until every node fits, and its weights are recomputed for the shifted offsets.
- More precisely, when an end of the stencil crosses a bound, the whole stencil shifts to the side with more room.
  Ties use the upper side.
- In an interval narrower than the stencil, both ends can cross.
  A shift toward the upper side at the upper bound would then leave no room for the step.
- Equal bounds fix a coordinate. It gets no probes, a zero gradient entry, and a zero Hessian row and column.
- `relative_points` and `step_sizes` of the result describe the requested stencil. `evaluation_points` records the fitted nodes.
- `gradient_from_function_values` reuses unbounded results, whose sample blocks share one stencil layout.
The bounded point algorithms use their own nominal stencils by default.
Their `gradient_relative_points`, `hessian_relative_points`, and `jacobian_relative_points` options select these general stencils instead; see the
[point README](../designoptpy-point/README.md#finite-difference-derivatives).

`signal_derivative` differentiates a uniformly sampled signal with a centered stencil, shifted near either end.
Signal values must be finite and real; complex values raise `ValueError`.
At each sample, it subtracts that sample's value from its stencil values before weighting.
The weights sum to zero, so the exact result does not change, and a constant signal of `1e20` gives exact zeros.
A coordinate vector `t` must be uniform within the deviation that float64 rounding can explain:
every interval must match the first one within `min(10 * spacing(max(max(abs(t)), 1)), 1e-6 * (t[1] - t[0]))`.
For example, `[0, 1, 2 + 1e-8]` raises `ValueError`.
For timestamps stored more coarsely, for example rounded to milliseconds, pass the nominal scalar step instead.

## Sampling, grids, integration, and signals

Each random sampler requires the keyword `rng`: a NumPy `Generator`, an integer seed, or `None`.
`numpy.random.default_rng` converts it.
A Generator is used directly, an integer seed creates a new seeded generator, and `None` draws fresh operating-system entropy.
Each generator retains state that determines later draws. Reusing its initial state reproduces its draws.

`designoptpy.core.sampling` provides random, full-factorial, Latin-hypercube, and hit-and-run samplers.
[sampling_methods.py](../../examples/simple_examples/sampling_methods.py), [runge_kutta_oscillator.py](../../examples/simple_examples/runge_kutta_oscillator.py), and [signal_filtering.py](../../examples/simple_examples/signal_filtering.py) are short lessons for the samplers, the Runge-Kutta integrator, and the signal filters of this section.

### Latin-hypercube sampling

- Latin-hypercube sampling uses SciPy optimization and candidate ranking.
- Each coordinate initially places one sample in each marginal interval, called a stratum.
- Randomized coordinate descent (`random-cd`) preserves those strata.
  Lloyd optimization and feasibility rejection can remove the Latin property of the final design.

Replaying a Latin-hypercube design:

- The Latin-hypercube sampler of SciPy does not draw from the supplied generator itself.
  It spawns a child generator from the seed sequence of the generator.
  This changes the spawn count but not `rng.bit_generator.state`.
- Restoring only the bit state therefore does not replay a Latin-hypercube design.
  Pass a full copy of the generator made before the call with `copy_generator(rng)`, or pass the same integer seed again.
- `copy_generator` copies the seed sequence and the bit state with every supported NumPy version.
  `copy.deepcopy(rng)` keeps the seed sequence only with NumPy 2.0 and later.
  NumPy 1.26 gives the copy a new seed sequence.
- Some generators have no seed sequence.
  Examples are a Philox built with an explicit key, such as `Generator(Philox(key=42))`, and an MT19937 from legacy `RandomState` seeding.
  They cannot spawn children, so a Latin-hypercube call raises an error for them.
  `copy_generator` gives their copies no seed sequence too, so a copy fails in the same way and never spawns from fresh entropy.
- Another seed source, such as a user-defined `ISeedSequence`, makes `copy_generator` raise `TypeError`.

### Work limits of rejection and chain sampling

- Rejection sampling with `random_sample` and `latin_hypercube_sample` draws batches until the region criterion accepts `n_sample` rows.
- `max_iterations` bounds the batch count.
  It bounds the criterion evaluations only in multiples of `n_sample`.
- The optional `max_proposals` bounds the proposed rows, and so the criterion evaluations, exactly.
  Each batch draws `min(n_sample, max_proposals - proposed)` rows.
  A spent budget raises `RuntimeError` with the message `proposal limit reached`.
  The default `None` sets no limit.
- `random_sample(..., adaptive_batch_size=True)` keeps the first batch and sizes each later batch by the remaining need:
  `ceil(need * proposed / accepted)` rows at most `n_sample`, or `n_sample` before the first acceptance.
  The criterion then evaluates fewer unused rows at high acceptance. The returned rows stay the same for a criterion that labels each row on its own.
  A passed Generator ends in another state, and more batches can be needed, so `max_iterations` can stop earlier. The default is `False`.
- `HitAndRunOptions.max_steps` is a hard chain-step budget.
  `point_hit_and_run_sample` raises `ValueError` before the chain starts when `burn_in_steps + n_sample * thinning_steps` exceeds it.

`compute_design_space_grid_value` evaluates a callback on a structured grid with one to three free dimensions.
NaN entries of `fixed_variables` mark free dimensions; finite entries fix the others.
Single-point design grids and initialization scans use the interval midpoint.
One `role` selects the callback convention:

| `role` | Accepted callback result |
| --- | --- |
| `"scalar"` (default) | One scalar output |
| `"objective"` | Values, or `(values, metadata)` |
| `"constraint"` | Inequalities, or `(inequalities, equalities[, metadata])` |

Constraint results always contain an inequality grid and an equality grid.
An absent equality-constraint output keeps its coordinates without inventing equality values.
`callback_options` supplies keyword arguments in every role.

`integrate_runge_kutta` integrates an ordinary differential equation (ODE) over the supplied time points.
`RungeKuttaMethod` selects forward Euler, Heun, midpoint, third-order, fourth-order, 3/8-rule, or fixed-step Dormand-Prince coefficients.
Integration uses the supplied time intervals and an explicit Runge–Kutta coefficient table, without adaptive error control.
The Dormand-Prince method therefore uses its fifth-order weights on the supplied steps and does not adapt the step size.

- For a single-time state query, `integrate_runge_kutta` returns the initial state without calling the derivative.
  To request validated auxiliary data at that time, set `evaluate_auxiliary_outputs=True`.
- For multiple times, the default `None` collects available auxiliary outputs and requires consistent output presence and shape.
  The value `False` returns states alone.
- Every supported tableau starts each interval with a stage at the stored state and time (`c[0] = 0`, zero first row of `A`).
  By default (`reuse_first_stage_outputs=True`), the auxiliary output at a stored time comes from that stage,
  and the function is called only once more, at the last time.
  `reuse_first_stage_outputs=False` instead runs a separate pass that calls the function once per stored time.
  With `n` times and `s` stages, the reuse needs `(n - 1) * s + 1` calls instead of `(n - 1) * s + n`.
  The reuse assumes a deterministic function that treats `-0.0` and `+0.0` alike and does not depend on the type of the time.
  For such a function, the outputs are the same, but the call order and the error order differ.
  The first stage passes `y + 0.0` and `t + 0.0 * h`, so a stored `-0.0` in the state or the time arrives as `+0.0`.
  The time also arrives as a NumPy float instead of a Python float.
  Set `False` for a function that can change between calls, distinguishes signed zero, or depends on the time type.
- Each stage state and the final update scale every tableau coefficient by the step `h` before it weights a stage derivative.
  Partial sums then stay near the size of the state change, so a large derivative over a short interval does not overflow.

`designoptpy.core.signal` provides a first-order low-pass filter, a low-pass filtered derivative, and Spencer smoothing.

Time constant:

- With the default `time_constant_policy="clamp"`, both filters use the time constant `max(filter_time_constant, largest sample interval)`.
  A smaller requested value therefore has no effect.
- The clamp keeps the weight of the previous output nonnegative.
  It so prevents a homogeneous transient that alternates sign from sample to sample.
  A homogeneous transient is the part of the output set by the initial value.
  For a constant input, such a transient makes the output alternate around the input.
- The trapezoidal recurrence is stable for every positive time constant. The clamp does not serve stability.
- `time_constant_policy="error"` raises `ValueError` instead of changing the requested constant.

Start and continuation:

- `initial_value` (low-pass filter) and `initial_derivative` (derivative filter) replace the default start.
  The default start is the first signal value, or the derivative of the polynomial through the first samples.
  That startup derivative subtracts the first sample value before its weights apply, so a large constant offset does not distort it.
- `return_state=True` also returns a `FilterState` with the last output, signal value, time, and effective time constant.
- Pass the state as `continuation` to filter the next chunk of the same signal.
  The call continues from the saved sample and keeps the saved time constant.
  A continued interval larger than that constant raises `ValueError`.

Spencer smoothing preserves the first and last three values, including at the minimum supported length of nine.
Its interior weights and polynomial edge filters smooth the remaining signal.

## Records, files, and plots

Public result and option records hold independent, read-only snapshots of their arrays and nested containers.
These records are immutable: ordinary code cannot change them after construction.
`snapshot_value` applies the same copy rule for other consumers.
Arrays become read-only copies, mappings become read-only mappings, sequences become tuples, and sets become frozensets.
Copying nested containers recursively is deep copying. Other objects, such as supplied functions, keep their identity.
Record equality compares the same concrete record type field by field, with exact array shapes and contents.
Corresponding NaNs compare equal as unavailable markers; equality uses no numerical tolerance.
Fields declared opaque keep the caller's object and compare by identity.
These records are unhashable: they cannot be dictionary keys or set members.
Pickle round trips restore the read-only snapshots.
A saved function reference does not prove that later imported code has the same behavior.
Closures and external handles are not portable. Archive values and their provenance explicitly.

### Input limits

`InputLimits` limits untrusted file input: file bytes, ZIP archive members and expansion, table extents, text length, and spreadsheet literals.

- Workbook readers, the spreadsheet literal parser, and the `designoptpy.sso` batch-table reader take one `InputLimits` object.
- Each reader applies the given limits as they are, including limits raised above the defaults.
- A reader rejects input that exceeds a limit before it creates the related data.
- These limits are input-security validation of untrusted files, not resource caps on the work.
  The readers keep them deliberately, because they parse untrusted files with OpenPyXL, python-calamine, and `defusedxml`.
- The spreadsheet literal parser reads data values only, with its documented grammar.
  It never calls `eval`, so it runs no expression. Do not replace it with `eval`.
- Numerical and plotting functions take no input limits.
  Their method options, such as sample counts, iteration budgets, and grid sizes, set their work.

An Excel workbook is a ZIP archive of Extensible Markup Language (XML) files.
The `io` extra, an optional dependency group, installs OpenPyXL, python-calamine, and `defusedxml`.
A workbook reader works in these steps:

1. It checks the file size and the ZIP member metadata.
2. It parses the workbook, shared-string, and worksheet XML with `defusedxml` to check text lengths and cell extents.
3. Only then does OpenPyXL load the workbook, in read-only mode.

An OpenDocument spreadsheet (`.ods`, in any letter case) is a ZIP archive too, with the members `mimetype`, `META-INF/manifest.xml`, `content.xml`, and the optional `styles.xml`.
Its format compresses repetition: one row or cell element can stand for many rows or cells, so a short file can describe a very large grid.
`load_opendocument_workbook` and `preflight_opendocument_worksheets` work in these steps:

1. They read the file once, bounded by `maximum_file_bytes`, so the checks and the parser see the same bytes.
2. They check the ZIP member metadata, the exact media type `application/vnd.oasis.opendocument.spreadsheet` in `mimetype`, the members `META-INF/manifest.xml` and `content.xml`, and that the manifest declares no encryption.
3. They stream `content.xml` with `defusedxml`, without a document type declaration. The scan counts every repeated row and cell position, applies `maximum_rows`, `maximum_columns`, and `maximum_cells` per sheet and the sum of the sheet rectangles against `maximum_cells`, and bounds each cell text by `maximum_string_length` and all text, counted once per repeated position, by `maximum_archive_expanded_bytes`.
   A value beyond row 1,048,576 or column 16,384 fails, because the parser would drop it without an error.
4. Only then does python-calamine parse the bytes. It builds every sheet at once, which is why the preflight bounds every sheet.

python-calamine 0.9.1 bundles calamine 0.37.0, the parser of DesignOptRs, so both implementations parse a file with the same code.
`OpenDocumentWorkbook`, `OpenDocumentWorksheet`, and `OpenDocumentCell` give the parsed cells the OpenPyXL type codes, so an error result (`calcext:value-type="error"`) is an error cell and a date is a date cell.
`WorksheetXMLInfo.error_coordinates` lists the error cells of both formats.
Formulas are not recalculated: a formula cell gives the result that the program saved.
`.ots` templates, flat `.fods` files, and the legacy `.xls` and `.xlsb` formats are not read.

The limits reduce accidental or hostile resource exhaustion. They do not sandbox code.
Treat a larger limit as a trusted-workload decision.
Understand the data and the expected work before you raise one.

### Workbook model data

`read_workbook_model_data` reads a one- or two-sheet `.xlsx` or `.ods` workbook and returns a `WorkbookModelData` record with the design and measure matrices and their column names.
Empty, unparseable, and complex cells become NaN, and numeric text such as `"inf"` becomes an infinity.
The matrices keep these values for inspection.
Five read-only properties report the data rows with a nonfinite value (NaN or an infinity):

- `invalid_design_rows` and `invalid_measure_rows`: the rows with at least one nonfinite design or measure value.
- `complete_rows`: the rows that are finite in every design and every measure column.
- `invalid_design_rows_by_column` and `invalid_measure_rows_by_column`: one array per column, in name order, with the nonfinite rows of that column.

Each array holds ascending zero-based data-row indices of type `int64`.
Index 0 is the first row after the header row, when there is one.
A model fit keeps only complete rows, because a nonfinite value leaves a design or its response undefined.
This rule is complete-case filtering, so `complete_rows` tells before a fit which rows the fit will use.
The per-column lists locate the cells to correct in the workbook.

### Staged output files

`designoptpy.core.io.staged_output_files` writes outputs to temporary sibling files.
A normal exit from its `with` block replaces every destination. An exception leaves the prior files untouched.
A context manager controls setup and cleanup for a Python `with` block.

- It backs up existing files first and restores prior bytes if a handled replacement fails.
- It rejects overlapping paths, directories, and symbolic-link destinations.
- If recovery also fails, an exception group lists the retained backups for manual recovery.
- The contract does not provide process-crash recovery, reader isolation, or locks.
- Each replacement goes through `designoptpy.core.io.rename_staged`, which the run archive, the X-Ray exports, and the animation export also use.
  Windows refuses a rename while another process, such as a virus scanner or the search indexer, briefly holds a staged file open.
  On Windows, the function therefore retries a rename that fails with the access-denied error (5) or the sharing violation (32).
  It waits 10, 20, 40, 80, 160, 320, 640, and 640 ms (1.91 s in all), and then it raises the error of the last attempt unchanged.
  On other systems, and for other errors, it makes one attempt.

### Figure export

`save_figure`, `save_print_figure`, and `save_gif_video_3d_azimuth_rotation` use this contract for their output sets.

- Caller-supplied figures remain open.
- After a failed export, `save_print_figure` restores changed, readable, settable figure properties.
  It restores the resolution before the physical size.
  Layout aliases restore the saved engine and its settings.
  It does not store a graphical window position, so supported window movement can remain.
- Rotation export restores the original camera view.
  Its GIF writer writes each frame before it captures the next one, so memory does not grow with the frame count.
- The `savefig_options` of Matplotlib override basic export defaults, including dots per inch (DPI) and the bounding box (`"bbox_inches"`).
- `save_figure` and `save_print_figure` save the whole figure canvas by default, so an image has the size and the shape of the figure.
  A global `rcParams["savefig.bbox"] = "tight"` does not change that; only an explicit `savefig_options["bbox_inches"]` does.
  `crop=True` cuts each image to the drawn content plus the margin `rcParams["savefig.pad_inches"]` (a tight bounding box).
  A cropped image keeps artists that reach past the canvas and loses its empty margins, but it no longer has the shape of the figure.
  EPS output of `save_print_figure` follows `eps_bounding_box` instead: `"tight"` (default) crops, and `"loose"` keeps the whole figure.
- The export functions write portable formats and change no global graphics defaults.
- `save_print_figure` offers the controls that Matplotlib implements: format, DPI, bounding box, and EPS paper type and orientation.
  Matplotlib has no control for the renderer, the EPS language level, an EPS preview, the EPS color space, or black-and-white EPS output.
- `set_figure_size` takes inches, centimeters, millimeters, points, or pixels. `size=None` keeps the size.
  Units relative to the screen are not supported.
- `save_gif_video_3d_azimuth_rotation` takes `gif_options` with three keys: `loop` (an integer from 0 to 65535; 0 loops forever),
  `duration` (the frame delay in milliseconds, at most 655350), and `comment` (text or bytes). Other keys raise `ValueError`.

#### Resolution

The save functions write raster images (PNG, JPEG, TIFF) with `RASTER_DPI = 200` pixels per inch of figure size.
`save_figure` uses it as its `dpi` default, and `save_print_figure` uses it for `resolution=None`; `resolution=0` keeps the figure DPI.
A full-width figure (6.4 inches) is therefore 1280 pixels wide, and a single-column figure (3.4 inches) 680 pixels wide.
Text, lines, and markers have sizes in points (1/72 inch), so the resolution changes only the sharpness, not the layout.
Vector files (PDF, SVG, EPS) have no resolution.
The SSO and point plotting functions save through `save_figure`, so they use the same resolution.
Animation frames (`AnimationOptions.dpi` of the point views) and GIF rotations keep their own resolution settings.
Tradeoff: a 200-DPI PNG file is about 2.3 times the bytes of a 100-DPI file and takes about 80 ms more to write.

#### Figure shapes

`figure_size(shape, column="full")` returns the width and height in inches of three shapes at the two print widths (`COLUMN_LAYOUTS`):

| Shape | Full width (inches) | Single column (inches) | Use |
| --- | --- | --- | --- |
| `"landscape"` | 6.4 by 3.955 | 3.4 by 2.101 | histories over the iterations, bar charts, fits; the default of `figure_style` |
| `"square"` | 4.8 by 4.8 | 3.4 by 3.4 | three-dimensional views, two-dimensional views with equal axis scales |
| `"portrait"` | 5.253 by 8.5 | 3.4 by 5.501 | tall content in one column, such as three stacked summaries |

A landscape is the golden ratio `GOLDEN_RATIO` = (1 + sqrt(5)) / 2 = 1.6180339887 times wider than high; a portrait is that ratio times higher than wide.
A square is at most `SQUARE_SIDE_LIMIT` = 4.8 inches, and a portrait at most `PORTRAIT_HEIGHT_LIMIT` = 8.5 inches high, so a figure and its caption fit a page column and a screen.
The shape applies to the saved image: legends and captions take their room inside the frame, and the axes get the rest.
The save functions keep the whole canvas, so at 200 DPI a full-width landscape is 1280 by 791 pixels, a square 960 by 960 pixels, and a portrait 1050 by 1700 pixels
(Matplotlib truncates the pixel size to an integer).
A legend wider than the figure is cut at the canvas edge, so a square figure gives its legend fewer columns than a landscape.
A three-dimensional axes keeps a fixed box aspect, and an equal-scale axes the aspect of its data; in a wide frame both leave empty sides, so they get the square.
Figures whose size follows their panel count or a physical aspect keep their own sizes: projection matrices, tile grids, side-by-side comparisons,
histories with three or more stacked rows (a height per row), truss drawings, and rotation frames.
Tradeoff: a golden landscape is about 18 % lower than the former 6.4 by 4.8 inch default, so its data area is shorter.
A one-column landscape is only 2.1 inches high, so a view whose legend and caption need several lines can keep a fixed axes height and grow instead; the SSO metric views do so at one column.
At the full width, the same axes height of 1.92 inches is their floor: an SSO metric view whose legend and caption would leave a lower axes grows to keep it.

#### Editable figure files

`save_figure` and `save_print_figure` also write `<name>.pickle.gz` next to the images (the format name `"pickle"`).
The file holds the whole Matplotlib figure, stored with Python's object serialization (a pickle) and compressed with gzip.
`load_figure(path)` opens it again as a live figure, registered with pyplot as the current figure:

```python
import matplotlib.pyplot as plt
from designoptpy.core.plotting import figure_style, load_figure

figure = load_figure("RESULTS/tutorial_02_box_solution_space/<timestamp>/sphere_box.pickle.gz")
figure.axes[0].view_init(elev=20, azim=45)  # rotate a three-dimensional view
with plt.rc_context(figure_style()):  # the settings that drew the figure
    plt.show()  # the mouse can rotate, zoom, and pan; every property can change
```

- `pickle_file=False` leaves the file out; the format name `"pickle"` in `formats` (or `print_format`) writes it also then.
  The SSO and point save options accept the entry `"pickle_file": False` for the same purpose.
- A figure that cannot be pickled gives a `UserWarning` that starts with "Figure file not written" and names the file and the cause.
  The images are still written. The usual cause is a local function (a `lambda`, or a function defined inside another function) in a tick formatter or a secondary axis:
  Python stores a function by its import name, and a local function has none. Use a module-level function, `functools.partial` of one, or a Matplotlib formatter class instead.
- Load only files that you made or trust: loading a pickle can run any code that the file asks for.
- Loading needs DesignOptPy and the same Matplotlib version. The file stores the Matplotlib version, and `load_figure` warns when it differs from the installed one.
  Matplotlib does not support figures pickled by another version, so these files are not for long-term storage; keep the data and the plotting script for that.
- Event callbacks (connected mouse handlers, slider widgets) are not stored. Animations are not figures and are not stored.
- Matplotlib creates some artists, such as the tick labels of three-dimensional axes, each time a figure draws, with the settings active then.
  Draw or save a reloaded figure inside `plt.rc_context(figure_style())` to reproduce it exactly; outside, those labels take the default font.
- Size and time: about 25 KB for a typical two-dimensional figure and up to several megabytes for a dense three-dimensional surface; about 10 ms to write.

DesignOptRs has no Matplotlib, so it has no counterpart of these files.
Its SVG files are vector drawings that a vector editor can change, and its azimuth frame sequences and redraw commands cover rotation and re-plotting.

### Run archives

Not yet in DesignOptRs: the DesignOptRs counterpart is incomplete (file archiving and console capture are lesson code in designopt-examples, no library component). This contract can change in DesignOptPy alone.
`RunArchive` creates a unique results folder below `root/RESULTS`, copies selected input files, and can capture console output.

- Pass `results_folder=path` for a direct destination: `path/folder_name/timestamp`.
- An example can enable this option without copying source files by leaving `archive_files` empty.
- `RESULTS` and its category folder must be ordinary directories below the resolved root.
  A symbolic link or Windows junction at either level raises `ValueError` before anything is written through it.
  A reparse point is a Windows filesystem redirection. A junction is one kind, which redirects a folder path.
- Archive requests are relative paths resolved inside the search roots. Links that leave a root are rejected.
- An archive update also rejects destination collisions and any link or Windows reparse point inside the archived `Files` tree.
- A file lock in the run folder lets only one process at a time replace the archived files of one run.
- Console capture replaces the standard output and standard error of the whole process, so captures run one at a time.
- Create archives below a trusted directory with access controls.
- An active instance cannot be entered again. After exit, the instance can be reused.

### Run results files

Not yet in DesignOptRs: the DesignOptRs counterpart is incomplete (lesson code in designopt-examples, no library component). This contract can change in DesignOptPy alone.
`write_run_results(folder, *, run_name, elapsed_seconds, settings, results)` writes the settings and the numerical outcomes of a run into `Results.json` (`RUN_RESULTS_FILE`) in an existing run folder.
`read_run_results(path, *, input_limits=None)` reads such a file back.

The file is one strict JSON object (RFC 8259) in UTF-8, with two-space indentation, sorted keys, and one final newline.
Its envelope has six keys:

| Key | Value |
| --- | --- |
| `schema` | `"designopt.run-results/1"` (`RUN_RESULTS_SCHEMA`) |
| `run_name` | the script stem, which is also the name of the run-folder parent |
| `implementation` | the implementation that wrote the file, `"DesignOptPy"` |
| `elapsed_seconds` | the finite, nonnegative run time up to the write |
| `settings` | an object with the settings of the run |
| `results` | an object with the results of the run |

Value encoding:

- Booleans, integers, floats, and text are JSON values. An integer is written without a fraction and a float with a fraction or an exponent, so a reader keeps counts and measures apart.
- Mappings with text keys become objects. Lists, tuples, and NumPy arrays of Boolean, integer, or floating type become nested lists in row-major order. NumPy scalars become the matching JSON value.
- An enumeration member is written as its value, for example `RequirementSpace.OMEGA_2` as `"Omega2"`.
- JSON has no NaN, no infinity, and no marker for a missing value. A tag replaces them:
  `None` (unavailable) becomes `{"state": "unavailable"}`, and NaN, positive infinity, and negative infinity become
  `{"state": "nonfinite", "value": "nan"}`, `"positive_infinity"`, or `"negative_infinity"`.
  A tag keeps a NaN apart from an unavailable value, and an unavailable value never reads as zero.
- The key `state` is reserved for the two tags. A mapping with this key raises `ValueError`.
- Any other value, such as a `Box`, an evaluator, or a figure, raises `TypeError` with its key path, for example
  `run results value at results.sphere.box has unsupported type Box`.
  The file never holds a placeholder for an object without a JSON form. Write the numbers of such an object instead, for example the box bounds.

The writer builds the whole document before it writes, so a rejected value creates no file.
It then writes a temporary file beside the results file and replaces the results file with it, through `staged_output_files`.
`file_name` (default `RUN_RESULTS_FILE`, `Results.json`) names another results file of the same run folder, for example a checkpoint `checkpoint-product-1.json`.
It must be a plain `.json` file name with a nonempty stem and without `/`, `\`, or `:`; otherwise `ValueError` is raised before any file exists.
On Windows, a colon starts a drive prefix: `D:x.json` names a file in the current folder of drive D, outside the run folder. The rule is the same on every system.
A second write therefore replaces the file atomically, and a failed write keeps the previous file.
The file records no absolute path and no source text.

The reader checks the file size against `maximum_file_bytes` of its `InputLimits` before it reads.
It rejects the bare tokens `NaN`, `Infinity`, and `-Infinity`, a JSON `null`, an unknown tag, another schema, and a missing envelope key with `ValueError`.
It also rejects a number outside the float64 range, such as `1e999`, which would otherwise read as infinity: the format holds an infinity only as a tag.
It returns the document with each tag decoded: `None` for unavailable, and NaN or an infinity for a nonfinite tag.
Arrays stay nested lists; convert them with `numpy.asarray`.

```python
import numpy as np
from designoptpy.core.io import read_run_results, write_run_results

path = write_run_results(
    run_folder,  # an existing folder, for example RunArchive.path
    run_name="tutorial_02_box_solution_space",
    elapsed_seconds=4.2,
    settings={"seed": 7, "limit": None},
    results={"volume": 215.27, "widths": np.array([5.9, np.nan])},
)
document = read_run_results(path)
```

The file then holds:

```json
{
  "elapsed_seconds": 4.2,
  "implementation": "DesignOptPy",
  "results": {
    "volume": 215.27,
    "widths": [5.9, {"state": "nonfinite", "value": "nan"}]
  },
  "run_name": "tutorial_02_box_solution_space",
  "schema": "designopt.run-results/1",
  "settings": {"limit": {"state": "unavailable"}, "seed": 7}
}
```

The writer indents every nested value on its own line; this listing is compact.

### Plotting helpers

Importing `designoptpy.core.plotting` loads none of its submodules.
Each public name loads its defining submodule on first access; this is a lazy import.
Color conversion and level-set extraction therefore do not import the Matplotlib figure, animation, and three-dimensional axes modules.
A color name, a resampled color map, and every figure function load Matplotlib or SciPy when they first need it.

`format_figure_text` sets the text sizes and the text markup of one figure.
`interpreter="tex"` (default) draws text between `$` signs with Matplotlib math text.
`"latex"` typesets all text with an external LaTeX installation (Matplotlib `usetex`; raster output also needs `dvipng`).
`"none"` shows every character literally.

`designoptpy.core.plotting.marching_tetrahedra(first, second, third, scores, level)` returns the triangles of a level set of a three-dimensional grid score, and `crosses_level(scores, level)` tests whether the grid scores reach the level.
Marching tetrahedra splits each grid cube into six tetrahedra and interpolates linearly along the edges that cross the level.
The triangles therefore lie exactly on the plane of an affine score.
The surrogate boundary plots and the SSO candidate-region plots share these functions.

`colormap_viridis` and `colormap_cmocean` return ordered red, green, and blue (RGB) rows with shape `(n_levels, 3)`, normalized to [0, 1].
Both preserve the source table when `number_levels=None` and use linear interpolation by default for requested levels.
Their function help lists constant, polynomial, and slope-based interpolation choices and the accepted SciPy options.
Higher-order interpolation can exceed the channel range; the result clips each channel to [0, 1].
`colormap_cmocean(invert=True)` uses its dedicated inverted palette data from the optional cmocean package.
Paul Tol's nightfall and iridescent intermediate colors follow his
[Figure 14 and Figure 20 definitions](https://sronpersonalpages.nl/~pault/).
[color_gallery.py](../../examples/simple_examples/color_gallery.py) draws every palette and colormap of this section and the role colors and colormaps of the figure style.

## Supported numeric domain

The supported numeric domain is ordinary engineering magnitudes in double precision.
The functions below use their plain formulas. They do not rescale sums, products, or differences that leave the float64 range.
Outside the domain, a local check raises `ValueError` that names the quantity.
A normal float64 number is finite and at least about 2.2e-308 in magnitude.
A subnormal number is smaller and has fewer significant bits.

- Finite differences in [`numdiff.py`](src/designoptpy/core/numdiff.py) divide a weighted response sum by the step once per derivative order.
  A gradient divides by `h`, a Hessian diagonal by `h` and then `h`, a mixed Hessian entry by the smaller and then the larger step, and a k-th signal derivative k times by `h`.
  No step product such as `h*h` is formed, so a step whose square is subnormal or overflows stays usable.
  Stencil nodes that are not finite and distinct, or whose rounding changes a relative offset by more than `1e-6` of its size, raise before the function is called.
  That error names `step_size`.
  The weights of a fitted stencil that miss their polynomial moment equations raise before the call and name `relative_points`.
  A fixed coordinate fits no stencil, so a call whose coordinates are all fixed checks no weights and returns zero derivatives.
  A derivative that is not finite raises and names its sample, output, and dimensions.
  Derivative weights sum to zero, so each weighted sum first subtracts one stencil response: the first response of a gradient or Hessian stencil (the base response when the stencil uses offset zero), or the value at the derivative sample of a signal.
  This keeps a large constant response offset out of the sum and reduces cancellation error.
- `low_pass_filter_first_order` and `derivative_with_low_pass_filter` in [`signal.py`](src/designoptpy/core/signal.py) use the ratio `(h / tau) / 2`, which never forms the product `2 * tau`.
  `spencer_smoothing` applies the predivided weight vectors to the individual samples.
  A filtered value, filtered derivative, or smoothed value that is not finite raises and names its sample.
- Ellipsoid membership in [`ellipsoid.py`](src/designoptpy/core/geometry/ellipsoid.py) uses `sum(((x - center) @ rotation / semi_axes)**2)`.
  A squared normalized radius that is not finite raises and names its sample.
  `quadratic_form` raises when an inverse squared semi-axis underflows to zero or the matrix is not finite.
- `measure_to_deficit` uses `(lower_limit - measure) / factor` and `(measure - upper_limit) / factor`.
  A deficit that is not finite for a finite measure and a finite active limit raises.
  Conversion skips inactive limits before subtraction, so matching infinities cannot produce NaN.
- `convert_base10hexcode_to_rgb` divides each channel by `16**number_digits - 1`.
  A channel width above 255 hexadecimal digits makes this scale infinite and raises.
- Classification ratios divide plain count sums. For example, precision is the true-positive count divided by the sum of true-positive and false-positive counts.
  These count ratios return `NaN` when their denominator is zero.
  A count sum that is not finite raises `ValueError` that names the metric.
  The Matthews correlation of `classification_evaluation_metrics` divides each count root by a marginal root before it multiplies, so every factor lies in `[0, 1]`: weighted counts cannot overflow, and a tiny count such as `1e-308` beside a huge count still gives the correlation 1 for a perfect prediction.
- Facet classification in [`convex_hull.py`](src/designoptpy/core/geometry/convex_hull.py) uses the plain difference `q - p` and its dot product with the facet normal.
  A facet projection that is not finite raises and names its facet and query row.
  With an omitted tolerance, a rounding tolerance that is not finite raises with its own message; an explicit tolerance does not form it.
  Each facet edge is divided by its largest entry before its Euclidean norm, so edge lengths such as 1e200 and 1e-200 give unit directions.
  An edge that is zero or not finite raises as a degenerate facet.
- `compute_affine_rank` in [`convex_hull.py`](src/designoptpy/core/geometry/convex_hull.py) uses the plain offsets `x_i - x_0`, or the length `max - min` for one coordinate.
  An offset, a length, or a singular value that is not finite gives `None`, the unavailable rank, never a rank that is too low.
  For example, the row `(0, 0)`, ten rows `(8e307, 0)`, and the row `(0, 8e307)` have finite offsets, but their first singular value exceeds the float64 range.
  `convex_hull` raises `ValueError` for an unavailable rank and names the float64 range in the message.
- `region_limit_line_search` in [`regions.py`](src/designoptpy/core/regions.py) uses the plain face distances and the quotient by the direction.
  A face distance on a nonzero direction component, a box-boundary step, or a ray point that is not finite raises.

`Box.interpolate`, `Box.unit_coordinates`, `grow_box`, `box_measure`, and the default violation norm keep the scale-aware forms described above.
These box forms accept every finite box, also when `upper - lower` overflows; box measures are range-safe because a high-dimensional volume leaves the float64 range for ordinary widths.
A unit coordinate that is not finite, for a point far outside its box, raises and names its sample and dimension.
`points_in_box` and `Box.classify` use unit coordinates, so they raise for such a point too.
`Box.contains` and `bounding_boxes` compare coordinates only, so they accept such a point.
`Box.measure` raises when the final product exceeds the float64 range. `box_measure` returns `inf` then, and zero for a positive final product below the range.
`Box.lengths` returns an infinite side length when `upper - lower` overflows.
