Metadata-Version: 2.4
Name: designoptrs
Version: 0.1.0
Requires-Dist: numpy>=2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
License-File: NOTICE
Summary: DesignOptRs native numerical workflows with checked NumPy interfaces
Author: Eduardo Rodrigues Della Noce
License-Expression: MIT OR Apache-2.0
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# Native Python interfaces

`designoptrs` is the Python interface of DesignOptRs. It exposes native Rust numerical workflows through NumPy arrays.
Import the package as `designoptrs`. This package is independent of DesignOptPy, the Python implementation.
It does not replace DesignOptPy or claim parity with it.

## Build

Use the existing Rust compiler described in `../PORTING.md`.
Create an isolated Python environment. Install `maturin` and `numpy` there.
Run `maturin develop --manifest-path crates/designopt-python/Cargo.toml --features python`
from `designoptrs`. Use `maturin build` to create an installable wheel.
Both commands build the optimized release profile by default, because `pyproject.toml` sets `profile = "release"`.
Every native computation that Python calls runs in this extension, so the optimized build is the one to use for real work.
Add `--profile dev` for a faster, unoptimized build while you change the bindings.
Numerical calls in that build run many times slower.

For a build that runs only on the computer that builds it, set `RUSTFLAGS` to `-C target-cpu=native` before the build.
The compiler can then use every vector instruction of that processor, which can speed up element-wise loops.
The wheel does not run on processors without those instructions, so do not distribute it.
Floating-point results can differ in rounding from the portable build, so seeded results can differ in the last digits.

The extension requires PyO3 0.30 and rust-numpy 0.30.
The guides describe current source interfaces. Changed source remains under coordinated qualification.
The numerical crates remain independent of Python.
`box_volumes(lower, upper, factors=1.0)` measures one finite ordered box per row.
Bounds have equal `(box_count, dimension)` shapes with positive dimension; zero rows are valid.
Factors are a finite nonnegative scalar, one-entry vector, or one value per row.
Supplied factors receive validation even for empty batches.
Strided inputs use the checked real-array extractor. Complex, object, string, and Boolean scalar inputs fail.
Boolean arrays retain the existing numeric-array policy.
The low-level result can be positive infinity after final overflow, or subnormal/zero after underflow.
Each row uses the native scalar volume kernel and its coordinate multiplication order.
The `designopt-python` crate enables bindings only with its `python` feature.
That feature also enables the `gif-export` feature of `designopt-plotting`, so `write_gif` can render SVG frames with
`resvg` and encode them with the `gif` crate. This costs build time and wheel size; no other feature is needed.

## Interface guides

The continuation adds native workflows through the same checked NumPy boundary.
The following guides define inputs, result evidence, callback protocols, and numerical limits.

- [Core plans, filters, integration outputs, and distances](CORE_INTERFACES.md).
- [Sample evaluation, grids, mappings, and sampling](CORE_MODEL_INTERFACES.md).
- [Point, constrained, population, and programming workflows](OPTIMIZATION_INTERFACES.md).
- [Regions, component SSO, native evaluators, and product families](SSO_INTERFACES.md).
- [Surrogates, custom estimators, model selection, and learning](SURROGATE_INTERFACES.md).
- [Independent validation weights and generalized fitting providers](VALIDATION_WEIGHT_INTERFACES.md).
- [Archives, workbooks, numerical tables, and staged output](IO_INTERFACES.md).
- [Numerical SVG rendering and inspectable spatial scenes](PLOTTING_INTERFACES.md).
- [Headless XRay sessions, captured inputs, persistence, and background jobs](XRAY_INTERFACES.md).

`CallbackSurrogate` accepts a fresh Python model factory for transactional fits.
`estimator_surrogate` uses explicit fit and prediction adapters for other estimator interfaces.
Weighted validation can use separate fitting and diagnostic weights.
A quadratic fitting matrix defines `r.T @ W @ r` directly. The package does not invert it.
Explicit generalized-fit providers own positive-semidefinite validation and transactional fitting.
Custom native algorithms can query counted objectives through owned generator requests.
The generator protocol keeps borrowed native evaluation handles inside their Rust call.
XRay background factories construct models on their worker thread from captured numerical inputs.
Their declaration protocol distinguishes observed inputs from unverifiable hidden state.

## Choice names

Every argument that names one choice of a fixed set, such as a method, a metric, a policy, or a plot style, follows the
choice-name rule of the native crates (`designopt_core::choice_names`) and of DesignOptPy (`designoptpy.core.choices`).
A name matches a valid name when both are equal after the ASCII letters `A` to `Z` are lowered and `_` is read as `-`.
Nothing else changes, so `"Quasi_Newton"` names `"quasi-newton"`, while `" quasi-newton"` names nothing.
Results and error messages show the canonical name, and an error for an unknown name lists the canonical names. The
choice values of X-Ray configuration JSON (`XRayDomain.from_json`) follow the rule too. Option keys, record keys, and file
paths are not choice names.

## Core records

```python
import numpy as np
from designoptrs import DesignBox, DesignEvaluation, sample_box, score_deficits

domain = DesignBox([-1.0, -1.0], [1.0, 1.0])
samples = sample_box(domain, 100, seed=7)
evaluation = DesignEvaluation(np.sum(samples**2, axis=1, keepdims=True) - 0.5)
feasible, scores = score_deficits(evaluation.performance_deficit)
```

Each design occupies one row. Bounds and numerical outputs use float64.
Real numeric and Boolean arrays convert to float64. Complex, string, and object arrays are rejected.
Scalar model outputs and numeric controls accept real Python/NumPy scalars or zero-dimensional real numeric arrays.
They reject Boolean, complex, string, object, and nonscalar values before invoking numeric conversion.
Boolean flags accept actual Boolean scalars. Integer counts, seeds, indices, and budgets reject Boolean values.
Integer controls also accept zero-dimensional integer arrays. Fractional numeric values are not integer controls.
Boolean arrays remain valid numeric arrays. A zero-dimensional Boolean array is a scalar and is rejected for numeric controls.
`DesignBox` bounds must be finite, ordered, nonempty, and equally sized.
Smooth point methods also accept `PointBounds`, with negative-infinite lower and positive-infinite upper endpoints.
Point coordinates remain finite. NaN, inward infinities, and reversed intervals are invalid.
Fixed coordinates are valid. Box membership includes both faces.
Properties return new arrays. Editing these arrays cannot change native records.

Nonpositive deficits satisfy requirements. Positive deficits violate requirements.
Negative infinity marks inactive requirements. Positive infinity marks model rejection.
NaN deficits are invalid. Missing physical deficits have zero columns.
Feasible scores use negative geometric margins. Violations use a stable weighted norm.
An empty or inactive requirement group is feasible and scores -1.
Scores rank evaluated samples. They do not certify feasibility between samples.

Sampling uses an independent seeded ChaCha8 random stream.
It does not modify Python or NumPy global random state.

## Requirement conversion

`measure_to_deficit(measure, **controls)` returns `(deficits, normalization_factors)`.
The measure matrix has one design per row and one response per column.
Each control accepts a real scalar or one-dimensional array.
Scalars and one-entry arrays apply to every response column.

```python
from designoptrs import measure_to_deficit

deficits, factors = measure_to_deficit(
    [[2.0, 4.0], [5.0, 3.0]],
    lower_limit=[1.0, 2.0], upper_limit=[4.0, 6.0],
    normalization_factor=2.0,
)
```

The converter calculates each active lower and upper margin, then selects the larger deficit.
A lower margin is `(lower - measure) / factor`.
An upper margin is `(measure - upper) / factor`.
Positive margins multiply by their weight. Nonpositive margins divide by that weight.
Side weights override `weight`. All weights must be finite and positive.

Omitted limits use lower `-inf` and upper `0`.
NaN limit entries disable that side. NaN factors request automatic normalization.
The native converter skips inactive limits before subtraction. This avoids undefined infinity subtraction.
Automatic factors first use limits, then optional observations, and finally one.
`normalize_with_measure=True` permits observed range and mean fallbacks.
Those fallbacks depend on the complete batch. Use fixed factors in stochastic evaluators.
See [native conversion](../crates/designopt-core/README.md) for the complete numerical contract.

## Sampled box optimization

```python
from designoptrs import DesignBox, DesignEvaluation, optimize_box
from designoptrs.contracts import FloatArray

def evaluate_disk(samples: FloatArray) -> DesignEvaluation:
    """Return one signed squared-radius requirement for each sampled design."""
    return DesignEvaluation(np.sum(samples**2, axis=1, keepdims=True) - 0.8)

result = optimize_box(
    evaluate_disk,
    DesignBox([-0.1, -0.1], [0.1, 0.1]),
    DesignBox([-1.0, -1.0], [1.0, 1.0]),
    options={"number_samples": 50, "maximum_iterations": 4},
    seed=7,
)
candidate = result["candidate_box"]
print(result["termination_reason"], result["evaluated_rows"])
```

The native method grows a box, samples it, evaluates requirements, and greedily trims rejected samples.
Exploration permits growth. Consolidation evaluates and trims without growth.
`box_sso_defaults()` returns every effective native default as a new dictionary.
Pass selected overrides through `options`. Unknown option names raise `ValueError`.
The default trimming policy is `full`. Cheaper `single` and `reduced` policies can change selected geometry.
The optional trimming pass cap can also change geometry. Its completeness signal remains visible.

Requirement spaces combine performance satisfaction and physical feasibility:

| Name | Acceptable samples | Useful samples |
| --- | --- | --- |
| `Omega0` | Good performance | Every sample |
| `Omega1` | Good performance and physical feasibility | Every sample |
| `Omega2` | Good performance | Physically feasible samples |
| `Omega3` | Good performance or physical infeasibility | Physically feasible samples |

The default is `Omega2`. Empty physical groups satisfy physical feasibility.
Results include initial geometry, domain, candidate, effective options, counts, time, and random provenance.
`termination_reason` describes iteration, budget, sampled convergence, work limits, or requested stops.
No box result certifies unsampled feasibility or global optimality.

`retain_history=False` disables stored iteration records. Counts and termination remain available.
The `save_*` controls retain samples, evaluations, labels, or box snapshots in retained records.
Unrequested diagnostics remain `None`. Consolidation growth rates remain `None`.
The optional `progress(record)` callback runs after each completed iteration. Return `True` to stop.
It remains active when history retention is disabled.
The optional `measure(box, useful_fraction)` callback replaces the native volume measure.
It must return a finite nonnegative scalar. A custom measure can change selected geometry.

`trim_box(samples, viable, orders, candidate, options=...)` exposes the same greedy trimming stage.
`viable` must contain actual Boolean values. Numeric values and NaN cannot stand in for feasibility labels.
Each item in `orders` is one sequence of zero-based sample row indices to exclude.
The result reports pass counts, search completeness, and remaining requested exclusions.
Inclusive faces can retain an excluded sample coincident with viable evidence.
These residual exclusions remain visible even when the configured search is complete.
The trimming option `workers` (default 1) runs the anchored passes of `passes="full"` on that many native threads.
The box, its measure, the pass count, and the completion flag are the same for every count.
More than one worker needs the native measure: `optimize_box` with a `measure` callback raises `ValueError`,
because a Python callback runs only on the calling thread. Results and defaults do not list `workers`.
See [native box optimization](../crates/designopt-sso/README.md) for algorithm details and option domains.

## Point optimization

```python
from designoptrs import DesignBox, limited_memory_bfgs
from designoptrs.contracts import FloatArray

def quadratic(point: FloatArray) -> float:
    """Return a finite smooth scalar over the two-coordinate box."""
    return float(np.sum((point - 0.25)**2))

def quadratic_gradient(point: FloatArray) -> FloatArray:
    """Differentiate the complete quadratic scalar at one design vector."""
    return 2.0 * (point - 0.25)

point_result = limited_memory_bfgs(
    quadratic, [0.9, -0.8], DesignBox([-1.0, -1.0], [1.0, 1.0]),
    gradient=quadratic_gradient,
)
print(point_result["status"], point_result["point"])
```

Projected limited-memory Broyden–Fletcher–Goldfarb–Shanno (BFGS) uses recent displacements and gradient changes.
Two loops apply an inverse-curvature estimate without storing a dense matrix.
Projection removes outward motion at active bounds. Armijo backtracking selects a decreasing feasible step.
Only `status="converged"` reports the requested local projected-gradient stationarity tolerance.
The optional `feasible` field refers to the supplied point bounds.
`None` means required qualification was unavailable. Budget denial preserves the nominal `solver_status` and prevents success.
Completed physical infeasibility changes nominal convergence or optimality to `infeasible` in both status fields.
This local solver does not certify global optimality. It is not the L-BFGS-B algorithm.

Omit `gradient` to use bounded three-point numerical differences.
The analytic gradient must differentiate the complete objective scalar.
Objectives return finite scalars. Gradients return one finite derivative per coordinate.
`limited_memory_bfgs_defaults()` returns all native controls as a new dictionary.
`max_evaluations` includes numerical probes. A zero budget prevents every objective call.
Unavailable objective and stationarity values remain `None`.
Reducing `memory_size` saves work and can change the path and solution quality.

Results retain candidate, initial values, qualified status, solver status, optional feasibility, counts, time, and optional history.
Counts distinguish objective/constraint rows from actual callback batches and optional analytic derivative attempts.
Each real constrained endpoint admits the objective first, then the combined constraint callback.
Complete numerical stencil batches reserve all required rows separately per channel, in that order.
Late constraint denial preserves invoked objective work and the prior accepted observation.
Population policies can admit a whole initialization or generation before starting that population work.
A denied final check cannot report success or known feasibility.
History includes copied search trials, curvature pairs, restarts, and optional stationarity evidence.
`history_stride` and `history_limit` control diagnostic retention.
The optional `progress(record)` callback observes each attempted search. Return `True` to stop.
See [native point optimization](../crates/designopt-point/README.md) for numerical assumptions and controls.

`pattern_search` provides derivative-free coordinate polling over the same finite boxes.
It receives a scalar objective, starting vector, bounds, optional controls, and optional progress callback.
`pattern_search_defaults()` returns the native controls.
The default stops at the first sufficient improvement. `complete_poll=True` compares all poll directions.
These policies can follow different paths and select different endpoints.
Convergence means that a complete unsuccessful poll reduced the mesh to tolerance.
It does not certify gradient stationarity. Results retain `final_mesh_size` and optional poll history.

`solve` selects one native point solver by its name (default `"sqp"`) and adds the workflow policies:
evaluation logs, best-feasible selection, refinement, feasible-start recovery, the returned-design tolerance, and the constraint back-off.
Its `details` keep the native record of the solver.
`optimize_quantities_of_interest`, `optimize_quantities_of_interest_pareto`, and `optimize_performance_score` optimize
quantities of a bottom-up mapping, or the deficit score of an evaluator, with the same solver selection.
`bayesian_optimization` minimizes an expensive objective with a Gaussian-process surrogate and optional Python
samplers, acquisitions, acquisition optimizers, model trainers, and stop callbacks. Its options add modeled
feasibility (the acquisition weighted by the probability of feasibility of `FeasibilityModel`), model-fit and
acquisition-row budgets with their own statuses, and warm-started hyperparameter fits.
See [the solver selection workflow](OPTIMIZATION_INTERFACES.md#solver-selection-workflow) for the options records and the result records.

## Native mappings and sampling

`MappingResponse` stores physical response groups before requirement conversion.
`MappedDesignEvaluator(mapping, performance_policy=..., physical_policy=...)` returns a callable evaluator.
The physical mapping receives a copied sample matrix and returns `MappingResponse`.
The native adapter performs requirement conversion. It preserves raw positive-infinity model rejection.
Observed-scale normalization is rejected because stochastic batches must not redefine requirement scales.

Optional `fixed_coordinates` inserts prescribed values before model evaluation.
Each finite value fixes a full coordinate. Each `None` consumes one free input column.
`expand_fixed_variables` exposes this native coordinate expansion separately.
All-fixed configurations accept a zero-column matrix with the desired row count.
`retain_diagnostics=True` retains successful evaluation counts, sample counts, elapsed time, and the latest physical response.
The `diagnostics` property returns a copy, or `None` when disabled.
`set_diagnostics(True)` starts fresh counts. `set_diagnostics(False)` clears retained diagnostics.
Mapped evaluator instances are thread-affine. Use each instance on its creating Python thread.

`score_deficits` also accepts `good_policy` and `bad_policy` keyword controls.
The defaults retain geometric-margin and Euclidean-violation rankings.
`worst-case` multiplies positive deficits by their weights and divides nonpositive margins by their weights.
Feasibility labels always come from deficit signs.
Box and component options expose `performance_scoring` and `performance_weights` for the performance ranking.
A box or component run labels physical rows by deficit signs only and keeps no physical score.
Their options therefore take no physical scoring policy or weights, and the box `scorers` take only `performance_good` and `performance_bad`.
Any other key raises `ValueError`. Compensation evaluators rank physical rows and keep the physical keys.

`sample_latin_hypercube` uses every equal-width interval once in each free coordinate.
It permutes intervals independently and applies uniform jitter. It performs no maximin refinement.
`sample_full_factorial` returns every coordinate-level combination. Its first coordinate changes fastest.
One level uses interval midpoints. `condensed=True` excludes interval endpoints.
Fixed coordinates can repeat rows. Factorial sample count grows exponentially with dimension.

`sample_rejection` proposes uniform box batches and applies a Boolean region-membership callback.
An exhausted limit raises an error with `geometry_status="work-limit"` and the work counts. `sample_individual_feasible` instead reports the limit in `termination`.
The callback returns a Boolean NumPy vector with one entry per proposed row.
Results include accepted samples, proposals, batches, elapsed time, termination, and optional proposal history.
A proposal-budget stop returns partial accepted rows with `proposal_budget_exhausted`.
Uniform accepted samples require deterministic membership and positive region volume.

## Geometry, distances, and functional variables

`DesignBox.interpolate(unit_samples)` maps unit coordinates in `[0,1]` to physical rows.
`unit_coordinates(samples)` reverses that map and allows finite rows outside the box.
Fixed coordinates map to zero when matching and positive infinity otherwise.
`classify(samples)` returns inclusive labels and the largest signed face violation.
Nonfixed faces use dimensionless coordinates. Fixed faces use absolute coordinate differences.
`as_array()` returns lower and upper bounds as two copied rows.

`Ellipsoid(center, semi_axes, rotation=None)` stores positive axes and an orthonormal rotation.
The default rotation is identity. `classify` returns labels and normalized squared radius minus one.
An optional nonnegative tolerance changes only labels. `quadratic_form()` and `volume` return checked native geometry.
Unrepresentable numerical results raise errors rather than returning an invalid geometry matrix.

`pairwise_distances(first, second, metric=...)` compares finite sample-major point rows.
Native choices include Euclidean, squared Euclidean, Manhattan, Chebyshev, Minkowski, standardized Euclidean, Mahalanobis, cosine, and correlation.
Minkowski requires `power`; standardized Euclidean requires positive `variance`; Mahalanobis requires positive-definite `inverse_covariance`.
Minkowski power must be positive and finite. Powers below one do not satisfy the triangle inequality.
Supplied scale parameters stay fixed. The wrapper estimates no pooled statistics and substitutes no pseudoinverse.
Cosine distance rejects zero vectors. Correlation distance rejects constant vectors.
`workers` (default 1) fills blocks of output rows on native threads; the distances do not depend on it.

`InterpolationCurve(locations, values, method="pchip", extrapolate=True)` owns finite scalar support data.
PCHIP means piecewise cubic Hermite interpolating polynomial. Its native slope rules preserve shape on monotone intervals.
`method="linear"` selects secant segments. Changing the interpolation rule can change model responses and optimization results.
Call a curve with a finite query vector. Disabled extrapolation rejects queries outside multi-point support.
A single support point defines a constant everywhere.

`FunctionalVariable(free_locations, fixed_locations=..., fixed_values=...)` declares free and fixed function nodes.
Fixed locations replace coincident free nodes. Contradictory fixed values raise errors.
`build_functional_samples(samples, variables, ...)` constructs native curves for each finite design row.
Input columns concatenate each variable's remaining free values. Fixed-only variables consume zero columns.
Use the returned curves inside a physical mapping callback. Numerical reconstruction remains in Rust.

## Native differentiation and integration

`finite_differences_coefficients(offsets, order)` returns polynomial stencil weights at offset zero.
Apply these to model values and divide by physical spacing raised to derivative order.
`finite_differences_derivative(values, step, order=1, stencil_width=3)` differentiates a uniformly spaced finite signal.
Step scaling uses sequential divisions when intermediate step products would lose range.
It shifts the complete stencil near endpoints.

`differentiate(samples, model, order="jacobian", options=...)` estimates sample-major model derivatives.
The model returns a finite response matrix with a constant column count.
Results include values, Jacobians, optional Hessians, model-row counts, time, termination, and optional stencil diagnostics.
Jacobian shape is `(samples, outputs, coordinates)`.
Hessian shape is `(samples, outputs, coordinates, coordinates)`.
The native method shifts or reduces stencils near finite bounds.
Custom `StencilDifferentiationPlan` adds relative-step defaults, independent bounds, and actual per-sample fitted layouts.
First-derivative relative steps default to cube-root epsilon; second derivatives default to `1e-4`.
Fixed coordinates have zero derivatives along allowed box motions.
Budget exhaustion returns only complete sample derivatives. Smaller steps can amplify noise and rounding.

`integrate_ode_runge_kutta(ode, times, initial_state, external_input=..., options=...)` integrates coupled ordinary differential equations.
The callback receives `(state, external_input, time)` and returns a finite derivative vector with matching state length.
Times must increase strictly. Each interval holds its starting external-input row constant.
The default is forward Euler. Other explicit methods include fourth-order Runge–Kutta and fixed-step Dormand–Prince.
`RungeKuttaTableau` permits a checked custom explicit coefficient table.
Consistency checks do not prove a higher convergence order.
Results retain reached times, state rows, derivative-call counts, time, termination, and optional stage history.
A derivative budget stops before an incomplete interval. The method never adapts the requested grid.
Accuracy and stability depend on suitable time spacing.

## Local gradient methods and coefficient programs

`optimize_gradient(method, objective, initial_point, bounds, ...)` selects one native local gradient method explicitly.
Choices are `steepest-descent`, `conjugate-gradient`, `quasi-newton`, and `modified-newton`.
The native direction formulas remain distinct. Shared controls use the `LocalOptions` dictionary.
The default line search is golden-section refinement. It assumes a locally unimodal line objective.
`line_search={"kind": "backtracking_search"}` selects sufficient-decrease backtracking with its native defaults.
Changing line-search policy can change work, path, and selected endpoint.
Armijo has a finite trial cap. Tight stationarity targets can require a larger explicit cap.
Exhausting that cap does not establish stationarity.

Supply the optional analytic gradient of the complete objective scalar.
Modified Newton accepts an analytic symmetric Hessian and records its applied curvature shift.
Dense BFGS uses Powell damping; its record retains damping, curvature, and skip decisions.
Conjugate gradients accept an optional `conjugacy_coefficient(current_gradient, previous_gradient)` callback.
The optional `convergence(previous_value, current_value, iteration)` callback requests stationarity verification when it returns `True`.
A requested progress stop cannot certify convergence. Unverified small progress returns `stalled`.
Only a verified projected-gradient test gives `converged`.
Optional derivative matrices and line-search histories remain `None` when not requested.
Counts retain objective, gradient, constraint, Hessian, and subproblem work independently of history.

`LinearProgram` stores `linear dot x + constant` with affine constraints and variable bounds.
`QuadraticProgram` stores `x.T @ Q @ x + linear dot x + constant`.
The quadratic Hessian is `Q + Q.T`. The native solver requires numerically nonnegative curvature.
Unlike finite design boxes, program bounds permit negative-infinity lower endpoints and positive-infinity upper endpoints.
Constraint dictionaries accept `inequality_matrix`, `inequality_rhs`, `equality_matrix`, and `equality_rhs`.
Their conventions are `A @ x <= b` and `E @ x == d`.

`solve_linear_program` uses native two-phase simplex.
`solve_quadratic_program` uses native convex active-set steps and can repair starting feasibility through simplex.
Its option `tangent_basis="householder"` builds the tangent basis from one QR factor, which is faster for larger models.
The default `"gram-schmidt"` keeps the explicit projections; the two choices can differ by rounding.
Both return candidate, objective, status, feasibility, multipliers, elapsed time, and optional iteration records.
Success requires independent numerical optimality qualification.
Karush–Kuhn–Tucker (KKT) evidence keeps primal feasibility, stationarity, dual feasibility, and complementarity separate.
Dual lower bounds and gaps remain `None` when unavailable.
Infeasible results can retain a numerical separating certificate.
Unbounded results can retain a verified improving recession direction.
A candidate alone does not establish feasibility or optimality.

## Scalar population search

`optimize_population(method, objective, bounds, initial=None, seed=0, options=...)` selects a native bounded scalar search.
Choose `differential-evolution`, `particle-swarm`, or `genetic-algorithm` explicitly.
Each method preserves its native defaults. Optional initial rows must be finite and box feasible.
Missing rows use uniform sampling by default. Nested `population` controls permit randomized Latin hypercube sampling instead.
Native ChaCha8 seeds replay native runs. They do not reproduce NumPy draws or change NumPy's global random state.
With `vectorized=True`, the objective receives one 2-D array per generation, with one design per row, and returns one value per row.
This gives the same designs and values with one Python call per generation instead of one per design.
`OPTIMIZATION_INTERFACES.md` lists the other point methods with this switch.

Differential evolution excludes each target from three distinct donors and clips the full-factor donor.
Default binomial crossover includes one forced donor coordinate. Unchanged projected trials reuse their observations.
Particle swarm combines preceding displacement, personal memory, and global memory.
Velocity bounds are fractions of coordinate widths. Defaults use fraction 0.2, inertia 0.7298, and attraction weights 1.49618.
Independent positive-uniform coordinate draws supply attraction. An explicit initial-velocity sampler receives physical velocity bounds.
Genetic search separates selection, crossover, mutation, and age-based survival.
Its defaults use normalized fitness, roulette-wheel selection, heuristic crossover, and one-coordinate uniform mutation.
Optional rank fitness, tournament size, crossover choice, and Gaussian mutation scale expose native alternatives.
Changing these policies can change work and solution quality.

The result retains the best finite observation across the run, even when the final population no longer contains it.
No finite observation produces `point=None` and `objective_value=None`.
Nonfinite objectives raise errors under the explicit error policy.
Genetic defaults permit positive-infinite rejection merits; NaN and negative infinity still fail.
The explicit reject policy retains invalid observations as `None`.
Hard budgets include initialization and invalid observations. A required full generation batch must fit before work starts.
Objective spread is a termination test. It does not certify stationarity or global optimality.
Optional histories retain donor sources/crossover decisions, swarm memories/velocities, or genetic parents/ages.
Each progress callback receives copied retained evidence and can stop by returning `True`.

## Nonlinear constrained optimization

`optimize_constrained(method, objective, constraints, initial_point, bounds, ...)` keeps original-model evidence separate from transformed search.
Choose `penalty`, `barrier`, or `augmented-lagrangian` explicitly.
The constraint callback returns `ConstraintResiduals(inequality=..., equality=...)`.
Inequalities satisfy `c <= tolerance`. Equalities satisfy `abs(h) <= tolerance`.
Supply finite nonnegative tolerance vectors. Their lengths define the exact callback dimensions.
At least one residual is required. Empty families remain empty arrays.

An exterior penalty adds the squared violation divided by a decreasing factor.
A barrier penalizes approach to the strict inequality boundary. Its default is the natural-log barrier.
A callable `barrier_function` option replaces this default. For example, it can return the inverse barrier `-1/c` for `c < 0` and `inf` otherwise.
A gradient inner solver requires an interior start. The default differential evolution can reach the interior from an infeasible start.

A raw nonfinite objective or residual is an error by default, because a failed model evaluation stays visible.
`nonfinite_policy="reject"` treats positive infinity, and an infinite equality, as a rejected design and a negative-infinite inequality as inactive. The run returns a status and keeps the accepted design.
NaN and a negative-infinite objective stay errors under both policies.
The augmented Lagrangian updates physical multipliers and quadratic penalty strength.
All methods use a real native bounded inner optimizer.
Nested `options["common"]` controls budgets, physical verification, history, and the inner solver.
The default inner solver follows DesignOptPy: differential evolution for penalty and barrier, and quasi-Newton for augmented Lagrangian.
`inner_solver` also takes `"limited-memory-bfgs"` and `"pattern-search"`; `inner_options` overrides the controls of a named solver.
Omitted tolerances use the absolute tolerance `1e-6` on every residual row.

Results retain accepted original objective/residual witnesses, physical feasibility, stationarity, complementarity, multipliers, and actual model counts.
With an unlimited budget, a fresh final residual query qualifies feasibility without replacing `final_constraints` or the objective.
Final feasibility requires both the accepted witness and fresh verdict to be feasible.
Changed values preserve convergence when both verdicts remain feasible; either infeasible verdict prevents success.
This conservative conjunction extends the target's fresh-only feasibility field for stateful callbacks with disagreeing observations.
Inner success does not establish physical convergence. Budget stops can leave final objective or residual evidence `None`.
`final_checked` records available endpoint qualification; it does not imply a fresh objective/residual callback pair.
Feasible-start recovery reserves a required final residual row. An inner merit limit can still permit later restarts.
A recovery-satisfying observed probe prevents unnecessary restarts, including after a custom inner own-limit error.
MMA custom stops can end at an infeasible completed endpoint. Both statuses then become `infeasible`, without success.
MMA probe designs must stay strictly between reciprocal poles. Returned selections must also satisfy move and artificial-variable bounds.
Rounded pole/move-bound collisions return `no_representable_progress` at the accepted point.
Unavailable internal physical derivative evidence returns `numerical_error`; original callback exceptions still propagate.
Positive infinity remains physical rejection after finite transformed solver views.
Negative infinity marks an inactive inequality; equality infinity rejects the design.
Optional history retains physical outer records and actual inner results.
Finite samples and first-order conditions do not prove global optimality or infeasibility.

## Native surrogate models

`Surrogate(kind, options=...)` selects a named native regression family.
Kinds include linear, polynomial, Gaussian process, radial basis, kernel ridge, support-vector regression,
tree, ensemble, neural network, nonlinear, hierarchical stepwise, random-feature kernel, and regression factory.
Models remain on their creating Python thread.
`fit` replaces paired observations; `update` appends and refits.
Regression fitting filters nonfinite paired rows. Failed replacement preserves the prior successful model.
Queries must be finite. `training-data` and fitted evidence remain `None` until available.

Gaussian processes fit outputs independently.
Defaults compare five kernels and four trends using five modulo folds, with a 256-fit cap per output.
Each covariance candidate profiles its trend through whitened minimum-norm least squares.
Only designs are standardized. Signal/noise standard deviations use original response units.
Data-based initial values, unconstrained log-coordinate native BFGS, and one complete reduced-family recovery are explicit controls.
The optimizer differs from SciPy L-BFGS-B. Recovery does not establish prediction accuracy.
Response uncertainty includes observation noise; `latent=True` excludes it.
Both omit uncertainty in fitted trend coefficients and hyperparameters.
Per-output diagnostics retain selected/fitted provenance, rank, actual likelihood work, failures, and recovery.
Native likelihood BFGS requires strict Armijo decrease. Only an accepted full step can satisfy its step-size stopping rule.
The gradient test also runs at the last accepted iterate. A stalled iteration can request up to 60 trial likelihood calls.
Uncached representable trials factor covariance and refit the profiled trend; this runtime cost is unmeasured.
An undecodable returned optimizer vector adds no likelihood evaluation; no-query primary work remains zero.
Posterior variance uses a relative allowance in squared response units, without an absolute unit floor.
Family scoring computes conditional means only. Public uncertainty prediction retains negative-variance errors.
The amplitude-aware prediction extension is disabled; nonunit signals retain checked scalar prediction.

Stepwise regression uses hierarchical partial F-tests, default thresholds 0.05/0.10, and interactions as its upper model.
Random-feature regression uses epsilon-insensitive loss; kernel ridge keeps its separate squared-error objective.
Automatic regression factories use 50 trials and five contiguous folds per output, then refit the first best candidate.
`search="none"` preserves explicit estimator settings for one fit per output.
Polynomial feature allocation defaults to a 512 MiB estimated limit.
The cascade-forward route defaults omitted L2 regularization to zero.
See [surrogate interfaces](SURROGATE_INTERFACES.md) for exact controls, diagnostics, snapshots, and callback protocols.

## Native classifiers

`Classifier(kind="svm", options=...)` selects a support-vector machine (SVM) or `kind="logistic"` selects logistic regression.
`fit(samples, labels, weights=None)` accepts sample-major designs and actual Boolean labels.
SVM fitting rejects nonfinite designs. Regression paired-row filtering does not apply to that classifier boundary.
Numeric label values and NaN do not convert to Boolean labels.
Unknown options raise `ValueError`. Numeric controls use the checked scalar boundary described above.
Failed fitting preserves the last accepted model and its diagnostics.

`classify(samples)` returns copied Boolean labels, finite decision scores, and optional true-class probabilities.
Scores point toward the true class. The native decision boundary labels nonnegative scores true.
SVM scores are margins. Their probabilities remain `None`.
Two-class logistic scores are log-odds and their probabilities describe the fitted model.
One-label logistic fits use fixed scores of positive or negative one.
Neither margin size nor numerical convergence certifies classification accuracy.
To use a true-is-feasible decision score as a signed design deficit, negate the score.

SVM controls expose linear, radial, or polynomial kernels, observation penalties, standardization, balancing, and dual convergence.
Two-class defaults use 50 stratified search trials, fold-local preprocessing, and search seed zero.
Set `hyperparameter_trials=None` for fixed C/gamma. Internal estimator fits remain separate from workflow trainer calls.
A one-label SVM fit learns the occupied region through its native one-class dual.
An observed false class reverses score orientation, so positive scores still point toward true.
Logistic fitting uses native damped Newton steps on penalized cross-entropy.
A one-label logistic fit returns the observed constant class and model probability zero or one.
These constants do not quantify uncertainty about an unseen class.

`diagnostics` retains family-specific convergence and one-class evidence, or `None` before fitting.
SVM diagnostics include the Karush-Kuhn-Tucker dual gap and equality residual.
Iteration-limited SVM fits commit only when `allow_nonconvergence=True`.
Logistic diagnostics include the final gradient norm and explicit constant-class state.
Optional histories remain `None` when disabled. `support_vectors` returns copied original-coordinate SVM rows when available.

## Native sparse truss analysis

`TrussModel` copies node coordinates, integer endpoint pairs, positive areas/moduli, loads, and prescribed displacements.
Arrays use one node per row. Endpoint indices are zero based.
Finite prescribed displacements fix coordinates. NaN marks free coordinates.
Areas and moduli accept real scalars or one value per element. Use consistent engineering units.
The model assumes pin joints, axial linear elasticity, and small displacements.

`prepare_truss_geometry(model)` prepares immutable geometry and support-rigidity evidence.
`analyze_truss(model, geometry=None, keep_diagnostics=False, condition_method='exact')` solves native sparse supported equilibrium.
`condition_method='exact'` forms every inverse column of the stiffness, one solve per free coordinate.
`condition_method='hager-higham-estimate'` estimates the condition numbers from at most 10 solves each.
The estimate is a lower bound of the exact value. It can accept a design that the exact rank test rejects, or omit a warning.
The result names the method in `condition_method`. The batch evaluators accept the same keyword for every row solve.
Prepared geometry can be reused with exactly matching positions and connectivity.
`with_properties_and_loads` creates a checked model with new material properties or nodal loads.
Each analysis rebuilds stiffness and its factorization. Geometry preparation does not cache the material factorization.

Results retain displacements, reactions, tensile-positive axial force, strain, stress, conditioning, and equilibrium backward error.
Accepted equilibrium can remain sensitive when `conditioning_warning=True`.
Optional diagnostics retain sparse storage, rigidity, refinement, timing, and individual residuals.
Structural rejection raises `TrussDesignRejected`. Invalid input raises `ValueError`; arithmetic failures raise `RuntimeError`.
These categories prevent numerical failures from masquerading as rejected designs.
See [native truss analysis](../crates/designopt-truss/README.md) for the mechanical and numerical contracts.

## Headless X-Ray projections

`XRayDomain(design_space, solution_box, performance_quantities, ...)` creates an immutable native study snapshot.
Outer variable widths must be positive and finite. The selected solution box must lie inside the outer box.
Quantity names define the exact deficit column order. Optional physical quantities form a separate group.
Native defaults select all unordered pairs and 3000 samples per pair.
Specify `desired_pairs`, `samples_per_pair`, and `batch_size` to control work explicitly.
`work_plan` reports exact pairs, sample/evaluation/figure counts, numeric channel layout, and retained bytes.
A request admits at most 2,000,000 total projection samples before worker submission.
Configuration can remain editable above that request bound.
These estimates describe native-owned work. Python callbacks and copied interface arrays add memory use.

`configuration_json` preserves the complete declared native configuration.
Edit a decoded copy and call `XRayDomain.from_json(...)` to create a new checked snapshot.
Signed infinite quantity limits use the JSON strings `"+Infinity"` and `"-Infinity"`.
Quantity activation, display metadata, parameters, pair order, and resource limits remain available through this native format.
Declared model identity is provenance. It does not load code or capture hidden Python model state.

`compute_xray_projections(domain, evaluator, seed=0, maximum_seconds=None)` runs the headless engine synchronously.
The evaluator receives copied sample rows and returns `DesignEvaluation`.
It can return `XRayEvaluation` to add aligned optional raw measure matrices.
Callbacks supply converted deficits; quantity limits do not convert these values again.
Projected coordinates span the outer domain. Other coordinates stay inside the selected solution box.
Results retain samples, raw normalized primary deficits, optional measures, labels, markers, and actual work.
`performance_active` affects performance decisions only. Every physical deficit remains mandatory.
Named numeric channels preserve supported dtype and row-major bytes; opaque metadata retains its caller type.

The native elapsed-time limit is cooperative. It cannot interrupt a running callback.
It is the only `XRayResourceLimits` field, defaulting to one hour.
Schema-3 portable sessions use independent input byte limits. Diagnostic archives and workbooks retain their own input limits.
`maximum_seconds` defaults to the configured resource limit and cannot exceed it.
Deadline expiry raises `TimeoutError`. Model or deadline failures return no partial result.
The wrapper starts no desktop application or worker thread.
Finite projection samples do not certify the full continuous solution box.

## Callback ownership and errors

Every callback receives owned data. Array edits cannot change the native algorithm's stored inputs.
Callback adapters run while attached to Python. They require no universal thread-safety contract.
Some native calls take no callback and use only copied inputs: `sample_box`, `score_deficits`, `measure_to_deficit`,
`relax_lloyd_unit`, `trim_box`, and `evaluate_movable_node_truss`.
They release the global interpreter lock (GIL) while they compute, so other Python threads can run at the same time.
Their results do not change.
The original Python exception propagates with its identity and traceback.
Native invalid inputs raise `ValueError`. Native arithmetic and evaluation failures raise `RuntimeError`.
Native file failures raise `OSError`. Ordinary budget exhaustion returns a structured result.

The native crates write progress records through the Rust `log` facade, but the package installs no `log` backend and
forwards no record to the Python `logging` module. Native progress is therefore visible only through the result
records and the progress callbacks.

`contracts.py`, `_native.pyi`, and `py.typed` describe public inputs and result dictionaries.
The option and result classes are `TypedDict` descriptions of ordinary dictionaries.
Native code validates runtime inputs.

## Interface scope

The component guides define the supported Python protocols. They do not imply complete parity with DesignOptPy.
Optional region operations require explicit native capabilities and proof evidence.
Unavailable capabilities and measurements remain explicit results or typed failures.
Python callbacks remain subject to the interpreter and their declared model assumptions.
Numerical kernels run in Rust. The package does not translate arbitrary Python code.
Desktop X-Ray interaction remains a native application concern.
Workbook input and output preserve values rather than formulas, formatting, macros, or external links.

## Local qualification

Build and install the wheel in an isolated environment.
From the repository root, run `python -m unittest discover -s designoptrs/python/tests -v`.
Keep behavior output separate from build and static-check output under `.artifacts`.
`qualification/check_sources.py --output PATH` checks discovered annotations and documentation without Git metadata.
It writes the current component source inventory to the selected evidence path.

`qualification/compare_trim.py` optionally compares fixed samples with DesignOptPy, the Python implementation in `designoptpy`.
It needs the DesignOptPy dependencies. These are not runtime dependencies of `designoptrs`.
The script checks geometry and logical work before timing unchanged full greedy search.
Its timing evidence applies only to that fixture and includes interface overhead.

## Current native workflow alignment

Core filter startup uses `startup_polynomial_degree`; the straddle acquisition is `gaussian_straddle_acquisition`.
Mapping metadata records use `CallableMappingMetadata` and `SurrogateMappingMetadata` with explicit callback-role field names.
Grid results retain opaque callback evidence in `function_metadata`.

Region policies expose shape-evidence selection and cut-adding redundancy cadence.
Component trimming defaults to `"reduced"` passes, as DesignOptPy does. Budgets of designs are the only caps.

`XRaySampleData` supplies immutable stored observations to `XRayDomain.from_samples`.
Stored projection and box trimming use those rows without evaluator calls.
Source-aware work plans, source row indices, and session schema 5 keep that evidence separate from model predictions.
Schema 5 writes the stored observations, and the deficits and labels of every stored row, once per session.
The [Python X-Ray guide](XRAY_INTERFACES.md) describes the complete public boundary.

