designoptpy-point
designoptpy-point searches for one best design: the variable values that minimize an objective.
This search is point optimization. This component has its own installation and version. Import it through designoptpy.point.
- After publication, install with
python -m pip install designoptpy-point. - The optional extra
designoptpy-point[symbolic]adds SymPy for exact symbolic coefficient extraction. - From the source workspace, run
uv sync --package designoptpy-point. Add--extra symbolicfor SymPy. - For the complete package family, including X-Ray, optional workbook and palette support, and the
symbolicextra, installdesignoptpy.
See the workspace documentation for development and release procedures.
The optimization problem
A point optimizer solves this problem:
minimize f(x)
subject to c(x) <= 0, h(x) = 0, lower <= x <= upper
Here x is one design vector, f is the objective, c holds inequality residuals, and h holds equality residuals.
A residual is a constraint value. An inequality residual at or below zero satisfies its constraint.
OptimizationProblem stores these parts:
- an objective with one scalar column or several objective columns;
- closed variable bounds, which can use outward infinite limits;
NonlinearConstraintsfor inequality and equality residual callbacks, with acceptancetolerance(default1e-6);LinearConstraintsfor coefficient-form linear inequalities and equalities;- zero-based
integer_variablesindices, where the first index is 0; - an optional
EvaluationBudget, described in Result signals.
A callback is a supplied function that the solver invokes to evaluate a model or observe a step.
Objective and constraint callbacks receive sample-major design matrices: one design per row and one variable per column.
They return one result row per design. Evaluating several design rows in one call is vectorization.
A constraint callback that returns None or [] declares that its residual group is absent.
A nonempty objective result needs at least one column, so a constant zero objective returns a real zero explicitly.
The problem keeps the two sources in two fields, linear_constraints and constraints, exactly as supplied.
problem.evaluate_constraints(points)evaluates both. It returns the linear residual columns first, then the nonlinear columns, each column with the acceptance tolerance of its source.problem.has_constraintstells whether either source exists.problem.constraint_toleranceis the smallest source tolerance.- The default tolerance of both sources is
DEFAULT_CONSTRAINT_TOLERANCE(1e-6) indesignoptpy.point.problem.
Several objective columns become one merit value through scalarization.
The selected weights or EvaluationOptions.scalarizer define how the objectives compete.
A custom scalarizer applies only to objectives with more than one column.
Worked example
Minimize the squared distance to [1, -2] while keeping x0 + x1 >= 0.
Write the constraint in residual form as c(x) = -(x0 + x1) <= 0.
import numpy as np
from designoptpy.point import Bounds, NonlinearConstraints, OptimizationProblem, solve
problem = OptimizationProblem(
objective=lambda x: (x[:, 0] - 1.0) ** 2 + (x[:, 1] + 2.0) ** 2,
initial_design=np.array([[0.0, 0.0]]),
bounds=Bounds([-3.0, -3.0], [3.0, 3.0]),
constraints=NonlinearConstraints(inequality=lambda x: -(x[:, 0] + x[:, 1])),
)
result = solve(problem, "scipy-minimize")
print(result.converged, result.feasible) # True True
print(np.round(result.point, 4), round(result.objective_value, 6)) # [ 1.5 -1.5] 0.5
The unconstrained minimum [1, -2] violates the constraint, so the optimum lies on the line x0 + x1 = 0.
The nearest point of that line is [1.5, -1.5], with objective 0.25 + 0.25 = 0.5.
This analytic answer is a stronger check than the termination status alone.
The scipy-minimize solver, also the default of solve, runs Sequential Least Squares Programming (SLSQP) here.
Real input values
Use real numerical inputs and callback outputs. This requirement includes residuals, derivatives, scalarizers, and policy controls.
- The validators reject complex arrays before conversion, including complex values inside object arrays and values with zero imaginary parts. They accept real numeric object arrays.
- Validation occurs before conversion because a numeric cast can otherwise discard an invalid imaginary component. Converting values to the required numeric type is coercion.
- Finiteness depends on the boundary. Bounds allow infinite endpoints. Scalarization targets use NaN to omit a term. A barrier can return positive infinity to exclude a design, and a penalty can saturate to positive infinity.
- NaN is invalid at every response boundary.
Choose a solver
Call solve(problem, solver, options=...). It selects the implementation named by solver and calls it.
This selection is dispatch. Each bundled solver has one name. The name follows the choice-name rule of designoptpy.core.choices, so case and underscore/hyphen forms of that name are equal.
| Solver names | Bounds | General constraints | Integers | Objective | Retained trace |
|---|---|---|---|---|---|
steepest-descent, conjugate-gradient, quasi-newton, modified-newton |
Finite or outward infinite, projected directions | Merit or penalty terms; final feasibility checked | No | Scalar or scalarized | Accepted iterations and line searches |
trust-region, limited-memory-bfgs |
Finite or outward infinite, projected steps | Merit or penalty terms; final feasibility checked | No | Scalar or scalarized | Model agreement or memory pairs |
nelder-mead, covariance-matrix-adaptation |
Finite box; fixed variables removed | Merit or penalty terms; final feasibility checked | No | Scalar or scalarized | Simplex operations or sampling distribution |
augmented-lagrangian |
Finite or outward infinite, passed to the inner solver | Linear and nonlinear | No | Scalar or sum of objective columns | Inner solves, multipliers, penalty, optimality residuals |
slp, sqp |
Finite or outward infinite; SLP absolute move limits need a finite box | Linear and nonlinear | No | Scalar or scalarized | Subproblems and constraint linearizations |
mma |
Finite box | Linear and nonlinear | No | Scalar or scalarized | Subproblems and constraint linearizations |
gauss-newton, levenberg-marquardt |
Finite or outward infinite (LeastSquaresProblem.bounds) |
Rejected by the problem type | No | Half sum of squared residuals | Linearizations, trials, damping |
genetic-algorithm, differential-evolution, particle-swarm |
Finite box | Feasible-first selection by default, or merit terms under constraint_selection="scalar-merit"; final feasibility checked |
Yes | Scalar or scalarized | Population per iteration |
pattern-search |
Finite box | Feasibility-aware polling | No | Scalar | Polls and accepted iterations |
sampling with generated points |
Finite box | Best feasible sample | Yes | Scalar or scalarized | Batches and evaluated rows |
sampling with explicit points |
In-box by default; explicit outside sweep (outside rows infeasible) | Best feasible sample | Yes, projected | Scalar or scalarized | Every evaluated row, at most max_evaluations |
pareto-search |
Finite box | Feasible archive | Yes | Vector | Population and archive |
bayesian |
Finite box | Feasibility-aware acquisition and selection | No | Scalar | Fitted surrogate and evaluated points |
scipy-minimize |
Method-dependent | Method-dependent | No | Scalar | Callback iterations. Python only. |
scipy-differential-evolution |
Finite box | Supported SciPy constraints | Yes | Scalar | Callback iterations. Python only. |
Integer-capable solvers project integer variables before every evaluation. Continuous-only solvers reject integer metadata. Dispatch rejects unsupported bound or constraint capabilities before objective evaluation.
Infinite bounds by solver:
- Steepest descent, conjugate gradient, quasi-Newton, and modified Newton accept infinite bounds. Their line searches start at the unit step and expand along a ray without a restricting bound.
- Limited-memory BFGS also accepts them. Its Armijo backtracking starts at the unit step and only shortens it.
- Trust region accepts them because the trust radius limits every step.
- SLP and SQP accept them.
The default relative SLP move box is finite for every design, and an infinite-width QP coordinate is free with scale one.
Absolute SLP move limits scale by the design-box width, so an infinite width raises the move-box
ValueError. - The augmented Lagrangian passes them to its inner solver. The default
quasi_newtonaccepts them. penalty_barrierleaves them to its base optimizer. The defaultdifferential_evolutionneeds a finite box, andquasi_newtonaccepts outward infinite bounds.- For infinite bounds with another local method, choose a compatible SciPy local method.
MMA needs a finite box, because its asymptotes lie a multiple of the design width from the design.
Its reciprocal approximations use the coefficients of Svanberg (2007) with MmaOptions.raa0=1e-2, so MMA results differ slightly from the 1987 form everywhere.
- An interior optimum converges only for about
raa0 > asymptote_distance_bounds[0] * H * w**2 / 8(curvatureH, design widthw). - The default
1e-2departs from Svanberg's1e-5. It meets this condition forH * w**2up to about 8, which covers normally scaled problems. For example,(x - 0.3)**2on[0, 1]converges with the default but not with1e-5. - The tradeoff is slightly more conservative steps.
- For a larger
H * w**2, raiseraa0or multiply the objective values by a positive factor below one. A linear change of design units leavesH * w**2unchanged and does not help.
Every bundled solver takes one options record.
Python only: these adapters wrap SciPy. DesignOptRs fills these roles with its native sqp and differential-evolution solvers and has no counterpart.
This marker covers the two SciPy adapters: the solver names scipy-minimize and scipy-differential-evolution, the functions scipy_minimize and scipy_differential_evolution, and their options records.
scipy-minimize is the default solver of DesignOptPy solve. The DesignOptRs default is the native sqp, the closest analog of SciPy SLSQP.
The two SciPy adapters use these records from adapters.py.
The package root exports the adapter functions scipy_minimize and scipy_differential_evolution, but not these two records; import them with from designoptpy.point.adapters import ScipyMinimizeOptions, ScipyDifferentialEvolutionOptions:
ScipyMinimizeOptions(method="SLSQP", scipy_options={...}, gradient=..., hessian=..., history_limit=..., retain_backend_result=True, stationarity=StationarityOptions(), reuse_constraint_residuals=True).methodselects thescipy.optimize.minimizemethod.scipy_optionsis its method-specificoptionsmapping, for example{"maxiter": 50, "ftol": 1e-10}.ScipyDifferentialEvolutionOptions(rng=..., scipy_options={...}, history_limit=..., retain_backend_result=True, reuse_constraint_residuals=True).rngis the random generator of the population draws: a NumPyGenerator, an integer seed, orNone.scipy_optionsholds the keyword arguments ofscipy.optimize.differential_evolution, for example{"maxiter": 50, "popsize": 15}.
For example, solve(problem, "scipy-minimize", options=ScipyMinimizeOptions(method="Powell")) runs Powell's method.
Two runs with equal seeds, such as ScipyDifferentialEvolutionOptions(rng=5), return the same design.
Use list_solvers(problem_family="scalar") to discover bundled methods without running a solver.
Use describe_solver("genetic-algorithm") to read the description of one solver.
Each immutable SolverSpec contains the solver name, options import reference, integer support, and problem family.
solve imports the implementation module of a SolverSpec only when it selects that spec, so a custom spec can name a module that nothing has imported yet.
Importing the package root designoptpy.point already imports every bundled solver.
A caller can pass a SolverSpec directly to solve for a small extension without changing a shared solver list.
See workflow_dispatch.py for these discovery operations.
A custom solver callable is also accepted. solve calls it as solver(problem), or as solver(problem, options=options) when options is not None.
The solver must return a normalized result. It receives the problem with counted callbacks, so the result reports the objective and constraint rows that the solver caused.
To use a solver with another parameter list, pass a closure or a functools.partial object that receives the problem and calls the solver.
Dispatch never inspects the solver's parameter list, so a wrapped solver receives the same arguments.
Read the algorithms
Each optimizer belongs to one module in src/designoptpy/point/methods.
Open its module to read its behavior, mathematical mechanism, executable example, options, records, and implementation.
Explicit iteration loops make the methods easy to compare.
| Method | Implementation |
|---|---|
| Steepest descent | steepest_descent.py |
| Fletcher-Reeves conjugate gradient | conjugate_gradient.py |
| Inverse BFGS | quasi_newton.py |
| Modified Newton with an identity shift | modified_newton.py |
| Newton trust regions with truncated conjugate gradients | trust_region.py |
| Projected limited-memory BFGS | limited_memory_bfgs.py |
| Nelder-Mead | nelder_mead.py |
| Covariance matrix adaptation evolution strategy (CMA-ES) | covariance_matrix_adaptation.py |
| Augmented Lagrangian | augmented_lagrangian.py |
| Gauss-Newton for residual problems | gauss_newton.py |
| Levenberg-Marquardt for residual problems | levenberg_marquardt.py |
| Genetic algorithm and its operators | genetic_algorithm.py |
| Differential evolution | differential_evolution.py |
| Particle swarm | particle_swarm.py |
| Pattern search | pattern_search.py |
| Direct sampling | sampling_optimization.py |
| Pareto search | pareto_search.py |
| Bayesian optimization and its Gaussian process | bayesian_optimization.py |
| Sequential linear programming | sequential_linear_programming.py |
| Sequential quadratic programming | sequential_quadratic_programming.py |
| Method of moving asymptotes | method_of_moving_asymptotes.py |
| Penalty/barrier outer iteration | penalty_barrier.py |
| Python two-phase simplex | simplex.py |
| Active-set quadratic programming | active_set.py |
| SciPy HiGHS linear-program adapter | linear_program.py |
Start with steepest descent. Compare its direction calculation with conjugate gradient, inverse BFGS, and Newton. BFGS means Broyden-Fletcher-Goldfarb-Shanno, a Hessian approximation update based on successive design and gradient changes. Each overview explains the implemented variant, bounds, safeguards, and stopping rule. test_point_gradient_methods.py checks quadratic steps against manually calculated endpoints. It also checks restart and curvature update decisions.
Gradient methods with line searches
Stationarity test:
- Steepest descent, conjugate gradient, quasi-Newton, and modified Newton test first-order stationarity after every gradient evaluation, before the line search.
- The projected gradient is the gradient
gwith each blocked component set to zero. A component is blocked when the design lies at a bound and-gpoints out of the box. - The projected gradient is zero exactly when the bounds permit no first-order descent. This is first-order stationarity for a box.
- The solver reports
CONVERGEDwhen the infinity norm of the projected gradient is at mostgradient_tolerance * max(1, ||pg_0||_inf). Herepg_0is the projected gradient at the initial design, and the default isgradient_tolerance=1e-6. - The relative scale keeps the test reachable for large objective magnitudes, where finite-difference rounding noise of about
eps * |f| / hexceeds an absolute1e-6. Below an initial norm of one, the threshold is absolute. - The projected gradient keeps gradient units, so a box narrower than the tolerance cannot certify a nonstationary design.
Objective-change stop rule:
- The solvers also stop when the objective change between accepted designs is at most
objective_tolerance + objective_relative_tolerance * max(|f_previous|, |f_current|). The defaults areLocalOptions.objective_tolerance=1e-6andLocalOptions.objective_relative_tolerance=0, the absolute rule. objective_change_within_tolerance(previous, current, absolute_tolerance=..., relative_tolerance=...)is this rule. With a positive relative tolerance it divides both sides bymax(|f_previous|, |f_current|), so values near the float64 limit cannot giveinf <= inf, a false stop. Withobjective_tolerance=0and a positive relative tolerance, a positive rescaling of the objective does not change the decision. A NaN or infinite value never passes. SLP, SQP, MMA, andpenalty_barrierapply the same rule with theirtoleranceandobjective_relative_tolerance. A customconvergence_functionreplaces the rule and receives no relative tolerance.- A small change measures progress only. The next pass computes the gradient at the accepted design, and the stationarity test decides:
CONVERGED, otherwiseSTALLED, which is not a success. - This pass runs also after the last permitted iteration.
trust_regionandlimited_memory_bfgsuse the same projected-gradient test, at the initial design and after each accepted step, also after the last permitted iteration. They have no objective-change stop rule.
Direction and curvature:
- Conjugate gradient computes its Fletcher-Reeves coefficient from the projected gradients. It restarts when the blocked set changes or when the bound-projected direction fails the descent check.
- It keeps the unnormalized projected direction for its recurrence.
normalize_direction=Truerescales only the copy passed to the line search. - With an exact line search, the iterates are then the same in exact arithmetic.
The default golden-section search starts at the absolute multiplier
initial_step, so a rescaled direction moves its first trial to another design and can change the selected step. - Quasi-Newton and modified Newton solve their curvature system on the free coordinates only, with the active coordinates fixed. This is the projected-Newton step.
- Modified Newton adds the smallest tried multiple of the identity that makes the free Hessian block positive definite (Nocedal and Wright, Algorithm 3.3).
NewtonIteration.hessian_shiftrecords it. bfgs_inverse_update_with_record(H, s, y, include_terms=False)returns the next inverse-Hessian approximation with aBfgsInverseUpdateRecord:applied,curvature(y @ s),curvature_threshold(t * (norm(y) * norm(s))), andskip_reason. The checks run in this order:"no-change"(s or y is zero),"nonfinite"(the curvature overflows),"curvature"(not curvature > curvature_threshold, also for a NaN threshold), and"nonfinite"(the updated matrix is not finite). Withinclude_terms=Truethe record keepsfirst_term(H),second_term(c * outer(u, s)), andthird_term(outer(u, Hy) + outer(Hy, u)), withu = s / (y @ s)andc = 1 + (y @ H @ y) / (y @ s); the update isfirst_term + second_term - third_term. The terms areNonewhen the update arithmetic did not run.bfgs_inverse_updatereturns the same matrix andrecord.applied.
Descent fallback:
- Each
GradientIterationof these four methods recordsdescent_fallback. It isTruewhen the bound-projected method direction was not a descent direction, so the step used the projected negative gradient instead. - The descent check uses the plain dot product
direction @ gradient. Only a negative value keeps the method direction. A zero or NaN product gives no evidence of descent, and a product that underflows below the float64 range counts as zero. - With
normalize_direction=True, the solver normalizes the direction after this projection and fallback.
Evaluation reuse and bounds:
- The four methods reuse the current objective value. The finite-difference gradient and the golden-section search make no extra call at the current design.
- They also reuse the line-search trial at exactly the accepted design, so the committed value is the value that selected the step.
- The default golden-section search receives the problem bounds, so it clips each trial design to the box.
- After a positive step, a coordinate that lands within
4 * eps * max(|x_i|, |b_i|)of the boundb_iahead of it is placed on that bound. - The rounded
x + t * dat the step limittcan miss the bound by a few units in the last place. Without the placement, that coordinate would not be blocked at the next stationarity test, and its step limit of about1e-16would make the next line search fail.
Failure and budget:
- A line search that rejects its step leaves the current design unchanged, and the run stops with
NO_FEASIBLE_STEP. - When the evaluation budget denies a callback batch, the run returns the last accepted design with
MAX_EVALUATIONS. A denied initial evaluation returns the initial design with a NaN objective.
Trust region and limited-memory BFGS
Compare a line search with trust_region.
The trust-region method can reject a trial and shrink its radius when predicted quadratic improvement is inaccurate.
A rejected trial keeps the design, so the next trial reuses its Hessian. The method computes a new Hessian only after an accepted step.
Bounds in trust_region:
- A coordinate at a bound, or within
8 * epsrelative distance of it, whose negative gradient points out of the box is held. The conjugate-gradient step keeps it fixed, and the trial places it exactly on that bound. - A coordinate one unit in the last place inside its bound therefore cannot shorten the step of the other coordinates, and the next stationarity test finds it blocked.
limited_memory_bfgs:
- It stores a short history of displacement and gradient-change pairs instead of a dense inverse Hessian. Its two-loop recursion computes a direction from those pairs.
- The bounds follow the rules of the four line-search methods above: the bound projection with
descent_fallback, which also clears the stored pairs, and the placement of reached bounds. backtracking_searchwith the problem bounds accepts the first Armijo trial from the unit step. A rejected search along stored pairs clears them and retries once along the projected negative gradient.- This implementation uses projected limited-memory BFGS (L-BFGS). It differs from the distinct L-BFGS-B algorithm.
Shared behavior:
- When the evaluation budget denies a callback batch, both methods return the last accepted design with
MAX_EVALUATIONS. - Both methods evaluate the gradient right after an accepted step, so
projected_gradient_normalso has a value afterMAX_ITERATIONS.limited_memory_bfgsalso reports it afterSTOPPED;trust_regionstops before that gradient, so a stop after an accepted trial givesNone. trust_regionreturnsTrustRegionResult. Itsfinal_radiusis the radius of the next trial:initial_radiuswhen no trial completed, elsenext_trust_radiusof the last completed trial, also afterSTOPPEDand after the radius fell belowminimum_radius.return_best_feasible=Truekeeps it, because it describes the solver run.- Direction normalization scales components before it computes their norm. This prevents finite tiny or large gradients from disappearing through norm arithmetic.
- If an accepted step cannot change the represented coordinates, steepest descent, conjugate gradient, quasi-Newton, modified Newton, and limited-memory BFGS return
NO_REPRESENTABLE_PROGRESS. - A zero projected gradient at an exact stationary or bounded minimum remains a successful stop.
Derivative-free methods
For derivative-free optimization, inspect the reflection, expansion, and contraction decisions in nelder_mead.
Then inspect the sampling distribution and evolution paths in covariance_matrix_adaptation.
An evolution path accumulates successive mean movements to guide later sampling.
Constraints and bounds:
- Both methods require finite box bounds and remove fixed coordinates from the search.
- They accept linear and nonlinear constraints. The accounting boundary classifies the returned design with the constraint rows observed at its evaluation.
- Nelder-Mead compares the merit of
options.evaluation: its penalty, barrier, and merit-weight terms. The defaultpenalty_constant=0adds no term, so the search itself is unconstrained and only the final verdict uses the constraints. A converged infeasible design reportsINFEASIBLE. - CMA-ES ranks feasible first by default, as the other population methods.
constraint_selection="scalar-merit"ranks by the merit ofoptions.evaluationinstead. max_evaluationscounts the objective rows plus the nonlinear constraint callback rows. Each design therefore costs1 + callback_countrows, and the final check costs none.
Related methods:
- Nelder-Mead uses a geometric simplex of trial designs.
- The linear programming (LP) method named
simplexinstead pivots a coefficient model between feasible bases. A basis selects variables determined by the constraint equations. A pivot exchanges one selected variable. - Pattern search polls coordinate directions on an adaptive mesh. It retains every poll, mesh size, objective, and violation.
It converges when a complete unsuccessful poll reduces the mesh to
mesh_tolerance. A fixed box converges without a poll. When rounding makes every poll step of a free box vanish, it reportsNO_REPRESENTABLE_PROGRESS, because this does not prove stationarity. Withcomplete_poll=True,batch_poll=Trueevaluates each poll in one callback batch instead of one call per row. A deterministic row-wise model gives the same run; an evaluation budget then denies the whole poll batch.
Augmented Lagrangian and penalty/barrier
Compare augmented_lagrangian with penalty_barrier to inspect the effect of multiplier updates.
Augmented Lagrangian checks:
- The augmented Lagrangian outer records retain the inner solve, original objective, multiplier changes, and three residual checks.
AugmentedLagrangianOptions(retain_inner_results=False)storesinner_result=None; the outer endpoints, multipliers, penalties, and decisions stay. augmented_lagrangianreturns anAugmentedLagrangianResult. It keeps the evidence of the last completed outer iteration independent of the history retention:inequality_multipliersandequality_multipliers(zeros before the first completed iteration;Noneonly when the budget denied the initial evaluation), andstationarity,stationarity_threshold, andcomplementarity(Nonebefore the first completed iteration).- The checks measure feasibility, stationarity, and complementarity. All three must pass for success. Together they are the Karush-Kuhn-Tucker (KKT) conditions. This first-order check does not prove a local minimum.
- Stationarity means that no feasible first-order direction can decrease the objective.
- Projected stationarity is the infinity norm of the projected gradient of the updated Lagrangian. Each component is zero where the design lies at a bound and the negative gradient points out of the box.
- The check passes when this norm is at most
stationarity_tolerance * max(1, ||pg_0||_inf), with the projected objective gradientpg_0at the initial design. Each record keeps thisstationarity_threshold. - This is the test of the line-search methods and of the default inner solver.
It keeps gradient units, so a box narrower than the tolerance cannot certify a nonstationary design, as the earlier mapping
x - clip(x - g)could. - The scale costs one objective gradient at the start. Each outer iteration reuses its evaluation of the returned design as the base value of the stationarity stencil, so the stencil evaluates only its probe designs.
AugmentedLagrangianOptions.reuse_observations(default True) keeps the objective value and the residuals of each design that one inner solve observed, seeded with the accepted design. The inner start and the returned design then need no new callback rows: one objective row and one row per nonlinear constraint callback fewer at each end of every outer iteration. A batched inner request with known rows sends only the unknown rows. Each record counts the served rows inreused_rows. The reuse assumes a deterministic model whose callbacks treat their rows independently; set False for a model that can change between calls.- Complementarity requires each inequality residual times its multiplier to vanish, so an inactive inequality has a zero multiplier.
penalty_barrier setup:
- It uses differential evolution for its subproblems by default. This is robust but costly. For smooth problems, pass
base_optimizer=quasi_newton. - With penalty factor
c > 0, the merit addsc * barrier + penalty / c. Increasingcstrengthens barriers and weakens penalties. Zero disables both additions. - Barrier mode (
barrier=True) requires a base optimizer withsupports_infinite_objective = True.differential_evolutionandgenetic_algorithmset this attribute. A wrapper, such asfunctools.partial, must set it itself. PenaltyOptions.penalty_function(defaultsquared_inequality_penalty) andPenaltyOptions.barrier_function(defaultlogarithmic_barrier;inverse_barrieris the other provided barrier) select the inequality term.PenaltyOptions.equality_penalty_function(defaultsquared_equality_penalty,h**2) is the equality penaltyP_eof both modes: the merit addssum(P_e(h)) / c. It returns nonnegative values or positive infinity with the residual shape. A function that returns zeros removes the equality term.penalty_barrieradds no Lagrange multiplier terms and no merit weights to its subproblems. Each subproblem policy keeps the zero defaults ofEvaluationOptions.inequality_lagrange,equality_lagrange,inequality_merit_weight, andequality_merit_weight. This omission is deliberate: a penalty continuation with fixed multipliers duplicatesaugmented_lagrangian, which updates its multipliers.penalty_barrierbuilds each subproblem objective with this evaluator,EvaluationOptions(penalty_constant=factor, ...).PenaltyOptions.rng(default seed0) makes one generator per outer invocation for the default innerdifferential_evolution. A rerun therefore repeats, and successive subproblems still draw different populations. Anotherbase_optimizerowns its randomness.
Penalties and barriers:
- Custom penalties and barriers return arrays that match the residual shapes, with finite values or positive infinity.
- A positive-infinity penalty is saturated. The default squared penalties overflow to it without a warning, and the row then ranks after every finite merit.
- With
c == 0, value-only evaluations do not call the penalty and barrier policies. - The merit rejects NaN and negative infinity. Vector objectives are scalarized per row before the penalty is added.
Outer convergence:
- The outer stop compares successive subproblem results. The first previous objective is positive infinity, so one subproblem cannot converge.
- In barrier mode, convergence also requires the duality gap
factor * sum(B'(c) * (-c))to be at mostduality_gap_tolerance(default1e-6). - For convex problems the gap bounds the remaining objective improvement.
The natural-log barrier gives
m * factorforminequalities, and a residual that is not negative gives an infinite gap. - Without the gap test, a box bound can hold successive results at one design while the barrier still keeps it away from an active constraint.
For
0.1 * (x - 2)**2withx <= 1on[0, 3], every subproblem withfactor >= 0.4returnsx = 0. - The cost: penalty mode needs at least two outer solves.
Natural-log barrier mode needs
factor <= 1e-6 / m, about 20 halvings from factor 1 for one inequality, so barrier runs can cost up to about 20 times more inner solves. The tradeoff buys a truthful convergence signal.
Records and stop rules:
- Each penalty iteration retains
inner_result, thepenalty_factorof the subproblem, and, in barrier mode, itsduality_gap.PenaltyOptions(retain_inner_results=False)storesinner_result=None; the outer endpoints, factors, gaps, and decisions stay. - The factor is updated only before a next subproblem, so an
updatecallback is not called after the last permitted subproblem. - In barrier mode the final stationarity check also receives the multiplier estimates
factor * B'(c). A barrier design lies a distancefactor / lambdainside an active inequality, and a large multiplier term keeps that inequality active. - An inner
STOPPEDorNUMERICAL_ERRORstops the outer loop with that status. Other inner statuses, such asMAX_ITERATIONS, do not stop it, because an inexact inner solve is acceptable for penalty continuation. - A stop request comes first. An outer
stop_callbackthat returnsTruefor the completed outer record, or an innerSTOPPED, givesSTOPPEDbefore theNUMERICAL_ERRORtest, as inaugmented_lagrangian.
Sequential linear and quadratic programming
Sequential linear programming (SLP) and sequential quadratic programming (SQP) solve a sequence of local models. Each model is a linear program or a quadratic program (QP) of the linearized problem.
SLP is a steered l1 exact-penalty method (Fletcher and Sainz de la Maza; Byrd, Nocedal, and Waltz).
Its merit is f + nu * (sum(max(c, 0)) + sum(|h|)).
Each SLP iteration:
- Solves the elastic linear program of the linearized merit inside a move box, with the Python
simplex(SlpOptions.simplex_options, defaultSimplexOptions(tolerance=1e-6)). - Uses elastic variables, so the linear program is always feasible. The method therefore restores feasibility from infeasible starts and moves through infeasible designs. Each elastic variable has an upper bound, twice the largest magnitude of its linearized residual in the move box. An optimum never needs more, and the finite bound lets the simplex certify an optimum whose reduced costs keep rounding noise. The simplex scales a bounded column by its bound. A variable therefore stays unbounded above when its bound, or its bound times its LP cost, overflows the float64 range.
- At an infeasible design, multiplies the penalty weight
nu(initial valueinitial_penalty_weight=1) by ten, at most ten times per subproblem, until the step makes enough linearized feasibility progress. A second LP without the objective gives the largest possible violation reduction. SLP solves it only when a step keeps a linearized violation above the constraint tolerance, because a step that removes the violation already makes enough progress. - Accepts a trial when the ratio of actual to predicted merit decrease is at least 0.1.
- Updates the move limit. The move limit is dimensionless, and its initial and largest value is
move_limit=0.5. The method multiplies it bymove_limit_update=0.5when the ratio is below 0.25 and divides it by that factor when the ratio is at least 0.75. - Shrinks the move box after a rejected trial and solves again.
Stopping and failure:
- Below
minimum_move_limit=1e-6, a slope test withoptimality_tolerance=1e-6decides between a zero step (stationary at that resolution) andNO_FEASIBLE_STEP. - A zero step that does not converge stops the run. The status is
INFEASIBLEwhen the stopping rule passed at an infeasible design. Otherwise the status isNO_FEASIBLE_STEP. - The elastic LP is always feasible and bounded in its finite move box. A failed LP, such as one that reaches its pivot limit, therefore stops the run with
NUMERICAL_ERROR. The message isSLP subproblem failed at iteration k: <LP status>: <LP message>. - An LP limit is not an SLP budget stop, so
budget_exhaustedstaysFalse.SlpResult.subproblem_failurekeeps the failed LP result.
Records and move limits:
- Each
SlpIterationkeeps the move limit, penalty weight, predicted and actual merit decrease, rejected trials, step, and LP result. With the defaultretain_derivatives=Trueit also keepslinearization, the objective gradient and Jacobians of the iteration at the design before it.retain_derivatives=FalsestoresNonethere and solves the default elastic LPs withretain_tableau=False. - The ratio test costs one model evaluation per trial. The steering LPs cost none.
relative_move_limitsscales the move limit bymax(|x_i|, 1).absolute_move_limitsscales it by the design-box widthupper_i - lower_i. Forx = 5in[2, 8]with move limit0.1, the absolute box is[4.4, 5.6].
SQP merit and line search:
- The merit weights are
|lambda| + max(1, |lambda|)from the QP multipliers lambda at the first iteration, andmax(w_new, (w_old + w_new) / 2)later. Both rules keep the weights strictly above the multipliers. - The merit search receives the design bounds and the known merit of the current design. This saves one row per callback in each search, and a rounded trial cannot leave the box.
SqpOptions.line_search_optionsselects the merit search by its type:GoldenSectionOptions(default) orBacktrackingOptions(Armijo backtracking from the unit step). The Armijo test uses the one-sided directional derivative of the L1 merit,D = g @ d + sum_i w_i s_i + sum_j v_j t_j, formed from the gradient, the Jacobians, and the residuals of the iteration, so it costs no model row. Heres_i = J_i @ dfor a violated inequality,max(J_i @ d, 0)for an active one, and zero for a satisfied one;t_j = sign(h_j) (E_j @ d), or|E_j @ d|forh_j = 0. A step that restores feasibility while the objective rises therefore has a negative slope, as it must. Armijo often needs one to three merit samples instead of about nine, but it accepts the first sufficient decrease and does not minimize along the line, so steps, iteration counts, and statuses can differ.- The accepted endpoint reuses the objective value and residuals of the last merit trial when that trial is the endpoint; golden-section search evaluates its returned step last.
The numerical Hessian stencil starts from the known objective, or the known Lagrangian, of the current design. Each reuse saves one row per callback.
The reuse assumes a deterministic model.
reuse_observations=Falseevaluates both designs again for a model that can change between calls. - A rejected merit search keeps the current design and stops with
NO_FEASIBLE_STEP. The exception is a rejected zero step where the stopping rule passes at the unchanged feasible design.
SQP curvature handling:
SqpOptions.curvature_policy="diagonal-shift"(default) raises the smallest eigenvalue of the symmetrized curvature matrix tomax(minimum_subproblem_curvature, 100 * spacing(max|B|)), withminimum_subproblem_curvature=1e-8. Zero and weak curvature are lifted too."strict"passes the matrix unchanged, so indefinite curvature raisesValueError.SqpResultreportscurvature_modification_countandmaximum_curvature_shift.- Each
SqpIterationkeeps itscurvature_shift, multipliers, merit weights, step size, line search, and damped BFGSbfgs_updaterecord. With the defaultretain_derivatives=Trueit also keepslinearizationandcurvature_matrix, the curvature matrix of the step model before the diagonal shift. - With
use_bfgs=True, SQP appliesdamped_bfgs_hessian_update(Powell damping, Nocedal and Wright Procedure 18.2). A step with too little or negative curvature is damped, not skipped, so the matrix stays positive definite. - The function returns the updated matrix and a
BfgsUpdateRecord(skipped,damping,curvature,model_curvature). It skips only a zero step or a matrix whose model curvatures.T @ B @ sis not positive.
SQP failure statuses:
- An infeasible linearized subproblem gives
NO_FEASIBLE_STEP. This status does not prove nonlinear infeasibility. - Every other failed QP status, such as its iteration limit or an unbounded QP model, gives
NUMERICAL_ERROR. The message isSQP subproblem failed at iteration k: <QP status>: <QP message>. - A QP limit is not an SQP budget stop, so
budget_exhaustedstaysFalse.SqpResult.subproblem_failurekeeps the failed QP result.
SQP negligible steps:
- SQP skips the line search for a step below the subproblem accuracy.
Every step coordinate then lies within its rounding scale (
is_negligible_step,10 * spacing(max |x_i|)of the current and candidate designs), or within10 * tolerance * width. Heretoleranceis the QP tolerancequadratic_program_options.tolerance(default1e-10), andwidthis the finite bound width of the coordinate. - Such a zero step lets the stopping rule decide at the unchanged design. When the rule does not converge, the run stops.
- The accuracy rule makes algebraically equal constraint formulations give the same status. The tradeoff is that SQP does not take a true step below the subproblem accuracy.
- A
hessian_functionmust return a symmetric matrix within1e-8 * max|H|. SQP uses its symmetric part, asmodified_newtondoes.
Method of moving asymptotes
The method of moving asymptotes (MMA) solves Svanberg's subproblem with artificial variables y >= 0.
The costs are artificial_linear_cost=1000 and artificial_quadratic_cost=1.
An inconsistent linearization therefore does not stop the run. The final feasibility signal reports an infeasible result.
Subproblem solver:
- The native primal-dual interior-point solver follows the barrier parameters 1, 0.1, ... down to
subproblem_tolerance=1e-7. - It takes at most
subproblem_max_iterations=200Newton steps per parameter. - Each Newton step solves the reduced (n + m)-square system by default (
newton_system='full').newton_system='schur'solves the smaller positive definite Schur complement by a Cholesky factorization, as Svanberg'ssubsolvdoes. The work per step falls fromO((n + m)**3)toO(min(n, m)**2 * max(n, m)). The direction is the same in exact arithmetic; the rounding differs, so iterates and Newton step counts can change in the last digits, and a borderline subproblemsuccesscan change. - A nonconverged subproblem stops the run with
NUMERICAL_ERROR. - Equalities enter as two linear rows.
- A custom
subproblem_solver(objective, start, bounds, constraint)works inw = [x, y]and returns(w, success)withsuccessTrue, False, or None.
Asymptote controls:
- Asymptote distances stay within
asymptote_distance_bounds=(0.01, 10)design widths. asymptote_update(default 0.7) lies in(0, 1]. The value 1 keeps the asymptote distances fixed (no adaptation), so a run can cycle untilmax_iterations.asymptote_relaxation_exponent(default 0.5) is finite and nonnegative. The value 0 contracts after oscillation and never relaxes.- A rounded pole or move-bound collision leaves no representable reciprocal subproblem. The run then stops with
NO_REPRESENTABLE_PROGRESSat the last accepted design, before any division.
Fixed coordinates and records:
- Fixed coordinates keep their value and do not enter the subproblem. Their recorded asymptotes are NaN.
- When every coordinate is fixed, one iteration applies the stopping rule at the unchanged design without derivatives or a subproblem, and then stops.
The status is
CONVERGEDat a feasible design andINFEASIBLEwhen the rule passed at an infeasible design. Otherwise it isNO_FEASIBLE_STEP. - Each
MmaIterationkeeps the asymptotes, move bounds, and theMmaSubproblemResultwith its artificial variables. - It also keeps the reciprocal approximation that produced the step:
positive_coefficients(p) andnegative_coefficients(q), shape(1 + n_inequalities, n_variables)with the objective row first and zero columns for fixed coordinates, andconstant(r), shape(1 + n_inequalities,). At the design x before the iteration,p_ij = (U_j - x_j)^2 * (max(df_ij, 0) + 0.001 * |df_ij| + raa0 / w_j),q_ij = (x_j - L_j)^2 * (max(-df_ij, 0) + 0.001 * |df_ij| + raa0 / w_j), andr_i = f_i(x) - sum_j (p_ij / (U_j - x_j) + q_ij / (x_j - L_j)). Each row matches the value and the gradient at x:p_ij / (U_j - x_j)^2 - q_ij / (x_j - L_j)^2 = df_ij. Equality rows are linearized separately and are not part of these arrays. All three areNonewhen every coordinate is fixed.MmaOptions(retain_derivatives=False)storesNoneinpositive_coefficients,negative_coefficients, andlinearization;constantstays.
The default cost c = 1000 assumes objective and constraint values of order 1 to 100.
For larger multipliers, scale the problem or raise c.
Actual objective and residual evaluations and the final stationarity check decide the returned convergence signal.
Population methods
The population methods use the canonical update rules. The example point_population_search.py compares the genetic algorithm, differential evolution, and particle swarm on the Himmelblau function, with the order-2 stability test of the swarm, and pareto_search_demo.py checks a Pareto archive against a known constrained front and its exact hypervolume.
Constraint selection:
differential_evolution,particle_swarm,genetic_algorithm, andcovariance_matrix_adaptationhaveconstraint_selection, default"feasible-first".- A feasible design ranks before an infeasible one. Feasible pairs compare the objective. Infeasible pairs compare the largest tolerance-adjusted excess, then the objective.
- The result is the best feasible design when one was observed, and
feasiblestays the final verdict of the accounting boundary. - No convergence test, the default one or a supplied
convergence_function, can stop a population with an infeasible member. Agreement among infeasible designs says nothing about the constrained problem. "scalar-merit"compares the scalar merit ofoptions.evaluationonly. A penalty, barrier, multiplier, or merit weight has an effect only in this mode, and setting one with"feasible-first"raisesValueError.- A problem without constraints gives the same run in both modes. This includes the subproblems of
penalty_barrier. - Tradeoff: results on a directly constrained problem differ from a scalar comparison, and a run can use more evaluations, because infeasible convergence is blocked.
- Each iteration record keeps the excess that selection used in
population_constraint_excess. retain_evaluations(default False) keeps the objective decomposition (ObjectiveEvaluation: design, raw objective columns, scalarized objective, constraint values, penalty and barrier sums) of every evaluated row. It fillspopulation_evaluationsandevaluation(the incumbent) of each iteration record,trial_evaluationsof differential evolution, andinitial_population_evaluationsandfinal_evaluationof the result. Each entry is the record of the observation behind the value at the same index, sopopulation_evaluations[i].objective == population_objectives[i]; a kept member, a trial equal to its target, and a reused design keep the record of their original observation. ANoneentry marks an objective thatskip_infeasible_objectivesskipped. The records come from the same callback batches and change no count, draw, design, or status. Tradeoff: the penalty and barrier policies run for every evaluated row, also withpenalty_constant=0, and memory grows with one record per row.- A fixed box stops after the initial evaluation with zero generations, in all four methods.
The status is
CONVERGED, orNO_FINITE_CANDIDATEwithsuccess=Falsewhen the only design has no finite merit, for example at a barrier that rejects it. skip_infeasible_objectives(default False,"feasible-first"only) evaluates the constraints of each batch first and the objective only at the feasible rows. Feasible-first selection reads the objective of an infeasible design only to break an exact excess tie, so the objective rows drop by the infeasible share. A skipped row has the value positive infinity (unavailable), and its positive excess marks it. Two infeasible designs with equal excess then no longer compare objectives, so the result can differ. The supported criteria are the default one,population_objective_range, andbest_objective_change. Anotherconvergence_functionand a custom geneticfitness_functionraiseValueError.population_objective_rangethen needs two evaluated rows, so a one-member population does not meet it. Under a finite budget, the final check can need a new constraint query. In the mapped workflows the option adds model rows, so keep it off there.
Differential evolution:
differential_evolutionapplies DE/rand/1/bin (Storn and Price).- Each target row gets a donor from three other distinct rows:
x_r1 + F * (x_r2 - x_r3)with0 < F <= 2(mutation_factor, default 0.8). - Binomial crossover takes each trial coordinate from the donor when a draw in
[0, 1)is belowCR(crossover_probability, default 0.5), plus one forced coordinate per row. DifferentialEvolutionIteration.recombination_maskis the coordinate mask, andforced_coordinatesholds each forced coordinate.recombination_factorskeeps the uniform draws that crossover compared withCR, sorecombination_mask == (recombination_factors < CR)except at the forced coordinate. The propertiesbase_vectors(x_r1) anddifference_vectors(x_r2 - x_r3, unscaled and unclipped) givedonor_vectors == problem.project(base_vectors + F * difference_vectors)exactly.- The population needs at least four rows. A trial equal to its target reuses the known value and costs no callback row.
Particle swarm:
particle_swarmuses the inertia-weight updatev = w*v + c1*R1*(p - x) + c2*R2*(g - x)with uniform factors per particle and coordinate.- The options
inertia=0.7298(w), andcognitive=1.49618(c1) andsocial=1.49618(c2) are the Clerc-Kennedy constriction values. velocity_bounds(default 0.2) are fractions of each design width.- The initial velocities are uniform inside these limits.
particle_swarm(..., velocity_sampling_function=..., velocity_sampling_options=...)replaces that draw, for example with zero or Latin-hypercube velocities. - The sampler is called as
(velocity_box, population_size, rng, options), withvelocity_box = [lower; upper]of the velocity limits. Its rows must lie inside those limits.
Genetic algorithm:
genetic_algorithmcallsmutation_functiononly when at least one row is selected for mutation. It callscrossover_functiononly for selected pairs.- It reuses the known value of a new proposal that exactly repeats a current row. This assumes a deterministic objective.
- Its age limit
maximum_population_agecounts generations that a member survives unchanged. An expired member accepts its next new proposal. - The default
normalized_fitnessgives positive-infinity (barrier-rejected) members zero weight. When no member has a finite value, the run stops withNO_FINITE_CANDIDATE. - The result keeps the incumbent. The incumbent is finite when an earlier generation found a finite value, for example before an age replacement made every member infinite.
inverse_fitnessreturnsmin(f) / ffor finite positive values.
Shared behavior:
- Both particle swarm and the genetic algorithm project per coordinate. A coordinate that leaves the box is clipped to its bound, so the other coordinates keep moving.
- A clipped particle coordinate also loses its velocity (an absorbing bound).
- A one-member population has no objective spread, so its default convergence test is the best-objective change with tolerance
1e-6instead of the range test. - Without
convergence_function,convergence_options={"tolerance": value}sets the tolerance of the default test and replacespopulation_tolerance. Another option name raisesTypeError. - When the evaluation budget denies a batch, each population method returns its best evaluated design with
MAX_EVALUATIONS. - Every population batch also evaluates the constraints. Under a finite budget, the final check therefore reuses the constraint rows observed with the returned design and needs no new row.
- The population methods keep no witness of their own, so the accounting boundary compares every recorded observation of the returned design. Their verdicts must agree. Otherwise the final check queries the constraints again. See callback accounting.
Exact-design reuse (reuse_evaluated_designs, default False):
- Differential evolution, the genetic algorithm, and particle swarm accept the option. With it, one store per run maps the exact bits of each evaluated design to its first observation.
- Each evaluation call then receives only the new distinct rows. The other rows take the stored merit and constraint excess. On integer and mixed-integer domains, projection rounds many trial designs onto designs that the run already evaluated, so the saving can reach most rows of the late generations.
- The iteration records mark each reused row (
evaluation_is_reused) and name its original observation (evaluation_origin: generation and row; generation 0 is the initial population).PopulationOptimizationResult.reused_design_rowscounts the served rows. - Contract: deterministic, row-independent callbacks and a row-independent scalarization policy. The callbacks receive smaller batches in another composition.
- Tradeoff: a run under an evaluation budget can continue further and return another result. Memory grows with the number of distinct designs. The random stream does not change.
Result signals of the four population methods:
statusnames only the reason why the run stopped.feasiblereports whether the returned design satisfies the constraints.CONVERGEDrequires both the convergence test and a feasible returned design. A passed test at an infeasible design givesINFEASIBLE.- Differential evolution, particle swarm, and the genetic algorithm also succeed with
OBJECTIVE_THRESHOLD:objective_threshold(default-inf, disabled) stops the run when the best member is feasible (zero tolerance-adjusted excess, also under"scalar-merit") and its finite merit is at most the threshold. The test runs after the initial population (unless the box is fixed; thenn_iterationsis 0) and after each completed generation, afterstop_callbackand before the convergence test.+infaccepts the first feasible best member.successrequires that the final check confirms feasibility. When a noisy constraint callback makes that check fail,feasibleandsuccessare False and the status staysOBJECTIVE_THRESHOLD, because the accounting boundary replaces only a converged status. CMA-ES has no threshold option. - An infeasible design at the iteration limit keeps
MAX_ITERATIONS, withfeasible=False. - A
stop_callbackrequest givesSTOPPED. The callback runs before the threshold and convergence tests of the same generation. - Objective agreement among the members can pass the default test. It proves neither a global minimum nor first-order stationarity.
- The module docstring of
methods/population.pylists every status. Thecovariance_matrix_adaptationdocstring lists its statuses, includingNUMERICAL_ERROR.
Direct sampling
Direct sampling evaluates generated or supplied designs and keeps the best feasible sample. A feasible sample has a finite objective, satisfies its constraint tolerances, and lies in the design domain (inside the bounds, with integer values in integer coordinates).
Supplied points:
- By default, direct sampling rejects supplied points outside the bounds and rounds integer coordinates to the integer lattice.
SamplingOptions(outside_points="sweep")evaluates every supplied point exactly as supplied, without clipping or integer rounding.- Sweep rows outside the bounds or with a fractional integer coordinate are recorded diagnostics. They are infeasible, so a feasible inside row takes priority and such a row cannot reach the threshold.
max_evaluations(default 1000) caps suppliedpointstoo. The solver validates all supplied points and then evaluates only the firstmax_evaluationsrows, so later points are not searched.- A sweep of all supplied points, fewer than the cap, ends with
EVALUATIONS_COMPLETED. Reaching the cap ends withMAX_EVALUATIONS.
Batches and budgets:
batch_sizedefaults toceil(sqrt(n))rows fornplanned rows, independent of the objective threshold.- Any
objective_thresholdabove negative infinity is active. Positive infinity accepts the first batch with a feasible design. lazy_sampling(default False) generates the rows of each batch just before the batch is evaluated, instead of all generated rows before the loop. Each batch takes the remaining initial designs first and asks the sampler only for its missing rows; a batch that the initial designs fill makes no sampler call. The default uniform sampler then gives exactly the eager rows. A custom or stratified sampler (for example a Latin hypercube) builds one design per call, so it can give another row set. A threshold or callback stop leaves the later batches ungenerated, so the sampler does no work for them. Explicitpointswithlazy_sampling=TrueraiseValueError.SamplingResult.selected_observation_indexidentifies the processing position of the returned design, andselected_constraintsholds its constraint row. Final qualification reads that row, so it spends no extra constraint row.max_evaluations=0evaluates nothing: no model and no sampler runs. The result reportsMAX_EVALUATIONS,n_iterations=0, a NaN objective, no observation, andfeasible=None. Its design is a placeholder: the first supplied point, or the projected bound midpointproject(0.5 * lower + 0.5 * upper)for generated rows. A problem with initial designs and a zero budget still raisesValueError("initial designs cannot exceed max_evaluations.").- A problem
evaluation_budgetsmaller than the planned rows stops the sweep withMAX_EVALUATIONSand the incumbent of the completed batches. - A denied first batch returns the first planned row with a NaN objective and no observation.
retain_populations=False(default True) dropsevaluated_points,evaluated_objectives, andevaluated_constraints(they become None). The result keeps the selected observation, the first observation, the counts, the status, and the batch-incumbent history, so its memory does not grow with the row count. Decisions and counts do not change.
Bayesian optimization
Bayesian optimization fits a Gaussian process (GP) surrogate and evaluates each design once by default.
For noisy repeated evaluations, set allow_repeated_evaluations=True explicitly.
Default surrogate:
- The default GP has one isotropic squared-exponential kernel with a constant mean.
Maximum marginal likelihood (
fit_hyperparameters=True) fits it on standardized inputs and responses. - The fit chooses the length scale, the signal variance, and the noise. The constant mean is the generalized least-squares coefficient.
- The fit standardizes the inputs. Each design coordinate is centered by its mean and divided by its sample standard deviation.
A coordinate whose deviation is below
sqrt(eps)(about1.49e-8) stays in design units (center 0, scale 1). - The likelihood fit, the model, and its predictions use this one input transformation.
Predictions therefore do not depend on the response units or on the units of a coordinate whose deviation is at least
sqrt(eps). - Each fit runs one L-BFGS-B search with three parameters, four with
kernel="rational_quadratic", and the lower bounds below, so fitting costs more than a fixed kernel.kernelandbasisfix the family (see "Kernel and basis families" below). The fit does not search families or per-coordinate length scales. - By default (
likelihood_gradient="finite_difference"), SciPy estimates the likelihood gradient by forward differences: four likelihood evaluations per gradient, each with a new distance matrix and a factorization.likelihood_gradient="analytic"computes the squared distances of the standardized designs once per fit and passes the exact gradient0.5 * sum((alpha alpha' - K^-1) * dK/dtheta). The constant mean is profiled out, so this partial derivative is the derivative of the profile likelihood. It requires the default family (kernel="squared_exponential",basis="constant"). Tradeoff: the fitted settings can differ within the optimizer tolerance, so a seeded run can differ from the default.
Kernel and basis families:
BayesianOptions,GaussianProcess, andGaussianProcess.fittakekernel,basis, andrational_quadratic_alpha. The objective model and every surrogate constraint model use the same family.- With the scaled distance
r = ||u - u'|| / length_scaleof two standardized designs, the kernel correlations are:"squared_exponential"(default):exp(-r**2 / 2), the smoothest surface;"exponential":exp(-r), a continuous but rough surface;"matern32":(1 + sqrt(3) r) exp(-sqrt(3) r), once differentiable;"matern52":(1 + sqrt(5) r + 5 r**2 / 3) exp(-sqrt(5) r), twice differentiable;"rational_quadratic":(1 + r**2 / (2 alpha))**(-alpha), a mixture of length scales.rational_quadratic_alphais the start (or the fixed value) of the shapealpha, default 1. It is valid only with this kernel.
- The basis sets the prior mean
h(u)' betaon the standardized designsu:"zero"(no trend),"constant"(default,[1]),"linear"([1, u]), or"quadratic"([1, u, u**2], no cross products). The fit profiles the coefficientsbetaby generalized least squares;GaussianProcess.basis_coefficientsreports them in standardized response units.GaussianProcess.constant_meanis the response-unit constant of the constant basis andNonefor every other basis. - The
"zero"basis does not center the responses, so its prior mean is zero in response units. It assumes responses that vary around zero. The other bases center the responses by their mean, which their intercept absorbs. - A basis with more columns than training rows, or with dependent columns, is not identified. The coefficients are then the minimum-norm least-squares solution.
- The analytic likelihood and acquisition gradients require the default family; another family raises
ValueError. - Tradeoff: a fixed family is cheaper and repeats without random choices, but it can fit a response worse than a searched family. A
model_trainercan supply a model of another family or with per-coordinate length scales.
Bounds and starting values:
- The noise standard deviation has the lower bound
max(1e-3, 0.01 * std(y))in response units (noise_standard_deviation_lower_bound). - The fit searches the length scale (standardized design units) and the signal standard deviation (response units) with the lower bound
1e-6for every kernel family, and the fitted rational-quadratic shape with the lower bound1e-6. These are bounds of the search; no kernel clips a value. No setting has an upper bound. kernel_length_scale,signal_variance, andnoiseare starting values in standardized units. They set where the search begins and do not limit the fitted values.- Their default
Noneuses a data-based start:- length scale
max(1e-3, mean column standard deviation of the standardized designs), which is 1 unless a coordinate is near-constant; - signal and noise standard deviations
max(1e-3, std(y) / sqrt(2)), where a fitted noise starts at least1e-3above its lower bound.
- length scale
- With
fit_hyperparameters=False, these start values are the fixed settings. - The likelihood can have several local maxima, so the start decides which one the local search finds.
- The data-based start gives half of the response variance to noise. On small data sets the fit can therefore stop at a smoother, noisier model than a near-interpolating start, and acquisition choices change. Pass explicit start values to choose another start.
Retention and final check:
max_training_samplesfits each model to the newest observations only. Incumbent selection still uses all of them.- With
retain_surrogates=False, the solver fits a model only when an acquisition needs it, and the result keeps no model. reevaluate_final_candidate=Trueevaluates the selected design once more and returns that fresh observation. A fresh result can withdraw threshold success (FINAL_FEASIBILITY_FAILEDorFINAL_OBJECTIVE_THRESHOLD_FAILED).- An acquisition iteration that returns only known designs did real work. It counts in
n_iterationsand keeps a record with its trial points, candidates, and scores and no evaluated point. The run then stops withNO_FEASIBLE_STEP.
Acquisition and uncertainty:
- Public predictions default to response uncertainty, which includes observation noise.
Request
uncertainty_kind="latent"for noise-free process uncertainty. - Expected improvement and probability of improvement request latent uncertainty explicitly.
- Expected improvement is the default acquisition. Pass
acquisition_function=probability_of_improvementfor probability of improvement. - Both use the standard normal distribution function and density in closed form (
scipy.special.ndtrandexp(-z**2 / 2) / sqrt(2 * pi)) for every positive deviation. Only an exactly zero deviation uses the deterministic limit. - With the improvement
I = current_best - mean - exploration, the latent deviations > 0, andz = I / s, expected improvement returnsmax(I * Phi(z) + s * phi(z), 0). The exact value is nonnegative. The clamp changes only a far-tail result (zbelow about -37) that is smaller than the rounding error of the two terms, and it makes that result zero. - Surrogate constraints use predicted means during acquisition. Actual residuals decide final feasibility. This mean policy supplies no probabilistic feasibility certificate.
- By default (
acquisition_gradient="finite_difference"), SciPy estimates each acquisition gradient of the SLSQP search by forward differences. One gradient then costsn_variables + 1single-design acquisition calls. acquisition_gradient="analytic"passes the exact gradient of expected improvement or probability of improvement through the Gaussian-process prediction. The chain rule includes the input standardization and the response scaling:dEI/dx = -Phi(z) * dmean/dx + phi(z) * dsigma/dxanddPI/dx = phi(z) * (dI/dx - z * dsigma/dx) / sigma. One SLSQP request then costs one value-and-gradient evaluation, and one batched call scores the optimized candidates. It requires a built-in acquisition, the built-in SLSQP search, and aGaussianProcessmodel of the default family. Tradeoff: the SLSQP iterates follow another gradient, so candidates, scores, and seeded runs can differ from the default in low-order digits, and then in the evaluated designs.- With
retain_trial_points=True(default), eachBayesianIterationkeepsacquisition_optimizer_outputs: oneAcquisitionOptimizerOutputper trial start, in start order. It holds the optimizer's design before clipping, the final negative acquisition, the convergence flag, the termination text, the iterations, and the acquisition calls. The built-in SLSQP search reports every field. A custom optimizer that returns only a design reports no evidence, so these fields areNone, neverFalseor zero. The stored scorepredicted_improvementis the acquisition at the clipped candidate, so it can differ from-negative_acquisitionwhen the optimizer left the bounds. Withretain_trial_points=False, the tuple is empty, as the trial and candidate arrays.
Modeled feasibility, work budgets, and warm starts (all off by default):
modeled_feasibility=Truefits one model per inequality column at the start of each iteration, with the objective-model policy (window, family, warm start). The acquisition search then has no constraint and makes no constraint query. Its score isacquisition(x) * PF(x)when a feasible observation exists (kind"feasibility_weighted") andPF(x)alone otherwise (kind"feasibility").PF(x)is the probability of feasibility: the product over the inequality columnsjofPhi((t_j - mu_j(x)) / sigma_j(x)), with the latent meanmu_jand deviationsigma_jof the column model. The tolerancet_jisconstraint_tolerancewhen set, else the tolerance of the observed column (default1e-6). A zero deviation gives the indicatormu_j <= t_j.FeasibilityModel(inequality_models, tolerances).probability(points)computes it; the solver, the iteration record, and the progress views use this one formula.- The product of the improvement and the probability is the expected feasible improvement (Schonlau, Welch, and Jones 1998; constrained expected improvement in Gardner et al. 2014). It rewards designs that are likely feasible and likely better, without a feasible region in the search. The product assumes conditionally independent columns; correlated constraints make it too small or too large. The probability guides the search only: actual residuals still decide the incumbent.
- Modeled feasibility needs inequality constraints only. A problem without a constraint source or with an equality source raises
ValueErrorbefore any callback. A combined callback shows its columns only after evaluation, so its check runs after the initial evaluation and before any model fit. It excludesuse_surrogate_constraintsandacquisition_gradient="analytic". - Each record keeps
acquisition_kind,predicted_feasibility(PF at the candidates), and, withretain_surrogates,previous_feasibility_model. Tradeoff: every retained record then keeps one model per inequality column. max_model_fitscaps the model fits (one fit of one response column). The initial fit is always allowed. An iteration starts only when its fits fit the budget (an objective fit for a stale model and one fit per constraint model); otherwise the run stops withMAX_MODEL_FITS. A denied refit after a batch keeps the record without a new model and stops after it; the result then has no surrogate.max_acquisition_rowscaps the acquisition rows (one design at which the search score is evaluated). An iteration does not start without a remaining row. A request beyond the remaining rows is denied before evaluation; the iteration keeps no record and the run stops withMAX_ACQUISITION_ROWS. Tradeoff: SLSQP does not know its request count in advance, so the budget stops a search instead of shortening it, and the last iteration's work is lost.- Both budgets are independent of the evaluation budget. Neither status is a success or a useful completion. The result reports
model_fitsandacquisition_rows. warm_start_hyperparameters=Truestarts each refit of a response at the fitted values of its previous fit (the configured starts apply to the first fit only). It requiresfit_hyperparameters=True. With amodel_trainer, the trainer receives the previous model of the response incontext.previous(see "Custom model trainers" below). Tradeoff: fewer likelihood evaluations, but the search can stay near the previous optimum, so models, selected designs, and work counts can change. The previous fitted values belong to the standardization of the previous training rows, so the start lies near, not at, the previous optimum.- bayesian_feasibility_search.py teaches modeled feasibility on a problem with a forbidden interval.
Custom model trainers:
model_trainer(points, values, options, context)replaces the built-in fit. The solver calls it once per model fit with copies of the training window (the newestmax_training_samplesobservations), theBayesianOptionsrecord, and aBayesianFitContext. It returns any model with a callablepredict(the structural typeSurrogateModel).context.responseis aBayesianResponse. Itskindis"objective","inequality", or"equality", and itscolumnis the zero-based constraint column (Nonefor the objective). The record is hashable, so a trainer can keep its own state, or choose another model family, per response.context.previousis the model that the trainer returned at the previous fit of the same response, whenwarm_start_hyperparameters=True. It isNoneat the first fit of each response, and alwaysNonewithout the option. The solver keeps the last model of each response until the next fit of that response.fit_bayesian_model(points, values, options, *, previous=None)is the public built-in fit. It reads the start values,fit_hyperparameters,noise_standard_deviation_lower_bound,hyperparameter_max_iterations,likelihood_gradient,kernel, andbasisfromoptions. ApreviousGaussianProcessreplaces the start values with its fitted values; apreviousof another type raisesTypeError.- The one-line trainer
lambda points, values, options, context: fit_bayesian_model(points, values, options, previous=context.previous)reproduces the built-in fit exactly, with and without warm starts. A trainer that wraps or post-processes the returned Gaussian process keeps the warm start of the built-in fit in the same way. - In each iteration, the solver fits the objective first (when its model is stale), then the inequality columns in column order, then the equality columns.
The decision-history example runs seven of these methods on known problems. It prints selected decisions for comparison. The point-optimization lessons compare four gradient methods, five constrained methods, and three population methods on problems with known minima, and check every returned design independently.
Imports and module layout
Use from designoptpy.point import conjugate_gradient in short examples.
Internal code imports definitions from their owning module, such as designoptpy.point.methods.conjugate_gradient.
Method-specific options and records stay beside their solver. options and results contain shared definitions only.
Importing designoptpy.point 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.point submodule also runs this eager import.
Plot functions and plot options are available only from designoptpy.point.plotting, so a numerical import never pays for the plotting library.
BayesianOptimizationResult lives in designoptpy.point.results, because the accounting boundary checks every
result against it. The accounting module therefore does not depend on the Bayesian method module, and the two modules form no import cycle.
MappedOptimizationResult, MappedParetoResult, and ResponseRecord live in designoptpy.point.workflow_mapping.
Least-squares problems
gauss_newton and levenberg_marquardt require LeastSquaresProblem.
They exploit the residual vector instead of differentiating a precomputed scalar sum of squares.
Problem definition:
LeastSquaresProblem(residual=..., initial_design=..., jacobian=..., bounds=..., evaluation_budget=...)defines the problem.- The residual callback maps
(n_samples, n_variables)to(n_samples, n_residuals). - The optional Jacobian takes one design vector and returns
(n_residuals, n_variables). It stores residual derivatives in rows and design variables in columns. - Both methods minimize
0.5 * sum(residuals**2)over continuous variables inside optionalbounds(outward infinite limits allowed; None means unbounded). - Bounds express physical parameter limits, for example a positive rate constant. Every residual evaluation, including finite-difference probes and trials, stays inside them.
Bounds in the steps:
- At active bounds both methods use an active-set step. Blocked coordinates keep a zero step, and the linear model is solved on the free Jacobian columns.
- Gauss-Newton then projects the direction and runs
backtracking_searchinside the box. A non-descent direction falls back to the projected negative gradient and setsdescent_fallback. - Levenberg-Marquardt removes outward step components, shortens the trial to the box along its ray, and computes the predicted reduction from the evaluated trial step.
LevenbergMarquardtOptions.spectral_steps=True(default False) decomposes the free Jacobian once per linearization,J_F = U diag(s) V.T, and forms each damped step asV diag(s / (s**2 + damping)) U.T (-r)with the overflow-safe filters(s / t) / t,t = hypot(s, sqrt(damping)). A trial after a rejection then costs matrix-vector products instead of a newlstsqsolve. The rank rule oflstsqon[J_F; sqrt(damping) I]is kept. The step is the same in exact arithmetic; rounding differs, so a borderline acceptance can change, and at extreme scales results can differ beyond rounding. For a 400-by-60 Jacobian the decomposition costs about two augmentedlstsqsolves, so the option pays when linearizations see rejected trials.
Budget and cost:
- The optional
evaluation_budget=EvaluationBudget(total=...)caps the residual callback rows, finite-difference probes included. Analytic Jacobian calls cost no row. - A denied row ends the run with
MAX_EVALUATIONSat the last accepted design. A denied initial evaluation gives objective NaN andfinal_residuals=None. - No accounting boundary wraps these solvers. Their own evaluator counts and limits the work. Their results report
elapsed_secondsfor their own loop. - The numerical Jacobian reuses the known residual vector at the current design, so it costs two residual rows per free coordinate.
To run a residual solver, call solve(problem, "gauss-newton") or solve(problem, "levenberg-marquardt"), or call either method directly.
solve rejects an ordinary OptimizationProblem for a residual solver, because objective columns are never reinterpreted as residuals.
Call custom residual solvers directly. to_optimization_problem() exposes the scalar cost with the same bounds (infinite where none are set) and budget.
Compare the Gauss-Newton step with the damped Levenberg-Marquardt (LM) step and inspect rejected trials.
Each record identifies the retained endpoint and the last trial separately. final_residuals belongs to the final design.
These separate states explain the local model even when a trial is rejected.
Success means that the stationarity test passed.
A small objective gradient can occur with nonzero residuals; stationary least squares does not require an exact residual solution.
Stationarity test of both methods:
- Both methods test
||pg||_inf <= gradient_tolerance * max(1, ||pg0||_inf)before every step. Herepgis the projected gradient ofJ.T @ r(each component is zero where an active bound blocks descent),pg0is its value at the initial design, and the default isgradient_tolerance=1e-8. - Below an initial gradient norm of one, the threshold is absolute.
- A step with
||step|| <= step_tolerance * (1 + ||x||)requests one more pass, which tests the resulting design. The status isCONVERGEDwhen the test passes andSTALLEDotherwise. - This pass runs also after the last permitted step. Without it, the run ends with
MAX_ITERATIONSand evaluates no further Jacobian. - Gauss-Newton accepts an Armijo trial also at an equal cost, as
backtracking_searchdoes. The stationarity test still decides success. - A rejected search stops with
NO_FEASIBLE_STEP. An accepted step that cannot change the stored design stops withNO_REPRESENTABLE_PROGRESS.
Final-design diagnostics, independent of history retention:
LeastSquaresResult.gradient_normis the projected-gradient norm of the last stationarity test when that test ran at the returned design, andNoneotherwise, for example afterMAX_ITERATIONSthat follows an accepted step.levenberg_marquardtreturnsLevenbergMarquardtResult. Itsfinal_dampingis the damping of the next trial:initial_dampingwhen no trial completed, elsenext_dampingof the last completed trial, also afterSTOPPED. A trial rejected atmaximum_dampinggivesmaximum_damping. A budget denial or a numerical stop inside a trial keeps thenext_dampingof the previous trial.
Workflow options of solve
Six independent workflow options add a policy around a named scalar or Pareto solver. Each option is off by default. The solver itself runs unchanged. Custom and residual solvers reject these options.
log_evaluations=Truerecords every objective and nonlinear constraint call inobjective_logandconstraint_log.ObjectiveLoggerandConstraintLoggerretain the exact call history. For a direct solver call, pass the logger as the objective andConstraintLogger.logged_constraintsas the nonlinear constraints.log_history_limitcaps the retained calls of both logs; the full row counters remain. Each log counts the attempted calls (number_of_calls) and their rows (number_of_evaluations) before the callback runs, so a call that raises still counts, as the accounting boundary counts it; a call that the evaluation budget denies does not count, and only successful calls enter the history. It isNone(keep every call) or a nonnegative integer; zero keeps no call, ashistory_limit=0does in the SciPy adapters. The loggers keep the callback layout: acombinedcallback stays one combined callback, and separateinequalityandequalitycallbacks stay separate. Each user callback therefore runs as often as without logging, so logging changes neither the returned design nor the counts, andcounts.constraintsreports the user-callback rows.constraint_loghas one entry per user-callback call. An entry of a separate callback holds only the residuals of its own group andNonefor the other group.constraint_log.inequalityaligns withconstraint_log.inequality_samples, andconstraint_log.equalitywithconstraint_log.equality_samples.feasible_start=FeasibleStartOptions()replaces an infeasible start before the solver runs. Recovery is opt-in: the defaultfeasible_start=Noneskips it. A scalar solver starts from the first feasible initial row. Otherwise recovery starts from the row with the smallest summed overall violation of every constraint source. It minimizes positive nonlinear inequalities plusFeasibleStartOptions.equality_residual_weight(default 1) times the squared nonlinear equalities, and it keeps the bounds, the linear constraints, and the integer variables as hard requirements. The weight changes only the objective of the start preparation, not the constraints of the solver. It must be finite and positive, because a zero weight would let recovery stop at an equality-violating design. This is the standard phase-one formulation: linear rows are exact for SLSQP and SciPy differential evolution, so the objective measures only the nonlinear part. Continuous problems use SLSQP. Integer problems use SciPy differential evolution. The recovery uses therngof the solver options whenFeasibleStartOptionshas norng.solveconverts thatrnginto one Generator before the run, so the recovery and the solver advance the same generator and one integer seed reproduces both phases. A Pareto solver keeps its initial population only when every row is feasible.return_best_feasible=Truereturns the best feasible design among the start, the retained history, and the final design. A candidate is feasible when its residuals meet their tolerances and it lies in the domain: inside the bounds, with integer values for integer variables. It applies when that design improves the result or replaces an infeasible final design, for example a sampling sweep point outside the bounds. It applies to scalar solvers. A returned earlier design has statusBEST_FEASIBLE_SELECTED;solver_statuskeeps the solver termination. See Result signals. Withreuse_history_residuals=True(default), the selection reuses the residuals that the history records of the gradient methods hold for the same design. It then evaluates the constraints only at the other candidates, at least the start. This assumes a deterministic constraint model.reuse_history_residuals=Falseevaluates every candidate again, for a model that can change between calls.refinement="scipy-minimize"runs a second scalar solver from the design that the first solver returns. For example,solve(problem, "pattern-search", refinement="scipy-minimize")seeds SLSQP with the pattern-search result.refinement_optionssets the options of the second solver, for exampleScipyMinimizeOptions(scipy_options={"maxiter": 50}). The other workflow options apply to both phases. The returnedSequentialOptimizationResultretains both phase results, their histories, and merged logs. Its design, objective, status,success, andevaluation_optionscome from one phase, named byreturned_phase. The refinement design is returned only when it passes its final check and costs no more than a qualified search design. Otherwise the search design is returned, also when neither phase qualifies. A local refinement usually ends no higher than its start, but a refinement that stops at a worse iterate, or slightly outside a constraint, cannot replace a better qualified search design. Both checks use one rule: the constraint tolerances of the problem, orreturn_constraint_tolerancewhen it is set. With the source tolerances, a phase whose solver reports its final check costs the selection no callback row. When the two phases use different merit policies, their objective values are not compared, and a qualified refinement design is returned. Themerit_functionof the result matches itsobjective_value.log_history_limitalso caps the merged logs.return_constraint_tolerance=t(defaultNone, the source tolerances) judges every returned design of the workflow with one residual tolerance: each residual column passes whenc <= tand|h| <= t, and the bounds and integer coordinates stay exact. It applies to the final verdict (feasible,success, and the replacement of a converged status byINFEASIBLE), the best-feasible candidates, and both phase verdicts of a refinement. The solvers keep searching with the source tolerances, and recovery keeps them for its start check. Example: formin xsubject to0.5 - x <= 0with tolerance1e-6, a search that returns0.5and a refinement that returns0.4999995both pass the source tolerance, so the cheaper refinement wins; witht = 0the search design is returned.tmust be finite, nonnegative, and at mostproblem.constraint_tolerance, the smallest source tolerance. Then the returned check can only be stricter than the search: a design that the search judged infeasible never becomes feasible, and a converged status can only becomeINFEASIBLE. Each judged design runs the final check of its accounting boundary witht: a sampling or Bayesian result reads its selected row, and under a finite budget a result reuses its own record or matching observations; otherwise the check costs one counted constraint query. It applies to scalar solvers only. The mapped workflows keepconstraint_tolerancefor their noisy final observation.constraint_backoff=d(default0.0, no tightening) solves a tightened problem and judges the returned design against the original constraints. Each nonlinear and linear inequality becomesc(x) + d <= 0. A coordinate with two finite bounds moves inward bys = min(d, 1/2) * (ub - lb), a coordinate with one finite bound byd; equalities, fixed coordinates, and infinite bounds stay unchanged (backed_off_bounds(lower, upper, d)returns the tightened bounds ands_min = min(d, every two-sided s)). Ford >= 1/2, or bounds that would cross, both bounds become the midpoint. The start rows are clipped into the tightened bounds. The tightened problem accepts residuals withinbackoff_tolerance, by defaults_min / 10. Theory: a design that meets the tightened problem withint = s_min / 10meets each original requirement with the margins - t >= 0.9 s. Tradeoff: the design can cost more than a design on the original boundary; to first order, the extra cost is each active back-off times its Lagrange multiplier. Withoutrefinementthe solver phase is tightened; withrefinementonly the refinement phase is. Recovery and best-feasible selection of a tightened phase run on the tightened problem. The records of a tightened phase describe the tightened problem, so one counted query of the original constraints decidesfeasible(withreturn_constraint_tolerancewhen set). Under a finite budget, a returned tightened refinement design keeps the verdict of that query, so the final check of the workflow does not query the same design again. A tightened phase reports its own status:INFEASIBLEthere means that the run did not meet the tightened constraints, whilefeasibledescribes the original constraints. Counts and logs record the original residuals. A retained tightened phase keeps its tightened bounds, linear rows, shifted constraints, and tolerance over the caller's callbacks. The option applies to scalar solvers and requires a problem without integer variables.
Recovery is an attempt, not a feasibility certificate.
The main solver continues from the recovered design even when recovery does not reach constraint feasibility.
The retained feasibility_result evaluates the nonlinear violation as its objective.
Its domain and linear feasibility do not certify the original nonlinear residual constraints.
With recovery, best-feasible selection, or a returned-design tolerance, the counts include recovery work, selection checks, and one final constraint check.
FeasibleStartOptions.evaluation_budget limits recovery separately from the problem budget.
FeasibleStartOptions.stationarity sets the first-order check after an SLSQP recovery success (default on, as in scipy_minimize).
Its verdict only labels feasibility_result (STALLED or CONVERGED); the recovered design does not depend on it.
StationarityOptions(verify=False) saves about 4 * n_free rows of each nonlinear constraint callback, but every SLSQP success then reports CONVERGED in that record.
See workflow_wrappers.py and options.py for recovery budgets and evidence.
nonlinear_constraint_violation computes sum(max(c, 0)) + w * sum(h**2) for each design row: the positive inequality violation plus the weighted squared equality violation.
Its equality_residual_weight w defaults to 1, applied after the caller normalizes each constraint group.
Explicit finite nonnegative weights, including zero (the inequality-only measure), remain supported.
Solver option defaults
The option records of each method hold its settings and their defaults.
Start repair and best-feasible selection are opt-in workflow options of solve:
feasible_start=FeasibleStartOptions(...) repairs a start, and return_best_feasible=True returns the best feasible iterate.
"pareto-search" handles nonlinear equalities.
See solve for the option contract.
| Method or setting | Options and defaults |
|---|---|
| Integer variables | OptimizationProblem(..., integer_variables=...) (0-based columns); NumPy rint rounds an exact half to the even integer |
| Population stop criteria | population_objective_range compares the largest and smallest population objectives; best_objective_change compares successive best objectives with tolerance (1e-6) and relative_tolerance (0) |
| Direct sampling | sampling_optimization(problem, options=SamplingOptions(...)); max_evaluations (1000; 0 evaluates nothing), batch_size (None: ceil(sqrt(n))), lazy_sampling (False), retain_populations (True) |
| Population methods (DE, PSO, GA) | PopulationOptions(...); constraint_selection ("feasible-first"), retain_evaluations (False), objective_threshold (-inf, disabled; a feasible best member at or below it stops the run with OBJECTIVE_THRESHOLD) |
| Line searches | GoldenSectionOptions(initial_step=1.0, initial_step_relative_factor=0.01, sectioning_relative_tolerance=..., retain_history=True), BacktrackingOptions(initial_step=1.0, retain_history=True); backtracking_search(..., directional_derivative=..., starting_value=..., bounds=Bounds(...)) and golden_section_search(..., starting_value=..., bounds=Bounds(...)) |
| Gradient methods | LocalOptions(gradient_tolerance=1e-6), relative to `max(1, |
| Search-direction normalization (steepest descent, conjugate gradient, quasi-Newton, modified Newton) | LocalOptions(normalize_direction=False); normalization applies after the bound projection and any fallback, and conjugate gradient keeps the unnormalized direction for its recurrence |
| Derivative callbacks | gradient_function=..., hessian_function=...; gradient_function(scalar, point) receives the solver scalar; NewtonIteration.hessian_shift records the modified-Newton shift |
| Finite-difference work | evaluation_batch_size=1 (one probe row per objective call), first_derivative_stencil ("three-point"), gradient_relative_points, hessian_relative_points, and jacobian_relative_points (None: nominal stencils), use_relative_step_size=True, two_probe_mixed_derivatives=False, hessian_from_gradient=False, adaptive_initial_step=False, inverse_update_form ("product"); see Finite-difference derivatives |
| Finite-difference records | retain_derivative_records=False; True keeps gradient_record, hessian_record, jacobian_record, and constraint_jacobian_record in the iteration records; see Finite-difference records |
| Evaluation limit | OptimizationProblem(..., evaluation_budget=EvaluationBudget(total=...)) counts callback rows |
| Gauss-Newton and Levenberg-Marquardt | gauss_newton(LeastSquaresProblem(residual=..., initial_design=x0, bounds=Bounds(lower, upper)), options=GaussNewtonOptions(...)) and levenberg_marquardt(...); bounds=None means no bounds |
| Least-squares limits | LeastSquaresProblem(..., evaluation_budget=EvaluationBudget(total=...)) counts residual callback rows; Jacobian calls cost no row |
| Least-squares derivatives | LeastSquaresProblem(jacobian=...), jacobian_step (default the central step eps^(1/3)) |
| Least-squares stops | gradient_tolerance (1e-8), step_tolerance (1e-12), max_iterations (100) |
| Gauss-Newton step control | sufficient_decrease_fraction, step_contraction_factor, max_backtracks |
| Levenberg-Marquardt damping | initial_damping, minimum_damping, maximum_damping, damping_increase, damping_decrease, acceptance_threshold, spectral_steps (False) |
| Nelder-Mead | nelder_mead(problem, options=NelderMeadOptions(...)) or solve(problem, "nelder-mead", ...); initial_step (0.05), reflection (1), expansion (2), contraction (0.5), shrink (0.5), rank_check_interval (1; a larger value tests rank loss less often, see the option text), defer_constraint_witness (False; True calls the constraints only once, at the returned vertex, see the note below the table), retain_evaluations (False; True keeps the trial and initial-simplex records) |
| CMA-ES | covariance_matrix_adaptation(problem, options=CovarianceMatrixAdaptationOptions(...)) or solve(problem, "covariance-matrix-adaptation", ...); population_size (None: 4 + floor(3*log(n))), initial_step_size (0.2), rng, reuse_eigendecomposition (False; True reuses the floored eigenpairs of the last covariance update instead of a new decomposition, so seeded runs change at rounding level), retain_evaluations (False) |
| Nelder-Mead and CMA-ES stops | point_tolerance (1e-7), objective_tolerance (1e-10), max_iterations (500 or 300), max_evaluations (10000 or 100000); see the note below the table |
| L-BFGS | limited_memory_bfgs(problem, options=LimitedMemoryBFGSOptions(...)) or solve(problem, "limited-memory-bfgs", ...); memory_size (10), curvature_tolerance (1e-10), sufficient_decrease_fraction (1e-4), step_contraction_factor (0.5), max_line_search_iterations (40), max_iterations (200) |
| Trust region | trust_region(problem, options=TrustRegionOptions(...)) or solve(problem, "trust-region", ...); initial_radius (1), maximum_radius (100), minimum_radius (1e-12), acceptance_threshold (0.1), cg_tolerance (0.1), max_iterations (100) |
| L-BFGS and trust-region derivatives | gradient_tolerance (1e-6), gradient_step (cbrt(eps)), hessian_step (1e-4, trust region), typical_x (1.0), gradient_function, hessian_function (trust region) |
| Trust-region conjugate-gradient stop | TrustRegionIteration.cg_stop_reason values "residual_tolerance", "negative_curvature", "trust_boundary", "dimension_limit" |
| Python simplex | SimplexOptions max_iterations (100 total pivots), tolerance (1e-10), pivot_rule ("dantzig"), retain_tableau (True), history_limit (None keeps every pivot record; 0 keeps none) |
| Sequential linear programming (SLP) | tolerance (1e-6), objective_relative_tolerance (0), move_limit (0.5), move_limit_update (0.5), minimum_move_limit (1e-6), initial_penalty_weight (1), optimality_tolerance (1e-6), simplex_options (SimplexOptions(tolerance=1e-6)), retain_evaluations (True), retain_derivatives (True) |
| Sequential quadratic programming (SQP) | tolerance (1e-6), objective_relative_tolerance (0), curvature_policy ("diagonal-shift"), minimum_subproblem_curvature (1e-8), use_bfgs (False; Powell-damped update), line_search_options (GoldenSectionOptions() or BacktrackingOptions()), reuse_final_derivatives (True), retain_evaluations (True), retain_derivatives (True) |
| Method of moving asymptotes (MMA) | tolerance (1e-6), objective_relative_tolerance (0), asymptote_distance_bounds ((0.01, 10.0)), artificial_linear_cost (1000), artificial_quadratic_cost (1), subproblem_tolerance (1e-7), subproblem_max_iterations (200), newton_system ('full'), retain_evaluations (True), retain_derivatives (True) |
| Penalty and barrier | tolerance (1e-6), objective_relative_tolerance (0), penalty_function (squared_inequality_penalty), barrier_function (logarithmic_barrier), equality_penalty_function (squared_equality_penalty), duality_gap_tolerance (1e-6), retain_inner_results (True; also AugmentedLagrangianOptions) |
| Constrained stationarity check | StationarityOptions verify (True), tolerance (None = max(sqrt(constraint_tolerance), 1e-6), relative to `max(1, |
| Plots | plot_objective_value_progress_nd accepts two or more variables; plot_population_progress(result, stage="differential_evolution"), stage="genetic_algorithm", or stage="particle_swarm"; animation_options=AnimationOptions(...), with the slider in AnimationOptions(slider=SliderOptions(...)) |
For Nelder-Mead and CMA-ES, the evaluation cap counts the objective rows plus the nonlinear constraint callback rows.
The final check reuses the constraint rows observed with the accepted value of the returned design.
That observation is its witness, final_constraints.
NelderMeadOptions(defer_constraint_witness=True) requires a merit that gives every constraint term zero weight, as the default EvaluationOptions does.
The vertices and trials then call only the objective, and one constraint call at the returned vertex gives the witness.
The simplex path stays the same, a design costs one row, and the cap keeps the rows of the final call.
The witness is then a new observation, so a noisy or stateful constraint callback can give another verdict.
Typed result records hold the normalized result data of each method.
Mapped workflows
optimize_quantities_of_interest optimizes quantities derived from a bottom-up mapping. It shares one cached response between objectives and constraints.
optimize_performance_score minimizes the deficit score of the performance requirements and treats physical deficits as inequalities.
Mapping responses and evaluator results follow the core result contract.
optimize_performance_score requires deficits, so a measure result raises TypeError.
optimize_quantities_of_interest_pareto runs pareto-search on two or more mapped objective columns.
It returns a MappedParetoResult with the reconstructed full archive designs, their objective rows, a per-row rejection mask (rejected), a per-row final verdict (final_feasible), the Pareto result, and the response evidence.
optimize_quantities_of_interest stays scalar-only and raises ValueError for "pareto-search".
Mapped workflows accept one initial design, as a vector or one-row matrix, or an empty start such as np.empty((0, n_variables)).
Population solvers generate candidate batches from this design and the supplied bounds.
An empty start adds no arbitrary member to such a search. It requires full ordered bounds and no fixed variable, because it supplies no fixed value.
A solver that needs a start raises its own error for an empty start.
Fixed coordinates retain their initial values. See workflow_mapping.py.
Mapped responses keep inactive -inf and rejected +inf values as raw evidence.
The solver receives finite values instead.
Finite solver values:
finite_solver_residualsreplaces-infwith -1, then applies the positive physical weight. For example, a physical weight of two turns an inactive-infdeficit into -2.- A rejected row uses the objective placeholder one and the residual placeholder zero in every mapped column, in both workflows. Its partial physical deficits are not trusted solver evidence.
- A separate unweighted inequality, +1 for a rejected row and -1 otherwise, preserves rejection even when a custom mapper omits that response.
- Exception:
optimize_performance_scorewith the default gradient solver ("scipy-minimize"with SLSQP or trust-constr) omits this inequality when it is the only constraint and constant near the start: no physical feasibility requirement, deterministic mode, and an accepted start strictly inside the free bounds. These methods estimate the constraint Jacobian by finite differences, so the constant column would cost model rows at every iterate. The workflow observes the start once to decide; the solver's first request reuses that response. A row rejected during the solve is then seen only through the objective placeholder 1. The final qualification below still applies. In a three-variable score run without physical requirements, the model rows fell from 32 to 15 with the stationarity check off. - A solver that ranks infeasible rows by summed violation, such as pattern search or Pareto search, therefore ranks all rejected rows equally.
- Final qualification always rejects a raw
+infrow. The reported objective of a rejected selected design isinf, not the placeholder. - These finite placeholders keep the solver arithmetic defined. The raw response stays authoritative.
- An inequality mapper can return
-infonly in a row whose raw response contains-inf. A-infderived from finite measures, for example throughlog(0), raisesValueError.
The solver tolerance guides the search, but final feasibility uses the requirement label deficit <= 0.
optimize_performance_score reads the raw physical deficits of the selected observation.
A positive deficit, even one inside the solver tolerance, reports feasible=False, success=False, and status FINAL_FEASIBILITY_FAILED.
A failed final qualification reports one of three statuses:
REJECTED_DESIGN: the raw response is+inf.FINAL_FEASIBILITY_FAILED: a raw physical deficit is positive, or a noisy mapped residual is aboveconstraint_tolerance.FINAL_OBJECTIVE_THRESHOLD_FAILED: a noisy threshold recheck failed.
Related fields:
solver_statuskeeps the termination of the solver run, for exampleCONVERGEDorMAX_ITERATIONS, because the qualification describes the returned design and not the run.- A rejected Bayesian design also reports
optimization.objective_value=inf.selected_observation_index, the point, andevaluated_objectiveskeep the observation and its finite placeholder. final_evaluationis the mapping record that qualified the returned design. In deterministic mode it is the response of the returned design, which needs no model row when a stored request is that design.- A deterministic Bayesian result is qualified by
selected_observation_indexinstead and keepsfinal_evaluation=None.response_retention="all"keeps the mapping record of that observation.
Quantity mappers receive performance and physical-feasibility matrices, rather than design coordinates.
- Both matrices contain the same usable sample rows. Rejected model rows are omitted before mapping.
- Multiple objective columns keep the scalarization of the selected solver.
- Mappers must accept
(0, k)response batches, so that an entirely rejected first batch can discover the output width. Once a width is known, an entirely rejected batch does not invoke that mapper. - The performance score has a known width of one, so it needs no empty query.
combined=lambda performance, physical: (inequality, equality)replaces the separateinequalityandequalitymappers ofoptimize_quantities_of_interestandoptimize_quantities_of_interest_paretowith one call per batch, which helps when both groups share work. Each group follows the rules of its separate mapper;Noneor an empty vector is an absent group. One zero-row call learns both widths. MixingcombinedwithinequalityorequalityraisesValueErrorbefore any model call.
Response reuse:
- The cache stores the responses of the latest
response_cache_sizedistinct free-coordinate request matrices (default 1, only the latest request). When the store is full, a new request evicts the request that was used least recently. - Only a request with exactly a stored free-coordinate matrix reuses its response. Equal signed zeros match.
- This reuse assumes a deterministic mapping.
- A row subset or reordering of a stored batch is a new request, for example the final check of one population member. Such runs can therefore need extra model rows. The returned design does not change.
- A gradient solver estimates the objective gradient and then the constraint Jacobian by finite differences over the same probe designs.
With the default size, each constraint probe misses, because the latest request is another probe.
A size of
2 * n_free + 1, withn_freefree coordinates, lets the constraint sweep reuse the objective sweep. In a four-variable run with one constraint, size 9 lowered the model rows from 53 to 28 (scipy-minimize), from 134 to 106 (sqp), and from 279 to 150 (slp). The designs, objectives, and statuses stayed the same. - A larger store lowers
number_of_evaluations, keeps fewer records inevaluations, and can makefinal_evaluationan earlier record of the same design. It keeps up toresponse_cache_sizerecords in memory.
Noisy repeated evaluations:
noisy_repeat_evaluations=True(default False) requests independent observations. Every solver request then evaluates the mapping again.- After the solve, one fresh final observation of the returned design gives the returned objective and the final constraint check.
final_evaluationkeeps it. - For
optimize_quantities_of_interest, the final check allows mapped residuals up toconstraint_tolerance. Its defaultNoneuses the tolerance of the solver's own feasibility verdict: a Bayesianconstraint_toleranceoverride, else the constraint-source tolerance1e-6. Both checks then judge residuals alike. An explicit value applies to the final observation only. - For
optimize_performance_score, the final check requires every raw physical deficit to be at most zero. feasibleis False when the final check fails, the solver verdict when it passes, and None when the solver gave no verdict.- The returned objective is on the solver's objective scale: the scalarization and merit terms of the solver's evaluation policy applied to the fresh mapped values.
- An
OBJECTIVE_THRESHOLDstop is rechecked against that final objective. A failed recheck setssuccess=Falseand the statusFINAL_OBJECTIVE_THRESHOLD_FAILED.
Pareto workflow:
optimize_quantities_of_interest_paretoacceptsnoisy_repeat_evaluationsandconstraint_tolerancetoo.- In noisy mode it observes every archive design once more, returns the fresh objective rows, and checks each row against the mapped residual tolerance.
final_feasiblekeeps the verdict of each row. - The Pareto objectives are not scalarized, so the fresh objective rows are already on the archive scale.
- When any archive row fails its final check, in either mode,
optimization.feasibleandoptimization.successare False. The status isREJECTED_DESIGN(any rejected row) orFINAL_FEASIBILITY_FAILED. - The scalar mapped workflow uses the same rule.
- In noisy mode, a hypervolume-target success is rechecked with the hypervolume of the fresh objective rows.
A fresh hypervolume below the target sets
success=Falseand the statusFINAL_OBJECTIVE_THRESHOLD_FAILED.
Linear and quadratic programs
program_models.py defines coefficient models for LP and QP.
QuadraticProgram and QuadraticCoefficients use x.T @ Q @ x + c.T @ x + constant, so the Hessian is Q + Q.T.
The standard ProgramCoefficients objective instead uses 0.5 * x.T @ Q @ x.
QuadraticProgram.from_coefficients(coefficients, bounds) converts between the two conventions; LinearProgram.from_coefficients handles affine records.
An affine function is a weighted sum of variables plus a constant.
The example programming_solver_demos.py solves a linear program, a quadratic program by both callback and coefficient routes, and SLP, SQP, and MMA problems with hand-derived solutions.
| Solver | Entry point | Bounds | Retained evidence |
|---|---|---|---|
| SciPy HiGHS LP | solve_linear_program |
Finite or infinite | Backend status; no pivot tableaux |
| Python two-phase simplex | simplex |
Finite or -inf lower bounds; finite or +inf upper bounds |
The pivots that retain_tableau and history_limit keep, as SimplexIteration records |
| Callback LP | optimization_linear_programming |
As simplex |
Recovered model, callback counts, and the simplex pivots that retain_tableau and history_limit keep |
| Active-set convex QP | solve_quadratic_program |
Box | Active set, multipliers, start-repair pivots, optional iteration records |
| Callback QP | optimization_quadratic_programming |
Box | Recovered model, callback counts, and the active-set evidence |
LPBackendOptions configures HiGHS: method ("highs", "highs-ds", or "highs-ipm"), max_iterations (default 100), and validated backend_options.
SimplexOptions belongs to the Python simplex: max_iterations (default 100 total pivots), tolerance (default 1e-10), pivot_rule ("dantzig", the default, or "bland"), retain_tableau (default True), and history_limit (default None).
Two controls limit the pivot records:
retain_tableau=Falsekeeps oneSimplexIterationper pivot withtableau=None. One tableau holds aboutrows * columnsnumbers.history_limitkeeps only the newest records, with their absolute iteration numbers.Nonekeeps every record, and0keeps none (historyis empty).- Neither control changes the pivots,
n_iterations, the pivot budget, the phase statuses, or the result.
SLP solves its elastic LPs with this simplex (SlpOptions.simplex_options), and the final constrained stationarity check uses it too.
The stationarity check exposes no pivot history, so it always solves its LP with retain_tableau=False and history_limit=0.
StationarityOptions therefore takes only the three other controls, as simplex_max_iterations, simplex_tolerance, and simplex_pivot_rule, with the SimplexOptions defaults.
optimization_linear_programming solves its recovered model with this simplex and accepts SimplexOptions as options.
By default the simplex retains every pivot with its tableau. It certifies its status with relative checks.
HiGHS uses absolute tolerances, so at a small objective scale it can report a suboptimal vertex as optimal; for example, it returns x = 0 for min -1e-8 * x on [0, 1].
The tradeoff is cost: dense tableaus grow with rows times columns, so solve a large coefficient model with solve_linear_program instead.
Both LP solvers return slack_values in one layout: b - A @ x for each inequality row, then x - lower and upper - x for each variable.
A nonnegative entry means that its row or bound holds; an infinite bound gives an infinite entry.
phase_one_status and phase_two_status come only from the Python simplex.
HiGHS reports one status for the whole solve, so its phase statuses are None, which means unavailable.
The Python simplex stores the problem in a tableau, the table of constraint and objective coefficients. Phase I finds a feasible basis. Phase II minimizes the original objective. One pivot budget covers both phases and the artificial-basis cleanup.
Scaling:
- The simplex scales each design coordinate by its finite positive bound width, and it scales the constraint rows.
- A coordinate whose finite bounds have a width beyond the float64 range, such as [-1e308, 1e308], uses
max(|lower|, |upper|). Any other coordinate keeps the scale one. - The solver scales before it shifts by the lower bound, so such a box still solves.
- Small slopes across wide coordinates therefore keep their full objective contribution. On a coordinate without a finite width, the attainable-gain rule below keeps them material.
Pivot rules:
- A reduced cost is the objective-change coefficient of a nonbasic variable.
- The simplex pivots only on a material reduced cost. A reduced cost is material when it is above
tolerancetimes the largest reduced-cost magnitude, or when its largest allowed step changes the objective by more thantolerance * max(1, |objective|)in caller units. - A positive reduced cost on a column that no row blocks is always material, because its gain has no limit.
- This rule avoids pivots on rounding-level reduced costs. The objective constant never changes a pivot.
- The Dantzig rule enters the largest material reduced cost and usually needs fewer pivots.
- The Bland rule enters the lowest-index material column and breaks ratio ties by the lowest-index basic variable. It prevents repeated bases (cycling) in degenerate problems in exact arithmetic, but it can need more pivots.
Free coordinates:
- A lower bound of
-infmakes a coordinate free. The simplex writes it asx = x_plus - x_minuswith two nonnegative parts and turns a finite upper bound into the rowx_plus - x_minus <= u. - Results map back to the caller's coordinates. The free coordinate has the slack entry
x - lower = inf, and pivot tableaus belong to the split problem.
Certificates:
- Before it reports
OPTIMAL, the simplex checks an independent dual lower bound, including residual costs over the row-implied movement ranges. A dual bound is an independently calculated lower limit on the minimized objective. Pivot designs and objectives remain in caller units. - After every Phase II end (
OPTIMAL,MAX_ITERATIONS,UNBOUNDED, or a failed certificate),feasiblereports the primal feasibility check of the returned design. A stop in Phase I or the artificial-basis cleanup leaves itNone. - A residual cost within its own rounding error counts as zero, so a free or basic coordinate cannot fail the check at random.
Returned evidence of the simplex (LinearProgrammingResult):
| Field | Present when | Meaning |
|---|---|---|
dual_certificate |
The dual certificate ran, also when it failed | SimplexDualCertificate: multipliers per tableau row, residual costs, coordinate limits, primal and dual objectives, gap, and certified, in internal units |
inequality_multipliers, equality_multipliers |
The dual certificate ran with finite multipliers, and every caller-unit multiplier of that family is finite | Caller-unit multipliers of the supplied rows: linear + A.T @ lambda + E.T @ nu - mu_lower + mu_upper = 0 with lambda >= 0 |
dual_lower_bound, duality_gap |
The dual certificate ran with a finite dual objective | Lower bound on every feasible objective in caller units, constant included, and objective_value - dual_lower_bound |
unbounded_ray |
Status UNBOUNDED |
The recession direction that passed the supplied-model check, in supplied coordinates |
infeasibility_certificate |
Status INFEASIBLE |
InfeasibilityCertificate: the verified multipliers of the supplied rows and the positive contradiction |
infeasibility_candidates |
Phase I ended at an optimum with a positive sum of artificial variables | Zero to two InfeasibilityCandidate records in build order, each with the tested multipliers, its separation, and its verdict (contradiction, stationarity_residual) |
- The multipliers cover the supplied rows only, as in DesignOptRs.
QuadraticProgrammingResult.inequality_multipliersinstead appends the bound rows. - The conversion to caller units multiplies binary mantissas and adds exponents, so a multiplier overflows only when its own value is outside the float64 range. Such a family is
None, not infinite, and the status does not change. For example,1e-310 * x <= 1e-310with objective-xhas the multiplier1e310. - The plain candidate holds its multipliers on a short binary grid, a positive multiple of the dual multipliers; the margin candidate holds unrounded multipliers. Each listed candidate holds the multipliers that the verifier tested, so its verdict can be recomputed from them.
- A candidate whose separation is not above the tolerance has no verdict (
None), and the search stops there. The certificate equals the last candidate. - The callback LP wrapper keeps these fields of the recovered coefficient model. When its callback check of the returned design turns
OPTIMALintoINFEASIBLE, the result keeps the dual evidence and has noinfeasibility_certificate, because the callback check, not a simplex proof, decided that status.
The active-set QP solver works as follows.
Scaling and start:
- It scales each coordinate by its finite bound width, without translation, and each row and right-hand side by
max(|row|, |rhs|). - A row with scaled residual at least
-tolerancestarts active. - The start is clipped to the bounds. A start that still violates a constraint is repaired with Phase I of the Python simplex, within
feasibility_max_iterationspivots (default 100).
Start repair:
- The repair LP solves for the displacement from the clipped start with the supplied rows only. The bounds go to the simplex as displacement bounds.
- A free coordinate therefore keeps its start value when the repair does not need it.
- Phase I proves a violated constant row infeasible, so its result keeps the repair evidence.
- A failed repair returns a result at the clipped start with
n_iterations=0andfeasible=False. The status isINFEASIBLE,MAX_ITERATIONSwith the message "feasibility repair reached feasibility_max_iterations", orNUMERICAL_ERROR. preparation_iterationsreports the repair pivots separately from the active-set iterations, andpreparation_resultkeeps the repair simplex result.
Stationarity and certificate:
- A working-set point is stationary when the gradient-balance residual and the Newton correction are small relative to their own arithmetic terms.
Each test also allows a rounding floor of
8*n*epsof the largest term, because the orthogonal solves have errors relative to the whole vector. - The multiplier-sign test then compares each negative multiplier contribution with
lagrange_tolerance(positive, default1e-10) times those terms. It releases the row with the largest scaled violation. - Before it reports
OPTIMAL, the solver checks primal feasibility and the convex gap-lambda @ r - mu @ e - m. Hererandeare the residuals, andmbounds the remaining model decrease. - A residual passes within
tolerance * (1 + |b| + |A| @ |x|), and a Lagrangian-gradient entry within the stationarity tolerance counts as zero. - Both gap terms are nonnegative, so a multiplier on an inactive row cannot cancel a remaining descent. The gap must be at most
tolerance * max(1, |objective|). QuadraticProgrammingResult.optimality_certificatereturns this check as aQuadraticOptimalityCertificate:primal_feasible,minimum_change_bound(m;-infwithout a finite box bound),duality_gap(caller objective units),dual_lower_bound(objective_value - duality_gap, constant included), andcertified. It is present whenever the check ran, forOPTIMALand for theNUMERICAL_ERRORof a rejected certificate, andNonefor a failed start repair,MAX_ITERATIONS,UNBOUNDED, and a failed step guard or tangent solve. A failed primal check leavesminimum_change_bound,duality_gap, anddual_lower_boundatNone. Forx^2 - 2xon [0, 4],lagrange_tolerance=1.0keeps the lower bound active at x = 0, and the certificate reports the gap 1 and the bound -1 before the status becomesNUMERICAL_ERROR.- The solver reports mathematical QP infeasibility as
INFEASIBLE.
Step guard and the feasible signal:
- Every new iterate passes a step guard. It is finite, and each scaled residual stays within
10 * tolerance * max(1, |b| + |A| @ |x|). A failed guard stops the run withNUMERICAL_ERRORat the last checked point. feasibleisTruefor every result after a feasible start (alsoMAX_ITERATIONS,UNBOUNDED, andNUMERICAL_ERROR). It isFalseafter a failed start repair, and it is the primal check of the final certificate when that certificate fails.
Curvature and unbounded directions:
- The solver retains every positive tangent eigenvalue. Tangent directions preserve active constraint equalities. Their eigenvalues measure curvature along independent directions.
- Positive curvature bounds residual effects on unbounded coordinates.
- A null-space direction has zero quadratic curvature. A nonzero slope in that direction needs a feasible design bound or produces an unbounded result.
- A flat slope counts only when it exceeds its rounding bound, which uses the full gradient. Rounding left after a rotated active row cancels a large gradient therefore does not create a false unbounded ray.
save_tableauretains accepted iterates, andprint_tableauprints active-set diagnostics. Neither is a simplex tableau.
Linear algebra of one iteration:
- One singular value decomposition (SVD) of the working-set rows gives the tangent basis, with the rank rule of
scipy.linalg.null_space. The eigendecomposition of the reduced Hessian gives the step, and a least-squares solve gives the minimum-norm multipliers. reuse_working_set_svd(defaultFalse) computes the multipliers from the factors of the first SVD, with the same rank cutoff. It saves one factorization per iteration. The multipliers and steps then differ in the last digits.cholesky_tangent_step(defaultFalse) first solves the reduced system by Cholesky factorization. It accepts the factor only when the LAPACK reciprocal condition estimate exceeds1024 * d * epsfor tangent dimensiond, so the matrix is clearly positive definite. Every other matrix uses the eigendecomposition, which keeps the flat-direction rules above. For a tangent dimension of 40 or more, the Cholesky solve costs a small fraction of the eigendecomposition.- Tradeoff of both options: other rounding, so iteration counts and a borderline stationarity, multiplier-sign, or
OPTIMALversusNUMERICAL_ERRORdecision can change.
Convexity validation preserves representable subnormal coefficients when forming the symmetric matrix part. Subnormal coefficients are floating-point values smaller than the smallest normal positive value. The validator balances diagonal units before checking positive semidefiniteness (PSD). A PSD matrix has nonnegative quadratic curvature in every direction. The stored model uses symmetric coefficients so canceling antisymmetric terms cannot corrupt objective evaluations or adapter records. These effective coefficients can differ from the supplied raw matrix; all solver paths use the stored symmetric model.
Recover coefficients from callbacks
coefficients.py recovers affine, quadratic, and standard-form program coefficients from callbacks.
Callbacks receive sample-major designs (n_samples, n_variables) and return (n_samples, n_outputs), including one column for a scalar output.
The returned coefficients are output-major:
| Record field | Shape |
|---|---|
AffineCoefficients.linear |
(n_outputs, n_variables) |
AffineCoefficients.constant |
(n_outputs,) |
QuadraticCoefficients.quadratic |
(n_outputs, n_variables, n_variables) |
For output j, the quadratic model is x.T @ quadratic[j] @ x + linear[j] @ x + constant[j].
The quadratic matrix is symmetric. Its two off-diagonal terms together define each cross term.
With m movable variables, affine recovery evaluates m + 1 probe rows and quadratic recovery evaluates (m + 1)(m + 2)/2 rows.
Row cap:
CoefficientProbeOptions(max_evaluations=...)caps the design rows of one operation. The defaultNonesets no cap.- An operation is one recovery (its probe rows) or one program validation (its four validation designs).
- The operation compares its planned rows with the cap after the geometry checks and before any callback runs. Rows above the cap raise
ValueError, for example "coefficient recovery needs 6 probe rows, which exceeds max_evaluations (5)". - Rows count once per operation. Batching, output columns, and the callbacks of a sequence do not change the count. Fixed coordinates add no rows.
- Zero rejects every operation with a callback, because the center row is always needed. An absent callback returns its empty model before the check.
- With validation on,
extract_program_coefficientsand both callback wrappers raise "coefficient validation needs 4 rows, which exceeds max_evaluations (...)" for a cap below 4, before any callback runs. The final constraint check of the callback wrappers evaluates one row outside this cap; any cap that admits a recovery admits that row. - A partial probe set cannot determine the interpolation equations, so the extraction refuses instead of returning an incomplete model. To use fewer rows, fix coordinates with a zero scale or recover the affine model.
CoefficientProbeOptions(bounds=..., center=..., scale=...) declares a physical callback domain.
Probe domain:
- Finite intervals use midpoint and half-width probes. Recovered coefficients remain in original coordinates.
- Fixed coordinates stay fixed and receive zero coefficients, because the domain cannot resolve them.
- An explicit center without a scale uses the largest symmetric step inside the bounds.
A center on a bound of a movable coordinate raises
ValueError, because a zero step would report a zero coefficient for a coordinate that can move. - A probe may leave a bound only by the rounding of the midpoint arithmetic,
4 * spacing(|center| + scale). The extraction clips it to the bound. - Without a domain, low-level extraction keeps origin and unit probes.
- Each recovered model carries
geometry, aProbeGeometryrecord with the probecenter, the half-stepsscale(zero for a fixed coordinate), the zero-basedfree_coordinates, and the declaredbounds. Absent probe bounds appear as-infand+inf. The geometry does not depend onretain_probes; an absent callback givesgeometry=None. CoefficientProbeOptions(bounds=g.bounds, center=g.center, scale=g.scale)reproduces the same probe rows, because an explicit center and scale take precedence and infinite bounds clip nothing. A caller can use the geometry to place independent validation designs in the same domain.
Probe spacing:
- Recovery divides each probe difference by the nominal offset, so rounding must not change that offset materially.
- Before any callback runs, each normalized realized offset
((center + factor * scale) - center) / scalemust be withinmax(1e-6, 32 * eps)of its factor (+1, and -1 for quadratic recovery). - Otherwise extraction raises
ValueError("rounding materially changed probe spacing"). For example, center 1e16 with scale 3 would give a slope of 4/3 forf(x) = x. - The quadratic diagonal uses
((f(+e) - c) + (f(-e) - c)) / 2, which cannot overflow for a large constant. - A coefficient that is not finite raises
ValueError. A quadratic entry that underflows below the normal float64 range in the coordinate transform also raisesValueError. The extraction never returns a nonfinite or asymmetric model.
Zero coefficients and batching:
- When every recovered coefficient of an output is zero and the floating-point spacing of its center value exceeds the largest probe scale, extraction returns the model with a
RuntimeWarning. Zero coefficients then mean a constant or a dependence below the response resolution. Increase the scale or subtract the known offset. batch_size(default 256) limits rows per callback call, andretain_probes=Falseomits the probe evidence. Batching does not change coefficient axis meanings.- Program extraction accepts separate objective and constraint evaluation adapters.
evaluation_adapteris the shared default.
Callback wrappers and validation:
- The callback-based
optimization_linear_programmingandoptimization_quadratic_programmingreturn the recovered coefficient problem with recovery and validation counts. - Numerical validation evaluates four designs inside the probe domain: the probe center and three fractional off-center patterns, clipped to the bounds.
extract_program_coefficientsand both callback wrappers use this one rule. - For the objective and for every constraint column, validation compares the values and also the changes from the center, so a large constant cannot hide a nonlinear response.
- Numerical validation checks agreement at finite sample points. It cannot certify the polynomial degree of an arbitrary callback.
- The comparison tolerance is
validation_tolerancein the wrappers andtoleranceinextract_program_coefficients. Its default is1e-8. It must be positive and finite, and the check runs before any callback runs, also when validation is off. A zero tolerance would demand bit-exact agreement and reject a valid model for the rounding of its recovered coefficients.
Final check of the callback wrappers:
- After the solve, both callback wrappers evaluate the constraint callback once at the returned design. This row joins
counts.constraints. - A residual passes within
tolerance * (1 + |b| + |A| @ |x|)with the solver tolerance, so a design that the coefficient solver accepts is not rejected for rounding alone. - A violation sets
feasible=Falseandsuccess=Falseand replacesOPTIMALbyINFEASIBLE. A pass keeps the solverfeasiblevalue.
Python only: this adapter wraps SymPy. DesignOptRs fills this role with its native numeric extract_affine_coefficients and extract_quadratic_coefficients and has no counterpart.
extract_program_coefficients_symbolic(objective, inequality_constraints, equality_constraints, n_dimension, *, programming="linear") is the exact route.
- It calls each callback once with a
(1, n_dimension)array of real SymPy symbols and differentiates the expanded expressions. - It rejects a nonconstant gradient (linear objective), Hessian (quadratic objective), or constraint Jacobian.
- It returns the same
ProgramCoefficientsrecord, with the Hessian asquadratic. - For example,
x (x - 1) (x + 0.73) (x - 0.4893) (x + 0.7191)vanishes at every numeric probe and validation point, so the numeric route accepts the zero affine model. The symbolic route rejects it. - Only callbacks that use arithmetic or SymPy functions work. NumPy functions such as
np.sindo not accept symbols. - The route needs the optional extra
designoptpy-point[symbolic]. Without SymPy it raisesImportErrorthat names SymPy and this extra.
Use coefficient-form LP and QP models when the coefficients are already known.
coefficient_extraction.py recovers a known affine and a known quadratic polynomial, compares H = 2 Q symbolically, and saves the coefficients.
Supply collaborators
A collaborator is a caller-supplied function that replaces one step of a method.
Which methods accept which collaborators:
- Local methods accept caller-supplied gradient, Hessian, line-search, conjugacy-coefficient, and convergence functions where they apply.
- A modified-Newton
hessian_functionmust return a symmetric matrix. An asymmetrymax|H - H.T|above1e-8 * max|H|raisesValueError, and the solver uses the symmetric part0.5 * H + 0.5 * H.T. - SLP accepts derivative, move-limit, convergence, and elastic-LP solvers. It has no line search.
- SQP accepts derivative, line-search, convergence, and QP subproblem solvers.
- MMA accepts derivative, convergence, and subproblem solvers in the variables
w = [x, y]. - Population methods accept population samplers and convergence criteria, with an optional mapping of options.
- Bayesian optimization accepts samplers, acquisition functions, acquisition optimizers, exploration updates, and model trainers.
The model trainer returns any object that satisfies the
SurrogateModelprotocol: a callablepredict(points, *, uncertainty_kind)that returns aGaussianProcessPrediction. It receives the newestmax_training_samplesobservations. Plotting accepts the same interface. ScipyMinimizeOptionsaccepts single-pointgradientandhessianfunctions, andscipy_minimizeforwards them to supporting SciPy methods.
Stop callback:
- Iterative methods accept
stop_callback. It receives each completed iteration record and returnsTrueto stop. - It sees every iteration, independently of history retention.
- The method calls it after the record is complete and the iterate is accepted, and before its own stop tests of that iteration.
- A
Trueresult therefore givesSTOPPEDandsuccess=False, also when a convergence test, an objective threshold, or a rejected step of the same iteration would also end the run. - An iteration that the evaluation budget interrupted gets no call.
The call layouts differ by method family. Keep the selected method's layout when you supply a collaborator.
| Collaborator | Call and returned value |
|---|---|
Local gradient_function (steepest descent, conjugate gradient, quasi-Newton, modified Newton, trust region, L-BFGS, SLP, SQP, MMA, penalty) |
gradient_function(scalar, point) returns a finite vector of length n_variables. A callback that needs a finite-difference step captures it from its own scope. |
Local line_search (steepest descent, conjugate gradient, quasi-Newton, modified Newton) and SQP line_search_function |
line_search(scalar, point, direction, maximum_step, *, starting_value, directional_derivative) returns a LineSearchResult. The solver passes the value at point and the slope along direction that it already holds (gradient @ direction, or the L1 merit slope in SQP). functools.partial(backtracking_search, bounds=problem.bounds) plugs in directly and evaluates only its trials. |
SLP, SQP, or MMA jacobian_function |
jacobian_function(problem, point) returns (inequality_jacobian, equality_jacobian). |
Local convergence_function (steepest descent, conjugate gradient, quasi-Newton, modified Newton, SLP, SQP, MMA) |
convergence_function(state) returns a Boolean stop request. state is a ConvergenceState: iteration, the accepted point and the starting_point before the iteration, objective_value and starting_objective_value, the method's absolute tolerance, and the one-row constraints at point (None for the gradient methods). A displacement rule is lambda state: np.max(np.abs(state.point - state.starting_point)) <= 1e-6. A constrained method stops only at a feasible design and then runs the final stationarity check. |
Population convergence_function |
convergence_function(state, **convergence_options) returns a Boolean stopping decision. |
Genetic-algorithm crossover_function |
crossover_function(parent_one, parent_two, rng, fitness_one=..., fitness_two=..., **options) returns two child matrices. rng is the Generator of the run. |
Bayesian sampling_function |
sampling_function(bounds, count, rng, phase) returns a sample-major design matrix. phase is "initial" or "trial". |
Bayesian acquisition_function |
acquisition_function(points, model, current_best, exploration) returns one finite nonnegative score per design. Larger scores have priority. |
Bayesian acquisition_optimizer |
acquisition_optimizer(negative_acquisition, start, bounds, constraints) returns a design vector or an AcquisitionOptimizerOutput. start is a copy. constraints is a tuple of SciPy dictionaries: "ineq" values must be nonnegative and "eq" values zero. The solver clips the design to the bounds. A value that cannot be converted to a real array, for example a dict or a nonnumeric string, raises TypeError. |
Bayesian exploration_update |
exploration_update(initial, current, iteration) returns the next finite nonnegative exploration offset. The solver calls it from iteration 2. Return current for a constant schedule. |
Sampling sampling_function |
sampling_optimization(problem, sampling_function=..., sampling_options=...) calls sampling_function(problem, remaining_count, rng, sampling_options), which returns remaining_count design rows. SamplingOptions holds no sampler. |
point is an independent copy of one design vector.
A local gradient differentiates the evaluator scalar, including scalarization and constraint terms.
A constrained-method gradient differentiates the scalarized objective; constraint derivatives use the separate Jacobian.
Jacobian arrays have shapes (n_inequalities, n_variables) and (n_equalities, n_variables).
An absent constraint group returns shape (0, n_variables).
These separate groups let constrained methods construct their linearized constraints explicitly.
Crossover operators receive paired (n_pairs, n_variables) parent matrices and (n_pairs,) fitness vectors.
They return finite child matrices of the same shape.
A population convergence criterion receives one read-only PopulationState record per generation.
It holds the one-based iteration and the current and previous best candidate, best objective, population, and population objectives.
A previous state is None when it is unavailable.
population_objective_range compares the largest and smallest current objectives.
best_objective_change compares the best objectives of successive generations.
It passes when |f - f_prev| <= tolerance + relative_tolerance * max(|f|, |f_prev|), with the defaults tolerance=1e-6 and relative_tolerance=0 (the absolute rule); this is the rule of objective_change_within_tolerance.
Select a relative test with convergence_function=best_objective_change and convergence_options={"tolerance": 0.0, "relative_tolerance": 1e-8}.
Pass the tolerances through convergence_options, because a functools.partial wrapper is not the supported criterion that skip_infeasible_objectives requires.
The default criterion of a one-member population keeps its absolute rule.
A supplied criterion replaces the default objective-range test, so population_tolerance is not used.
Under constraint_selection="feasible-first", a true value of the criterion counts only when every member is feasible.
A custom line search must return a finite step within the admissible segment, with a 32-epsilon roundoff allowance; the segment can be an infinite ray.
converged=True accepts the step. converged=False rejects it: the four line-search methods keep the current design and stop with NO_FEASIBLE_STEP.
Rejected trials remain separate in the trace.
Use Python closures and functools.partial when a callback needs configuration.
A closure retains surrounding variables. functools.partial fixes selected arguments in a reusable function.
Finite-difference derivatives
Native derivative-based methods estimate each missing derivative with differentiation.py.
Each derivative uses three probes per design variable.
Variable i uses the step h_i = relative_step_i * max(|x_i|, typical_x_i); relative_step and typical_x are one scalar or one value per variable.
The functions default to relative_step = cbrt(eps), about 6.1e-6, for gradients and Jacobians, and 1e-4 for Hessians, with typical_x = 1.
Here eps is the float64 machine epsilon. A three-point first difference has truncation error O(h**2) and rounding error O(eps / h), which balance near eps**(1/3).
A second difference has rounding error O(eps / h**2), which balances its truncation error near eps**(1/4), about 1.2e-4.
An interior variable uses central differences:
f'(x) ~ (f(x + h) - f(x - h)) / (2 h)
f''(x) ~ (f(x + h) - 2 f(x) + f(x - h)) / h**2
Near a bound, the probes (x, x + h, x + 2 h) or (x - 2 h, x - h, x) stay inside the box, and h shrinks to half the available span.
When neither side holds the central stencil, as in an interval narrower than 2 h, the stencil uses the side with more room. Ties use the upper side.
Two-point first differences:
stencil="two-point"offinite_difference_gradientandfinite_difference_jacobian(solver optionfirst_derivative_stencilofLocalOptions,LimitedMemoryBFGSOptions,TrustRegionOptions,LeastSquaresOptions, andDerivativePolicy, default"three-point") uses(f(x + h) - f(x)) / h, or(f(x) - f(x - h)) / hfor a variable without room above. A numerical first derivative then costs one probe per free variable instead of two.- The truncation error grows from
O(h**2)toO(h). The matching step isTWO_POINT_GRADIENT_STEP = sqrt(eps), with a relative error near1e-8instead of about4e-11. With the default stepcbrt(eps)the two-point error is near6e-6. - The stationarity test of a method then uses the less accurate derivative, so iterates, counts, and statuses near a tolerance can change. The final stationarity check of SLP, SQP, MMA, the penalty method, and the SciPy adapter keeps the three-point stencil, and Hessians keep their three-point stencils.
Weights and fixed variables:
- A fixed variable has zero derivatives. Mixed Hessian entries multiply the first-derivative weights of two variables.
- The weights are the nominal textbook weights (central
1/2; one-sided-3/2, 2, -1/2). - The weighted sum of value differences is divided by
hafter the summation. A second derivative divides twice. A mixed entry divides by the smaller step and then by the larger step.
Callback cost:
- A gradient or Jacobian evaluates the callback once at
xand twice for each variable that is not fixed. - A one-sided stencil reuses the value at
xfor its probe atx. - A Hessian evaluates each distinct probe design once. The mixed probes of a one-sided stencil repeat diagonal probes of the other variable, and these repeats reuse the known values.
two_probe_mixed=True(solver optiontwo_probe_mixed_derivativesofLocalOptions,TrustRegionOptions, andDerivativePolicy, default False) estimates the mixed entry of two central variables from two corners and the four diagonal probes:H_ij ~ [d(+i+j) + d(-i-j) - d(+i) - d(-i) - d(+j) - d(-j)] / (2 h_i h_j)withd(a) = f(x + a) - f(x). An interior Hessian then costsn**2 + nrows instead of2 n**2. Both formulas are exact for quadratics. The two-probe formula addsh_i h_j f_iijj / 4to the truncation error, and its worst-case rounding error is about three times larger, so the default keeps the four corners.finite_difference_gradient,finite_difference_jacobian, andfinite_difference_hessiantake a known value atxasvalue_at_pointand then make no callback there.finite_difference_gradient_and_hessianreturns the gradient from the diagonal probes of one Hessian stencil, so the gradient costs no extra callback. Modified Newton shares one Hessian sweep in this way when no derivative callback is supplied,gradient_stepequalshessian_step,first_derivative_stencilis"three-point", andgradient_relative_pointsequalshessian_relative_points(both None, or the same general offsets).
Probe batches:
- By default each probe is one callback call with one design vector. Every derivative function builds all probe designs first, then evaluates them, then forms the weighted sums.
batched=Truesends all probe designs of one sweep to the callback in one call, as the rows of one matrix. The weights and the order of the sums do not change, so a callback that treats its rows independently gives the same derivative. A gradient or Jacobian then costs one call instead of up to2 n + 1, and a Hessian one call instead of about2 n**2.- The solver option is
evaluation_batch_sizeinLocalOptions,LimitedMemoryBFGSOptions,TrustRegionOptions,LeastSquaresOptions, andDerivativePolicy(SLP, SQP, MMA, penalty, and the SciPy stationarity check throughScipyMinimizeOptions.derivative_policy). The default1evaluates one probe design per call.Nonesends all probe designs of one sweep in one call. An integerk >= 2cuts each sweep into consecutive calls of at mostkrows, and the evaluation budget admits each call on its own. - Tradeoffs of large calls: an evaluation budget admits or denies a whole call, so a run near its row limit can stop before it spends the remaining rows (the status stays
MAX_EVALUATIONS). The batch counts fall, and a callback whose batch arithmetic differs at rounding level gives other last bits, which the difference quotient amplifies by1 / h. A callback that accepts only one design per call needsevaluation_batch_size=1.
General stencils and absolute steps:
gradient_relative_points,hessian_relative_points, andjacobian_relative_points(default None) select a general stencil ofdesignoptpy.core.numdiffinstead of the nominal stencil: distinct integer offsets, at least two for a first derivative and three for a Hessian. For example,(-2, -1, 0, 1, 2)is the five-point central stencil, exact for polynomials up to degree four.LocalOptionsandTrustRegionOptionstake gradient and Hessian offsets,LimitedMemoryBFGSOptionsgradient offsets,LeastSquaresOptionsJacobian offsets, andDerivativePolicyall three (objective gradient, stacked constraint Jacobian, and the numerical SQP Hessian).- The solver passes the derivative step,
use_relative_step_size,typical_x, the problem bounds,evaluation_batch_size, and the value it already holds at the design (base_value). Near a bound the core stencil shifts to the open side and its step shrinks. Each row goes through the solver's counted evaluator, so a budget denial givesMAX_EVALUATIONSas before. - Offsets conflict with the two-point stencil, the two-probe mixed formula, and
hessian_from_gradient; these combinations raiseValueErrorwhen the options are built. - Tradeoff: a wider stencil costs more rows per derivative. The step defaults do not depend on the stencil, so set the step to match it; the five-point stencil balances its errors near
eps**(1/5). use_relative_step_size(default True) keepsh_i = step_i * max(|x_i|, typical_x_i). False usesh_i = step_iat every design, for every finite-difference derivative of the solver, nominal or general, including the gradient-difference Hessian ofhessian_from_gradient;typical_xis then unused. Tradeoff: an absolute step can round away at a large coordinate; the stencil check then raisesValueError.LeastSquaresOptionsandDerivativePolicyalso taketypical_x(default1.0). Their steps stay one scalar. With finite bounds, relative steps, andtypical_x_i >= max(|lower_i|, |upper_i|), coordinateiuses the constant stepstep * typical_x_iat every design inside the bounds.- The public functions
finite_difference_gradient,finite_difference_jacobian,finite_difference_hessian, andfinite_difference_gradient_and_hessiankeep their relativerelative_step. Usedesignoptpy.core.numdiff.gradientorhessiandirectly for absolute steps, general stencils, a row budget, or a row cap outside a solver.
Constrained methods:
- SLP, SQP, MMA, and the final stationarity check estimate the inequality and equality Jacobians in one sweep. Each probe design calls each constraint callback once.
- They pass the objective value and the residuals that the solver already holds at the design as
value_at_point. A numerical gradient or Jacobian then evaluates only its probe designs, and an analyticjacobian_functioncosts no constraint row. - The reuse keeps deterministic values unchanged and saves rows under the total evaluation budget.
A smaller step reduces the truncation error but increases the rounding error from the callback values.
Method options set other steps:
- SLP, SQP, MMA, and penalty options take one
designoptpy.point.DerivativePolicywith the stepsgradient_step,jacobian_step, andhessian_step. Their mode followsuse_relative_step_size: relative by default, absolute otherwise. Its defaults are the same balanced steps:cbrt(eps)for gradients and Jacobians and1e-4for Hessians. The policy is defined indesignoptpy.point.differentiation, next to the bounded stencils that use its steps. LocalOptionsexposesgradient_step,hessian_step, andtypical_xfor the four line-search methods.TrustRegionOptions(gradient_step,hessian_step,typical_x) andLimitedMemoryBFGSOptions(gradient_step,typical_x) use the same names and defaults.- The trust-region Hessian stencil reuses the current objective value, as the gradient stencil does.
hessian_from_gradient=True(default False) inLocalOptions(modified Newton) andTrustRegionOptionsdifferences a suppliedgradient_functioninstead: two gradient calls per free variable and no objective row, symmetrized, withcounts.gradientincluding these calls. It requiresgradient_functionand nohessian_function. The Hessian then has other truncation and rounding errors, so iterates and statuses can change.- The augmented Lagrangian
gradient_stepdefaults to 1e-6. - Quasi-Newton exposes the inverse BFGS
curvature_tolerance, default 1e-12, throughLocalOptions. It rejects an update with too little curvature.LocalOptions.inverse_update_form="rank-two"(default"product") evaluates the same update with one matrix-vector product instead of two dense matrix products,O(n**2)instead ofO(n**3)work. The rounding differs, so iterates can differ in the last bits, and at extreme magnitudes the update guard andupdate_appliedcan differ. SQP instead damps such an update (damped_bfgs_hessian_update), so it has no curvature tolerance.
Final stationarity check of constrained methods
SLP, SQP, MMA, and penalty options also take StationarityOptions for the final first-order check.
How the check works:
- The check solves a small LP with the Python
simplex(simplex_max_iterations,simplex_tolerance,simplex_pivot_rule). The LP minimizesg @ dover the directions withnorm(d, 1) <= radius(default 1) that keep the active linearized constraints and do not leave the box at an active bound. - Inactive bounds do not truncate the direction, so a box narrower than the tolerance cannot certify a nonstationary design.
- The claim passes when the descent rate
-(g @ d) / radiusof the LP direction is at mosttolerance * max(1, ||pg_0||_inf), with the projected gradientpg_0at the initial design. - A failed check, or an LP without an optimum, replaces
CONVERGEDwithSTALLED. The message reports the descent rate and the threshold.
Tolerance:
- The default
tolerance=Noneusesmax(sqrt(constraint_tolerance), 1e-6), which is1e-3for the default constraint tolerance. Near a minimizer, an objective change of about tau corresponds to a descent rate of aboutsqrt(tau). - The 1-norm ball is the dual of the infinity norm. Without an active nonlinear constraint, the descent rate is therefore
||pg||_inf, and the check has the form of the projected-gradient test of the line-search methods. tolerance=1e-6gives the gradient-method default strictness. Slowly converging runs, such as SLP on a curved constraint, then often reportSTALLED.
Active constraints:
- An omitted
active_set_toleranceusesmax(constraint_tolerance, 1e-8). - An inequality is active when its residual is at least
-active_set_tolerance. - A bound is active within
active_set_tolerancetimes the finite design width of its coordinate. An interior-point MMA design a small distance inside a bound therefore still counts as on it, and a narrow box stays free. - When a problem combines linear and nonlinear sources,
constraint_toleranceis the smaller source tolerance. A looser source therefore cannot make a row of a stricter source active. - The cost: a row of the looser source that lies inside its bound by more than the stricter tolerance counts as inactive. The check can then reject a design that the looser tolerance alone would accept.
Final verification keeps the selected analytic derivative providers. The check depends on derivative accuracy, so it does not certify a local minimum.
Returned evidence and the public check:
ConstrainedOptimizationResult.stationarity_evidencekeeps the evidence of the final check of SLP, SQP, MMA, and the penalty and barrier methods. It isNonewhen the check did not run (noCONVERGEDclaim, an infeasible design,verify=False, or the augmented Lagrangian, which has its own KKT test) or did not complete (a budget denial). With every coordinate fixed, aCONVERGEDclaim carries the trivial evidence without any evaluation: stationary, a zero direction, and the thresholdtolerance.verify_constrained_stationarity(problem, point, ...)runs the same check at one design. Its keywords areoptions(StationarityOptions;verifyis ignored),scale(default 1, so the threshold istolerance * scale),objective_valueandconstraint_values(known values at the design, the stencil base values),gradient_functionandjacobian_function,derivative_policy, andinequality_multipliers. It validates its inputs before any callback and changes no counter of the problem.StationarityEvidenceholdsstationary,measure(the descent rate,Nonewhen the LP value is not finite),threshold,direction(the LP direction d),directional_derivative(g @ d),linearization(aConstraintLinearizationwith the point, the objective gradient, and both Jacobians), the masksactive_inequalities,active_lower_bounds, andactive_upper_bounds,linear_program(the LP result without pivot records), and the countsgradient_evaluationsandjacobian_evaluations.- A count is 1 when the check computed that derivative, with an analytic callback or finite differences, and 0 when no derivative was needed, the problem has no residual column (Jacobian only), or the solver passed the derivatives of its last linearization.
- When every direction is blocked by active bounds, the check computes the derivatives, solves no LP (
linear_program=None), and reports stationary with a zero direction.
Known derivatives:
- SLP and SQP pass the gradient and the Jacobians of their last linearization to the check. When the run ends at exactly that design, for example after a zero step, the check uses them and makes no derivative row or gradient evaluation.
- For a deterministic model the verdict is the same, because the function, the design, the steps, and the base values are the same. Under an evaluation budget, a check that a new estimate would exceed can then complete.
SlpOptions.reuse_final_derivativesandSqpOptions.reuse_final_derivatives(default True) turn the reuse off for a model that can change between calls. The reuse applies only with the three-pointfirst_derivative_stenciland withoutgradient_relative_pointsandjacobian_relative_points, the nominal stencils of the check.- The check keeps the nominal three-point stencil. It uses the policy steps,
use_relative_step_size,typical_x, andevaluation_batch_size, but not the general offsets or the two-point stencil.
Numeric domain of finite differences
The supported numeric domain is ordinary engineering magnitudes in double precision.
The formulas use their plain form. They do not rescale sums that leave the float64 range.
No h**2 is formed, so a very narrow box or a step whose square is subnormal stays usable.
A stencil raises ValueError that names relative_step (or absolute step with use_relative_step_size=False) and the design variable in two cases:
- Three distinct finite probes do not fit inside the bounds. A box one floating-point spacing wide is an example.
- Float64 rounding moves a probe from its nominal offset by more than a relative
1e-6, so the nominal weights do not apply. A step near the rounding scale of the coordinate is an example.
A derivative that is not finite raises ValueError that names its entry.
Finite-difference records
retain_derivative_records=True (default False) keeps the evidence of each finite-difference derivative in the iteration records.
The switch exists on LocalOptions, LimitedMemoryBFGSOptions, TrustRegionOptions, LeastSquaresOptions, SlpOptions, SqpOptions, and MmaOptions.
Each record is a designoptpy.core.numdiff.DerivativeResult with one design sample:
valuesholds the derivative: shape(1, n_outputs, n)for a gradient or Jacobian,(1, 1, n, n)for a Hessian.gradient_valuesholds the axial gradient of a Hessian sweep.evaluation_pointsandfunction_valueshold the probe designs that the solver evaluated, in call order, and their outputs. A known value at the design adds no row. Constraint records stack the inequality residuals before the equality residuals.relative_pointsholds the offsets:(-1, 0, 1)for the nominal three-point stencils,(0, 1)for the two-point stencil, or the general offsets.step_sizesholds the requested physical steps before they shift or shrink at a bound.evaluationscounts the rows, andbatch_metadatais empty.
| Record field | Iteration records |
|---|---|
gradient_record |
every gradient, trust-region, and least-squares iteration (None for least squares, whose gradient is J.T @ r); SlpIteration, SqpIteration, MmaIteration |
hessian_record |
NewtonIteration, TrustRegionIteration, SqpIteration |
jacobian_record |
GaussNewtonIteration, LevenbergMarquardtIteration |
constraint_jacobian_record |
SlpIteration, SqpIteration, MmaIteration |
A field is None when the derivative came from a callback, from hessian_from_gradient, or from BFGS curvature, and when the iteration reused the derivatives of an unchanged design (a rejected trust-region or Levenberg-Marquardt trial).
When modified Newton takes the gradient from the Hessian sweep, gradient_record is the same object as hessian_record.
The record values equal the matrices of the same iteration bit for bit when retain_derivatives=True.
The switch is independent of retain_derivatives and of history thinning, so every record passed to stop_callback carries its records.
Tradeoff: a gradient record holds about 2 n rows and a Hessian record about 2 n**2 rows of n coordinates per iteration; iterates, counts, and statuses do not change.
Read iteration records
Point results share OptimizationResult and immutable IterationRecord records.
Each method family adds meaningful fields instead of an untyped dictionary.
For a gradient method, each record describes this transition:
starting_point → gradient → search_direction → step_size → point, objective_value
The gradient and curvature belong to starting_point.
point, objective_value, and evaluation describe the retained endpoint.
For a rejected trust-region trial, that endpoint remains the starting point.
Separate trial fields preserve the rejected proposal and its model agreement.
Python gradient records require starting_point, including when history_stride omits intermediate steps.
These two states make each retained transition understandable without the omitted records.
SLP, SQP, and MMA records describe the same kind of transition: linearization.point is the design before the iteration, where the gradient and the Jacobians were taken, and point is the accepted design.
evaluation holds the objective decomposition of point. See Retained history and plots for the switches that drop these fields.
Scalar results expose point, objective_value, initial_point, and initial_objective_value.
A gradient method records an accepted endpoint. A population method selects an incumbent, its current best candidate.
A selected candidate does not prove global optimality.
Generic point and objective histories stack retained selected records; they do not calculate a best-so-far envelope.
Pareto results expose pareto_designs and pareto_objectives because multiple objective tradeoffs do not define one best design.
One design dominates another when no objective is worse and at least one is better.
The Pareto archive retains feasible designs that no other compared design dominates.
The crowding distance divides neighbor gaps by the objective span of a front; a finite span above the float64 range raises ValueError, so rescale such objectives.
The hypervolume of an archive is the measure of the objective region that the archive dominates up to a reference point r:
the union of the boxes [f_i, r] of the archive rows f_i. It grows when the archive moves toward smaller objectives or covers more of the front.
pareto_hypervolume(objectives, reference_point) computes it exactly, without sampling:
a sum of rectangles for two objectives, and hypervolume by slicing objectives (HSO) for more, with work that grows like n**(m-1) log n.
It scales each objective by an exact power of two, so an intermediate product of a thin or wide box cannot underflow or overflow.
A measure beyond the float64 range is unavailable (None). Integer inputs beyond 2**53 in magnitude raise ValueError, because their float64 conversion is inexact.
pareto_hypervolume(..., options=HypervolumeOptions(...)) and ParetoSearchOptions(hypervolume_options=...) select two faster forms of the same measure. Both are off by default, and the default slicing stays bit-identical.
remove_contained_rows=Trueremoves, in every cross-section at every slicing depth, the boxes that another box of the cross-section contains. It reuses the previous cross-section measure when the remaining boxes did not change. A contained box adds nothing to its slice or to a later slice, because the cross-sections are nested.incremental_three_objective_sweep=Truecomputes three objectives (and the last three coordinates of the recursion for more objectives) by a dimension sweep. The cross-section is a staircase of uncontained rectangles, and each new box adds only its newly covered area, so no slice needs a new two-dimensional sweep.- Measured on 300 random rows in the unit cube with three objectives: 10 ms by default, 3.5 ms with row removal, 0.4 ms with the sweep. With four objectives and 120 rows: 214 ms, 12 ms, 8 ms, and 2.4 ms with both.
- Tradeoff: the terms of the floating-point sum change, so the value can differ in the last bits. A value within rounding of a hypervolume target can then reach or miss the target, and the run can stop in another generation.
- Availability: with row removal, a contained box adds no thin slice, so an input whose only slice below the normal float64 range comes from such a box gives a value instead of
None. The sweep givesNonewhen an area term with positive factors, or a slice product, falls below the normal range (numpy.finfo(float).tiny).
ParetoSearchOptions(hypervolume_reference_point=..., hypervolume_target=...) sets a target; both default to None (no target).
After each archive update, including the initial archive, a hypervolume at least the target stops the run.
The final archive check then decides the hypervolume of the checked archive.
When the check removes no row, the solver reuses the last value, because the hypervolume depends only on the archive rows:
| Final archive | Status | success |
|---|---|---|
| Still reaches the target | OBJECTIVE_THRESHOLD |
True |
| Rows removed, hypervolume below the target | FINAL_OBJECTIVE_THRESHOLD_FAILED |
False |
| Empty | INFEASIBLE |
False |
The archive-stall stop (the archive changed by at most front_tolerance for max_stall_iterations generations) is the convergence test of the search.
It reports CONVERGED, and success is True when rows pass the final archive check; an empty checked archive gives INFEASIBLE.
The test checks only that random variation found no material archive change. It proves neither a complete front nor Pareto stationarity.
With a target, a stall before the target also reports CONVERGED. A caller that requires the target reads OBJECTIVE_THRESHOLD.
final_hypervolume, hypervolume_reference_point, objective_threshold, and the hypervolume of each ParetoIteration record the target evidence. They are None without a target.
Each ParetoIteration also keeps the evidence of its generation:
offspringandoffspring_objectives: the children evaluated in this generation, in generation order, and their raw objective rows. Underskip_infeasible_objectivesa skipped row isNaN.front_change: the archive change of the generation, the Hausdorff distance between the archive objective rows before and after it (the larger of the two largest nearest-neighbor Euclidean distances, in raw objective units). It is0.0for an unchanged archive andinfafter a size change or an empty previous archive.stall_iterations: the successive generations up to this one withfront_change <= front_tolerance. The stall test reads exactly this count, so astop_callbacksees the evidence of the next stall decision.- Each retained record holds its offspring arrays;
history_strideandhistory_limitthin them.
ParetoSearchOptions(skip_infeasible_objectives=True) evaluates the constraints first and the objective only at feasible designs (default False).
Ranking, selection, and the archive read only the violation of an infeasible design, so a seeded run with a row-independent objective keeps its designs, survivors, and archive.
The objective rows of infeasible designs are then NaN in the population records, and counts.objective counts only the evaluated rows.
The objective must be row-independent: the value of a row must not depend on the other rows of its batch.
Other signals change: a budget can deny another batch, a non-finite objective at an infeasible design no longer raises, the callback order is constraints first, and a stop_callback that reads the unavailable rows can stop elsewhere.
Until the first feasible design, the objective matrices have zero columns, because the column count is not known yet.
Keep it off in the mapped Pareto workflow: its objective and constraints share one cached model response, so the option adds model rows there.
ParetoSearchOptions(offspring_sampling="batched") draws the tournaments, crossover decisions and factors, mutation masks, and normal steps of all children as arrays (default "per_child").
The offspring distribution is the same, and the draws take about 0.14 ms instead of 4.9 ms for 100 children of six variables.
Tradeoff: the random stream changes, so a seeded run or an initial_rng_state replay gives another run than the default.
Conjugate gradient records contain conjugacy_coefficient (the raw callback value), effective_coefficient, and restarted, which is True when a changed blocked set or a descent fallback forced the effective coefficient to zero.
The first step calls the coefficient function with a zero previous projected gradient and always uses the effective coefficient zero.
BFGS records contain update_applied: None before an update attempt, False when skipped, and True when applied.
Newton records contain hessian_shift, the multiple of the identity added to the free Hessian block.
Each gradient method describes bound projection separately because projection and method-specific restart decisions have different causes.
Population records combine the generation operators with the population after selection or movement.
Read the owning module to identify the timing of each field.
Genetic fitness belongs to the parent population; the stored population follows survivor selection.
The random decision draws are part of the records: DifferentialEvolutionIteration.recombination_factors (one draw per coordinate, compared with CR),
and GeneticIteration.crossover_factors (one per couple) and mutation_factors (one per member).
DifferentialEvolutionIteration.base_vectors and difference_vectors give the mutation vectors before scaling and projection, computed from starting_population and donor_indices.
With retain_evaluations=True, population records also explain their values: population_evaluations holds one ObjectiveEvaluation per population row,
evaluation holds the record of point, and differential evolution adds trial_evaluations, one per trial. By default these fields are None.
nelder_mead returns a NelderMeadResult, a ConstrainedOptimizationResult with three more fields.
With NelderMeadOptions(retain_evaluations=True), each NelderMeadIteration keeps trial_evaluations (one record per row of trial_points) and evaluation (the best vertex),
and the result keeps the initial simplex before the first update sorts it:
initial_simplex: the evaluated initial vertices in construction order, shape(n_vertices, n_variables). Row 0 is the start, and rowk + 1steps the k-th free coordinate toward its farther face. Only complete observations appear, so a row cap can truncate it; zero rows mean that no vertex was evaluated, and None means not retained.initial_simplex_objectives: the merit of each vertex, the values that the simplex compares. Entry 0 equalsinitial_objective_value.initial_simplex_evaluations: oneObjectiveEvaluationper vertex from the same callback batch. Withdefer_constraint_witness=Truethe records holdconstraints=Noneand zero penalty sums, because no constraint callback runs at the vertices.- The best initial vertex is
initial_simplex[np.argmin(initial_simplex_objectives)], the first minimum. Bayesian acquisition scores use the model before candidate evaluation; the stored surrogate is the refitted model. A surrogate predicts objectives from observations. An acquisition score uses predicted improvement and uncertainty to choose another evaluation. Retained history can be shorter than the completed iteration count.
Line-search records keep bracketing, sectioning, and sufficient-decrease backtracking as distinct mechanisms.
Starting step:
- Both searches start at
initial_step, default1, the natural Newton step. - Golden-section search falls back to
initial_step_relative_factor * maximum_stepwhen the unit step exceeds a finite limit. - Backtracking starts at
min(initial_step, maximum_step). LocalOptions.adaptive_initial_step=True(default False) starts each later golden-section search of steepest descent and conjugate gradient att_previous * slope_previous / slope, the step that repeats the first-order change of the previous accepted step (Nocedal and Wright, section 3.5).LimitedMemoryBFGSOptions.adaptive_initial_step=Truestarts an Armijo search with an empty memory atmin(1, 1 / ||d||_2). Quasi-Newton, modified Newton, and a filled L-BFGS memory keep the unit start, because their directions reach the model minimum at step one. Tradeoff: the sampled steps change, so paths, counts, and statuses can change; a start that is too short costs expansion rows or, for backtracking, a shorter step.
Acceptance rules:
- Golden-section search always evaluates its returned step and accepts it only when that value is strictly lower than the start value.
GoldenSectionOptions.reuse_bracket_point=True(default False) keeps the interior middle sample of the bracket as one sectioning point and evaluates only the other, at the golden fraction of the larger subinterval. Each later reduction places its new sample the same way, beside the retained sample, so a middle at any position keeps the minimizer of a unimodal line inside the interval. A search then makes one objective call fewer, but its sampled steps, and so the iterates, counts, and possibly the status of the solver, change.- Armijo backtracking accepts a step at exact equality with the sufficient-decrease threshold.
Bounds:
backtracking_searchtakes a scalardirectional_derivative, a knownstarting_value, and optionalbounds. With bounds, its trials and finite-difference probes stay inside the box.golden_section_searchalso takes optionalbounds. The box then limitsmaximum_step, and each trial design is clipped to the box, so a rounded trial at the step limit cannot leave it.
Rejected steps:
- If a search rejects its step, it returns step zero with
converged=False. last_rejected_trialseparately keeps the last evaluated rejected design and value.accepted_trialkeeps the accepted trial of an accepted search.n_evaluationscounts the objective calls of a built-in search: the start whenstarting_valueis not supplied, every trial, and the finite-difference probes of backtracking.GoldenSectionOptions(retain_history=False)andBacktrackingOptions(retain_history=False)(default True) returniterations == (). The steps, decisions, calls,accepted_trial,last_rejected_trial, andn_evaluationsstay the same. Passed to a solver throughLocalOptions.line_searchorSqpOptions.line_search_options, the switch keeps the solver path and counts and only empties the retained traces.plot_line_searchthen shows only the selected step, andplot_point_line_search_progressraisesValueErrorfor such an iteration.- Both searches also accept an
ObjectiveEvaluatorin place of the scalar callback. An accepted search then returns the decomposition record of its accepted design inaccepted_evaluation, with the raw objective and the constraint values observed with it. - On a zero-length golden-section line (
maximum_step=0after the bound reduction, or a zero direction), the start is the only admissible point. The search evaluates no trial, andlast_rejected_trialis the start record at step zero, so a solver reports no descent. - The unchanged design is a no-motion fallback. It does not satisfy the failed search criterion. Plots label that point as a fallback without changing the zero step.
Merit decomposition records explain each scalar merit. ObjectiveEvaluator.evaluate returns one ObjectiveEvaluation per design:
the raw objective columns, the scalarized objective, the merit, the constraint values, the penalty and barrier totals, and the term of each residual
(inequality_penalty_terms, equality_penalty_terms, barrier_terms), all before scaling by penalty_constant.
The terms show which constraint drives a penalty or barrier total; unused entries are zero, and a total is the sum of its terms.
ObjectiveEvaluator.evaluate_batch makes the same callback calls and returns one ObjectiveEvaluationBatch, whose arrays hold one row per design
(for example inequality_penalty_terms of shape (n_samples, n_inequalities)); batch.record(i) equals record i of evaluate.
A zero-row batch calls the callbacks with the zero-row matrix and keeps the column widths of their outputs.
Records prevent field reassignment and retain independent, read-only numerical copies. These protected values are immutable snapshots. Unsupported supplied objects can remain shared.
Random generators and replay
Every stochastic method has the options field rng: a NumPy Generator, a nonnegative integer seed, or None.
These methods are:
- differential evolution, the genetic algorithm, and particle swarm;
- covariance matrix adaptation, Bayesian optimization, and Pareto search;
- pattern search with
randomize_poll=True, and sampling optimization with generated points; penalty_barrier, for its default inner differential evolution, with the default seed0;- SciPy differential evolution.
How rng is used:
- The solver converts
rngwithnumpy.random.default_rng. - A Generator is used directly and advances with each solve.
- An integer seed creates a new generator at each solve, so repeated solves with the same options give the same result. A seed is an integer that sets the initial state of a new generator.
Nonedraws fresh operating-system entropy.
Each stochastic result records initial_rng_state: the bit_generator.state of its generator before the first draw.
A bit generator is the NumPy object that produces the raw random bits of a Generator.
The record lets you replay an unseeded run:
bit_generator = getattr(np.random, result.initial_rng_state["bit_generator"])()
bit_generator.state = dict(result.initial_rng_state)
replay = differential_evolution(
problem, options=dataclasses.replace(options, rng=np.random.Generator(bit_generator))
)
This replay is exact only when every draw comes from that bit state.
A step that spawns a child generator draws from the seed sequence of the generator, which the bit state does not record.
SciPy quasi-Monte Carlo samplers spawn children: Latin-hypercube sampling, and the "sobol" and "halton" initial populations of SciPy differential evolution (scipy_options["init"]).
Replay such a run with a full copy of the generator made before the solve, designoptpy.core.sampling.copy_generator(rng), or with the same integer seed.
copy_generator copies both the seed sequence and the bit state. copy.deepcopy(rng) keeps the seed sequence only with NumPy 2.0 and later.
A deterministic method records None. A nested result, such as inner_result, search_result, refinement_result, or feasibility_result, records its own state.
Result signals
status states why a run stopped. Read it together with success, converged, feasible, and budget_exhausted.
| Signal | Meaning |
|---|---|
CONVERGED, OPTIMAL |
The method's convergence criterion or optimality certificate holds; converged is True. |
OBJECTIVE_THRESHOLD |
A feasible objective reached the requested threshold. |
MAX_ITERATIONS, MAX_EVALUATIONS |
An iteration or evaluation budget ended the run; budget_exhausted is True. sampling_optimization with max_evaluations=0 also reports MAX_EVALUATIONS: it evaluates nothing and returns a placeholder design with a NaN objective and feasible=None. |
EVALUATIONS_COMPLETED |
sampling_optimization evaluated every supplied point, fewer than max_evaluations, without reaching its threshold. It is not a budget stop. |
NO_FINITE_CANDIDATE |
genetic_algorithm found no member with a finite objective, for example because a barrier rejected every member, so selection could not continue. The returned incumbent can still be finite. A population method on a fixed box also reports it when the only design has no finite merit. |
FINAL_OBJECTIVE_THRESHOLD_FAILED |
A fresh final observation is feasible but above the threshold that the run reached: in bayesian_optimization (reevaluate_final_candidate=True) or in a noisy mapped workflow. |
REJECTED_DESIGN |
The model rejected the observation that qualifies the returned design of a mapped workflow (raw +inf). The reported objective is inf. |
FINAL_FEASIBILITY_FAILED |
The observation that qualifies the returned design violates a requirement: a positive raw physical deficit, a noisy mapped residual above constraint_tolerance, or a Bayesian fresh final observation that violates the constraints. |
INFEASIBLE |
The run returned no feasible design. Only the LP and QP solvers certify mathematical infeasibility. The other uses are listed below. |
UNBOUNDED |
The objective decreases without bound. |
NO_FEASIBLE_STEP |
The method found no acceptable step before stationarity. Nonlinear infeasibility is not proved. The uses are listed below. |
NO_REPRESENTABLE_PROGRESS |
An accepted step could not change the represented coordinates. Pattern search: every poll step of a free box rounds to the current design. MMA: a rounded pole or move bound leaves no reciprocal subproblem. |
STALLED |
A stop rule fired, but a stationarity check failed. The design is not certified stationary. The uses are listed below. |
NUMERICAL_ERROR |
A numerical operation failed. SQP and MMA: the step subproblem failed. SQP keeps the failed QP result in subproblem_failure. |
STOPPED |
A stop callback requested termination after a completed iteration. The request takes priority over the stop tests of that iteration, so it is never a success. |
BEST_FEASIBLE_SELECTED |
return_best_feasible=True returned an earlier feasible design instead of the final solver design. success is False, because the solver did not stop at that design. |
INFEASIBLE has these uses besides the LP and QP certificates:
- The callback LP and QP wrappers report it when the true constraint callback rejects the coefficient-model candidate. This does not certify infeasibility.
- SLP and SQP report it when the stopping rule passed at an infeasible design with a zero step that would repeat.
STALLED has these uses:
- Steepest descent, conjugate gradient, quasi-Newton, and modified Newton met their stop rule (the objective-change rule or a supplied
convergence_function, which receives aConvergenceState), but the projected gradient exceededgradient_tolerance * max(1, ||pg_0||_inf). gauss_newtonandlevenberg_marquardtreport it when a step metstep_tolerancebut the residual gradient failed the stationarity test.- SLP, SQP, MMA, and
penalty_barrierreport it when the stop rule fired at a feasible design, but the final first-order check found a linearized feasible descent direction. Their result keeps the evidence of that check instationarity_evidence(aStationarityEvidence;Nonewhen the check did not run or the budget denied it). scipy_minimizereports it when a SciPy success fails the stationarity check (see below).
In each of these cases, a progress stop rule is separate from the first-order stationarity test that certifies convergence.
A method whose own convergence test is a stall test reports that test as CONVERGED, for example the archive stall of pareto_search and the population-spread test of the population methods and scipy_differential_evolution.
NO_FEASIBLE_STEP has these uses. In each case the method could not continue, and the design is not certified.
- Steepest descent, conjugate gradient, quasi-Newton, and modified Newton: the line search rejected its step (
converged=False), and the current design was kept. The message names a rejected zero step (no evaluated step lowers the objective) or a rejected positive step. limited_memory_bfgs: the Armijo search rejected its step, also after the retry along the projected negative gradient.trust_region: the trust radius fell belowminimum_radius, or only roundoff-sized bound motion remained.gauss_newtonandlevenberg_marquardt: the Armijo backtracking of Gauss-Newton found no sufficient decrease, or a Levenberg-Marquardt trial was rejected atmaximum_damping. A Gauss-Newton direction without descent is replaced by the projected negative gradient (descent_fallback) and does not stop the run.sequential_linear_programming: a trial was rejected belowminimum_move_limitand the linearized merit slope exceededoptimality_tolerance, or a zero step did not converge.sequential_quadratic_programming: the quadratic subproblem was infeasible, the merit line search rejected its step, or a zero step did not converge.bayesian_optimization: the acquisition returned no unevaluated design. That iteration counts inn_iterationsand keeps a record without evaluated points.scipy_minimizewith SLSQP: SciPy exit mode 8, a positive directional derivative in its line search.
Final-design diagnostics of the local derivative methods do not depend on history retention:
GradientOptimizationResult.projected_gradient_norm(steepest descent, conjugate gradient, quasi-Newton, modified Newton,limited_memory_bfgs,trust_region) andLeastSquaresResult.gradient_norm(gauss_newton,levenberg_marquardt) hold the infinity norm of the projected gradient at the returned design, the stationarity measure. They areNonewhen the solver computed no gradient at exactly that design, for example afterMAX_ITERATIONSthat follows a moving step, or after a denied initial evaluation.CONVERGEDandSTALLEDalways have a value.return_best_feasible=Truesets the field of a selected earlier design toNone.trust_regionreturns aTrustRegionResultwithfinal_radius, the radius of the next trial (see Trust region and limited-memory BFGS).levenberg_marquardtreturns aLevenbergMarquardtResultwithfinal_damping, the damping of the next trial (see Least-squares problems).
scipy_minimize translates the numeric SciPy status code of each method, not its message text.
A SciPy work limit gives MAX_ITERATIONS or MAX_EVALUATIONS, so budget_exhausted is True:
- Nelder-Mead and Powell: the
maxfevlimit givesMAX_EVALUATIONSand themaxiterlimit givesMAX_ITERATIONS. - TNC: the
maxfunlimit givesMAX_EVALUATIONS. - L-BFGS-B: one SciPy code covers both limits. SciPy tests
maxiterfirst, sonit >= maxitergivesMAX_ITERATIONS; otherwise themaxfunlimit givesMAX_EVALUATIONS. - COBYLA:
maxiterlimits the function evaluations. Its limit code is 2 before SciPy 1.16 and 3 from SciPy 1.16, and each code has another meaning in the other version. So code 2 or 3 givesMAX_EVALUATIONSonly whennfevreachedmaxiter. - COBYQA: the
maxfevlimit givesMAX_EVALUATIONSand themaxiterlimit givesMAX_ITERATIONS. The COBYQA initialization reports themaxitercode, withnit = 0, also whenmaxfevstops it. So that code withnit = 0givesMAX_EVALUATIONSwhennfevreachedmaxfev. - SLSQP, trust-constr, and BFGS: the iteration limit gives
MAX_ITERATIONS.
An unknown code gives STOPPED; backend_result keeps the SciPy status and message.
scipy_differential_evolution reports MAX_ITERATIONS when its maxiter generation limit ends the run.
A SciPy success is not always an optimality test.
SLSQP stops on a small objective change, L-BFGS-B also on a small relative reduction (ftol), TNC also on small objective or step changes,
trust-constr also on a small step (xtol), and Powell on small relative decreases.
After a SciPy success of SLSQP, L-BFGS-B, TNC, trust-constr, BFGS, CG, Newton-CG, Powell, dogleg, or a trust-region Newton method,
scipy_minimize checks first-order stationarity at a feasible returned design with ScipyMinimizeOptions.stationarity.
The check is the one of the native constrained methods (StationarityOptions):
a linear program finds the steepest descent rate over the directions that keep the active linearized constraints and the active bounds.
The success stays CONVERGED when that rate is at most tolerance * max(1, ||pg_0||_inf); otherwise the status is STALLED with success=False.
The check costs the residuals at the returned design, the objective gradient and one constraint Jacobian there, and one linear program.
The scale max(1, ||pg_0||_inf) is at least one, so a rate within tolerance passes for every start gradient.
Only a rate above tolerance needs a second objective gradient, at the start, to compute the scale; the verdict is the same as with the start gradient first.
The residuals cost one constraint row per nonlinear callback, or none when the residual store of the adapter holds the returned design (see Callback accounting and budgets).
The bound-aware finite differences evaluate two probe rows per coordinate for each derivative; an analytic gradient replaces the objective probes.
StationarityOptions(verify=False) turns it off: faster, but a stall can then pass as convergence.
Nelder-Mead, COBYLA, and COBYQA stop on the size of their simplex or trust region, the analog of a mesh-size test, so their success stays CONVERGED without the check.
SciPy differential evolution ends its generations by the population-spread test (the standard deviation of the population objectives is at most atol + tol * |mean|) or by the maxiter limit.
The spread test is its convergence test, so scipy_differential_evolution reports it as CONVERGED. The test checks only that the population objectives agree. It proves neither a global minimum nor stationarity.
The status stays CONVERGED when the exact SciPy check then finds a constraint violation above zero: the final check decides feasibility with the problem tolerances, and an infeasible design gives INFEASIBLE.
Both SciPy adapters follow the budget-stop rule of the native methods. When problem.evaluation_budget denies a callback batch, the status is MAX_EVALUATIONS and success is False.
The result keeps the last iterate (scipy_minimize) or the best member of the last completed generation (scipy_differential_evolution) that SciPy reported with its value, or else the start design.
A denial before SciPy starts gives the start design with a NaN objective and feasible=None.
solver_status keeps the termination of the solver run after the final feasibility check.
It equals status unless best-feasible selection returned an earlier design, or the evaluation budget denied the final feasibility check; then status is MAX_EVALUATIONS, feasible is None, and solver_status keeps the nominal termination.
A mapped workflow whose final qualification fails also keeps solver_status: status names the qualification failure (REJECTED_DESIGN, FINAL_FEASIBILITY_FAILED, or FINAL_OBJECTIVE_THRESHOLD_FAILED), and solver_status keeps the termination of the solver run.
Pareto results follow the same rule for their final archive check.
For example, a solver that converges to a design that violates the constraints has solver_status INFEASIBLE.
If selection then returns a feasible start, status is BEST_FEASIBLE_SELECTED and feasible is True.
success uses each method's documented criterion. feasible reports verified final bound and residual feasibility.
None means that the route did not verify feasibility.
constraint_violation is the largest raw excess (tolerance zero) at the returned design over every requirement that the final check reads:
positive inequality and absolute equality residuals of the linear and nonlinear sources, the bound excess, and the distance of each integer coordinate to its nearest integer.
It is 0.0 for a design that meets every requirement exactly and None when feasible is None, and it comes from the same evidence as the verdict.
With one shared tolerance t, a feasible design has constraint_violation <= t. A design outside the bounds gets no nonlinear query, so its value is a positive lower bound.
A Pareto result reports the largest value over its returned archive rows (None for an empty or unchecked archive); its constraint_violation_feasible is the different recovery objective at the recovered start.
The coefficient-program and least-squares solvers do not pass the accounting boundary and keep None.
A finite point alone does not certify convergence. A penalized objective_value is a merit value and can differ from the physical objective.
A small objective change, collapsed population, or small polling mesh can satisfy a stopping rule without proving global optimality.
Inspect the status, constraint residuals, and bounds before you use a design.
Steepest descent, conjugate gradient, quasi-Newton, and modified Newton converge when the projected gradient is within gradient_tolerance * max(1, ||pg_0||_inf), tested before every line search.
After a small objective change they report success only when that test also passes at the returned design; otherwise they report STALLED.
Trust-region Newton and projected L-BFGS converge on the same test, at the initial design and after each accepted step; they have no objective-change stop rule.
Nelder-Mead and CMA-ES use point-spread and objective-spread criteria, the population methods use objective spread, and pattern search uses its mesh size.
All of these also require final feasibility.
Under constraint_selection="feasible-first", the population tests also require a population without an infeasible member.
An iteration or evaluation budget stop is never a success.
Sampling reports success only for OBJECTIVE_THRESHOLD. Pareto search reports it for the archive-stall CONVERGED and for a reached hypervolume target (OBJECTIVE_THRESHOLD), each with a nonempty checked archive.
Differential evolution, particle swarm, and the genetic algorithm report it for CONVERGED and for a reached objective_threshold (OBJECTIVE_THRESHOLD), each with a feasible returned design. A failed final check keeps OBJECTIVE_THRESHOLD with success=False, because INFEASIBLE replaces only a converged status.
After a budget stop, feasible tells whether the returned design or archive is usable.
Bayesian success and converged require a feasible design that meets objective_threshold.
useful_completion separately marks a finite feasible incumbent after threshold, iteration-limit, or no-new-design termination.
selected_observation_index identifies the returned design, objective, and constraints as one evaluated observation.
selected_constraints returns its one-row residuals. Repeated noisy coordinates remain distinct observations.
Final qualification uses this row with the effective constraint_tolerance, or the source tolerances when it is None.
It performs no fresh constraint-only measurement.
ConstraintValues.feasible() applies the tolerance of each residual source, or DEFAULT_CONSTRAINT_TOLERANCE
(1e-6) when a column has none.
feasible(tolerance=...) applies one explicit global tolerance instead.
Callback accounting and budgets
Callback-accounted results count actual objective and constraint rows and batches.
The accounting boundary owns these four row and batch fields of EvaluationCounts; it replaces any value that the
solver reported. The solver reports the derivative and subproblem counts.
The boundary also measures elapsed_seconds, the wall-clock time of the whole call with time.perf_counter,
including the final feasibility check. A nested solver result keeps its own time. The time includes the user
callbacks and depends on the machine load. None means that the route did not measure it, for example the
coefficient-based linear and quadratic program solvers, which have no accounting boundary.
Counts include derivatives, start recovery, nested solves, and final validation.
Separate inequality and equality callbacks count separately. Linear matrix arithmetic adds no callback work.
Integer starts are projected before any callback.
Row limits cap evaluated designs; batch counts measure callback invocations.
OptimizationProblem.evaluation_budget takes an EvaluationBudget(total=...), one optional hard cap on the rows sent to the objective and constraint callbacks together.
Budget rules:
- All recorders of a solver share one
EvaluationBudget. - A whole batch must fit before its callback runs. A batch that does not fit raises
EvaluationBudgetExceededError. - The error has status
MAX_EVALUATIONS, the completed row and batch counts, and the best feasible scalar incumbent when one was captured. An incumbent is the best feasible design recorded so far. Unavailable incumbent evidence isNone. - No verification calls are spent after exhaustion. Work inside callbacks and later plotting are outside the budget.
Methods that catch the error and return a result with MAX_EVALUATIONS and success=False:
- steepest descent, conjugate gradient, quasi-Newton, and modified Newton;
nelder_meadandcovariance_matrix_adaptation;differential_evolution,genetic_algorithm, andparticle_swarm;bayesian_optimization,sampling_optimization, andpareto_search;- the constrained methods;
- the SciPy adapters
scipy_minimizeandscipy_differential_evolution.
Returned design after a denial:
- A denied first batch returns the initial design with NaN objective values.
- A later denial returns the last accepted design, the best retained simplex vertex, the CMA-ES incumbent, or the best evaluated population member or observation. A SciPy adapter returns the last iterate or generation best that SciPy reported with its value, or else the start design. The denied generation or acquisition iteration has no record.
- A NaN objective means that no design was evaluated, so the accounting boundary runs no constraint query and reports
feasible=None. - A denied initial Bayesian batch also leaves no observation, so
selected_observation_indexisNone.
The observation whose constraint rows qualify the returned design is its constraint witness.
The reported objective and the feasibility verdict should come from that one observation.
A Bayesian or sampling result qualifies its design from the row of selected_observation_index, with or without a budget, so the final check needs no new row.
Under a finite budget (an EvaluationBudget with a numeric total), other results take the witness in this order:
- The result's own record of the returned design:
final_constraintsof a constrained, pattern-search,nelder_mead, orcovariance_matrix_adaptationresult. - The recorded observations of the returned design, when they all agree on one feasibility verdict.
- A recorded observation is a row of an objective batch whose constraint rows were also observed. It can come from any batch of the run, for any number of objective columns, and also from a batch that contains a non-finite objective value (NaN or an infinity).
- The incumbent observation (the best feasible design seen) is one of them. Only a row with one finite raw scalar objective can become the incumbent, so the finiteness filter applies only to incumbent selection.
In both cases the final check needs no new row.
How the two rules differ:
nelder_meadkeeps the witness with each retained vertex, andcovariance_matrix_adaptationkeeps it with its incumbent, so rule 1 qualifies the accepted observation.- Rule 2 is a fallback for methods that keep no witness, for example
differential_evolution,genetic_algorithm,particle_swarm, and the gradient methods. It matches the returned point by coordinate equality alone, so it does not know which observation the solver accepted. - Observations of one design with conflicting verdicts occur only for a noisy or stateful callback, for example when such a callback gives repeated population members different residuals. Rule 2 then certifies nothing, and the final check queries the constraints again, because any choice could borrow the verdict of an observation that the solver did not accept.
- When the verdicts agree, the verdict is the same for every recorded observation, but the reported objective can still come from another observation of the same design.
- A batch with a non-finite objective value can add or remove the final check, which is one constraint query at the returned design. It can supply the only observation of the returned design, so no query runs. It can also conflict with another observation, so the query runs or ends in the budget stop below.
Cost of the final check:
- A completed query costs one constraint row per nonlinear callback: one row for a
combinedcallback, and two rows for separateinequalityandequalitycallbacks. - Each callback reserves its own row, so the budget can deny the equality callback after the inequality callback has spent its row. Objective rows do not change.
- Without a finite budget, the final check queries the constraints again, because a noisy or stateful callback can return another value.
EvaluationBudget()(a total of None) is unlimited, so it counts the same rows as no budget. - When the budget denies the final feasibility check, the accounting boundary returns the design with
feasible=None,success=False, andMAX_EVALUATIONS.solver_statuskeeps the nominal solver termination.
The constrained methods sequential_linear_programming, sequential_quadratic_programming, method_of_moving_asymptotes, penalty_barrier, and augmented_lagrangian follow the same contract.
- Their initial evaluation is the objective batch and then the constraint batch of the start.
- A denied objective batch returns the start with a NaN objective,
final_constraints=None, andfeasible=None. - When only the constraint batch is denied, SLP, SQP, and MMA keep the observed start objective in
objective_valueandinitial_objective_value, because the budget already charged that row.final_constraintsisNone, the final feasibility check is denied too, andfeasibleisNone. penalty_barrierandaugmented_lagrangianreturn a NaN objective for a denial in either batch.- A later denial returns the last accepted design with its objective, residuals, history, and counts.
- A denial in the final stationarity check also gives
MAX_EVALUATIONS, instatusand insolver_status. The stop rule fired, but the claim was not verified, so it is not convergence evidence. - The
penalty_barrierandaugmented_lagrangiansubproblems call the counted callbacks of the run. An inner solver can catch a denial and return early, so the subproblem objective records the denial. The outer method then stops at its last accepted design instead of judging the inner design.
pareto_search returns MAX_EVALUATIONS too.
- A denied initial population gives the initial population with zero objective columns,
final_population_constraints=None, an empty archive, andfeasible=None. - A denied offspring batch keeps the population and archive of the last completed generation.
- A denied final archive check keeps the unchecked archive with
qualification_available=Falseandfeasible=None.solver_statuskeeps the loop status.
SciPy adapters count actual calls of supplied analytic derivatives.
Without supplied derivatives, they use SciPy's derivative counts, or None when SciPy reports none.
By default, the SciPy differential-evolution adapter calls the objective once per population member, with one design row.
With scipy_options={"vectorized": True}, it sends the members of each generation to the objective and to each constraint group as one batch of design rows.
SciPy then updates the population once per generation (updating="deferred"), so the search path and the result differ from the serial run with the same seed: a solution-quality tradeoff that the caller selects.
The counters keep one row per member and one batch per call; an empty batch (no feasible trial) calls no callback, and the polishing step still sends single designs.
In a four-variable constrained Rastrigin run (population 60, 100 generations), the run time fell from 1.75 s to 0.15 s with about the same number of objective rows.
The options record rejects workers != 1 before model evaluation, because the callbacks run on the calling thread.
Adapters retain the native backend_result for multipliers, derivatives, and population diagnostics.
Set retain_backend_result=False in the options record to omit that record; work counters and termination do not change.
The SciPy adapters evaluate the objective once at the start for initial_objective_value. SciPy makes the other objective calls.
Each history record stores the observation (x, fun) that SciPy passes to its iteration callback, so retained history adds no objective calls.
Then the objective rows equal SciPy nfev plus one, plus the rows of the stationarity check after a success (see Result signals).
TNC passes only x, as SLSQP and COBYLA do in older SciPy versions; the adapter then evaluates the objective at x for each retained record.
history_limit=0 retains no record and makes no such call.
Differential evolution does not evaluate the objective of a member that violates the constraints. SciPy reports its value as positive infinity, and a record of such a generation keeps that value.
SciPy takes the inequality and equality residuals as two separate constraint groups and requests each group in its own call.
SciPy also requests some designs again: SLSQP and trust-constr request one group at an iterate and its finite-difference probes and then the other group at the same designs,
and COBYQA requests its interpolation points again in later iterations.
By default (reuse_constraint_residuals=True in both options records), the adapter keeps the residuals of the last 2 * n_variables + 2 designs, or of every design of a larger vectorized population request, keyed by the exact bits of the design vector.
A request at a stored design reuses them and costs no callback row; the stationarity check after a SciPy success reads its base residuals from the same store.
This exact reuse assumes a deterministic model. Set reuse_constraint_residuals=False for a model whose residuals can change between calls at the same design.
A request that the store cannot answer runs only the callbacks of its group: a separate inequality or equality callback runs only for its own group.
A combined callback returns both groups, so one call stores both groups of its design; with the reuse off, it runs once for each group request.
In a four-variable test problem with one combined callback, the constraint rows fell from 107 to 44 for SLSQP, from 331 to 169 for trust-constr,
from 1174 to 50 for COBYQA, and from 2010 to 962 for differential evolution; the returned designs did not change.
With log_evaluations=True, the loggers keep this layout, so logging adds no callback run.
Retained history and plots
Retention options limit saved data. They do not reduce the model work that the solver performs.
history_stride retains the first, latest, and every stride-th iteration, while stop callbacks still see every iteration.
history_limit caps the retained records after stride thinning.
Every options class with history_stride also has history_limit: the LocalOptions and PopulationOptions methods,
trust region, L-BFGS, Nelder-Mead, CMA-ES, augmented Lagrangian, least squares, and the constrained, Bayesian,
pattern, sampling, and Pareto methods. Most solver options take None or a positive cap, so the newest record stays.
BayesianOptions and the constrained methods (SlpOptions, SqpOptions, MmaOptions, AugmentedLagrangianOptions, PenaltyOptions) also accept 0, which keeps no record.
n_iterations and the counts still include every iteration.
LocalOptions separately controls endpoint decompositions (retain_evaluations), line searches (retain_line_search), and derivatives (retain_derivatives).
PopulationOptions, CovarianceMatrixAdaptationOptions, and NelderMeadOptions have retain_evaluations too, default False: it keeps one decomposition record per evaluated row (and, for Nelder-Mead, the initial simplex), so its memory grows with the evaluated rows.
history_stride and history_limit thin the iteration records but not the initial-simplex fields of NelderMeadResult.
TrustRegionOptions.retain_derivatives and LeastSquaresOptions.retain_derivatives drop the gradients, steps, and Hessian or Jacobian matrices of the trial records.
LimitedMemoryBFGSOptions has the same three switches as LocalOptions. With retain_derivatives=False its records also skip the copy of the curvature pairs, so the history no longer grows with memory_size * n_variables per iteration.
retain_derivative_records (default False) adds the finite-difference records of each iteration; see Finite-difference records.
It is independent of retain_derivatives and of history thinning, and a record holds about 2 n rows per gradient and 2 n**2 rows per Hessian.
BayesianOptions separately controls surrogate and trial-point records (retain_surrogates, retain_trial_points).
The constrained methods have their own switches, all default True:
| Switch | Methods | Effect when False |
|---|---|---|
retain_evaluations |
SLP, SQP, MMA | Each record's evaluation (the ObjectiveEvaluation of its point, from the objective call that produced objective_value) is None |
retain_derivatives |
SLP, SQP, MMA | linearization is None; SQP curvature_matrix and the MMA positive_coefficients and negative_coefficients are None; SLP elastic LPs keep no tableau |
retain_inner_results |
augmented Lagrangian, penalty and barrier | Each record's inner_result is None |
A record with retain_derivatives=True keeps about n + n * (m + p) more numbers for n variables, m inequality residuals, and p equality residuals; SQP adds n * n.
No switch changes the points, the counts, the statuses, or a stop decision, and the stop callback sees every completed record, also with history_limit=0.
With Bayesian history_limit=0, no acquisition records are retained; completed iteration counts and stop callbacks remain.
SamplingResult retains the complete evaluated sweep separately from iteration history.
Full retention is the default. SamplingOptions(retain_populations=False) drops the evaluated arrays (they become None) and keeps the selected observation (selected_observation_index, selected_constraints), so the result memory does not grow with the row count.
lazy_sampling=True also keeps the generated rows of later batches out of memory until their batch runs.
Population methods preserve supplied initial designs, including with a supplied sampler or zero generations. Refinement phases and log copies retain linear and integer metadata. Combined search and refinement histories use completed search iterations to offset refinement identifiers. Each retained phase result keeps its original identifiers. Capped histories therefore preserve the combined time coordinate.
plotting draws retained evidence. Each function shows one view:
| View | Function | Retained evidence |
|---|---|---|
| Design and objective histories with a contour and path | plot_results (summary) or plot_point_optimization_results (dashboard with surface, constraint, normalized, per-variable, and pairwise projection panels) |
Point and objective histories |
| Value, final-minus-current, and normalized history of each design variable, one figure per variable | plot_point_design_variable_summaries |
Point history |
| Objective contour of a callback | plot_point_optimization_contour_2d |
None; it evaluates the callback on the bounds, or draws a prepared LandscapeGrid |
| Constraint boundaries in existing axes | plot_constraint_boundaries_2d |
Precomputed inequality and equality values on a two-dimensional grid |
| Pareto front and Pareto designs | plot_point_multiobjective_optimization_results |
Pareto archive and final population |
| Raw objective columns of a scalarized run | plot_point_scalarized_objective_results |
Point and objective histories; the objective is evaluated again on the recorded designs unless base_objectives is supplied |
| Path projections for each variable pair beside the objective history | plot_objective_value_progress_nd |
Point and objective histories |
| Constrained path and largest constraint violation | plot_constraint_optimization_progress |
ConstrainedIteration records |
| Gradient norms and step sizes | plot_gradients |
GradientIteration derivatives |
| Gradient and search-direction vectors | plot_point_gradient_progress |
GradientIteration derivatives |
| One line search | plot_line_search (trial curve) or plot_point_line_search_progress (phases, selected step, fallback) |
Line-search trace |
| Bayesian surrogate | plot_bayesian (final model) or plot_bayesian_progress_1d (each iteration's model and the acquisition of the previous model) |
Retained surrogates |
| Bayesian run history | plot_bayesian_history (best objective and largest acquisition value of each retained iteration; any dimension, no model, no objective call) |
BayesianIteration records |
| Populations | plot_population, animate_population, or plot_population_progress |
PopulationIteration records |
The plot functions return PlotResult or AnimationController objects instead of changing global figure state.
The examples point_progress_views.py and population_progress_views.py replay point and population searches in these progress views, with sliders over the retained iterations.
Figure style:
-
A plot that creates its own figure uses the shared DesignOptPy style (
designoptpy.core.plotting.style.figure_style): the Computer Modern font, Paul Tol's colorblind-safe colors, and the constrained layout. A plot that draws into a suppliedaxkeeps the caller's font and sizes. -
Green marks only feasible, accepted, or kept designs, and red only infeasible, rejected, or discarded ones, always with a second cue (marker shape, fill, or hatching). Other series take blue, cyan, yellow, and purple.
-
Objective backgrounds are a light field with thin contour lines. A level count places the levels at value quantiles, so steep fields still show their valleys; the colorbar says so when the quantile rule set the levels.
-
Legends sit above the panels. In
plot_objective_value_progress_ndand in the whole-space panel ofplot_point_gradient_progress, a dense design path marks about ten landmark designs instead of every design; the other dense histories draw lines without markers. Converged populations in static population figures are zoomed, the title says so, and grey triangles on the edges mark designs outside the zoom. -
Design-space panels of coordinates with comparable bound spans (within a factor of four) use equal scaling, so distances and angles are true. Animations keep one panel layout in every frame.
-
plot_point_gradient_progressdraws the gradient and the search direction as long as the step by default (arrow_scale=None): the arrows show directions, and the legend states both norms. A number forarrow_scaledraws both vectors at that multiple, so their lengths stay comparable. -
plot_constraint_optimization_progressevaluates the constraints once at the start design (evaluate_start_constraints=True), so the violation history starts at iteration 0. This can run the constraint callbacks once more;Falseavoids it. -
Large differential-evolution and genetic-algorithm stage figures draw the connector lines of at most 12 evenly spaced targets or couples; the title states the count. Markers show every design.
-
Stage figures trace one decision through all stages with dark rings and lines (one target, couple, or particle) and count designs that stack on one point. A count includes the designs within 0.5 % of the bound range of both plotted coordinates of the most crowded design; the figure footnote states this.
-
selected_pairs=[(0, 2)]makes a stage figure show chosen coordinate pairs; one pair gives a two-by-two grid of the four stages. Use one pair for a report or a slide: the four-column figures of many pairs are for screen inspection. -
column="single"draws a stage figure 3.4 inches wide, the width of one column of a two-column paper, with 9-point text, so the text keeps its size in print. Each pair takes a two-by-two grid of its four stages, and particle-swarm panels take two columns. Withoutselected_pairs, the figure shows four panels: the first pair of a staged figure, or the first four particle-swarm pairs. Long titles, legend entries, and the footnote break into lines. The defaultcolumn="full"keeps the full-width figure. The generic view (stage="none") rejects"single". The single-view functionsplot_line_search,plot_point_line_search_progress,plot_bayesian, andplot_point_optimization_contour_2dacceptax=to draw into an existing axes. The Bayesian frames and history and the one-pair population view are golden landscapes (6.4 by 3.955 inches); the variable summaries ofplot_point_design_variable_summaries(three stacked panels) are golden portraits (5.253 by 8.5 inches); figures with side-by-side panels keep their sizes (see Figure shapes).PlotOptions.save_pathand thesave_folderof the Bayesian frames save throughdesignoptpy.core.plotting.save_figure: raster images at 200 dots per inch unlesssave_optionsgives"dpi", the whole figure without a tight crop, and the editable figure file<name>.pickle.gzbeside each image (save_options={"pickle_file": False}leaves it out). The other views create their own figure. Constraint boundaries: -
plot_constraint_boundaries_2d(ax, x_grid, y_grid, inequality_values, equality_values)adds zero-level constraint contours to existing axes and returns separate tuples of contour handles. -
Residual rows follow NumPy row order:
[x_grid.ravel()[k], y_grid.ravel()[k]]for rowk. -
An absent constraint kind accepts
Noneor an empty array and returns an empty tuple. -
Default inequality boundaries are solid dark grey lines and equality boundaries are dashed purple lines, with numbered labels
inequality boundary <k>andequality boundary <k>. Red is kept for infeasible designs: the result dashboard and the constraint-progress plot shade the region where an inequality is violated with red hatching. -
The result dashboard and constraint-progress plot use the same boundary function.
-
The contours interpolate sampled values. A coarse grid can miss small features, and a zero without a sign change need not produce a boundary. Solver feasibility tolerances do not move these contours.
-
plot_point_optimization_results(..., constraint_function=callback)overrides the plotted constraint callback. It keeps the constraints of the saved optimization problem unchanged.
Population and animation plots:
plot_population_progressshows the current and next populations by default.stage="differential_evolution","genetic_algorithm", or"particle_swarm"shows the recorded decisions of that algorithm, andstage="auto"selects them from the record type.- The generic view shows the first six variables (
MAX_MATRIX_VARIABLES) as a lower-triangle scatterplot matrix.selected_variables=(0, 3, 7)shows the chosen variables instead, in this order, with no upper limit.kvariables givek(k - 1)/2panels, and the title notes", 3 of 8 variables"when the selection leaves variables out. A stage figure takesselected_pairsinstead and rejectsselected_variables. PlotOptionsseparates figure, line, axes, legend, grid, export, and close-after-save settings.AnimationOptionsholds every animation setting: frame rate, theslider(SliderOptions), writer, dots per inch (DPI), still-image and animation export, andselected_framesfor still images.plot_create_gif_video_slideranimates any figure through one frame-update callback.
Bayesian progress plots:
plot_bayesian_progress_1ddraws one frame for the initial data and one for each selected iteration of a one-variable run. The upper panel shows the model prediction with its 95 % band (mean plus or minus 1.96 standard deviations); the lower panel shows the acquisition of the previous model, which chose the new design. A band edge that overflows to an infinity (|mean| + 1.96 * standard_deviationabove about 1.8e308) raisesValueError.objective_curve="evaluate"(the default) calls the problem objective once with all grid rows."omit"draws no objective curve and calls nothing. A finite array of shape(n, 2)(design, objective) is drawn as given, also without calls. These evaluations are outside the solver counts.max_evaluation_points(default 1000000) capsnumber_evaluation_points; a larger grid raisesValueErrorbefore any allocation or call.acquisition_functionnames the acquisition of the run:Noneorexpected_improvement(the solver default),probability_of_improvement, or another callable. Pass the function that the run used: the result does not record it, and the panel texts and the numerically-zero test follow this choice.figure_optionsapplies Matplotlib figure properties to every frame, for example{"facecolor": "#eeeeee"}.- Saved frames are
InitialData.pngandIteration-<n>.png;<n>is padded to the digits of the largest retained iteration number, so the names sort in iteration order. plot_bayesian_historydraws the best objective and the largest acquisition value of each retained iteration against the iteration number. It needs no model and calls no objective, so it works for any number of design variables and withoutretain_surrogates. A gap in the retained iteration numbers breaks the lines.- Under modeled feasibility, both views name the plotted score by the
acquisition_kindof each record. A frame of kind"feasibility_weighted"draws the acquisition timesprevious_feasibility_model.probability(grid)and readsEI × PF; a frame of kind"feasibility"draws PF alone and states that no feasible observation exists yet. Such a frame needsprevious_feasibility_model. The history view then draws one series per kind (circles, diamonds, squares), joins no points of different kinds, and labels the panellargest search score. Runs without modeled feasibility keep every text.
Progress plot layout:
- Plots draw every requested view. A progress plot of
nvariables showsn(n-1)/2coordinate pairs and one objective-history panel by default. - To show fewer views, use
selected_pairsorpanel_budget.panel_budgetkeeps the objective history. subplot_structure="grid"(the default) arranges a two-column dashboard in one figure;"horizontal"puts all panels in one row and"vertical"in one column.- The dashboard arrow defaults to
gradient_policy="reference", a finite-difference gradient at the start design with the controls ofReferenceGradientOptions(gradient_options).gradient_policy="retained"draws the first saved gradient inside the plotted slice without a callback;"none"omits the arrow. pairwise_projections=Trueadds one dashboard panel per coordinate pair: the recorded path, and each recorded design colored by its recorded objective value.selected_pairs=[(0, 2)]chooses the pairs (zero-based, in the given order and orientation); without it, the panels show every pairi < j.maximum_history_ticks=mlabels at mostmretained iteration coordinates on every iteration axis of the dashboard, always with the first and the last. The default None keeps at most six automatic whole-number ticks. Limiting tick labels changes axis decoration. It does not remove history samples.plot_point_design_variable_summariesdraws one figure per design variable, with its value, final-minus-current, and normalized histories on one iteration axis. A foldersave_pathreceivesdesign_variable_summary_<k>.pngfor each variablek.- Each objective or constraint background evaluates the model at
contour_resolution**2grid points for each evaluated grid (one per displayed pair). These evaluations are outside the completed solver counts. Disabling both backgrounds avoids model work. max_landscape_evaluations(default 1,000,000) caps the grid points of one view, summed over its grids, and is checked before the first callback. A larger landscape raisesValueErrorthat names the keywords that make it smaller.Noneremoves the cap.landscape_batch_sizeevaluates the grid rows in consecutive blocks of at most that many rows per callback call (objective, merit, and constraint callbacks). The values do not depend on the block size. The defaultNoneevaluates each grid in one call.- For more than two dimensions, unplotted coordinates stay at
initial_point. - With infinite bounds, contours use finite display extents from the recorded trajectory. The problem does not change.
- Plots reject complex callback values before numeric conversion, including complex values with zero imaginary parts.
Plotters use retained iteration identifiers and each record's pre-step origin under sparse history.
Merit contours:
-
Landscape contours use
result.merit_function(points). This method rebuilds the merit fromresult.problemand the savedevaluation_options, so the background always matches the policy of the method. -
Without
evaluation_options, for example in a result built by hand, contours use the problem objective. -
The merit adds no local function to a result, so a solver result whose callbacks are module-level functions can be saved with
pickle. This also holds for asolveworkflow result that retains phase results (search_result,refinement_result) or a recoveryfeasibility_result. -
objective_landscape(result)evaluates the landscape of coordinates 0 and 1 once and returns aLandscapeGrid(nodesxandy, valuesvalues[row, column]at(x[column], y[row])). The viewsplot_point_optimization_results,plot_point_optimization_contour_2d,plot_point_gradient_progress,plot_constraint_optimization_progress, andplot_population_progresstake it aslandscape_grid=and draw it without objective calls:grid = objective_landscape(result) plot_point_optimization_results(result, landscape_grid=grid) plot_point_gradient_progress(result, landscape_grid=grid)
With a prepared grid,
contour_resolutionandcontour_use_design_space_limitsdo not choose the grid. A panel with coordinate 1 across uses the transposed grid. Constraint boundaries are still evaluated on the grid points, and the dashboard's schematic gradient arrow still evaluates finite differences unlessgradient_arrow_scale=0orshow_contour=False. -
Positive infinity in a landscape marks an unavailable value, for example a design that the model rejects. The plots mask it: levels, field, and colorbar use the finite values, the field leaves out every grid cell with an unavailable corner, and a grey cross hatch with the legend entry "objective unavailable" covers these cells (the dashboard surface has holes there). White is the low end of the field, so a blank area would read as low values. NaN, negative infinity, and a landscape without a finite value raise
ValueError. Contour line options cannot restore corner masking, which would draw lines inside these cells: acorner_maskother thanFalseraisesValueError.
Counted callbacks and the rebuild:
- During the run, the phases of a workflow call counted callbacks, which count rows and enforce the evaluation budget.
- When the workflow returns,
solvegives the retained results the caller's callbacks instead. A recovery result gets the violation of the caller's constraints as its objective. - This rebuild is recursive, so it also reaches the phases of a nested workflow result that a custom
SolverSpecsolver returns. - Their
merit_functiontherefore calls the caller's model directly. It adds no row to the finished run and cannot raiseEvaluationBudgetExceededError. - The
inner_resultrecords of the augmented Lagrangian and penalty methods are an exception, because their subproblems keep the counted callbacks of the run. Their merit can therefore raiseEvaluationBudgetExceededErrorafter the run used its whole budget, and these records cannot be saved withpickle.
Omitted evidence and constraint plots:
- Requesting omitted derivative, line-search, or acquisition evidence raises an explicit error.
- Bayesian progress frames require saved prediction models. Keep
BayesianOptions(retain_surrogates=True)and suitable history.plot_bayesian_historyneeds only the retained records. Seeplotting/bayesian.pyfor the saved-model learning views. - Constraint plots align each objective and violation with its record's iteration identifier.
- The violation curve shows the largest positive inequality or absolute equality residual (
ConstraintValues.violation), without a tolerance allowance. Small positive values can therefore coexist with accepted feasibility under source tolerances. - Residual scaling affects this raw value. It is not necessarily the solver merit or recovery objective.
- A two-objective view of a higher-dimensional Pareto archive can contain dominated projections. Connecting archive points does not certify a continuous frontier or feasible intermediate designs.
Shared definitions
problem.pydefines design bounds, objectives, constraints, and evaluation budgets.least_squares.pydefines residual problems, common residual evaluation, and least-squares results.evaluation.pydefines scalarization and constraint merit terms. Methods usingObjectiveEvaluatordifferentiate and report its configured scalar, which can differ from the raw objective. Scalarizers select limit violation before nominal deviation before raw value, separately for each objective column. Paired limit violations are added. Derived divisors use target width, upper magnitude, lower magnitude, then nominal magnitude. The first positive finite candidate is used; otherwise the divisor is one. Only limit violations use these divisors. NaN omits a target term. Outward infinite limits yield zero violation but still select the limit term.differentiation.pyandline_search.pycontain shared numerical routines. Optimizers reuse these routines instead of maintaining copies.options.pyandresults.pydefine common input and result rules. These includeLocalOptions,PopulationOptions,GradientIteration,OptimizationResult, the constrained evidence recordsConstraintLinearizationandStationarityEvidence, the simplex evidence records, and the stop-rule stateConvergenceState.program_models.pyandcoefficients.pydefine LP and QP models and coefficient recovery.methods/population.pyandmethods/constrained.pyhold the public records of their method family and the support that the family shares.population.pydefinesPopulationStateand the built-in criteriapopulation_objective_rangeandbest_objective_change;constrained.pydefinesStationarityOptionsandverify_constrained_stationarity. The privatemethods/_gradient.pymodule contains support shared between the gradient methods. It also defines the objective-change stop ruleobjective_change_within_tolerance, which the package root exports and the local, constrained, and population criteria share. Plotting uses its own package.
benchmarks.BenchmarkDefinition keeps each experiment's regime, output labels, and units with its formula.
An all-good-shape-only entry accepts every design in its domain and cannot test good-versus-bad classification.
Levy-2 states this regime explicitly because its finite upper limit accepts every response in its domain.
The micro-actuator entries label pull-in displacement in micrometers and pull-in voltage in volts.
MicroActuator3D-Log10Voltage replaces the voltage by its base-10 logarithm, with the upper limit log10(100) = 2.
The logarithm is strictly increasing, so the good designs and the classification boundary stay the same.
Only the output scale changes: the voltage spans several decades over the domain, and its logarithm spans a few units.
A regression surrogate then fits a well-scaled target. A label-only classifier gives the same result on both scales.
Other entries default to Output 1, Output 2, and so on, with dimensionless units.
The A-space holds early-decision variables. The B-space holds late-decision variables used for compensation.
Local verification
From designoptpy, run the behavioral tests and executable method examples:
python run_all_tests.py packages/designoptpy-point/tests --fail-on-skips --junit-file .artifacts/point-tests.xml
python -m pytest --doctest-modules packages/designoptpy-point/src/designoptpy/point/methods -p no:cacheprovider
Run workspace qualification with run_local_quality_checks.py and the existing specialized local test groups.
Store generated check reports below .artifacts.
Metadata
Release files for designoptpy-point 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| designoptpy_point-0.1.0.tar.gz | 1.4 MB | Without provenance | Details for designoptpy_point-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| designoptpy_point-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for designoptpy_point-0.1.0-py3-none-any.whl |
Total release size: 2.3 MB
Release files / designoptpy_point-0.1.0.tar.gz
| Download URL | designoptpy_point-0.1.0.tar.gz |
|---|---|
| Size | 1.4 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f66024bd97323b6214faa5fedda167ab2a4deed994f87c3365cf805ad715894f
|
|
BLAKE2b-256 checksum How to use checksums |
54fa383425b99f3cef294e6fd88beb98123e46b825ad35196043dd400dd707cd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.7.17
|
Release files / designoptpy_point-0.1.0-py3-none-any.whl
| Download URL | designoptpy_point-0.1.0-py3-none-any.whl |
|---|---|
| Size | 913.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
535d2cc400359c3fd7999f69f081d2aff31d3fe8562ac5b92dcacee327a8569a
|
|
BLAKE2b-256 checksum How to use checksums |
0f7534c1910f23f7e567a0ad03b597bfdf39ab72e2478e6bbdc81bb3b90b2568
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.7.17
|
Security for designoptpy-point 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.