Migrating to Basin 4.0
Root-finding errors
BrentRoot::solve now returns Result<RootResult<F>, RootError<E, F>>, the same result type as the other scalar root solvers. Replace imports, type annotations, and match patterns that use BrentRootError with RootError. The corresponding variants keep their fields, and RootError::Evaluation(error) holds the original callback error. Use a wildcard arm for other variants when matching the non-exhaustive RootError. Formatted error messages now use RootError's wording.
L-BFGS and L-BFGS-B construction
Lbfgs::new() now selects unconstrained L-BFGS and ignores declared box bounds. If your Basin 3.x code uses Lbfgs::new() for a box-constrained problem, switch to Lbfgsb::new() before upgrading.
| Basin 3.x | Basin 4.0 |
|---|---|
Lbfgs::new() | Lbfgsb::new() |
Lbfgs::with_line_search(search) | Lbfgsb::with_line_search(search) |
Lbfgs::default() for bounded mode | Lbfgsb::default() |
Lbfgs::new().unbounded() | Lbfgs::new() |
Lbfgs::with_line_search(search).unbounded() | Lbfgs::with_line_search(search) |
For type annotations, use Lbfgs<V, F, S> for L-BFGS and Lbfgsb<V, F, S> for L-BFGS-B. Use basin::solver::lbfgs::LimitedMemoryBfgs<V, F, Mode, S> for code that is generic over both modes. The explicit .bounded() and .unbounded() conversions remain available on the opposite mode.
Tolerance setter names
Use the replacement for the test your solver runs. Pass the same tolerance value or None to the new setter.
| Test | Basin 3.x setter | Basin 4.0 setter |
|---|---|---|
| Gradient infinity norm in Gauss–Newton, LM, and pivoted-QR LM | with_absolute_gradient_tolerance | with_absolute_gradient_infinity_tolerance |
| Shared Euclidean gradient norm | with_absolute_gradient_tolerance | with_absolute_gradient_l2_tolerance |
| Relative trial step in LM and pivoted-QR LM | with_relative_step_tolerance | with_relative_trial_step_tolerance |
| Shared relative iterate change | with_relative_step_tolerance | with_relative_iterate_change_tolerance |
Both LM variants compare the Euclidean norm of the attempted step with the tolerance times the norm of the retained iterate. That iterate is the accepted point on acceptance and the base point on rejection. The shared relative iterate-change test compares the Euclidean distance between consecutive observed iterates with the tolerance times the current iterate norm. Trust-region solvers skip rejected trials in the shared test.
Absolute stationarity defaults
Basin 4.0 uses 1e-8 for f64 and 1e-6 for f32 when a solver defaults to an absolute stationarity check. Each check uses the solver's gradient, projected gradient, or scaled gradient infinity norm. To restore a previous threshold, configure the affected solver as follows.
| Solver | Setter | Previous threshold |
|---|---|---|
| Gauss–Newton, LM, and pivoted-QR LM | with_absolute_gradient_infinity_tolerance | 1e-8 in f32 |
| Bounded LM and TRF | with_absolute_scaled_gradient_tolerance | 1e-8 in f32 |
| Bounded L-BFGS | with_absolute_projected_gradient_tolerance | 1e-9 in f64, 1e-10 in f32 |
| TNC | with_absolute_projected_gradient_tolerance | 1e-6 in f64 |
| Barrier method and augmented Lagrangian | with_absolute_stationarity_tolerance | 1e-8 in f32 |
Gradient descent default stationarity
GradientDescent now checks the gradient infinity norm before each step, including at the starting point. The threshold is 1e-8 for f64 and 1e-6 for f32. The check reports ConvergenceTest::AbsoluteGradientInfinity with the compact code TerminationCode::SolverConverged.
Use .with_absolute_gradient_infinity_tolerance(None) to disable the gradient check. Explicit absolute or relative Euclidean gradient tolerances also replace the default check. Custom parameter types now need to implement NormInfinity<F>.
Projected gradient descent default stationarity
ProjectedGradientDescent checks the unit-step projected gradient infinity norm before each step, including at the projected starting point. The cutoff is 1e-8 for f64 and 1e-6 for f32. Use .with_absolute_projected_gradient_tolerance(None) to disable the check.
BFGS default stationarity
Bfgs now checks the gradient infinity norm before each line search, including at the starting point. The threshold is 1e-8 with f64 and 1e-6 with f32.
Use .with_absolute_gradient_infinity_tolerance(None) to restore runs without a gradient stop, or pass a different threshold. Explicit Euclidean gradient tolerances keep their existing meaning and replace the default check.
Custom parameter vectors now need to implement NormInfinity<F>. Move any DenseBackend::dense_norm_infinity implementation to NormInfinity::norm_infinity, which returns the norm directly as F. Keep DenseBackend<F> to infer the inverse-Hessian matrix type with Bfgs::new or Bfgs::with_line_search. To supply the matrix type yourself, use Bfgs::<V, F, M, _>::with_matrix_and_line_search(search).
L-BFGS default stationarity
Lbfgs::new() now checks the gradient infinity norm before each line search, including at the starting point. The threshold is 1e-8 for f64 and 1e-6 for f32.
Use .with_absolute_gradient_infinity_tolerance(None) to disable the gradient check. An explicit absolute or relative Euclidean gradient tolerance also replaces the default check. The default check reports ConvergenceTest::AbsoluteGradientInfinity with the compact code TerminationCode::SolverConverged.
Nonlinear CG default stationarity
NonlinearCg now checks the gradient infinity norm before each line search, including at the starting point. The threshold is 1e-8 for f64 and 1e-6 for f32.
Use .with_absolute_gradient_infinity_tolerance(None) to restore exact-zero detection. An explicit absolute or relative Euclidean gradient tolerance also replaces the default threshold.
Trust-region default stationarity
TrustRegion now checks the gradient infinity norm before solving each subproblem, including at the starting point. The threshold is 1e-8 in f64 and 1e-6 in f32. The check reports ConvergenceTest::AbsoluteGradientInfinity with the compact code TerminationCode::SolverConverged.
Exact-Hessian MoreSorensen still examines the model first so it can find negative curvature at a stationary point. It reports convergence when the finite model predicts no decrease and the gradient norm is exactly zero. Gauss–Newton MoreSorensen uses the early infinity-norm check by default.
An explicit infinity-norm or Euclidean gradient tolerance can stop at an iteration boundary before the solver examines the model, including at a saddle. Use .with_absolute_gradient_infinity_tolerance(None) to disable the early check and use the exact-zero fallback.
Custom parameter vector types now need to implement NormInfinity<F>.
Checkpoint and snapshot names
| Use | Basin 3.x | Basin 4.0 |
|---|---|---|
| Store a run for exact continuation | ExactCheckpoint<So, S> | Checkpoint<So, S> |
Write a checkpoint with Executor::checkpoint_with | ExactCheckpointWriter | CheckpointWriter |
| Load a checkpoint | read_exact_checkpoint | read_checkpoint |
Write a state snapshot with Executor::observe_with | CheckpointWriter | StateSnapshotWriter |
| Load a state snapshot | read_checkpoint | read_state_snapshot |
Pass a checkpoint to Executor::resume_from_checkpoint with the same problem. The executor restores cumulative evaluation counts and continues without initializing the solver again. Reapply any execution controls you need. Specify the solver and state types that wrote the file when you load it.
Executor::resume and ExactResumeState have been removed. Capture a checkpoint with Stepper::into_checkpoint or call run_with_solver and convert the result with into_checkpoint. Both capture the initialized solver, state, and counts together.
type Solver = GradientDescent<Constant<f64>, Vec<f64>>;
let checkpoint: Checkpoint<Solver, FirstOrderState<Vec<f64>>> =
read_checkpoint("run.ckpt")?;
let result = Executor::resume_from_checkpoint(problem, checkpoint)
.max_iter(1_000)
.run()?;For a warm start, use read_state_snapshot and pass the concrete state to Executor::new. The solver initializes a fresh run from the saved iterate with fresh counters.
let state: FirstOrderState<Vec<f64>> = read_state_snapshot("run.snapshot")?;
let result = Executor::new(problem, solver, state).run()?;Checkpoint features
If you enabled serde for Basin's built-in file APIs in 3.x, switch to checkpoint-postcard. This feature enables Serde and both native Postcard file APIs, including CheckpointStatus and CheckpointWriteError.
Keep serde if your application serializes Basin types with its own codec. Choose a codec that preserves the values your solver and state can contain, including non-finite floats if applicable. Before decoding, check your codec and settings, format revision, exact Basin version, and concrete solver and state types, including the dependency builds that determine their layout. Codecs that serialize the Serde struct name now see Checkpoint.
Use Checkpoint, CheckpointSink, and Executor::resume_from_checkpoint without either feature to capture and continue a run in memory, or to supply your own persistence code.
Existing files
read_checkpoint checks the file format, exact Basin package version, and concrete solver and state types before decoding the payload. To continue a 3.x run exactly, open the checkpoint with the Basin version that wrote it. To start a new run in Basin 4.0, export the saved point with that version and pass it to Executor::from_start with a newly configured solver.
The native state snapshot format is now version 2. read_state_snapshot checks the concrete Rust state type name before decoding the payload. Load the snapshot with the same state type, including its parameter and scalar types. Open older snapshots with the Basin version that wrote them, then export the saved point and pass it to Executor::from_start for a fresh run in Basin 4.0. The exact checkpoint format is version 7. Both readers reject older formats before decoding. Application-managed Serde payloads need a new format revision for the ten-counter layout, the expanded inner budget array, and the step- and cost-change convergence caches.
Evaluation budgets
| Basin 3.x builder | Basin 4.0 replacement |
|---|---|
max_cost_evals(n) | max_evaluations(EvaluationKind::Cost, n) |
max_gradient_evals(n) | max_evaluations(EvaluationKind::Gradient, n) |
Budgets read the problem wrapper's callback counts. Use EvaluationKind::Residual and EvaluationKind::Jacobian for least-squares work. Use EvaluationKind::TotalWork for the sum of all categories. If a custom state's cost_evals() reports a different aggregate, use stop_when to check that value and return an ApplicationStop.
Replace max_evaluations(EvaluationKind::Residual, n) with max_evaluations(EvaluationKind::ConstraintValues, n) where you budget nonlinear values in COBYLA, MADS, or SLSQP. For SLSQP's nonlinear Jacobian, replace EvaluationKind::Jacobian with EvaluationKind::ConstraintJacobian. The old calls still compile and now budget least-squares callbacks only. Read the corresponding counts in constraint_value_evals and constraint_jacobian_evals. Each equality or inequality block callback counts once, and the callback that returns the combined Jacobian counts once. Failed attempts also count.
Custom solvers can request products through Problem using the JacobianProduct and TransposeJacobianProduct traits. Budget them with the matching EvaluationKind variants. Each attempt contributes to TotalWork, including a callback that returns an error.
Match result.report.termination on Termination::Limit and read each ExecutionLimit::Evaluations { kind, observed, limit } for the exhausted category, observed count, and configured limit. This replaces the CostEvaluations and GradientEvaluations variants. The compact budget code is TerminationCode::MaxEvaluations (23). Bindings that handled codes 1 and 2 for cost and gradient limits should handle code 23. The WASM status tag is max_evaluations.
Each borrowed inner run counts requests from its own entry. An exact continuation uses the cumulative counts in the checkpoint. With serde, numeric InnerExecutor budgets travel with the inner solver. Recreate inner configurations saved by earlier versions using the builders above.
Checked progress records
Use current_record() for the last published point and selected_record() for the point retained by the solver's selection policy. An unevaluated seed has no record. An available record can have a violation report and no objective value. An evaluated NaN or infinity remains an available objective value.
For a selected record, read iter and counts for the completed iteration and raw evaluation counts at publication. These counts include all callback requests charged through that boundary. Use the selected record’s optional cost field to check whether the objective has been evaluated.
| Basin 3.x reader | Basin 4.0 replacement |
|---|---|
cost() | current_record().and_then(|record| record.cost) |
incumbent_record() | selected_record(), with an optional cost |
best_param() | selected_record().map(|record| record.param) |
best_cost() | selected_record().and_then(|record| record.cost) |
best_iter() | selected_record().map(|record| record.iter) |
best_cost_evals() | selected_record().map(|record| record.counts.cost_evals) |
Custom states implement both record readers on State. Return None when the corresponding record is unavailable. For EvaluatedState, return the point and cost from the current record once all advertised evaluations are available. For ObjectiveIncumbentState, expose the eligible incumbent and its objective through selected_record().
Replace State::update_best with publish_selection() -> Option<SelectionChange>. Update the selected record and return Some(SelectionChange::NewObjectiveBest) for the first eligible objective incumbent or a strict improvement. Return Some(SelectionChange::SolverSelected) for a new selection made by the solver's policy, or None if there is no new selection to publish. Rename reset_best to reset_selection to clear the selection for a fresh run.
Implement the mapped cost_evals() reader on CountsMirror. Use result.counts for authoritative run counts.
cost_evals() on both OptimizationResult and OptimizationResultWithSolver returns result.counts.cost_evals. If you used it to read the sum of evaluation categories, switch to result.counts.total_work(). For a custom metric, read it from result.state.
ObserverMode::NewBest now fires only on completed steps that publish the first eligible objective or a strict improvement. Switch existing NewBest observers and checkpoint sinks on constrained runs to ObserverMode::SelectionChanged to keep receiving solver-selected incumbents. This mode observes new selections during initialization and partial or completed steps. Implement observe_selection for a trait observer, match ObservationEvent::SelectionChanged in a closure, or override CheckpointSink::save_with_selection to inspect the reason in a sink. Use EvaluatedState::evaluated_record() for a complete evaluated iterate.
In-place solver steps
Custom solvers implement next_iter with state: &mut S and return Result<SolverStep<S::Float>, Self::Error>. Update the borrowed state before returning. Use SolverStep::completed(), SolverStep::partial(), SolverStep::stopped(reason), or SolverStep::completed_with_termination(reason). The executor publishes the state and counts after a successful call. A typed error discards the partially updated state and retains the attempted evaluation counts.
Replace SolverStep::from((state, termination)) with SolverStep::new(termination.is_none(), termination) to preserve the convention that a step with a stopping reason is partial.
For manual solver calls, pass &mut state and read it after a successful call. Use into_parts() to extract the completion flag and termination.
Initialization outcomes
Custom solvers take state: &mut S in init and return Result<SolverInit<S::Float>, Self::Error>. Initialize the borrowed state and return Ok(SolverInit::Ready) to proceed. Wrappers should forward the outcome. For manual calls, keep the state and inspect the outcome before calling next_iter.
Return SolverInit::Stopped { termination, resumable } to publish the available progress and stop at iteration zero. Initialization stops take precedence over cancellation, executor budgets and hooks, and convergence checks. The executor publishes counts and selection before reporting TerminationStage::Initialization { resumable }. Initialization and final observers fire when Executor::into_stepper() returns an already-stopped stepper. With require_evaluated_state(), every successful publication requires a complete evaluated record.
Set resumable: true when the solver and state are ready for next_iter without another call to init. Set resumable: false to return progress that can seed a fresh run. OptimizationResultWithSolver::into_checkpoint() and Stepper::into_checkpoint() return Option<Checkpoint<So, S>>. Check can_checkpoint() before consuming the result or stepper if you need to recover its state for a fresh run. Exact checkpoint sinks receive only resumable initialization boundaries.
Solver boundary checks
Move implementations of Solver::terminate to check_convergence(&mut self, problem: &Problem<P>, state: &S). Return Option<Termination<S::Float>>. The executor calls this hook after its controls and application hooks at each boundary, starting at iteration zero after SolverInit::Ready. Wrappers forward check_convergence with both the problem and the published state.
Line searches
Replace next, next_with_outcome, next_with_evaluation, and next_with_bounds with LineSearch::search. Direct callers construct a LineSearchContext::new(&mut problem, ¶m, cost, &gradient, &direction) and pass it by mutable reference. Use with_bounds(LineSearchBounds::new(initial, max)) to supply a step interval for a direct call. Built-in solver calls construct their own context.
To cap a delegated search, call context.with_restricted_bounds(bounds, |context| inner.search(context)). The delegated search uses the smaller of your cap and any active cap, and its supplied initial step is clamped to fit. It shares the original box checks and evaluation counts. The caller's interval is available again after delegation, so a wrapper can retry with a different cap.
Custom strategies implement search(&mut self, context: &mut LineSearchContext<'_, P, V, F>). Read context.bounds() for the initial step and cap supplied to a bounded search. Use context.trial(step) to construct a point on the ray. It returns None for invalid steps and for points outside a bounded solver's box. Only a constructed trial exposes the counted cost and gradient callbacks:
let Some(mut trial) = context.trial(step) else {
return Ok(LineSearchResult::Failed);
};
let cost = trial.cost()?;
Ok(trial.accept(cost, None))LineSearchResult::Accepted carries the trial point and cost with an optional gradient. To reuse a fused evaluation, call trial.cost_and_gradient()? and pass Some(gradient) to trial.accept. Use LineSearchResult::Step(step) for an unevaluated proposal such as a fixed step. On exhaustion, return an evaluated fallback if available or LineSearchResult::Failed. The step() accessor returns the selected step for either successful variant. Callback errors retain their original type and counted requests. To reuse parameter storage between probes, call context.trial_reusing(step, &mut buffer) with an Option<V>. Recover a rejected trial's buffer with trial.into_param().
Wolfe, fused Wolfe, and Moré–Thuente can return a cached trial with sufficient decrease when they exhaust their trial limits without satisfying curvature. They return Failed if they have no usable fallback. Moré–Thuente can also select a positive evaluated step on a native warning, as in L-BFGS-B. With a gradient tolerance below machine precision, BFGS can stop with SolverFailed when Wolfe exhausts its trials. The result retains the last evaluated iterate.
For projected gradient descent, switch ProjectedGradientDescent::with_line_search(Backtracking::new()) or another ray search to the projected search:
use basin::{ProjectedArmijo, ProjectedGradientDescent};
let solver = ProjectedGradientDescent::with_line_search(ProjectedArmijo::<f64>::new());Projected Armijo starts at a unit step, projects every trial, and tests sufficient decrease using the projected displacement. Configure it with with_sufficient_decrease_coefficient, with_contraction_factor, and max_iter. Use ProjectedGradientDescent::new(alpha) for a fixed projected step. Exhaustion reports a numerical failure after counting attempted evaluations and retaining the current iterate.
Nelder–Mead stopping
Remove calls to with_absolute_cost_change_tolerance and with_relative_cost_change_tolerance from both unbounded and projected NelderMead. The best vertex can stay fixed while the simplex improves. The default checks use the size and cost spread of the whole simplex.
To adjust the allowed cost spread, use with_absolute_simplex_cost_tolerance or with_relative_simplex_cost_tolerance. To stop after a chosen number of iterations without sufficient improvement in the best cost, use Executor::no_objective_improvement(patience, min_delta). See the Nelder–Mead guide.
Moving configured runs between threads
Executor can move to a worker before run() when its problem, solver, state, state scalar (S::Float), and registered hooks are Send. This works with serial evaluation. The worker owns the run and calls its hooks on the thread driving it. If you use a stepper, call into_stepper() on the worker to run initialization and subsequent callbacks on that thread. If you move an initialized stepper, later callbacks run on the receiving thread.
When an observer, checkpoint sink, or stop callback captures thread-local data such as Rc, call .into_local() before registering it:
let result = Executor::from_start(problem, solver, initial_guess)
.into_local()
.observe_with(observer, ObserverMode::Always)
.run()?;The switch keeps earlier settings and hooks. In explicit type annotations for a local executor or stepper, add LocalHooks as the last type argument. Use the same switch on a standalone RunControl or InnerExecutor before registering a local stop callback. Wrappers that support both modes can use H: HookMode for their hook mode parameter.
For BasinHopping, CmaInject, BoundedCmaInject, and DeInject, call .into_local() on the solver before attaching a thread-local inner_stop_when_factory. A transferable inner stop requires both the factory and its returned callback to be Send. Inner numerical settings such as with_inner_max_iter use the usual builder calls.
In a custom ResumableInner::configure_segment implementation for MA-LSCh, take and return RunControl<Self::State, LocalHooks> by value. MA-LSCh creates local controls for each segment. Apply builders directly to the supplied controls and return the result.
Threaded population evaluation
Population batches in CmaEs, De, GlobalBestPso, and RandomSearch, and independent probes in Direct, run serially by default. To retain threaded evaluation from Basin 3.x, enable the parallel feature and opt in on the solver.
use basin::{De, ParallelEvaluation};
fn solver() -> De<f64, ParallelEvaluation> {
De::new(42).with_parallel_evaluation()
}Use the threaded solver type in explicit annotations, including factory return types and the solver type of a checkpoint reader for a threaded run. Keep the same parameter, matrix, scalar, and RNG types where applicable.
| Solver | Type after with_parallel_evaluation() |
|---|---|
CmaEs | CmaEs<V, M, F, ParallelEvaluation> |
De | De<F, ParallelEvaluation> |
Direct | Direct<F, ParallelEvaluation> |
GlobalBestPso | GlobalBestPso<V, F, R, ParallelEvaluation> |
RandomSearch | RandomSearch<ParallelEvaluation> |
MaLsChCma::new(seed) also evaluates its CMA-ES chains serially. To run those chains with threaded evaluation, pass a threaded CMA-ES prototype to MaLsCh::with_inner. For example, with the Vec<f64> backend:
use basin::{CmaEs, DenseMatrix, MaLsCh};
let inner = CmaEs::<Vec<f64>, DenseMatrix>::new(0, 1.0)
.with_parallel_evaluation();
let solver = MaLsCh::with_inner(42, inner);To migrate with_inner_lambda(lambda), call with_lambda(lambda) on the CMA-ES prototype.
Custom solvers can call Problem::cost_batch_parallel for a threaded batch. Threaded batches require a shareable problem and parameters, and sendable outputs and errors. A serial batch can use local callbacks and errors even when another dependency enables parallel.
Borrowing a problem
Pass &problem to an executor or problem adapter to reuse a problem across solves. For example, Executor::from_start(&problem, solver, x0) uses the callbacks and constraints declared by the problem type.
If you implemented the same Basin trait for both P and &P, remove the reference implementation when it duplicates the one on P. To preserve different callbacks or constraints, move the reference implementation to a separate wrapper around &P. Implementations defined only on a reference can continue to serve callers that pass that reference.
Threaded finite differences
FiniteDiff, BoundedFiniteDiff, and DerivativeChecker evaluate probes on the calling thread by default, including when a dependency enables parallel. To retain threaded evaluation from Basin 3.x, enable parallel and call with_parallel_evaluation() on the adapter or checker. Independent probes run on the active Rayon pool. Directional checks evaluate their probes on the calling thread.
Standalone finite-difference functions now also evaluate their probes on the calling thread. To migrate a threaded helper call, configure the corresponding stencil, function precision, and optional fixed step on a FiniteDiff adapter. For example, replace a threaded forward_difference_gradient call with:
use basin::{FiniteDiff, Gradient, Method};
let finite_diff = FiniteDiff::new(problem)
.gradient_method(Method::Forward)
.function_precision(precision)
.with_step(step)
.with_parallel_evaluation();
let gradient = finite_diff.gradient(&point)?;Omit .with_step(step) to use adaptive steps. Use FiniteDiff::new(&problem) to borrow the problem. For Jacobians and Hessians, use .jacobian_method(...) with Jacobian::jacobian or .hessian_method(...) with Hessian::hessian.
In explicit type annotations, use FiniteDiff<P, SQUARE, F, J, ParallelEvaluation>, BoundedFiniteDiff<P, F, ParallelEvaluation>, or DerivativeChecker<F, ParallelEvaluation>. Bounds and matrix shape builders preserve the selected evaluation mode.
Finite-difference Hessian matrices
FiniteDiff::new, FiniteDiff::new_with_scalar, and the standalone central_difference_hessian and forward_difference_hessian functions now use the square matrix associated with the parameter backend.
For nalgebra SVector<F, N> parameters, change named Hessian types and stored output buffers from OMatrix<F, Dyn, Const<N>> to SMatrix<F, N, N>. To keep the dynamic-row Hessian, use FiniteDiff::new(problem).with_dense_hessian(). If you previously called FiniteDiff::<_, false, F>::new_with_scalar(problem), construct with FiniteDiff::<_, true, F>::new_with_scalar(problem) and add .with_dense_hessian() when you need the old type. When migrating a standalone call to that builder, select the same stencil with .hessian_method(...), set the same .function_precision(...), and apply .with_step(...) if you passed a fixed step. Evaluate with Hessian::hessian.
Native array parameters [F; N] produce [[F; N]; N] Hessians by default. Residual and constraint Jacobians still take their row counts from the residual or nonlinear constraint count. For native array residual Jacobians, specify the row count with .with_array_jacobian::<M>().
For a custom parameter type, implement DenseBackend<F> on the vector and SquareMatrixFromFn<F> on its associated matrix to use the new default. Implement square_from_fn_into if you want to reuse existing output storage. You can keep an existing DenseMatrixFromFn<F> builder and select it with .with_dense_hessian().
Evaluation buffer reuse
Remove .with_evaluation_buffers() from exact-Hessian trust region, dense trust-region reflective, pivoted-QR Levenberg–Marquardt, SLSQP, and robust least-squares calls. Each now reuses evaluation storage automatically. Keep implementing the owned callbacks to supply initial storage and override the matching *_into callbacks to write into that storage on later requests.
For TrustRegion annotations, move the backend types into the model and remove the fourth type argument. TrustRegion<Sub, F> uses an exact Hessian of type DenseMatrix<F>.
| Type | Explicit Basin 4.0 annotation |
|---|---|
| Exact-Hessian trust region | TrustRegion<Sub, F, ExactHessian<M>> |
| Matrix-free trust region | TrustRegion<Sub, F, MatrixFree> |
| Least-squares trust region | TrustRegion<Sub, F, GaussNewtonModel<R, M, G>> |
| Trust-region reflective | TrustRegionReflective<F, R, M> |
| Pivoted-QR Levenberg–Marquardt | LevenbergMarquardtQr<V, M, F, R> |
| SLSQP | Slsqp<F, V> |
Sub names the trust-region subproblem strategy and F names the scalar. V is the parameter vector, R is the residual vector, and M is the Hessian or Jacobian. When the Gram matrix G has the same type as the Jacobian, use GaussNewtonModel<R, M> with TrustRegion::least_squares_with. For distinct types, name G and use TrustRegion::least_squares_with_gram. The executor helps infer model types from the problem. Give standalone solvers an explicit type when inference needs more information.
RobustLeastSquares::new infers the fourth type parameter from the problem's Jacobian implementation. Use RobustLeastSquares::from_residuals and the type RobustLeastSquares<P, L, F, ()> for residual-only or matrix-free problems. Custom matrices that already implement MatTransposeVec still provide scalar gradients. Override mat_transpose_vec_to to reuse the gradient output as well.
If your old buffered robust adapter used MatTransposeVecInto, construct it with RobustLeastSquares::new_with_in_place_transpose(problem, loss). This works with custom Jacobians and with built-in matrices that implement MatTransposeVecInto for your parameter type. Use RobustLeastSquares<P, L, F, M, true> in explicit type annotations.
Send and Sync now also depend on the solver's stored backend outputs. The robust adapter requires its scratch outputs to be Send for either trait. It implements Clone when the problem and loss do, with empty scratch in the clone, and drops its Copy implementation. Cloning TRF or SLSQP also clones its retained backend outputs.
In-memory checkpoints retain solver buffers. Resuming an exact-Hessian trust-region solve from a serialized checkpoint uses the owned Hessian callback on the next request, then resumes in-place evaluation. Serialized least-squares trust-region checkpoints retain the current residual and model. Start a new run from the saved parameters when migrating a trust-region checkpoint across Basin major versions. The built-in checkpoint reader checks the Basin version and concrete solver type.