Metadata-Version: 2.5
Name: designoptpy-surrogate
Version: 0.1.0
Summary: DesignOptPy surrogate algorithms and utilities
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: designoptpy-core<0.2,>=0.1.0
Requires-Dist: matplotlib<4,>=3.11
Requires-Dist: numpy<3,>=1.26
Requires-Dist: scikit-learn<2,>=1.4
Requires-Dist: scipy<2,>=1.12
Description-Content-Type: text/markdown

# designoptpy-surrogate

This package provides response approximation models, classifiers, validation metrics, plots, and active-learning workflows.
Regression predicts numeric responses. Classification assigns labels, such as whether a design meets its response limits.
This package has its own installation and version. Import its functions through `designoptpy.surrogate`.

- After publication, install with `python -m pip install designoptpy-surrogate`.
- In the source workspace, run `uv sync --package designoptpy-surrogate`.
- To install all DesignOptPy components, including X-Ray and optional workbook and palette support, install `designoptpy`.

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

Import behavior:

- Importing `designoptpy.surrogate` imports every listed name directly. This is an eager import, and it does not import Matplotlib.
- Python imports a package before its submodules, so an import of any `designoptpy.surrogate` submodule also runs this eager import.
- Plots are available only from `designoptpy.surrogate.plotting`, `designoptpy.surrogate.classifier_plotting`, and `designoptpy.surrogate.boundary_plotting`.
- scikit-learn is a required dependency.
  Its modules load when a function first needs one of its models, so a missing installation raises its import error at that call.

## Fit and predict a model

A surrogate predicts response measures from design coordinates using previously evaluated observations.
Training arrays contain one row per design and one column per input coordinate or response measure.
This layout is sample-major. Models preserve the pairing between design rows and response rows.

```python
import numpy as np
from designoptpy.surrogate import LinearSurrogate

x = np.array([[0.0], [1.0], [2.0]])
model = LinearSurrogate().fit(x, 1.0 + 2.0 * x)
model.update([[3.0]], [[7.0]])
prediction = model.predict([[0.5]])
print(prediction.mean)  # [[2.]]
print(prediction.standard_deviation)  # None
```

`LinearSurrogate` fits `y = b0 + b1*x1 + ... + bd*xd` by least squares.
Least squares chooses the coefficients that minimize the sum of squared residuals.
The three observations lie on `y = 1 + 2x`, so the fit recovers `b0 = 1` and `b1 = 2`.
The prediction at `x = 0.5` is therefore 2.
`update` appends the observation `(3, 7)` and refits. That point lies on the same line, so the coefficients stay the same.
A linear model has no uncertainty estimate, so `standard_deviation` is `None`.

Prediction returns a `Prediction` record with aligned means and, when supported, standard deviations.

- Unavailable uncertainty remains `None`. A zero deviation describes a deterministic prediction.
- Fitting removes rows that contain NaN or infinity, so retained training data are finite.
- Complex, Boolean, and nonnumeric designs and measures raise `ValueError` before numeric conversion.
- Prediction uses the configuration retained at the last successful fit.
  Changing a configuration field does not change the fitted model until the next fit.

Workflows request only the model capabilities that they use.
These capability interfaces are protocols: a class satisfies one by providing its methods, without inheritance.

| Protocol | Required members | Used by |
| --- | --- | --- |
| `PredictionModel` | `predict` | `predict_measures`, `validate_uncertainty_threshold` |
| `TrainableModel` | `predict`, `fit` | `cross_validate` |
| `UpdatingModel` | `predict`, `fit`, `update` | Base of `SurrogateModel` |
| `RetainedPredictionModel` | `predict`, `design_samples`, `measures` | Regional samplers, candidate strategies, `find_uncertainty_score`, `plot_surrogate_boundary` |
| `SurrogateModel` | `predict`, `fit`, `update`, `design_samples`, `measures` | Active-learning trainers, `plot_top_down_iteration_progress` |

## Prediction and training

### Accepted training rows

Each built-in model (`LinearSurrogate`, `PolynomialSurrogate`, `NonlinearSurrogate`, `CascadeForwardSurrogate`, `GaussianProcessSurrogate`, and `SklearnRegressorSurrogate`) records which input rows its last fit or update used.
A fit keeps a row only when every design value and every measure value of the row is finite.
This rule is complete-case filtering. One mask applies to every output, so all outputs share one set of training rows.

- `accepted_rows` holds the ascending zero-based indices of the kept rows (`int64`). `discarded_rows` counts the dropped rows.
  The dropped indices are the complement of `accepted_rows` in `range(accepted_rows.size + discarded_rows)`.
- After `fit`, the indices refer to the rows passed to `fit`.
- After `update` of a fitted model, they refer to the combined matrix `[previous design_samples; new rows as passed]`.
  The previous rows are finite, so they are always rows `0` to `n_previous - 1`. The dropped rows are the nonfinite new rows.
  For example, a model fitted on 3 kept rows and updated with `x = [[NaN], [2], [3]]`, `y = [8, 5, inf]` reports `accepted_rows = [0, 1, 2, 4]` and `discarded_rows = 2`.
- After `update` of an unfitted model, they refer to the rows passed to `update`.
- Both are `None` before the first successful fit. They change only together with `design_samples` and `measures`, so a failed fit keeps the previous record.

The record tells which observations of a caller's table entered the model, for example to report the rows of a workbook that a fit dropped.

### Selecting outputs

`predict_measures` and `select_prediction` accept zero-based numeric output indices or a Boolean vector.

- Numeric indices preserve order and repeated columns. `None` and empty numeric sequences select every output.
- A Boolean vector must have one entry per output. An all-false vector returns one row per query and zero columns.
- Fractional indices raise `ValueError`.
- Selection preserves the named uncertainty kind.
- A model that provides `predict_selected(design_samples, measure_index)` computes only the selected outputs.
  The GP and scikit-learn adapters provide it.
  Other models receive `predict(design_samples)`, and `predict_measures` selects the columns.
- Gaussian-process and estimator-adapter predictions bypass their backends for zero selected columns or zero query rows.
- Empty queries retain the selected output width.
  Available uncertainty keeps the same empty dimensions. Unavailable uncertainty remains `None`.

### Model families and estimator adapters

Built-in model families are `LinearSurrogate`, `PolynomialSurrogate`, `NonlinearSurrogate`, `GaussianProcessSurrogate`, and `CascadeForwardSurrogate`.

Python only: this adapter wraps scikit-learn. DesignOptRs fills this role with its native regression learners, for example `RegressionTreeSurrogate` and `NeuralNetworkSurrogate`, and has no counterpart.
An estimator is a Python object with fitting and prediction methods.
`SklearnRegressorSurrogate` gives scikit-learn estimators the shared surrogate interface. This interface translation is the adapter pattern.
It clones one estimator for each response column.

The factories `kernel_surrogate`, `regression_tree_surrogate`, `ensemble_tree_surrogate`, `svm_regression_surrogate`, and `neural_network_surrogate` return a `SklearnRegressorSurrogate`.
They accept `parameter_space`, `search_method`, and `search_options` for grid or randomized parameter search.
By default (`parameter_space="auto"`), each factory tunes its estimator over a preset hyperparameter space.
Each factory docstring lists its ranges.
DesignOptRs uses native algorithms in the roles of these factories, not scikit-learn, and tunes them with `RegressionFactorySurrogate`.
Each factory docstring names its native algorithm.

Cost of the default search:

- Randomized search tries 50 configurations, each scored by 5-fold cross-validated mean squared error, and refits the best one.
- That is about 251 estimator fits per output for every fit and update.
- `parameter_space=None` fits once without search. This is much cheaper but untuned.
- `search_interval=k` (factories and `SklearnRegressorSurrogate`, default 1) searches only at every `k`-th update; `None` searches in no update.
  An update without a search refits a clone of each output's `best_estimator_` on all rows: one fit per output.
  `fitted_models` then holds the refitted estimators. `last_search_models` and `search_rows` keep the last search and its row count.
  Tradeoff: the reused settings belong to the earlier rows, so a new search can choose better ones.
  `train_active` fits a new model in every round, so the option does not reach it.
- `search_options={"n_jobs": k}` reaches the scikit-learn search unchanged, which then fits its candidates in `k` processes.

Other factories:

- `kernel_surrogate` is a kernel-approximation learner.
  It standardizes the designs, builds random Fourier features of a Gaussian kernel, and fits a linear support-vector regression with the epsilon-insensitive loss.
  The kernel is `exp(-||u - u'||**2 / kernel_scale**2)` on designs standardized by the weighted mean and sample standard deviation.
  Observation weights are normalized, so a common weight factor does not change the fit.
  Prediction maps the query rows to features in blocks of at most 64 MiB (`8 * n_components` bytes per row),
  so the feature memory of a large candidate pool does not grow with its row count.
- For exact kernel ridge regression, wrap the scikit-learn estimator directly, for example `SklearnRegressorSurrogate(make_pipeline(StandardScaler(), KernelRidge(kernel="rbf")))`.
- Python only: this adapter wraps scikit-learn. DesignOptRs fills this role with its native hyperparameter search `RegressionFactorySurrogate` and has no counterpart.
  `hyperparameter_search_surrogate` wraps any estimator in the same search.
- `stepwise_linear_surrogate` also returns `SklearnRegressorSurrogate`, without the search arguments.
  It is classical stepwise regression with partial F-tests.
  It starts from the constant model and adds or removes one linear or pairwise-interaction term per step (`p_enter=0.05`, `p_remove=0.10`, `upper="interactions"`).
  `screening="refit"` (default) scores each candidate by its own least-squares fit.
  `screening="projection"` scores a sweep from a QR factorization of the current model: an addition by the squared projection of the residual on the new column's orthogonal part, a removal by `beta_j**2 / [(X'X)^-1]_jj`.
  It refits only the chosen move, whose refit p-value decides the step; a nearly dependent candidate (orthogonal part at most `sqrt(eps)` times its norm) gets a refit.
  Tradeoff: screened p-values differ by rounding, so a near tie can select another term.
  Each fitted model reports `least_squares_fits_` and `screening_projections_`.
- Construct the cascade-forward network directly with `CascadeForwardSurrogate`.
  Its `rng` field (default 0) sets the initial weights. An integer seed gives equal networks for equal data.
  Its `prediction_block_rows` field (default `None`, one batch) predicts a large query in row blocks of that size.
  The blocks bound the temporary memory; a block product can round differently, so predictions can change in their last bits.
- Support-vector classifiers fit boundaries using selected training points called support vectors.

### Gaussian processes

Gaussian processes model unknown responses through covariance between observed and queried designs.
Covariance describes how modeled responses vary together around their means.
A covariance kernel `k` calculates this relationship from design coordinates. Its length scales control correlation decay with coordinate separation.
A mean basis `h` supplies functions whose fitted combination describes the response trend.
The built-in kernels are squared exponential, exponential, Matérn 3/2, Matérn 5/2, and rational quadratic; a callable kernel is also accepted.
The bases are zero, constant, linear, and quadratic.
Select them by their names, which follow the choice-name rule of `designoptpy.core.choices`: `"squared_exponential"`, `"exponential"`, `"matern32"`, `"matern52"`, `"rational_quadratic"`, and `"zero"`, `"constant"`, `"linear"`, `"quadratic"`.
Other spellings, such as `"squaredexponential"` or `"pureQuadratic"`, raise `ValueError`; `"Squared-Exponential"` names `"squared_exponential"`.
Every built-in kernel fits one length scale per coordinate, so no name selects one shared length scale.

Independent outputs:

- Each response column is an independent GP with its own kernel and basis families, length scales, signal and noise standard deviations, and Cholesky factor.
- Outputs share only the training rows and the design standardization, so the prediction of one output never depends on another output.
- Design measures are often different physical quantities with different smoothness and noise.
  Independent outputs keep a rough output from distorting a smooth one.

Design standardization:

- `standardize=True` (the default) centers each design column by its training mean and divides it by its sample standard deviation (divisor `n - 1`).
- A column whose standard deviation is below `sqrt(eps)` (about `1.49e-8`) stays unchanged, which includes every constant column.
- Primary, scoring, and recovery fits apply this rule to their own training rows.
- The other surrogate families keep their own design scaling.

With standardized designs (the default) and responses in their own units, the prediction of one output at a design `x` is

```text
mean(x)            = h(x) @ beta + k(x) @ inv(K + s2 * I) @ (y - H @ beta)
latent_variance(x) = k(x, x) - k(x) @ inv(K + s2 * I) @ k(x)
response_variance  = latent_variance(x) + s2
```

Here `K` is the training covariance matrix, `k(x)` holds the covariances to the training designs, and `s2` is the noise variance.
Prediction computes the subtracted term as `v' v` with `v = inv(L) @ k(x)'`, where `L` is the lower Cholesky factor of `K + s2 * I`.
One forward triangular solve gives `v`, and the term is a sum of squares, so it cannot be negative.
A native kernel is `sf**2` times its correlation, where `sf` is the fitted signal standard deviation.
For every covariance setting, generalized least squares (GLS) gives the trend coefficients `beta` that maximize the likelihood; the fit inserts them, which is a profile likelihood.
The `"zero"` basis has no coefficients, so its prior mean is zero in response units. Responses are never centered, so no hidden intercept enters.
A rank-deficient basis, for example a linear basis with a constant design column, gets the minimum-norm coefficients.
The fitted values at the training rows do not depend on this choice.
Only a query that changes the constant coordinate gives a different value.
Remove such columns, or use the `"zero"` or `"constant"` basis.

Prediction holds `beta` and the covariance settings fixed.
The deviations therefore exclude uncertainty from estimating `beta`, the length scales, and the noise.

Latent and response uncertainty:

- Latent uncertainty describes the underlying response function.
- Response uncertainty also includes modeled observation noise.
- `GaussianProcessSurrogate` predictions use response uncertainty by default.
- `GaussianProcessSurrogate.predict_latent` returns `predict(design_samples, uncertainty_kind="latent")`.
- Built-in acquisition routes call `predict_latent(design_samples)` when the model provides it, and `predict` otherwise.
  An acquisition function assigns each proposed design a score for choosing the next expensive evaluation.
- An acquisition that scores one output calls `predict_latent_selected(design_samples, measure_index)` when the model
  provides it. `GaussianProcessSurrogate.predict_latent_selected` returns
  `predict(design_samples, uncertainty_kind="latent", measure_index=measure_index)`, so the other outputs need no
  covariance work. Each GP output has its own fit, so the selected column has the same values as in the full prediction.
  A model without the method predicts every output, and the route keeps the requested column.
- The routes that read only the predicted mean of one output pass its index: they call
  `predict_mean(design_samples, measure_index)` when the model provides it, then `predict_selected`, then `predict`.
  A negative or unavailable index raises `IndexError` on every route.
- A subclass of `GaussianProcessSurrogate` that overrides `predict` without the `uncertainty_kind` and `measure_index`
  keywords must also override `predict_latent`, `predict_latent_selected`, and `predict_selected`.
- A subclass that overrides `predict` but not `predict_mean` gets `predict_mean` from its own `predict` (all outputs)
  or `predict_selected` (a selection). The mean-only routes then use the overridden means, without the saving.

Mean-only prediction:

- `GaussianProcessSurrogate.predict_mean(design_samples, measure_index=None)` returns the means of `predict` bit for bit, with `standard_deviation=None`.
  It skips the variance step, which costs about `n_query * n_train**2` operations per output.
  The mean alone costs about `n_query * n_train * n_dimensions`.
- Built-in routes that read only the means call `predict_mean` when the model provides it, and `predict` otherwise.
  These routes are the pool and line-search samplers, `find_uncertainty_score`, `validate_uncertainty_threshold`, `cross_validate`,
  the region checks of `train_top_down`, the plots, and the family selection of the GP.
  The routes that read one output pass `measure_index`, so the GP computes only that output.
  The `AcquisitionModel` wrapper of `train_top_down` forwards the method and the selection.
- `SurrogateMapping` accepts a callable model. Pass `performance_model=model.predict_mean` for the same saving.
  The mapping metadata then holds predictions without standard deviations.

### Gaussian-process training

Gaussian process (GP) training selects covariance settings from observation density after integrating over unknown function values.
That integration is marginalization.
The resulting density is the marginal likelihood, and its logarithm is the log marginal likelihood.
Density describes probability spread across continuous response values.
The default fit of each output has two stages:

1. Discrete selection. The fit scores every pair of a kernel candidate and a basis candidate.
   - `kernel_candidates` defaults to `"exponential"`, `"matern32"`, `"matern52"`, `"rational_quadratic"`, and `"squared_exponential"`.
   - `basis_candidates` defaults to `"zero"`, `"constant"`, `"linear"`, and `"quadratic"`.
   - The score is the held-out mean squared error of 5 deterministic modulo folds.
   - The fit keeps the first pair with the smallest score.
   - A pair whose fit fails scores infinity.
   - A nonfinite held-out prediction or loss raises `ValueError`. This occurs only for responses far outside ordinary magnitudes. Scale such responses.
2. Continuous fit. The fit adjusts the length scales, the signal standard deviation, the rational-quadratic shape, and the noise standard deviation of the selected pair.
   It maximizes the marginal likelihood. This is type-II maximum likelihood.

The selection records `model_selection_scores`, `model_selection_fit_count`, `selected_kernel`, and `selected_basis`, one entry per output.
The 20 pairs and 5 folds cost 100 scoring fits plus the final fit per output, about 100 times one fit.
Pass `kernel_candidates=None` and `basis_candidates=None` to fit only `kernel` and `basis`. This is much cheaper but compares no families.
Cross-validation compares bases with different coefficient counts fairly. The marginal likelihood of a larger basis can only grow.
The section [Fitting metadata and model selection](#fitting-metadata-and-model-selection) states the partition and loss.

Threads for the selection:

- `model_selection_workers=k` (default 1) fits up to `k` candidate pairs at once on a thread pool.
  The folds of a pair stay in order, and the calling thread scores the pairs in kernel-then-basis order,
  so the scores, the selected families, the fit counts, and the raised errors equal those of the serial run.
- The pool runs only for native kernels and bases with the SciPy optimizer, and not for a `numpy.random.Generator` with `optimizer_starts > 1`.
  Caller functions therefore keep their call order on the calling thread.
- Measured: a 400-row fit ran about 1.9 times faster with 4 threads and a 150-row fit 1.4 times; a 40-row fit ran slower.
  The fits also use BLAS threads, so `k` times that count can exceed the processor cores.

Updates in learning loops:

- By default, `update` repeats both stages on the combined rows, so it costs as much as `fit`.
- `family_selection_interval=k` selects the families only at every `k`-th update; `None` selects them in no update.
  An update without a selection keeps each output's kernel and basis and runs only the continuous fit: one fit per output instead of 101.
  It records `model_selection_fit_count` 0 and keeps `model_selection_scores` and `model_selection_rows` of the last selection.
  `model_selection_rows` below the training-row count shows that the selection did not see the newest rows.
- `update_warm_start=True` starts the continuous fit of an unchanged kernel and basis at the previous fitted settings.
  The length scales are converted to the new design standardization.
- Tradeoff: new rows can favor another family, and a warm start can end in another local optimum.
  Predictions, uncertainty, and the designs that a learning loop selects can therefore change. Both options are off by default.
- `train_top_down` and `train_bayesian_uncertainty` call `update`, so the options reach them.
  `train_active` fits a new model in every round, so the options do not reach it.
  For one fit per output and round there, pass `kernel_candidates=None` and `basis_candidates=None`.

### Continuous fit

- The continuous fit starts from data-based values.
  The length scale is `max(1e-3, std(x_j))` per standardized coordinate.
  The signal and noise standard deviations are `max(1e-3, std(y) / sqrt(2))`.
- The noise standard deviation has the lower bound `max(1e-3, 0.01 * std(y))` in response units (`noise_standard_deviation_lower_bound`).
  The bound keeps the covariance well conditioned.
  For responses that vary by less than about 0.1, the absolute part `1e-3` dominates. Set a smaller bound or rescale such responses.
- `optimizer_starts` (default 1) is the number of marginal-likelihood optimizations per output.
  The first start uses the configured or data-based values.
  Each further start draws its length scales and noise from a search range with `rng` (default seed 0).
  The fit keeps the start with the largest log marginal likelihood.
  One start can stop in a poor local optimum. Each further start adds one optimization.
- For a native kernel, the optimizer receives the analytic gradient of the negative log marginal likelihood.
  A callable kernel uses finite differences.
  Each likelihood evaluation computes the scaled squared distance `r**2` of the training designs once.
  The covariance and the length-scale and shape gradient share it.
  The fit shares it only when scaling before subtraction keeps the separation of the designs.
  Large coordinates with small gaps, for example unstandardized designs near 1e15, lose digits there (cancellation).
  The gradient then subtracts the coordinates before it scales them.
- A gradient-free method (Nelder-Mead, Powell, COBYLA, COBYQA) receives no gradient, but the fit still computes it by default and rejects a setting whose gradient is not finite.
  `skip_unused_gradient=True` skips it: a Nelder-Mead fit of 200 rows then ran 3.8 times faster.
  Tradeoff: the rejection then does not occur, so in extreme settings the search path and the convergence result can change.
  A finite-difference gradient divides the rounding error of the likelihood by its small step, so near the maximum its error can be as large as the gradient itself.
- A start counts as converged when the optimizer reports success.
  It also counts as converged when L-BFGS-B ends with an `ABNORMAL` line-search stop at an iterate whose likelihood is larger than at its start.
- An iteration or evaluation limit is a recognized nonconvergence failure, because the fitted settings are then not the maximum-likelihood estimate.
  `fit_failure_kinds` records `"convergence"`.
- `fitted_length_scale`, `fitted_signal_standard_deviation`, `fitted_noise_standard_deviation`, `fitted_rational_quadratic_alpha`, and `fitted_log_marginal_likelihood` report the settings of each output.
- `hyperparameters_at_bounds` flags an output whose fitted noise ended at its lower bound.

### Fit failure and recovery

When covariance factorization or numerical optimization fails for one output, GP training refits only that output once.

- The recovery fit applies `fallback_options` to a copy of the configuration.
  The default fits a squared-exponential kernel with a constant basis, without family selection.
  It uses one maximum marginal-likelihood optimization (`optimizer_starts=1`) from the data-based values.
- Its length scales and noise therefore come from the data. The other outputs keep their primary fits.
- `NonlinearSurrogate` instead falls back to an intercept-plus-linear least-squares fit for the failed output.
  Its optimizer nonconvergence, such as the iteration limit, is a fitting failure.
- A custom `model_function` requires `initial_parameters`. Construction raises `ValueError` otherwise.
  The automatic seed describes only the parameters of the default quadratic model.
- Only numerical failures or reported optimizer nonconvergence permit either fallback.
  `fit_failure_action="error"` disables recovery.
- `used_fallback`, `fit_failures`, and `fit_failure_kinds` report, per output, whether recovery occurred and why.
- Invalid options, malformed responses, and unrelated callback errors propagate through direct fitting and model selection.
- If the recovery fit also fails, the fit raises `RuntimeError`. Its message names both failures, and its exception chain keeps them.
- Numerical recovery adds a bounded attempt with a simpler model. It does not establish model accuracy.
- GP, nonlinear, and cascade models accept an optional `optimizer` callable for integration and controlled failure tests.
  It must accept the arguments and return the result attributes of the corresponding SciPy optimizer.
  The GP optimizer also receives `jac`, the analytic gradient callable, or None for a callable kernel or a gradient-free method.
  A custom nonlinear optimizer receives `least_squares_options` unchanged, without `jac`.
  With SciPy's own optimizer, the default quadratic model is linear in its parameters, so the fit passes its exact constant
  Jacobian `[1, x, x**2]`, unless the caller sets `jac`, `args`, or `kwargs`.

### Memory and cost of Gaussian processes

- A GP fit with `n` training rows and `m` outputs stores one `n`-by-`n` Cholesky factor per output, about `8 * m * n**2` bytes.
- The factorization takes on the order of `n**3` operations, and every likelihood evaluation repeats it.
  The fit is always exact, at any row count.
- The library does not limit `n`.
- Prediction processes query rows in fixed blocks of about 32 MiB of temporaries.

### Polynomial surrogate limits

A total-degree polynomial basis in `d` dimensions has `comb(d + p, p)` terms for degree `p`. Degree 0 is the constant mean model.

- `maximum_terms` (default 100,000) is the enumeration budget for this combinatorial count.
  It counts every term, including the intercept, so it equals the coefficient count of each output.
- Fitting stores an `n_samples`-by-`n_terms` feature matrix and solves least squares on it.
- `maximum_feature_bytes` (default 536,870,912 bytes, 512 MiB) bounds the estimated model-owned feature arrays of each fit and each prediction call.
  For `n_rows` design rows, the estimate is `8 * ((2 * n_rows + 3 * d + 2) * (n_terms - 1) + n_rows)` bytes.
  A larger estimate raises `ValueError` that names `maximum_feature_bytes` before the features are allocated.
- The term count alone does not bound memory, because the feature matrix also grows with the row count.
  For example, 100,000 query rows with a 1,000-term basis need about 800 MB of features.
- The estimate covers the feature and exponent matrices. Coefficients, predictions, and the least-squares workspace lie outside it.
- A default candidate pool of 1,000,000 rows passes the default budget in one prediction call only for a basis of at most 34 terms.
  A quadratic in six variables (28 terms) is an example.
  Split a larger prediction query into row batches, or raise the budget explicitly.

Weighted fits: `fit(..., sample_weight=w)` minimizes `sum_i w_i * r_i**2` for each output residual `r`.
The fit scales each feature row and response row by `sqrt(w_i) / max_j sqrt(w_j)` and solves the ordinary minimum-norm problem.
Only weight ratios change the minimizer, so the scaling keeps the coefficients and prevents overflow: weights `1e300` give the fit of weights 1.
Equal weights reproduce the unweighted fit bit for bit. Weights of rows removed for NaN or infinite data are ignored;
at least one retained weight must be positive. `sample_weight` keeps the weights of the retained rows,
and `update(..., sample_weight=...)` adds weights for the new rows (weight 1 when omitted from a weighted model).
The top-down `training_weight_function` (see [Top-down options](#top-down-options)) refits all rows through `fit` with weights computed again for every row,
so these new-row semantics of `update` do not apply there.
Weights that are large near a response limit give a fit that is accurate near that limit, where the labels of a classification by regression change.

### Overflow checks

- A monomial feature that overflows float64 in a fit or a prediction raises `ValueError` ("polynomial features overflow float64; ...").
  The public `polynomial_features` still returns the infinite feature.
- A polynomial fit whose coefficients overflow raises `ValueError` ("polynomial coefficients are not finite; ...") at training.
  For example, the line through the responses -1.7e308 and 1.7e308 at the designs 0 and 1 has the slope 3.4e308.
- A prediction mean that overflows raises `ValueError` ("prediction mean is not finite: ...").
  Every surrogate builds its `Prediction` through one check, so the linear, polynomial, and Gaussian-process models give the same message.
  NumPy overflow warnings are suppressed, so the owned error is the only signal.

### Cascade-forward networks

Cascade-forward networks connect original inputs and earlier hidden outputs directly to each later layer.
Hidden activations are unit outputs after applying their configured activation functions.
By default, training uses every accepted row and minimizes the mean squared error.
`validation_fraction` (default 0, domain `[0, 1)`) turns on validation early stopping.
Each fit holds out `max(1, floor(validation_fraction * n + 0.5))` of the `n` accepted rows, drawn from `rng`, and trains on the others.
After each iteration, the fit evaluates the validation loss `0.5 * sum(r**2) / n_validation` of the held-out rows.
An iteration that does not set a new lowest loss counts as a failure, and `validation_patience` (default 6) failures in a row end training.
The fitted network is the iterate of the lowest validation loss. A patience stop is a regular stop and records no fit failure.
The model reports `validation_rows`, `validation_losses` (index 0 is the start), `best_validation_iteration`, `best_validation_loss`, and `validation_stopped`; all are `None` without validation.
The held-out rows estimate the error at unseen designs, so stopping at their lowest loss limits the fit to noise. This is early stopping, a form of regularization.
Tradeoff: the held-out rows do not train the weights, and the network depends on the random division.
`optimization_result` then describes the last optimizer iterate, not the returned network.
`l2_regularization` (default 0) optionally adds a squared-weight penalty.
This is L2 regularization, also called weight decay.
It reduces overfitting on noisy data and biases the weights toward zero.
Each `fit` and, by default, each `update` start L-BFGS-B from the seeded random start, so equal data give equal networks.
`warm_start=True` (default False) starts an `update` from the fitted weights instead.
It needs far fewer iterations, but the loss is not convex, so the network can end in another local minimum and then depends on the update history.

## Classification

`classify_designs` labels a row `True` when every measure lies inside its inclusive lower and upper limits.
Scalar limits broadcast over every output. A NaN limit marks an unavailable bound.
Negative infinity satisfies an upper-only requirement and violates a finite lower bound.
Positive infinity rejects the row, even when all bounds are disabled.
Measures that contain NaN raise `ValueError`.

`train_svm_classifier` fits a support-vector machine (SVM) from Boolean or finite 0/1 labels. Other labels raise `ValueError`.
With both labels, it fits a two-class classifier.
With one label, it fits a one-class classifier around the observed designs and retains the represented label.
This one-class bootstrap lets active learning start before both labels have been observed.
The returned `SklearnSvmClassifier` provides `predict` and a positive-for-`True` `decision_function`.
Its `support_vectors_` are in original design coordinates, including for a model fitted through a standardizing pipeline.
The classifier boundary and training-data plots accept this adapter directly.
For a classifier trained with other labels, such as `-1` and `1` or `"bad"` and `"good"`, `plot_classifier_training_data_2d` and `_3d` take `positive_class`: the rows with that label form the accepted group, and the default is the largest number or the last text in code-point order, the class that a positive decision score predicts in scikit-learn.

### Preprocessing and kernel

The SVM classifier standardizes the designs and gives each class the same prior weight.

- It normalizes the observation weights so each class has the same total weight.
  It standardizes each design column with the weighted mean and weighted standard deviation of these weights.
- A column without spread is only centered.
  An exactly constant column gets its constant as the center and the scale 1, so rounding in the weighted mean cannot produce a tiny scale that magnifies query changes.
- The adapter stores `center` and `scale` and applies them before every prediction, so callers pass original coordinates.
- The same class weights set the per-observation box constraints, so a rare requirement-satisfying class retains its influence.
  With unit weights this equals scikit-learn `class_weight="balanced"`.
- Both fitting paths use the radial basis function (RBF) kernel `exp(-gamma * ||u - v||**2)` with the explicit `gamma = 1 / s**2` for kernel scale `s`.
  The kernel acts on the standardized designs `u` and `v`, so `s` and a `gamma` option are in units of the column standard deviation, not in design units.
  The default scale `s = sqrt(d)` for `d` design variables keeps typical kernel values of order one as the dimension grows.
- One-class fitting uses `nu=0.05`, so the bootstrap boundary encloses about 95 percent of the observed class.
  See the [scikit-learn one-class SVM reference](https://scikit-learn.org/stable/modules/generated/sklearn.svm.OneClassSVM.html) for these bounds.

### Hyperparameter search

Two-class fitting tunes the box constraint `C` and the kernel scale `s` by cross-validated random search.

- `hyperparameter_trials` (default 50) pairs are drawn log-uniformly from `[1e-3, 1e3]` for both.
- By default, the rows are assigned once to `K = min(5, n_rows)` stratified folds.
  The rows of each label are shuffled, the label groups follow each other, and one continuous modulo-K sequence deals all rows to the folds.
  `search_validation` chooses another partition (see below).
- When each label has at least two rows, every training part keeps both labels.
  The rule also accepts labels with fewer rows than folds, for example three rows of each label with five folds, which scikit-learn `StratifiedKFold` rejects.
- Each pair is scored once by the balanced accuracy of all its out-of-fold predictions together (the pooled score).
  The best pair is refitted on all rows.
  A pooled score gives each row the same weight, so it is steadier than a mean of fold scores when the folds are small, as early in active learning.
- With `sample_weight`, the balanced accuracy weights each row.
- Each fold has its own class weighting and standardization of its own training rows.
  They do not depend on the trial, so each fold is prepared once and the trials vary only `C` and `s`.
- `search_workers` (default 1) sets the number of threads that fit the trials. The selected pair and score do not change,
  because all random draws occur before the trials and the first maximum by trial index wins.
  When a search runs, a value above 1 requires an integer `random_state` in `two_class_options`, so that no fit draws
  its seed from a shared random state in schedule order. A fit without a search ignores the option.
  libsvm releases the interpreter lock: one search on 600 rows took 1.4 s with 4 workers instead of 4.7 s,
  and on 40 rows the threads gave no gain.
- The adapter records `box_constraint`, `kernel_scale`, and `search_score`.
- `rng=None` uses the fixed seed 0 (`designoptpy.surrogate.classification.SVM_HYPERPARAMETER_SEED`), so default fits repeat.
- The default search makes `K * hyperparameter_trials + 1` fits per two-class model, 251 from five rows on.
  In general, a search makes `F * hyperparameter_trials + 1` fits, where `F` is the fold count of one partition.
- `hyperparameter_trials=None` fits the fixed `C=1` and `s = sqrt(d)`, or the `C` and `gamma` of `two_class_options`.
  This is cheaper and can classify worse.
- `PeriodicSearchSvmTrainer(search_interval=k)` is an opt-in `classifier_trainer` for `train_svm_active`.
  It searches on every k-th two-class fit and reuses the last selected `C` and `s` on the fits between, with one SVC fit each
  and `search_score=None`. The default trainer searches in every round. Tradeoff: a reused pair was selected on fewer rows,
  so the classifier can be worse on the new rows. A 20-round 2-D run took 2.2 s with `k=5` instead of 8.1 s.
- A smaller class with fewer than two rows also uses the fixed values, because stratified folds could not keep both labels in every fold.

`train_svm_classifier(search_validation=...)` selects the validation partition of the search. The option acts only when a search runs.

| Record | Partition | Fold count `F` |
| --- | --- | --- |
| `None` or `SvmKFoldValidation(fold_count=5, repartition=False)` | Stratified k-fold with `K = min(fold_count, n_rows)` folds, dealt as above; every row validates once | `K` |
| `SvmHoldoutValidation(fraction, repartition=False)` | Stratified holdout: a share of each label validates, the other rows train | 1 |
| `SvmPartitionValidation(folds)` | Supplied zero-based fold of each training row; every row validates once | number of folds |

- Holdout count rule: a label with `n_k` rows validates `m_k = min(max(floor(fraction * n_k + 0.5), 1), n_k - 1)` of its shuffled rows.
  The bounds keep both labels in the training part and in the validation part, because a search runs only when each label has at least two rows.
  For example, `fraction=0.25` with 8 False and 12 True rows validates 2 False and 3 True rows.
- The pooled score uses only the validated rows. A holdout therefore scores its validation rows, and k-fold and supplied partitions score every row.
- `fold_count` is at least 2, and `fraction` lies in `(0, 1)`. A supplied partition must hold one fold per row, number its folds from 0 without gaps,
  have at least two folds, and leave both labels in every training part. The search checks these rules before any fit.
- `repartition=True` draws a new partition for every trial, in trial order, after the trial pairs and before any fit.
  Tradeoff: one fixed partition favors the settings that suit its folds, and new partitions average out this luck, so the selection is more robust.
  But each score then mixes the quality of a setting with the luck of its partition, so a reliable choice needs more trials, about twice as many.
  With one trial, both choices draw the same partition. A supplied partition has nothing to draw again, so it has no repartition.
- `PeriodicSearchSvmTrainer(search_validation=...)` forwards the record to each search. It rejects a supplied partition when it is built,
  because an active-learning run changes the row count at every update, so a fixed assignment would fail after expensive evaluations.
  `PeriodicSearchSvmTrainer(search_interval=1, search_validation=...)` searches in every round, as the default trainer of `train_svm_active` does.

These classifier controls affect fitted boundaries. They do not certify accuracy on unseen designs.

## Active learning

Active learning selects new designs from model predictions before invoking the expensive response evaluator.
After evaluation, workflows append accepted observations and update or refit the model.
Bottom-up mappings return the result forms of the [core result contract](../designoptpy-core/README.md#evaluator-and-mapping-results).
Mapping routes use `measure_choice` to select the measures that the model learns.
The other group and the mapping metadata remain available in the result.

### Selection rules

Each route selects designs by its own rule and returns its own result record:

| Route | Selection rule | Result record |
| --- | --- | --- |
| `train_active` | Largest eligible acquisition score in a random candidate pool | `ActiveLearningResult` |
| `train_bayesian_uncertainty` | Largest optimized predictive standard deviation, separately for each output | `BayesianUncertaintyResult` |
| `train_top_down`, `train_top_down_mapping` | Limit and exploration candidate strategies | `TopDownActiveLearningResult` |
| `train_svm_active` | Up to `number_new_samples_per_iteration` candidates nearest the classifier decision boundary | `SvmActiveLearningResult` |

Limit routes rank predicted response boundaries with a configurable acquisition score.
The default `gaussian_straddle_acquisition` scores each output as `k*sigma - d`:

- `k` is the exploration factor.
- `sigma` is the predictive standard deviation.
- `d` is the nearest-boundary distance, the absolute difference between the predicted mean and its nearest finite response limit.
- The design score is the largest output score. An output without finite limits contributes `k*sigma`.

Behavior of the exploration factor:

- On bounded outputs, the default `k=0` favors means nearest a boundary, including means outside the response limits.
- At zero, an unbounded output can dominate negative bounded-output scores and produce tied design rankings.
- A positive factor expands an uncertainty band. For bounded outputs, a positive score means this band reaches across the nearest boundary.
- Positive infinity selects only the largest predictive deviation.
- The score is a margin, not a probability. Response units and output scales affect it.
- The default score still requires predictive standard deviations, even when `k=0`.

Exploration routes seek high uncertainty or designs far from known observations within a requested response region.

`train_bayesian_uncertainty` starts `batch_size` local searches for each output.
The `UncertaintyOptimizer`, by default `scipy_uncertainty_optimizer`, maximizes that output's predictive standard deviation.
In the role of `scipy_uncertainty_optimizer`, DesignOptRs uses a native algorithm: bounded coordinate pattern search (`optimize_acquisition`).
`BayesianMeasureSelection` records the starts, optimized designs, scores, selected design, and optimizer result.
The optimizer result keeps the evidence of every start in `optimizer_result.trials`: one single-design `AcquisitionOptimizationResult` per start, in start order,
with the endpoint, the objective, and that start's own `converged`, `termination_reason`, `predictor_rows`, `optimizer_iterations`, and `status_codes`.
`scipy_uncertainty_optimizer` fills it; its trial rows sum to `predictor_rows`, and the concatenated trial codes equal `status_codes`.
Every round record keeps it for every measure, also the final round without a novel design, because it shows why nothing was proposed.
`trials` is `None` for an optimizer that returned coordinates only (then `optimizer_result` is `None` too) or no per-start records.

The SVM route labels designs with the selected inclusive limits, as `classify_designs` does.
The SVM route needs explicit limits:

- Its `lower_limits` and `upper_limits` are required. `None` leaves a side unrestricted.
- It fits Boolean labels, so infinite response signals never become numerical training targets.
- Its initial `candidate_count` is a strict request, validated before physical evaluation or fitting.
- If a round's pool contains no eligible design, a retry draws `max(C, min(10 * C, 2_000_000, floor(67_108_864 / (3 * d + 8))))` candidates for `C = candidate_count`.
  This keeps the retry pool within an estimated 512 MiB.
  The effective options of the result record the retry count.
- If the retry pool also holds no novel design, the run stops with `no-novel-designs`.

The result's `predicate`, a `ClassificationPredicate`, records the selected measures and the normalized limits that labeled the data.
A resumed run with `initial_model` requires `resume_predicate`, usually the earlier `predicate`.
The run raises `ValueError` before any sampling or evaluation when the selected measures or the limits differ.
Limits are compared after NaN becomes infinity and after broadcasting to a common width, so a scalar limit equals a vector of equal values.
Labels from two feasibility rules would make the classifier answer neither question.

### Known designs and the evaluation ledger

Known designs are not evaluated again by default, because `allow_repeated_evaluations=False`.
Exact coordinates identify known designs. Nearby coordinates remain distinct.
Set `allow_repeated_evaluations=True` to collect repeated observations of noisy functions, including duplicates within one batch.
Each run keeps a ledger of the training designs and every design evaluated in the run, also rows that fitting dropped.
The result returns it as `evaluation_ledger`. The ledger contains no responses, so it cannot fit a model or supply classifier labels.
A resumed run starts its ledger from the retained training rows of the model only.
It can therefore evaluate a design again whose earlier response the model did not retain.
The trainers accept no input ledger.

Selection with known designs:

- Bayesian training chooses the maximum among novel optimized rows, so a known maximum cannot hide a novel candidate.
- Top-down strategies rank novel rows before they truncate a candidate pool, including optimizer refinements.
- `CandidateRequest` passes the evaluation ledger and the repetition policy to each strategy.
- An exhausted pool returns an empty selection, and no expensive evaluation occurs.

Regional samplers:

- Standalone regional samplers permit repeats by default.
  Pass `evaluation_ledger` and `allow_repeated_evaluations=False` to filter known rows before regional ranking.
- Top-down training passes its ledger and repetition policy to every regional sampler, also to a wrapped one such as a `functools.partial`.
  A custom regional sampler must therefore accept the keywords `evaluation_ledger` and `allow_repeated_evaluations`.
- Top-down training validates the width, finiteness, and box membership of every selected design before evaluation.

Initialization drops duplicate rows of its batch unless repeats are allowed. A new run starts without known designs, so at least one row remains.
Only `train_top_down` with an empty `(0, n_dimensions)` initial matrix returns `model=None`, empty observations,
zero physical rows and fits, and `stop_reason="no-novel-designs"`.
No responses, labels, or model fits are fabricated.

### Budgets and stop reasons

Two budgets and one fixed rule stop a learning run:

| Rule | Unit | Stop reason |
| --- | --- | --- |
| `iterations` | requested rounds | `iterations-completed` |
| `max_evaluations` | new expensive evaluations, including initialization | `evaluation-budget` |
| first round without a novel design (Bayesian, SVM, and `train_active`; top-down only with `stop_without_progress=True`) | rounds | `no-novel-designs` |

`stop_reason` is a `LearningStopReason`, a string enumeration whose values are the strings in this table.
`no-novel-designs` also reports a `train_top_down` initialization without a design.

Rounds without a novel design:

- The Bayesian, SVM, and basic trainers stop at their first round without a novel design, also in the last round.
  Their next round would draw the same kind of proposal from the same model, so it is unlikely to find a novel design.
- By default, top-down training continues after such a round. It keeps the record and logs a warning.
  Its cadences alternate the samplers and each round draws new starts or pools, so a later round can still find a novel design.
- `train_top_down(..., stop_without_progress=True)` and `train_top_down_mapping(..., stop_without_progress=True)` stop after such a round instead, with `no-novel-designs`.
  This saves the acquisition work of the later rounds. It can also miss designs that a later round would find, so the default is `False`.
  A round without a scheduled request never triggers the stop. Rust `LearningWorkflowOptions.stop_without_progress` has the same meaning.
- Top-down training also skips, with a warning, a round for which its cadences schedule no candidate request.
  Such a round makes no record.
  A run without any finite limit and with the default cadences therefore evaluates only its initial designs.

Budget arithmetic:

- The trainers count every model fit in `model_fits` but do not limit them.
- A round starts only while one evaluation remains.
- The trainers truncate each proposal batch to the remaining evaluation budget.
  For example, rounds of two designs under `max_evaluations=3` evaluate two designs and then one design.
- The run spends the budget exactly and never exceeds it.
- The same rule decides, before the update, whether a round is the final round.
- Budgets limit cost. Reaching one does not establish model accuracy or convergence.

Learning results retain `evaluated_rows`, `model_fits`, `completed_rounds`, `stop_reason`, and `elapsed_seconds`.

- `evaluated_rows` counts only rows evaluated in the current call, including initialization. Resumed observations are not charged again.
- `completed_rounds` counts the rounds that evaluated at least one design and updated the model, in every trainer.
  A round that requested designs but evaluated none keeps its record in the trace, where it shows what was requested, but it does not count.
- Every trainer also reports `proposal_rounds`, because an all-known candidate pool or acquisition result uses a proposal round but completes no round.
  `train_bayesian_uncertainty` and `train_svm_active` count every round that passed the budget check, also a final round without a novel design and also without a retained trace.
  The retry pool of an SVM round belongs to that round. A round that the evaluation budget prevents requests nothing and does not count.
  With `retain_trace=True`, `proposal_rounds` equals `len(result.iterations)` for both trainers.
  In `train_top_down` and `train_top_down_mapping`, `proposal_rounds` counts every round that called at least one candidate strategy, also without a retained trace.
  A round that the cadences skip calls no strategy and makes no record, so it does not count. With a retained trace, `proposal_rounds` equals `len(result.iterations)`.
- `elapsed_seconds` is the wall-clock time of the whole call, including initialization, measured with `time.perf_counter`.
- `effective_options` is an immutable `LearningRunOptions` record.
  It holds the effective budgets, candidate count, repetition policy, trace retention, initial random-generator state, and route options.
- These records stay available independently of the history mode, so a short retained history does not hide the actual work.

Random generators:

- Every trainer, regional sampler, and validator with an `rng` parameter accepts a NumPy `Generator`, an integer seed, or `None`. `numpy.random.default_rng` converts it.
- A Generator is used directly and advances. An integer seed creates a new seeded generator. `None` draws fresh operating-system entropy.
- The strategy callbacks that a trainer calls with its own generator require a Generator: `uniform_box_sampler`, `uniform_design_box_sampler`, `random_initial_point_selector`, `uniform_direction_sampler`, `scipy_uncertainty_optimizer`, and `scipy_internal_acquisition_optimizer`.

### Progress records

Each trainer writes live progress records while it works. A record is one `logging.LogRecord`.
Its severity, INFO or WARNING, states its importance. The records go to the module logger of the trainer:

| Trainer | Logger |
| --- | --- |
| `train_top_down`, `train_top_down_mapping` | `designoptpy.surrogate.top_down` |
| `train_active`, `train_bayesian_uncertainty` | `designoptpy.surrogate.active_learning` |
| `train_svm_active` | `designoptpy.surrogate.classification` |

A run writes these records in this order. `N` is a count, `R` a pool size, and `T` a stage time in seconds:

| Severity | Message | When |
| --- | --- | --- |
| INFO | `Performing initial sampling...` | before the run draws its initial designs: `train_top_down_mapping`, `train_bayesian_uncertainty`, and `train_svm_active` only |
| INFO | `Initial model fitted: new evaluations N; evaluation T s, fitting T s` | after the initial fit; not when the run resumes a fitted model |
| INFO | `Starting iteration N...` | at the start of each round that requests proposals, after the budget check |
| WARNING | `No candidate request scheduled. Skipping iteration N.` | a top-down round whose cadences request nothing |
| INFO | `No new unique samples to evaluate in iteration N. Trying a candidate pool of R rows...` | `train_svm_active`, before its one retry with the larger pool |
| WARNING | `No new points to evaluate found in iteration N. Stopping.` | a requesting round without a novel design; the top-down trainers write `Continuing.` instead of `Stopping.` when the run goes on |
| INFO | `Done with iteration N: new evaluations N; proposal T s, evaluation T s, fitting T s` | at the end of every requesting round, also of a round without a novel design |
| INFO | `Completed N rounds; <stop reason>` | once at the end, with `completed_rounds` and the `stop_reason` value |

Stage times are wall-clock seconds, measured with `time.perf_counter` and written with three significant digits (`%.3g`):

- The proposal stage runs from the round start until the designs to evaluate are known.
  It includes the candidate strategies, the scoring, the classifier retry, the novelty filter, and the budget truncation. It excludes the snapshot copy.
- The evaluation stage is the expensive response call of the round or of the initialization, including its output checks.
- The fitting stage is the model fit, refit, or update call of the round or of the initialization.
- A skipped stage reports 0. A round that finds no novel design therefore reports `evaluation 0 s, fitting 0 s`.

The library adds no log handler, so the application decides what is displayed.
By default, Python displays only WARNING and higher records. Without a configured handler, it writes them to standard error through `logging.lastResort`.
Call `logging.basicConfig(level=logging.INFO)` to display the progress.
Call `logging.getLogger("designoptpy.surrogate").setLevel(logging.WARNING)` to hide the INFO records of every surrogate logger.
The records change no result, count, or random draw, and no trainer has a logging option.

### Retained history and snapshots

The trace is the sequence of training-round records.
The Bayesian, classifier, and top-down trainers also record a round that evaluated nothing; `train_active` records only rounds that evaluated a design.
Set `retain_trace=False` and supply `trace_sink` to pass each record to a caller-supplied function without storing it.
Final training data and the round counts remain available.

Retained history costs memory. A trace record stores the selected designs and responses of one round.
Options that store candidate pools multiply this cost.
`save_candidates` in the built-in candidate strategies and `retain_candidates` in `train_svm_active`
store about `8 * number_candidates * (n_dimensions + 1)` bytes per round.
`save_candidate_acquisition` in `train_active` stores only the scores, `8 * candidate_count` bytes per round.

`ActiveLearningSnapshotPolicy` selects which pre-update model state the record of each model update keeps.
The `cadence` counts completed model updates:

| `SnapshotMode` | Retained state |
| --- | --- |
| `METRICS_ONLY` | No model state |
| `PARAMETERS` | The result of the supplied `parameter_snapshotter` at the first update and every `cadence`-th update |
| `CHECKPOINTS` | A deep copy of the model at the first update and every `cadence`-th update |
| `FULL_MODELS` (default) | A deep copy of the model at every update |

The default keeps every pre-update model, so a reader can plot iteration progress and reconstruct earlier predictions from any run.
Sparse policies give observation-only progress figures for the rounds without a snapshot.
Select `SnapshotMode.METRICS_ONLY` for long runs or large models when that history is not needed. The fitted models and selected designs do not change.
Deep copying recursively copies nested data, so later model updates cannot change the saved state.
The final post-update model is always `result.model`.

Which updates keep a snapshot:

- A round without an update (no novel design) keeps its record but no snapshot, so no unchanged model is copied twice.
- The first update holds the initial model, so the parameter and checkpoint modes keep it.
- The prior model of update `k * cadence` is the model before that completed update.
- With `retain_final=True`, the default, parameter and checkpoint modes also keep the actual final update when it is off cadence.

The final checkpoint:

- Bayesian, top-down, and classifier results expose the pre-update record of the final update as `final_checkpoint`, also when `retain_trace=False`.
- `final_checkpoint` is `None` in metrics-only mode, with `retain_final=False`, or when no update runs.
- The iteration count or the evaluation budget can end the run. The trainer then knows before the update that it is final, so the live `trace_sink` event of the final update already carries its snapshot.
- A round without a novel design can follow any update and end the run. The trainer cannot know this before the update.
- The trainers therefore hold the pre-update state of each update that the cadence skips as a pending snapshot until the next update.
- When the run ends, `final_checkpoint` is a copy of the record of the final update with this pending snapshot attached.
- The record in `iterations` and the streamed event keep the cadence decision. The record of a round without an update holds no snapshot.

Memory:

- A full-model snapshot of a Gaussian process with `n` training rows and `m` outputs holds one `n`-by-`n` covariance factor per output, about `8 * m * n**2` bytes.
- `FULL_MODELS` keeps one such copy per update. Checkpoints keep the first update, one copy per `cadence` updates, and the final update.
- With `retain_final=True`, the pending snapshot makes checkpoint mode copy the model at every update. It makes parameter mode call its snapshotter at every update. At most one pending copy exists at a time.
- Pass `retain_final=False` to copy only on the cadence.
- The library does not limit this memory. Choose the snapshot mode, the cadence, and the iteration count to fit the available memory.

Result records prevent field reassignment and protect copied numeric arrays against ordinary writes. These numeric results are immutable.

### Acquisition optimizers and regional samplers

The built-in acquisition optimizers return `AcquisitionOptimizationResult`.
It keeps finite candidate coordinates separately from convergence information.
It reports objective values, `converged`, a `termination_reason` token, and actual query rows and iterations when available.
Convergence means the optimizer met its numerical convergence criteria. An iteration limit alone does not establish convergence.
Useful coordinates can exist before convergence.
The regional optimal samplers and `train_bayesian_uncertainty` default to `nonconvergence="use_candidate"`, which keeps those coordinates.
Choose `"error"` to reject reported nonconvergence.
Coordinate-only callbacks report `converged=None`. Their valid bounded candidates remain usable under either policy.
Configuration errors and callback failures still propagate to the caller.
On a fixed box, whose lower and upper bounds are equal, SciPy skips the optimization and reports no iteration count or status.
The SciPy optimizers then return the only design with `optimizer_iterations=None`.
With a constraint, `scipy_internal_acquisition_optimizer` accepts only SLSQP (the default), trust-constr, COBYLA, or COBYQA.
Other SciPy methods ignore constraints with only a warning, so the optimizer rejects them before any acquisition call.
Without a gradient function, SciPy estimates each gradient by forward differences, with one one-row acquisition call per moved coordinate.
The optimizer option `batched_gradient=True` (default False; L-BFGS-B and SLSQP only) builds the same rows with SciPy's step and bound rule and predicts them in one call.
The constraint Jacobian of `scipy_internal_acquisition_optimizer` is batched the same way.
This removes the fixed cost of most model calls; `predictor_rows` still counts every predicted row.
The option is off by default, because a batched prediction can round differently from a one-row prediction, so designs and iteration counts can change in the last digits.
The directional line optimizer divides each direction by its largest coordinate magnitude before its norm.
This keeps huge and tiny finite directions on the same bounded search ray.
In the role of `scipy_internal_acquisition_optimizer`, DesignOptRs uses a native algorithm: bounded coordinate pattern search (`native_internal_acquisition_optimizer`).

The six regional samplers return a `CandidateSelection`: zero or one selected design and the evidence of its selection.
Exploration samplers report `is_in_requested_region` and `used_region_fallback`. A fallback design lies outside the requested region.
The optimal-acquisition samplers report the acquisition value of the selected design and an `optimizer_result` that combines every trial optimization.
They also report `trial_results`, one `AcquisitionOptimizationResult` per trial (one local optimization from one start) in trial order, and `used_start_fallback`, one Boolean per trial.
A trial record describes the optimizer endpoint before any start replacement; a coordinate-only optimizer gives a record with `converged=None` and no counts.
Random and line-search samplers rank by distance and report `acquisition=None`.
The random samplers also report `proposed_candidates`, the drawn pool size, and `novel_candidates`, the pool rows left after the novelty filter (all drawn rows when repeats are allowed); the other samplers leave both `None`.
Limit samplers request no response region, so they report membership and fallback as `None`, which means not reported.
A custom sampler can return a bare design matrix. Its evidence fields are then `None`.
`TopDownIteration.acquisition` stores NaN, not zero, for an evaluated design without an acquisition value.

Start replacement, when repeats are not allowed:

1. A row is novel when it is not in the evaluation ledger and no earlier row of the same matrix equals it, coordinate by coordinate.
   The samplers test the endpoints and the starts this way, each on its original rows.
2. The start of a trial replaces its endpoint when the endpoint is not novel and the start is novel.
   So an endpoint that is in the ledger, or that repeats an earlier endpoint of the same call, falls back to a start that is neither in the ledger nor a repeat of an earlier start.
   The acquisition value of each replacing start is computed again.
3. The samplers then keep the novel trial designs and rank only these.

`used_start_fallback` is the mask of step 2. With repeats allowed it is all `False`. With an empty ledger, a repeated endpoint can still be replaced.
A start is not compared with the endpoints of other trials: when a replacing start equals a kept earlier endpoint, its entry stays `True` and step 3 removes that row.
A start that repeats an earlier start never replaces its endpoint.
The rule keeps the pool close to the trial count: a refinement that repeats a known design would cost a second expensive evaluation, and one that repeats an earlier refinement adds no candidate, while its start is a valid design with a cheap acquisition value.

Exploration routes share one region-membership rule for a predicted response `y`.
Two limits request the closed interval `lower <= y <= upper`, so the boundary belongs to the acceptable interval.
One limit requests the open exterior `y > upper` or `y < lower`, the rejected side of that boundary.
Every exploration sampler and `ExplorationCandidateStrategy` apply this rule. An exploration request without any limit raises `ValueError`.
The optimal-acquisition exploration sampler constrains its optimizer with the closed condition `residual <= 0`, because a constrained optimum need not exist on an open set.
It then classifies the optimized designs with the shared rule, so a prediction equal to a one-sided limit is not reported as in the region.

A random regional pool of `n` candidates in `d` dimensions stores about `8 * n * (4 * d + 8)` bytes while it is ranked.
Without a count (`acquisition_parameters=None`), the random samplers use `default_candidate_count(d)`, which is `min(1_000_000, floor(53_687_091 / (3 * d + 8)))`.
For example, 20 design variables give 789,516 candidates.
This default resolves predicted boundaries finely. Its prediction work and memory grow with the count, up to about 546 MiB per pool.
The two-ray samplers divide that count by the largest number of predicted rows of one ray at the default 20 iterations:
85 for `sample_limit_line_search` (its start, 41 probes in each direction, and two final endpoints) and 84 for
`sample_exploration_line_search` (one chord point at the end). Up to 15 design variables this gives 11,764 and 11,904 rays,
so a default call has the prediction budget of one default random pool. More rays give more boundary points for the maximin choice.
Both searches of a ray start at the same point, so these samplers predict each distinct start once.
`sample_limit_optimal_acquisition` uses the exploration factor 0.5 when `acquisition_parameters=None`.
Proposal bounds can be narrower than historical training bounds. Line samplers project selected starts without changing observations.
Their default start selector samples with replacement, so ray starts can use repeated training rows.
Set `initial_point_selection_options={"replace": False}` for distinct indices when enough training rows are available.
A smaller start pool reduces work and can miss useful boundary candidates.

### Top-down options

Omitted top-down limits leave their side unrestricted. Pass `upper_limits=0` to learn the zero boundary.

High-level top-down mapping binds `point_candidate_count` to the random samplers `sample_limit_random` and `sample_exploration_random`, the point-prediction defaults.
When it is omitted, they use the default count above, up to one million candidates per route.
This is up to 1000 times more prediction work than a pool of 1000 candidates, with a finer boundary resolution; pass a smaller count for a cheaper, coarser search.
An `acquisition_parameters` entry in the route options takes precedence. `effective_options.candidate_count` records the count used.

`individual_limit_cadence` (default 3) sets the interval of rounds that sample each finite limit separately.
Infinity disables these split-limit rounds and keeps combined-limit rounds. `None` disables all limit sampling.
NaN, zero, negative, and fractional cadences raise `ValueError`.
Exploration rounds from `pure_exploration_cadence` supplement limit rounds; infinity or `None` disables them.

Top-down requests carry no acquisition state, and the trainers have no acquisition-state update callback.
Each sampler owns its settings.
Bind a setting in the route options, for example `sampling_limits_options={"acquisition_parameters": {"ExplorationFactor": 0.8}}`.
A custom regional sampler receives `(model, design_space, measure_index, lower_limit, upper_limit)` and the keywords `rng`, `evaluation_ledger`, and `allow_repeated_evaluations`.

Training weights: `train_top_down` and `train_top_down_mapping` take `training_weight_function`, a rule for the observation weights of every fit.
None (default) fits and updates without weights.

- The trainer calls `training_weight_function(measures, lower_limits, upper_limits)` before each fit and passes the result to the model's `fit` as `sample_weight`.
- `measures` holds the selected measures of the fit rows in fit order, shape `(n_rows, n_measures)`.
  At the initial fit, these are the evaluated initial rows. At each update, these are the model's retained training rows followed by the rows evaluated in this round.
- `lower_limits` and `upper_limits` are copies of the normalized limit vectors: a missing lower limit is `-inf`, and a missing upper limit is `+inf`.
- The function returns one weight per fit row, shape `(n_rows,)` or `(n_rows, 1)`.
  The trainer sets the weight of a rejected design (an infinite measure) to zero, because the fit leaves that row out. The model checks the other weights.
- Every weighted update is a complete refit of all rows through `fit`, with weights computed again for all rows.
  So a model option that saves work between updates, such as `SklearnRegressorSurrogate.search_interval`, does not apply.
- The model's `fit` must accept the keyword `sample_weight`. `PolynomialSurrogate`, `LinearSurrogate`, and `SklearnRegressorSurrogate` accept it.
  `GaussianProcessSurrogate`, `CascadeForwardSurrogate`, and `NonlinearSurrogate` do not, so the default models of both `model_type` values need a `model_factory` override.
- An unsupported model raises `TypeError` before the initial evaluation. A resumed `initial_model` is checked before any work and keeps its fit until the first update.
  Limit: the check reads only the signature of the surrogate's `fit`. `SklearnRegressorSurrogate` forwards the weights to its estimator,
  so an estimator whose `fit` takes no `sample_weight` raises inside the initial fit, after the initial evaluation.

A good or bad label depends only on where the predicted response crosses a limit.
An ordinary least-squares fit gives every row the same weight, so rows far from the limits can move the predicted crossing when the model cannot follow the response everywhere.
Weights that are large near a limit make the rows near the limit dominate the fit. This is weighted least squares, here a local fit near the limits.
The weights use evaluated measures, not predictions, so they do not depend on the current model.
The band rule below gives the weight `exp(-1)` to a row at the distance 0.3 (in measure units) from its nearest limit.
A missing limit gives an infinite distance, so the other limit decides.
`np.fmin` ignores the NaN distance `inf - inf` of a rejected design on the side of a missing limit, and `np.errstate` silences the NumPy warning of that subtraction.
The example replaces the cascade-forward default model of the point-prediction route by a line model, which accepts weights:

```python
import numpy as np
from designoptpy.surrogate import PolynomialSurrogate, train_top_down_mapping


def band_weight(measures, lower_limits, upper_limits):
    with np.errstate(invalid="ignore"):
        distance = np.fmin(np.abs(measures - lower_limits), np.abs(measures - upper_limits))
    return np.exp(-np.sum(distance**2, axis=1) / 0.3**2)


result = train_top_down_mapping(
    lambda x: x[:, :1] ** 2,  # performance measure x**2 on [0, 1]
    [0.0],
    [1.0],
    0.1,  # lower limit
    0.5,  # upper limit
    model_type="point-prediction",
    model_factory=PolynomialSurrogate,
    model_options={"degree": 1},
    point_candidate_count=1000,
    iterations=5,
    training_weight_function=band_weight,
    rng=0,
)
print(result.model.sample_weight.shape)  # one stored weight per training row
```

Limits: weights cannot repair a model that is too simple near the limits.
A narrow weight profile leaves fewer effective rows, which can make the fit rank deficient.

The regression trainers accept signed infinity in the selected measures as a rejected design, for example after a failed analysis.
Such a row gives no regression information, but its rejection is an expected result, not malformed data.

- The trainer evaluates, counts, and records the row and adds it to the evaluation ledger.
- The complete-row filter of the model fit or update leaves the row out.
- The result `design_samples` and `measures` of the Bayesian and top-down trainers are the rows that the final model fitted.
  `train_active` keeps every evaluated row in evaluation order.
- A fit or an update batch without any finite selected row still raises `ValueError` ("no finite training samples are available").
  One round whose every design is rejected therefore ends the run.
- NaN is always an error.
- The other group can hold signed infinite requirement signals.
  It does not enter the model and stays unchanged in the records.

### Boundary-band refit

`select_boundary_band(deficits, *, band=0.1, minimum_count=20)` selects the training designs near a requirement limit.
It returns a `BoundaryBandSelection` record with the fields `band`, `minimum_count`, `absolute_deficit`, `is_selected`,
`design_count`, `largest_deficit`, and `is_widened`.

- `deficits` holds the finite deficits of the evaluated designs, shape `(n_samples,)` or `(n_samples, n_requirements)`.
  Convert the measures with `designoptpy.core.evaluation.measure_to_deficit` first, so the conversion stays visible.
- The absolute deficit of a design is the absolute value of its largest deficit.
  For the limits `L <= y <= U` it is `min(|y - L|, |y - U|) / (U - L)` inside the limits: the normalized distance from the nearest limit.
- The band is inclusive: a design with an absolute deficit at most `band` is selected.
- When fewer than `minimum_count` designs lie in the band, the selection widens to the `min(minimum_count, n_samples)` designs
  with the smallest absolute deficits. A stable sort keeps the row order of equal values. `is_widened` reports it.
  With at least `minimum_count` designs, a widened selection holds a design outside the band, so `largest_deficit` exceeds `band`.
  With fewer designs, every design is selected, and `largest_deficit` exceeds `band` only when a design lies outside the band.
  For example, `select_boundary_band([-0.01])` gives `is_widened=True` and `largest_deficit=0.01`.
  Zero designs give an empty selection with `largest_deficit=None`.
- NaN or an infinite deficit raises `ValueError`: a rejected design has no distance from a limit.
  `band` must be finite and positive, and `minimum_count` a positive integer.

A two-stage refit uses the selection between two top-down stages.
Stage 1 trains from random initial designs. A fresh model of the same class is fitted to the selected designs.
Stage 2 resumes from that model with `initial_model`, so each of its updates fits the selected designs and the new designs together:

```python
import numpy as np
from designoptpy.core.evaluation import measure_to_deficit
from designoptpy.surrogate import PolynomialSurrogate, select_boundary_band, train_top_down_mapping


def distance(designs):
    return np.linalg.norm(designs, axis=1, keepdims=True)


rng = np.random.default_rng(4)
problem = (distance, np.full(3, -6.0), np.full(3, 6.0), 2.0, 5.0)  # mapping, bounds, limits
route = {
    "model_type": "point-prediction",
    "model_factory": PolynomialSurrogate,
    "model_options": {"degree": 2},
    "point_candidate_count": 10_000,
    "iterations": 20,
}
first = train_top_down_mapping(*problem, rng=rng, **route)  # stage 1
deficits, _ = measure_to_deficit(first.measures, 2.0, 5.0)
selection = select_boundary_band(deficits, band=0.1, minimum_count=20)
refit = PolynomialSurrogate(degree=2).fit(
    first.design_samples[selection.is_selected], first.measures[selection.is_selected]
)
second = train_top_down_mapping(*problem, initial_model=refit, rng=rng, **route)  # stage 2
```

The refit is a weighted least-squares fit with weight one inside the band and zero outside it, a local fit near the limits.
A model that cannot follow the response everywhere, such as a quadratic of a distance, then places its predicted boundaries
closer to the limits, because the far designs no longer pull the fit. The minimum count keeps the refit well determined:
a quadratic in three variables has 10 coefficients, and 20 designs give twice as many observations.
Limits: a wide band admits far designs again, and the refit cannot repair a model class that is too simple near the limits.
`training_weight_function` (above) is the one-call alternative that weights the rows near a limit at every fit.
[Tutorial 03](../../examples/tutorials/tutorial_03_surrogate_model.py) teaches the two stages on a hollow sphere.

## Observed classification uncertainty

Uncertainty validation returns the maximum absolute predicted score among observed classification errors.
This value is the uncertainty threshold. Scores with `abs(score) <= threshold` are uncertain.

- If the validation observes no error, the threshold is `None` and the status is `NoErrorsObserved`.
- Otherwise the status is `ObservedErrors`.
- A `None` threshold does not imply trust. Use physical evaluation by default.
- An empirical trust policy needs an explicit caller choice and an explicit score band.
- The result describes observed coverage. It does not establish reliability for unsampled designs.

Results report `tested_rows`, `error_count`, and `tested_absolute_score_range`, the checked absolute-score range.
That range describes the checked designs. It does not certify an interval.

`validate_uncertainty_threshold` checks supplied validation designs.
`find_uncertainty_score` draws candidates, sorts them by absolute predicted score, and evaluates evenly spaced ranks.
The checked one-based ranks are `round(linspace(1, n, m))`, rounded half away from zero, so the checks cover small and large scores symmetrically.
It samples the training-derived box by default. `validation_region`, a `Box` of the training dimension, replaces that box, for example to probe extrapolation beyond the training designs.
It limits expensive physical evaluations to `maximum_evaluations=500` rows by default and checks every candidate when the pool fits.
`maximum_evaluations=None` sets no budget, so every candidate is checked; the result then reports `evaluation_budget=None`.
The evaluation budget and the candidate count are positive, so the search always checks at least one row.
Its `evaluation_batch_size` defaults to 64 rows per mapping call.
The evaluation budget is separate from cheap candidate prediction and batch storage.
Unchecked candidates keep NaN evaluated scores and labels, so the result shows its coverage explicitly.
These defaults control cost; they do not guarantee statistical reliability.

The search result also keeps the evidence needed to review or repeat the search:

- `checked_indices`: the ascending zero-based ranks of the checked candidates in the sorted pool. The checked designs are `candidate_designs[checked_indices]`.
- `nearest_error_score`: the smallest absolute predicted score of an observed error, or `None` without an error.
  The observed errors lie in the score band `[nearest_error_score, threshold]`.
- `score_strata`: one row `[smallest, largest]` of absolute predicted scores per checked candidate.
  With the checked ranks `c_0 < ... < c_(m-1)`, stratum `k` holds the ranks from `floor((c_(k-1) + c_k) / 2) + 1` to `floor((c_k + c_(k+1)) / 2)`, the first stratum starts at rank 0, and the last ends at rank `n - 1`.
  The strata partition the pool, and each holds one checked candidate, so they show which scores each check stands for. They are not certified regions.
- `initial_rng_state`: a deep copy of the bit-generator state before the first candidate draw.
  Assign `dict(initial_rng_state)` to the `state` of a new bit generator of the same type, such as `numpy.random.PCG64()`, and pass `numpy.random.Generator(bit_generator)` as `rng` to replay the draws.

For example, a line `y = x` fitted on `[0, 1]`, the upper limit 2, nine evenly spaced candidates, and a mapping with errors at `x = 0.25` and `x = 0.75` give, with `maximum_evaluations=5`, the checked ranks `[0, 2, 4, 6, 8]`, `threshold = 0.875`, `nearest_error_score = 0.625`, and the strata `[[0.5, 0.5625], [0.625, 0.6875], [0.75, 0.8125], [0.875, 0.9375], [1, 1]]`.

Both validators accept the core `DeficitConversionPolicy` and `DeficitScoringPolicy`, and retain the effective policies.
Observed and predicted measures use the same conversion and scoring policies.
Calibration truth can contain signed infinities, but it cannot contain NaN.
Negative infinity satisfies an upper-only requirement; a finite lower limit rejects it.
Positive infinity rejects a design even when its limits are disabled.
Predictions and regression-training measures remain finite.
Observed-measure normalization is inferred once and then frozen, so both score scales share one divisor.
The standalone validator infers it from its evaluated measures; the search uses the model's training measures.
`normalization_reference` selects another observed reference explicitly.
Score-stratified searches select evenly spaced positions across candidates ordered by their absolute predicted score.
These searches do not assume errors change in only one direction with score rank.
Classification errors need not increase or decrease consistently with the predicted score.

## Fitting metadata and model selection

Estimator fitting accepts observation weights and `FitMetadataPolicy`.
Every weighted interface names its observation weights `sample_weight`, as scikit-learn does:
the `fit` and `update` methods of `LinearSurrogate`, `PolynomialSurrogate`, `SklearnRegressorSurrogate`, and `train_svm_classifier`,
`regression_metrics`, and the `ModelSelectionPolicy` field.
`LinearSurrogate` also accepts a weight matrix under that name. `PolynomialSurrogate` accepts one weight vector per input row,
so cross-validation can pass vector `training_weights` to it.
Metadata is additional fitting data or controls, such as weights and row-specific offsets.
The policy separates fixed fit options from metadata associated with individual rows.
Filtering, appending, and cross-validation preserve the association between each observation and its metadata.
An update with omitted weights uses unit weights for its new rows, and its metadata keys must match the retained keys.
Pipeline weights route to the final step by default; `sample_weight_parameter` selects another fit keyword.
Unsupported metadata raises through the estimator. Global scikit-learn metadata routing is unchanged.

Each validation fold is a group withheld from its training fit, then used to assess predictions.
Repeating fitting and prediction across withheld folds is cross-validation. Each out-of-fold prediction excludes its own fold from training.
`cross_validate` accepts a balanced fold count or one positive fold label per sample through `data_validation_partition` (default 5).
A fold count shuffles rows; without a supplied generator, it uses `CROSS_VALIDATION_PARTITION_SEED`, so reported metrics are reproducible.
Cross-validation subsets training weights and diagnostic weights independently.
Training weights influence fitted predictions; diagnostic weights influence reported validation statistics.
Each fold passes its training weights to the model's `fit` as `sample_weight`.
A training-weight covariance matrix is subset on both training-row axes.
Every held-out fold needs positive diagnostic weight. The check runs before any model is created or fitted.
`fit_metadata` follows each training fold, and `fit_adapter` supports other fitting interfaces.
Each `CrossValidationFold` retains its data, fitted model, predictions, and metrics; `save_only_performance_metrics=True` omits these records.
By default, the result model is refitted to all observations, the largest of the `folds + 1` fits.
`refit_all_rows=False` skips that fit for metrics-only callers and returns `model=None`.
The aggregate adjusted R-squared then uses the predictor count of the fold models; it is unavailable when the fold counts differ.
`executor` (default None, sequential) runs the fold fits and the all-rows fit concurrently; results are collected in fold order.
Use a process pool for Python-heavy fits, such as the Gaussian process; its `model_factory` and `fit_adapter` must be picklable.
Every call writes INFO progress records to the logger `designoptpy.surrogate.validation`:
`Training cross-validation fold K/F` before fold `K` of `F` (one-based), and `Training the final model on all N rows` before the all-rows fit, only when `refit_all_rows` is true.
With `executor`, a record marks the collection of its model, not the start of its fit.
[Progress records](#progress-records) states how to display or hide them.

`ModelSelectionPolicy` configures GP validation partitions and scoring.
Defaults preserve deterministic folds and raw unweighted mean squared error (MSE).
The GP selects the families of each output separately, so the policy scores one output column at a time and has no weight across outputs.
The default assigns rows to folds by their index remainder, so identical row order gives identical groups.
Grouped partitions keep related observations together, and custom scoring can apply a different loss.
A loss is a scalar measure of prediction error; smaller values receive priority during model selection.
`maximum_model_selection_fits` (default 256) caps the kernel-by-basis-by-fold scoring fits plus the final fit of one output.
The default selection plans 101 fits per output.
Only scoring fits that run count. With fewer than two folds, for example with one training row, no scoring fit runs.
Each scoring fit raises on numerical failure instead of using the squared-exponential fallback.
A fallback would score another kernel under the candidate's name. A candidate that cannot be fitted therefore scores infinity.
If no candidate can be fitted, every score is infinite and the first pair is kept.
The final fit on all rows then decides: it keeps `fit_failure_action`, so its failure uses the recovery fit or raises.

Estimator search defaults to random selection of 50 configurations per output with `cv=5` and `random_state=0`.
Override `n_iter` and `random_state` through `search_options`. Grid search evaluates every configured combination.
`random_state` is the scikit-learn parameter name, so the scikit-learn wrappers keep it; DesignOptPy's own parameters use `rng`.
Both searches set `error_score="raise"` unless `search_options` supplies another value.
A candidate setting whose fit fails then stops the search with its error.
scikit-learn's own default (`error_score=nan`) only warns and returns a fitted model, which hides an invalid setting.
Increasing `n_iter` adds fitting work and can improve selection, but cannot guarantee a better fit.
See the [scikit-learn randomized-search reference](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html) for sampling details.
The neural-network wrapper supplies one hidden layer of 10 hyperbolic-tangent units, `alpha=0`, the L-BFGS solver, and at most 1000 iterations.
It also supplies standardized inputs and outputs and `random_state=0`. An untuned comparison on four smooth responses favored this base in 10 of 12 cases.
Tradeoff: this smaller full-batch fit costs less per candidate than the scikit-learn defaults (100 units and Adam), with less capacity for an untuned fit.
Override these through estimator keyword options. Wider layers add capacity and work; larger iteration caps permit more optimization.
Neither change guarantees lower validation error, and an iteration cap alone does not establish convergence.
The ensemble-tree wrapper supplies 100 trees and `random_state=0`. More trees add work and can reduce averaging variability.

## Plots

`plot_surrogate_boundary` draws the predicted level set of one output on caller-supplied axes.
It supports one, two, or three free design coordinates. Training extrema define the default plotting box.
With the fitted model from [Fit and predict a model](#fit-and-predict-a-model), the level 2 is crossed at `x = 0.5`:

```python
import matplotlib.pyplot as plt
from designoptpy.surrogate.boundary_plotting import plot_surrogate_boundary

figure, axes = plt.subplots()
try:
    artists = plot_surrogate_boundary(axes, model, 2.0)
    print(artists[0].get_xdata())  # [0.5]
finally:
    plt.close(figure)
```

One free coordinate returns crossing-marker lines; interpolation locates each crossing, and an exact sampled root appears once.
The marker line is empty when the level is not crossed.
Two free coordinates return the contour set, or an empty tuple when the level lies outside the predicted range.
Three free coordinates return a one-element tuple with the isosurface collection.
`interpolation_points` (default 100) sets the grid nodes per free coordinate; `isosurface_points` (default `None`, the
same value) sets them for the three-coordinate route alone. The default 3-D grid predicts 1,000,000 designs.
A smaller `isosurface_points` divides the prediction work by the cube of the resolution ratio and places the surface less accurately.
The grid predictions use `predict_measures`, so a model with `predict_selected` computes only the plotted output.
The function never closes caller-created figures or axes.
`plot_classifier_decision_boundary_2d` and `plot_classifier_decision_boundary_3d` (in `designoptpy.surrogate.classifier_plotting`) query a regular grid over the training extrema.
Their `resolution` defaults to 201 nodes per axis in two dimensions and 41 in three dimensions.
The three-dimensional default scores 68,921 designs.
`prediction_batch_size` (default 10000) of `plot_surrogate_boundary` and of both classifier boundary plots sets the largest number of grid designs per model or classifier call; `None` predicts the whole grid in one call.
Batches bound the working memory of each call, not the grid arrays, and the results agree with one call up to floating-point rounding.
Three-dimensional surfaces use `designoptpy.core.plotting.marching_tetrahedra`, which interpolates linearly along grid edges and is exact for an affine score.
`plot_top_down_iteration_progress` (in `designoptpy.surrogate.plotting`) draws requirement boundaries for two- and three-dimensional design spaces.
It returns one new figure per selected measure and selected iteration record.
The options `measure_indices` (zero-based outputs) and `iterations` (iteration numbers) select a subset.
`measure_indices=None`, the default, plots every output; `iterations=None`, the default, plots the rounds that evaluated a design or keep a model snapshot.
A selection skips the grid predictions and isosurface extractions of the other figures. The figures keep the order by measure, then by iteration.
A record without a model snapshot (a sparse `snapshot_policy` or `METRICS_ONLY`) gives an observation-only figure: the designs measured before the round and the selected designs, without predicted boundaries, because a boundary needs the pre-update model.
The call then emits one `MissingModelSnapshotWarning` that names these iterations. A snapshot kept only in `result.final_checkpoint` is used for its iteration.
`maximum_figures` (default 512) raises `ValueError` before any figure, prediction, or warning when the selection requests more figures; each open figure keeps its artists in memory.
`figure_options` (default None) is a mapping of Matplotlib figure properties applied to every created figure, such as `{"dpi": 72}`.
`prediction_batch_size` (default 10000) bounds the grid designs per model call, and each batch is checked for its row and column count.
In three dimensions, `slices=k` replaces the isosurface view by `k` two-dimensional maps at fixed values of the third design variable, each with the designs of its slab; `max_columns` (default 3) sets the panels per row; the figure keeps its width, so 2 gives larger panels in a taller figure.
The isosurface view dims a marker that lies behind the shaded lower-limit surface (a core blended toward the surface tone with a thin light halo), so the figure shows its depth; a legend key shows the dimmed look.
`plot_top_down_learning_history` shows, per iteration, the share of the design space where a model snapshot predicts another limit status than the final model, and the number of designs evaluated per round.
A curve that falls to zero shows that the learned boundary stopped moving; it does not show that the model is correct.
`plot_cross_validation_predictions(show_residuals=True)` adds a panel of held-out errors under each measure, and `max_columns=1` stacks the measures in one column.
`plot_cross_validation_predictions(panels="per-fold")` draws one panel per measure and fold, titled with the metrics of that fold from `result.fold_metrics`; the folds of one measure share one range, so the spread of the out-of-fold error between folds becomes visible, which a pooled metric hides.
`plot_surrogate_sections` takes `variable_indices` and `measure_indices` to draw only some panels.
`plot_data_scatter_full(pairs="measure_variable")` plots only each measure against each design variable, in a compact grid.
`plot_classifier_decision_boundary_2d(show_predicted_sides=True)` shades and names the predicted accepted and rejected sides.
`plot_classifier_training_data_3d` dims the markers that lie behind a decision surface drawn before on the same axes and adds the legend label "behind the decision surface" (a dimmed accepted and a dimmed rejected marker); draw the surface and set the camera and limits first.
`plot_classifier_slices` draws a three-dimensional classifier as slices at fixed third coordinate, with the predicted sides and the designs of each slab; it creates its own figure and takes the same `max_columns` option.
Functions that create figures close them if rendering fails. The caller owns and closes returned figures.

## Regression metric behavior

`regression_metrics` excludes zero-weight observations before weighted arithmetic, scale estimation, and logarithmic-domain checks.
Maximum error remains the unweighted maximum across every supplied row.
The positive weights are divided by their largest value and then by their sum.
A common positive weight scale, also near 1e308, therefore leaves every weighted metric unchanged.

Mean absolute percentage error (MAPE) averages absolute residuals divided by absolute observations, then multiplies by 100.
Symmetric mean absolute percentage error (SMAPE) divides by the mean of absolute observed and predicted responses.
It also multiplies by 100, giving a percentage range from zero to 200.
Each denominator has a floor: the floating-point spacing at the largest effective response magnitude.
The floor prevents division by zero. MAPE near zero observations can still be very large.
If all effective observations of an output are zero, the floor is the smallest positive double, and MAPE overflows to `+inf` for any residual of ordinary size.
The weighted median orders absolute residuals and locates half the cumulative positive weight.
At a half-weight boundary within rounding tolerance, it averages the two adjacent residuals.

Mean squared logarithmic error (MSLE) and root mean squared logarithmic error (RMSLE) are undefined for negative effective observations.
They use natural-log residuals `log(1+observed) - log(1+predicted)`.
This transform reduces the influence of large absolute response differences.
Negative effective observations or predictions make these outputs return `NaN` with a warning.
A zero-weight negative observation does not invalidate logarithmic metrics.

`n_predictors=None` means the predictor count is unknown.
Ordinary R-squared remains available, but adjusted R-squared is `NaN` until a model or caller supplies a count.
R-squared compares squared prediction error with observed response variation.
Adjusted R-squared also accounts for the number of predictors used by the model.
Adjusted R-squared uses the positive-weight observation count.
It is also unavailable when that count is at most `n_predictors + 1`.
R-squared is `1 - SS_res/SS_tot`. `SS_res` is the weighted sum of squared residuals.
`SS_tot` is the weighted sum of squared deviations of the observations from their mean.
`SS_tot = 0` when all effective observations are equal; R-squared is then 0/0.
R-squared and explained variance are `NaN` when the range of the effective observations is at most one floating-point spacing at their largest magnitude.
This includes `SS_tot = 0`. At one spacing, the rounding error of the mean is as large as the variation, so `SS_tot` has no correct digits.
These statistical `NaN` values mean "undefined"; they differ from invalid `NaN` inputs, which raise errors.

## Supported numeric domain

The supported numeric domain of `regression_metrics` is finite double-precision data whose residuals and centered values are also finite.
Variances subtract the mean before squaring, which keeps ordinary accuracy for responses with a large offset.
Root mean squares divide each column by its largest absolute value before squaring and multiply the root by that value afterward.
A positive scale does not change a root mean square or a ratio of two of them, so this per-column scaling gives the textbook value.
It keeps the squares of residuals near 1e-200 from underflowing to zero; without it, a perfect fit of data near 1e-200 would give R-squared 0/0 = `NaN` instead of one.
It also keeps the squares of residuals near 1e200 finite.
The weights are divided by their largest value before their sum is formed, so weights near 1e308 keep a finite sum.
RMSE, R-squared, explained variance, and the residual standard deviation use the scaled roots; R-squared is evaluated as `1 - (RMSE/s_y)**2`, where `s_y` is the root mean square of the centered observations.
`MSE` is `RMSE**2`: it is `+inf` above an RMSE of about 1.34e154 and underflows to zero below about 1.6e-162, while the scaled-root metrics stay valid.
R-squared or explained variance is `-inf` when RMSE or the residual standard deviation exceeds `s_y` by a factor above about 1.34e154.
A residual, the maximum error, a centered residual, or a centered observation beyond the double range (about 1.8e308) is not representable.
`regression_metrics` then raises `ValueError` that names that quantity. A named error replaces `inf` or `NaN` metrics, because `NaN` R-squared already means a constant target.
An SMAPE denominator `(abs(y) + abs(p))/2` that overflows also raises `ValueError`, because the overflow would turn its SMAPE term into a wrong zero.

The built-in GP kernels also accept far finite queries.
When scaled squared distances overflow, the kernels subtract coordinates first and add squared distances in logarithmic space.
Matérn kernels use their zero-covariance limit when the exponential decay underflows.
Rational-quadratic covariance adds its terms in logarithmic space, which keeps small increments for large shape values.
Its likelihood gradient reads the same logarithmic distances, so the gradient stays finite where `r**2` overflows.
A far query therefore returns the prior trend and the prior deviation instead of an overflow error.
A kernel matrix that is not finite raises `ValueError`.
