Skip to main content

pounce_algorithm/
alg_builder.rs

1//! Algorithm builder — port of `Algorithm/IpAlgBuilder.{hpp,cpp}`.
2//!
3//! Reads `OptionsList`, walks the dependency order documented in
4//! `ref/Ipopt/AGENT_REFERENCE/ARCHITECTURE.md` §"BuildBasicAlgorithm",
5//! and assembles the strategy objects needed by `IpoptAlgorithm`:
6//!
7//! * `SymLinearSolver` (MA57 / MUMPS / FERAL) → `AugSystemSolver`
8//!   (`StdAugSystemSolver`) → `PdSystemSolver` (`PdFullSpaceSolver`)
9//!   → `SearchDirCalculator` (`PdSearchDirCalc`).
10//! * `BacktrackingLsAcceptor` (filter / penalty / cg-penalty) →
11//!   `BacktrackingLineSearch`.
12//! * `MuUpdate` (monotone / adaptive[+oracle]).
13//! * `ConvCheck` (`OptErrorConvCheck`).
14//! * `IterateInitializer` (default / warm-start) and
15//!   `EqMultCalculator` (`LeastSquareMults`).
16//! * `HessianUpdater` (exact / limited-memory).
17//! * `IterationOutput` (`OrigIterationOutput`).
18//! * `NLPScalingObject` (none / user / gradient-based / equilibration-based).
19//!
20//! Phase 7 ships the option-driven dispatch surface; the assembled
21//! `IpoptAlgorithm` lands once each strategy's arithmetic does.
22
23use crate::conv_check::opt_error::OptErrorConvCheck;
24use crate::eq_mult::least_square::LeastSquareMults;
25use crate::hess::exact::ExactHessianUpdater;
26use crate::hess::lim_mem_quasi_newton::{InitialApprox, LimMemQuasiNewtonUpdater, UpdateType};
27use crate::init::default::DefaultIterateInitializer;
28use crate::init::warm_start::WarmStartIterateInitializer;
29use crate::kkt::aug_system_solver::AugSystemSolver;
30use crate::kkt::low_rank_aug_system_solver::LowRankAugSystemSolver;
31use crate::kkt::pd_full_space_solver::PdFullSpaceSolver;
32use crate::kkt::pd_search_dir_calc::PdSearchDirCalc;
33use crate::kkt::perturbation_handler::PdPerturbationHandler;
34use crate::kkt::std_aug_system_solver::StdAugSystemSolver;
35use crate::line_search::backtracking::BacktrackingLineSearch;
36use crate::line_search::filter_acceptor::FilterLsAcceptor;
37use crate::line_search::ls_acceptor::BacktrackingLsAcceptor;
38use crate::line_search::penalty_acceptor::PenaltyLsAcceptor;
39use crate::mu::adaptive::{AdaptiveMuUpdate, MuOracleKind};
40use crate::mu::monotone::MonotoneMuUpdate;
41use crate::output::orig::OrigIterationOutput;
42use pounce_common::types::{Index, Number};
43use pounce_linsol::{SparseSymLinearSolverInterface, TSymLinearSolver};
44use std::cell::RefCell;
45use std::rc::Rc;
46
47/// Backend factory — the application supplies one before calling
48/// [`AlgorithmBuilder::build`]. Mirrors upstream's
49/// `SymLinearSolverFactory` knob in `IpAlgBuilder.cpp`. The default
50/// factory wires in FERAL; MA57 is selectable when the `ma57` cargo
51/// feature is enabled.
52pub type LinearBackendFactory =
53    Box<dyn FnMut(LinearSolverChoice) -> Box<dyn SparseSymLinearSolverInterface>>;
54
55/// Top-level algorithm choice. `InteriorPoint` is pounce's default
56/// (the existing `IpoptAlgorithm`); `ActiveSetSqp` is the
57/// Phase 5b SQP driver in `crate::sqp::SqpAlgorithm`, which uses
58/// `pounce-qp` for QP subproblem solves and reuses
59/// `FilterLsAcceptor` for globalization.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
61pub enum AlgorithmChoice {
62    #[default]
63    InteriorPoint,
64    ActiveSetSqp,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum LinearSolverChoice {
69    Ma57,
70    Feral,
71}
72
73/// Symmetric scaling method applied to the augmented KKT system by
74/// [`TSymLinearSolver`]. Mirrors the `linear_system_scaling` option
75/// in `IpAlgBuilder.cpp:302-318` and the `RuizTSymScalingMethod` /
76/// `Mc19TSymScalingMethod` strategies in upstream Ipopt.
77///
78/// * `None` (default) — no scaling; `TSymLinearSolver` runs with a
79///   null scaling method. Matches upstream's default.
80/// * `Ruiz` — iterative symmetric ∞-norm equilibration (Ruiz, 2001).
81///   Implemented in `pounce_linsol::RuizTSymScalingMethod`.
82/// * `Mc19` — Curtis-Reid (HSL MC19) scaling. Not yet implemented;
83///   falls back to `None` with a warning.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
85pub enum LinearSystemScalingChoice {
86    #[default]
87    None,
88    Ruiz,
89    Mc19,
90    /// `slack-based` — `IpSlackBasedTSymScalingMethod`. Unlike the
91    /// others this one is a function of the iterate, not of the matrix,
92    /// so the algorithm pushes the `s`-block factors down each
93    /// iteration (see `IpoptAlgorithm::push_slack_scaling`).
94    SlackBased,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum MuStrategyChoice {
99    Monotone,
100    Adaptive,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum HessianApproxChoice {
105    Exact,
106    LimitedMemory,
107    /// Partitioned quasi-Newton: one small dense block per element
108    /// function (the objective and each constraint row), assembled into
109    /// a genuine sparse `SymTMatrix`. See
110    /// [`crate::hess::partitioned_quasi_newton`].
111    Partitioned,
112    /// Sparse finite-difference Lagrangian Hessian, recovered by graph
113    /// coloring from the analytic Jacobian. See
114    /// [`crate::hess::fd_hessian`].
115    FiniteDifference,
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum LineSearchChoice {
120    Filter,
121    CgPenalty,
122    Penalty,
123}
124
125/// Assembled strategy bundle. Phase 7 ships the structural bundle;
126/// `IpoptAlgorithm::new` reads from this when it lands.
127pub struct AlgorithmBundle {
128    pub mu_update: Box<dyn crate::mu::r#trait::MuUpdate>,
129    pub conv_check: Box<dyn crate::conv_check::r#trait::ConvCheck>,
130    pub init: Box<dyn crate::init::r#trait::IterateInitializer>,
131    pub eq_mult: Box<dyn crate::eq_mult::r#trait::EqMultCalculator>,
132    pub hess: Box<dyn crate::hess::r#trait::HessianUpdater>,
133    pub line_search: BacktrackingLineSearch,
134    pub iter_output: Box<dyn crate::output::r#trait::IterationOutput>,
135    /// `Some` when the builder was given a [`LinearBackendFactory`];
136    /// `None` for the bare structural bundle that pre-Phase-6 unit
137    /// tests still rely on.
138    pub search_dir: Option<PdSearchDirCalc>,
139}
140
141/// Knobs read off `OptionsList` and baked into the assembled
142/// `OptErrorConvCheck`. Defaults mirror
143/// `IpOptErrorConvCheck.cpp:RegisterOptions`.
144#[derive(Debug, Clone)]
145pub struct ConvCheckOptions {
146    pub tol: Number,
147    pub dual_inf_tol: Number,
148    pub constr_viol_tol: Number,
149    pub compl_inf_tol: Number,
150    pub acceptable_tol: Number,
151    pub acceptable_dual_inf_tol: Number,
152    pub acceptable_constr_viol_tol: Number,
153    pub acceptable_compl_inf_tol: Number,
154    pub acceptable_obj_change_tol: Number,
155    pub acceptable_iter: Index,
156    pub max_iter: Index,
157    pub max_cpu_time: Number,
158    pub max_wall_time: Number,
159    pub infeas_stationarity_tol: Number,
160    pub infeas_viol_kappa: Number,
161    pub infeas_max_streak: Index,
162    /// Objective-scale floor below which a strict termination certificate is
163    /// refused while the unscaled KKT error is still above `acceptable_tol`
164    /// (gh #200). `0` disables the mechanism.
165    pub obj_scale_certificate_threshold: Number,
166    /// Safety factor on the per-row floor the **strict** gate uses to decide
167    /// when a constraint residual is finer than the row can represent
168    /// (gh #528). `0` disables the floor, restoring upstream Ipopt's
169    /// bare-absolute primal term.
170    pub primal_noise_floor_kappa: Number,
171    /// Fraction of `acceptable_tol` the KKT error and the objective may drift
172    /// across the acceptable-level streak's window while the streak still
173    /// counts as settled (gh #533). `0` disables the progress test, leaving
174    /// acceptable-level termination the bare consecutive-count criterion.
175    pub acceptable_progress_kappa: Number,
176    /// Safety factor on the scale-relative floor under `dual_inf_tol` the
177    /// **strict** gate judges the dual infeasibility against (gh #532). `0`
178    /// disables the floor, restoring upstream Ipopt's bare-absolute bound.
179    pub dual_inf_scale_kappa: Number,
180}
181
182impl Default for ConvCheckOptions {
183    fn default() -> Self {
184        Self {
185            tol: 1e-8,
186            dual_inf_tol: 1.0,
187            constr_viol_tol: 1e-4,
188            compl_inf_tol: 1e-4,
189            acceptable_tol: 1e-6,
190            acceptable_dual_inf_tol: 1e10,
191            acceptable_constr_viol_tol: 1e-2,
192            acceptable_compl_inf_tol: 1e-2,
193            acceptable_obj_change_tol: 1e20,
194            acceptable_iter: 15,
195            max_iter: 3000,
196            max_cpu_time: 1e6,
197            max_wall_time: 1e6,
198            infeas_stationarity_tol: 1e-8,
199            infeas_viol_kappa: 1e2,
200            infeas_max_streak: 5,
201            obj_scale_certificate_threshold: 1e-4,
202            primal_noise_floor_kappa: 64.0,
203            acceptable_progress_kappa: 1e-1,
204            dual_inf_scale_kappa: 1.0,
205        }
206    }
207}
208
209/// A block-parallel KKT partition published after a builder was cloned —
210/// see [`AlgorithmBuilder::kkt_blocks_shared`]. `None` inside means the outer
211/// solve resolved no partition, and the clone builds the standard solver.
212pub type KktBlocksCell =
213    std::sync::Arc<std::sync::Mutex<Option<(Vec<i32>, pounce_feral::FeralConfig)>>>;
214
215#[derive(Debug, Clone)]
216pub struct AlgorithmBuilder {
217    /// Top-level algorithm dispatch. Default `InteriorPoint` ⇒
218    /// `build_with_backend` returns the existing `AlgorithmBundle`
219    /// (consumed by `IpoptAlgorithm`). `ActiveSetSqp` ⇒ caller
220    /// must use `build_sqp_with_backend` to assemble the Phase 5b
221    /// `SqpAlgorithm`. The two builder methods sit side by side
222    /// because the assembled algorithm shape differs (IPM bundle
223    /// vs SQP struct).
224    pub algorithm: AlgorithmChoice,
225    pub linear_solver: LinearSolverChoice,
226    /// Symmetric scaling method for the augmented KKT system. Wired
227    /// into [`TSymLinearSolver`] by [`Self::build_with_backend`].
228    /// Mirrors upstream `linear_system_scaling` (`IpAlgBuilder.cpp:538-560`).
229    pub linear_system_scaling: LinearSystemScalingChoice,
230    /// Lazy-vs-eager scaling toggle (`linear_scaling_on_demand`,
231    /// `IpTSymLinearSolver.cpp:50-58`). Only consulted when
232    /// `linear_system_scaling != None`. Upstream default is `true`
233    /// (compute scaling only on the first solve that fails / shows
234    /// poor conditioning); pounce mirrors that. Set to `false` to
235    /// scale every factorization.
236    pub linear_scaling_on_demand: bool,
237    pub mu_strategy: MuStrategyChoice,
238    /// Selector forwarded to [`AdaptiveMuUpdate`] when
239    /// `mu_strategy = Adaptive`. Ignored for `Monotone`. Defaults to
240    /// `QualityFunction` per upstream's `RegisterOptions` default.
241    pub mu_oracle: MuOracleKind,
242    pub hessian_approximation: HessianApproxChoice,
243
244    /// Element update formula for
245    /// [`HessianApproxChoice::Partitioned`] (`partitioned_update_type`).
246    /// SR1 by default: a single constraint is not convex, so damped
247    /// BFGS would force every `∇²c_j` model PSD and then scale it by a
248    /// multiplier of either sign.
249    pub partitioned_update_type: UpdateType,
250    /// Whether the caller named `partitioned_update_type` explicitly, so
251    /// the block mode's BFGS default does not override them.
252    pub partitioned_update_type_was_set: bool,
253    /// Widest element that keeps a dense block under
254    /// [`HessianApproxChoice::Partitioned`]; wider elements degrade to a
255    /// diagonal approximation (`partitioned_max_element`).
256    pub partitioned_max_element: usize,
257    /// Variables the **objective** is nonlinear in, in the compressed
258    /// `x_var` space — `TNLPAdapter::objective_nonlinear_vars`. Consumed
259    /// by both the partitioned updater (as its objective element's
260    /// support) and the finite-difference updater (as the objective's
261    /// contribution to a Jacobian-derived Hessian pattern, which the
262    /// constraint Jacobian cannot supply). `None` leaves each to fall
263    /// back on the first `∇f`'s nonzeros, which is value-derived; see
264    /// that method for what it costs.
265    pub objective_nonlinear_vars: Option<Vec<Index>>,
266    /// The TNLP's declared Lagrangian Hessian sparsity in the compressed
267    /// `x_var` space, `(row >= col)`, when it has one and
268    /// `partitioned_structure` is `declared` (gh#989 item 5). Consumed by the
269    /// partitioned updater to split each element along the pattern.
270    pub hessian_declared_pattern: Option<Vec<(Index, Index)>>,
271    /// `partitioned_curvature_cap` — multiple of an element's implied
272    /// curvature that one update may reach. See
273    /// [`crate::hess::partitioned_quasi_newton`].
274    pub partitioned_curvature_cap: Number,
275    /// How the Lagrangian is split into elements under
276    /// [`HessianApproxChoice::Partitioned`] (`partitioned_elements`).
277    pub partitioned_elements: crate::hess::partitioned_quasi_newton::ElementMode,
278    /// Target primal-block width when `partitioned_elements` is
279    /// `blocks` (`partitioned_block_size`).
280    pub partitioned_block_size: usize,
281    /// Where [`HessianApproxChoice::FiniteDifference`] takes its
282    /// sparsity pattern from (`fd_hessian_pattern`).
283    pub fd_hessian_pattern: crate::hess::fd_hessian::FdPatternSource,
284    /// How finite-difference probe groups are formed
285    /// (`fd_hessian_coloring`).
286    pub fd_hessian_coloring: crate::hess::fd_hessian::FdColoring,
287    /// Relative movement in `x` AND `y` below which the previous Hessian
288    /// is reused (`fd_hessian_reuse_tol`). `0` rebuilds every iteration.
289    pub fd_hessian_reuse_tol: Number,
290    pub limited_memory_update_type: UpdateType,
291    /// History length for the limited-memory quasi-Newton approximation
292    /// (`limited_memory_max_history`). Defaults to upstream's 6.
293    pub limited_memory_max_history: i32,
294    /// `limited_memory_init_val_max` / `_min` — the clamp on the initial
295    /// Hessian scalar σ before the rank-2 updates. Upstream defaults 1e8
296    /// / 1e-8, which `LimMemQuasiNewtonUpdater` has carried as hard-coded
297    /// fields and consumed in `initial_hessian_scalar` all along; only
298    /// the read sites were missing (gh#483, #191 round 2).
299    pub limited_memory_init_val_max: Number,
300    pub limited_memory_init_val_min: Number,
301    /// `limited_memory_initialization` — which formula picks the initial
302    /// Hessian scalar σ. Matches upstream's `scalar1` (σ = sᵀy/sᵀs).
303    /// pounce shipped `scalar2` (σ = yᵀy/sᵀy) with no way to change it,
304    /// because the option was registered and never read (#677).
305    pub limited_memory_initialization: InitialApprox,
306    /// `limited_memory_init_val` — σ on the first iteration, before any
307    /// curvature pair exists, and every iteration under
308    /// `InitialApprox::Constant`. Upstream default 1.0.
309    pub limited_memory_init_val: Number,
310    /// `limited_memory_max_skipping` — consecutive skipped curvature
311    /// updates before the approximation is discarded (#686). Upstream
312    /// default 2.
313    pub limited_memory_max_skipping: Index,
314    /// Positions in the algorithm's compressed `x_var` space that enter
315    /// the problem *nonlinearly* (gh#624). `None` — the default —
316    /// approximates the Hessian over every variable, which is what the
317    /// limited-memory path has always done. When set, the quasi-Newton
318    /// update is restricted to this subspace and the Hessian is exactly
319    /// zero elsewhere. Comes from
320    /// `TNLPAdapter::quasi_newton_nonlinear_vars` (the TNLP's
321    /// `get_list_of_nonlinear_variables`, or the `num_linear_variables`
322    /// prefix fallback) and is ignored on the exact-Hessian path.
323    ///
324    /// The restoration sub-IPM must clear this: the mask indexes the
325    /// original NLP's variables, not the restoration compound primal.
326    pub limited_memory_nonlinear_vars: Option<Vec<Index>>,
327    pub line_search_method: LineSearchChoice,
328    pub warm_start_init_point: bool,
329    /// `mehrotra_algorithm` — when true, [`PdSearchDirCalc`] folds
330    /// the Mehrotra second-order complementarity term into the
331    /// search-direction RHS. Mirrors upstream's
332    /// `IpAlgBuilder.cpp:Mehrotra` flag. Requires `mu_strategy =
333    /// Adaptive` so that an affine step is computed each iteration;
334    /// [`Self::build_with_backend`] does not enforce this — the
335    /// option-parser in `application.rs` is responsible for the
336    /// cascading defaults (`mu_oracle = probing` etc.).
337    pub mehrotra_algorithm: bool,
338    /// `fast_step_computation` — when true, [`PdSearchDirCalc`] accepts
339    /// the search direction without the residual check and allows an
340    /// inexact linear solve. Mirrors upstream's flag of the same name,
341    /// default `no`. The field existed and was consumed from the day the
342    /// search-direction calculator landed, hard-coded to `false`; only
343    /// the option's read site was missing, so setting it did nothing
344    /// (gh#483 follow-up, #191 round 2).
345    pub fast_step_computation: bool,
346    /// `kappa_sigma` — factor bounding how far the bound multipliers may
347    /// deviate from their primal estimates. The clamp
348    /// (`kappa_sigma_clamp`) runs after every accepted step; `< 1`
349    /// disables the correction. Mirrors `IpIpoptAlg.cpp` (Eqn. (16)),
350    /// default `1e10`. Baked onto [`crate::ipopt_alg::IpoptAlgorithm`] by
351    /// the solve path.
352    pub kappa_sigma: Number,
353    /// `ftb_centrality_floor` (pounce gh#1098) — γ of the
354    /// centrality-floored fraction-to-the-boundary rule; `0` restores
355    /// upstream's τ rule. Baked onto
356    /// [`crate::ipopt_alg::IpoptAlgorithm`] by the solve path.
357    pub ftb_centrality_floor: Number,
358    /// `recalc_y` / `recalc_y_feas_tol` — least-square re-estimation of
359    /// the equality multipliers once feasible (#677). Registered
360    /// upstream, refused by pounce as unimplemented until now. Default
361    /// `false` matches the registry; the limited-memory path turns it on
362    /// for itself in `application.rs`, as upstream's own option text
363    /// says it does.
364    pub recalc_y: bool,
365    pub recalc_y_feas_tol: Number,
366    /// `kappa_d` — weight of the linear damping term added to the barrier
367    /// objective/gradient (and dual-infeasibility) to handle one-sided
368    /// bounds. Mirrors `IpIpoptCalculatedQuantities.cpp`, default `1e-5`.
369    /// Baked onto [`crate::ipopt_cq::IpoptCalculatedQuantities`] by the
370    /// solve path.
371    pub kappa_d: Number,
372    /// `s_max` — cap on the average multiplier magnitude used to build
373    /// the `(s_d, s_c)` scaling factors of the KKT error test
374    /// (`IpIpoptCalculatedQuantities.cpp:ComputeOptimalityErrorScaling`,
375    /// the paragraph after Eqn. (6) of the implementation paper).
376    /// Registered default `100`, which is what
377    /// [`crate::ipopt_cq::IpoptCalculatedQuantities`] already carries as
378    /// its struct default, so forwarding it is behaviour-neutral for a
379    /// run that does not set it (#551 / #677). Baked onto the cq by the
380    /// solve path, next to `kappa_d`.
381    pub s_max: Number,
382    /// `tiny_step_tol` — relative primal step size below which the full
383    /// step is accepted without line search; repeated tiny steps
384    /// terminate the solve. Mirrors `IpBacktrackingLineSearch.cpp`,
385    /// default `10·EPSILON`. Baked onto
386    /// [`crate::ipopt_alg::IpoptAlgorithm`] by the solve path.
387    pub tiny_step_tol: Number,
388    /// `tiny_step_y_tol` — dual-step threshold; when both primal and dual
389    /// steps are tiny in consecutive iterations the algorithm stops at the
390    /// best attainable accuracy. Default `1e-2`.
391    pub tiny_step_y_tol: Number,
392    /// `diverging_iterates_tol` — if `max_i |x_i|` exceeds this the solve
393    /// aborts as diverging. Default `1e20`.
394    pub diverging_iterates_tol: Number,
395    /// `dual_diverging_streak` (pounce#246) — consecutive growing-dual-
396    /// infeasibility iterations before the dual-divergence guard routes to
397    /// restoration. **Default `0` (off).**
398    ///
399    /// It defaulted to `15` when introduced, on the strength of a reported
400    /// emfl050 bad-warm-start grind. That justification did not survive being
401    /// reproduced: the measurement was caller-side JAX compilation, and the
402    /// build predating the guard solves both emfl050 instances to the same
403    /// optimum in the same time (pounce#246 / pounce#250). What remained was a
404    /// knife-edge, non-monotone effect on four of 1284 MINLPLib models — so it
405    /// is opt-in rather than imposed. See `upstream_options.rs` for the full
406    /// account.
407    pub dual_diverging_streak: Index,
408    /// `dual_divergence_retry_step_tol` (gh#884) — the scale-relative
409    /// step `max_i |d_i| / (1 + |x_i|)` at or below which the biactive
410    /// dual-divergence detector calls the primal iterate *settled*.
411    /// Default `1e-5`; `0` disables the detector without disabling the
412    /// `dual_divergence_retry` option. See `upstream_options.rs` for the
413    /// measured population behind the default.
414    pub dual_divergence_retry_step_tol: Number,
415    /// `dual_divergence_retry_du_floor` (gh#884) — the *unscaled* dual
416    /// infeasibility at or above which the same detector calls the
417    /// multipliers *diverged*. Default `1e2`. Measured in the model's own
418    /// units on purpose: the `s_d`-normalised aggregate is what hid the
419    /// defect. See `upstream_options.rs`.
420    pub dual_divergence_retry_du_floor: Number,
421    /// `tiny_step_dual_stall_iters` — consecutive tiny primal steps with no
422    /// dual progress after which the tiny-step stop stops waiting for the
423    /// multiplier step. Default `10`; `0` is upstream's rule. See
424    /// `upstream_options.rs`.
425    pub tiny_step_dual_stall_iters: Index,
426    /// `resto_decline_deferrals` (gh #534) — how many times the
427    /// acceptable-point restoration decline may be deferred on a solve whose
428    /// NLP error is still contracting. Default `1`; `0` restores the pre-#534
429    /// behaviour (decline immediately, always). See `upstream_options.rs`.
430    pub resto_decline_deferrals: Index,
431    /// `resto_decline_progress_ratio` (gh #534) — required per-iteration
432    /// contraction of the NLP error before a decline is deferred. Default
433    /// `0.5`; at or above `1` the progress requirement is dropped entirely.
434    pub resto_decline_progress_ratio: Number,
435    /// `neg_curv_escapes` (gh #797) — how many times a certified stationary
436    /// point with an indefinite reduced Hessian may be left along a direction
437    /// of negative curvature instead of reported. Default `1`; `0` restores the
438    /// pre-#797 behaviour. See `upstream_options.rs`.
439    pub neg_curv_escapes: Index,
440    /// `limited_memory_ls_failure_restarts` (gh #818) — how many times a
441    /// line-search failure at an already-feasible point may re-anchor the
442    /// quasi-Newton model and retry instead of entering restoration.
443    /// Default `0`, i.e. the rung is off and a line-search failure always
444    /// hands off, which is upstream's behaviour; see
445    /// `DEFAULT_LBFGS_LS_FAILURE_RESTARTS` in `ipopt_alg.rs` for the
446    /// measurement that put it there. See `upstream_options.rs`.
447    pub limited_memory_ls_failure_restarts: Index,
448    /// `kkt_fidelity_tol` (pounce#173). Read by the algorithm as well as by the
449    /// post-solve gate, because the #200 fallback's tiebreak has to rank the two
450    /// candidate points by the status each will be *reported* under. Default
451    /// `0.0` (gate disabled).
452    pub kkt_fidelity_tol: Number,
453    pub conv_check: ConvCheckOptions,
454    pub mu: MuOptions,
455    pub line_search: LineSearchOptions,
456    pub refinement: RefinementOptions,
457    pub perturbation: PerturbationOptions,
458    pub resto: RestoOptions,
459    pub output: OutputOptions,
460    pub warm: WarmStartOptions,
461    /// SQP-specific options (consulted only when
462    /// `algorithm = ActiveSetSqp`).
463    pub sqp: crate::sqp::SqpOptions,
464    /// QP-subproblem-solver options for the active-set SQP path
465    /// (`pounce_qp::QpOptions`), threaded into the `SqpAlgorithm` via
466    /// `with_qp_options`. Consulted only when `algorithm = ActiveSetSqp`.
467    /// Populated from the `sqp_qp_*` CLI options by
468    /// `application::apply_qp_subproblem_options`.
469    pub sqp_qp: pounce_qp::QpOptions,
470    pub init: InitOptions,
471    /// Optional block-triangular / Schur KKT partition (pounce#180 item 2):
472    /// `(schur_indices, feral_cfg)`. When `Some` and the IPM path is selected
473    /// with the feral linear solver and an exact Hessian, `build_with_backend`
474    /// wraps the standard aug-system solver in a
475    /// [`crate::kkt::SchurAugSystemSolver`] over the given KKT-space indices.
476    /// The Schur solver falls back to the standard solver transparently when
477    /// the partition is unsuitable. Set via [`Self::set_kkt_schur`].
478    pub kkt_schur: Option<(Vec<usize>, pounce_feral::FeralConfig)>,
479    /// Summary sink the Schur backend records into, so the solve's
480    /// `LinearSolverSummary` covers the Schur path too. Set via
481    /// [`Self::set_kkt_schur_summary_sink`]; `None` records nothing.
482    /// Optional block-parallel KKT partition (structured-KKT Phase 5b):
483    /// `(labels, feral_cfg)`, labels in KKT space with `< 0` for the shared
484    /// border and **empty** meaning "detect it from the assembled matrix".
485    /// Honored on the IPM + feral + exact-Hessian path; the block solver falls
486    /// back to the standard one transparently. Set via [`Self::set_kkt_blocks`].
487    pub kkt_blocks: Option<(Vec<i32>, pounce_feral::FeralConfig)>,
488    /// Late-bound partition, read only when [`Self::kkt_blocks`] is `None`.
489    /// The restoration sub-IPM's builder is constructed by the frontend before
490    /// the solve starts, which is before the outer KKT layout — and therefore
491    /// the mapping from a model-space declaration onto it — is known. The
492    /// application publishes the resolved labels into this cell as it builds
493    /// the outer algorithm, and the inner builder, a clone made earlier, reads
494    /// them here when restoration actually runs.
495    ///
496    /// Sound because `AugRestoSystemSolver` reduces the 8-block restoration
497    /// KKT onto the *original* 4-block system before delegating: the matrix
498    /// the inner solver factors has the outer system's dimension and sparsity,
499    /// so the outer labels describe it exactly. `BlockAugSystemSolver` checks
500    /// the length against the assembled matrix regardless and falls back.
501    pub kkt_blocks_shared: Option<KktBlocksCell>,
502    /// Refuse a partition whose median block is narrower than this many KKT
503    /// columns (`kkt_block_min_size`; `0` disables). Below the measured
504    /// crossover the block path is slower than the monolithic one — see
505    /// [`crate::kkt::block_aug_system_solver::DEFAULT_MIN_BLOCK_SIZE`].
506    pub kkt_block_min_size: usize,
507    pub kkt_schur_summary_sink:
508        Option<std::sync::Arc<std::sync::Mutex<pounce_linsol::summary::LinearSolverSummary>>>,
509    /// Sink the standard augmented-system solver publishes the inertia of
510    /// its zero-regularization trials into (`last_inertia_unregularized`,
511    /// gh#987 item 3). Set only on the main-IPM builder, so a restoration
512    /// sub-solve's differently-shaped KKT system never overwrites it.
513    pub inertia_sink:
514        Option<std::sync::Arc<std::sync::Mutex<pounce_linsol::summary::LinearSolverSummary>>>,
515    /// Shared tally of successful linear-solver quality escalations, handed
516    /// to the assembled
517    /// [`PdFullSpaceSolver`](crate::kkt::pd_full_space_solver::PdFullSpaceSolver)
518    /// by [`Self::build_with_backend`]. `None` leaves that solver with its
519    /// own private counter, which is what every test double and every
520    /// direct builder user gets.
521    ///
522    /// The point of sharing it is the restoration sub-solve: its inner
523    /// algorithm is assembled from a *clone* of this builder
524    /// (`resto_inner_solver::run_inner_resto`), so a `Some` here makes the
525    /// sub-solve's escalations land in the same total as the main loop's.
526    /// gh#857's exact leg escalates once in each, and counting only the
527    /// main loop would report half the trajectory change.
528    pub quality_escalation_counter: Option<Rc<std::cell::Cell<u64>>>,
529}
530
531/// Knobs read off `OptionsList` and baked into
532/// [`DefaultIterateInitializer`]. Defaults mirror
533/// `IpDefaultIterateInitializer.cpp:RegisterOptions`. The Mehrotra
534/// cascade in `application.rs` overrides `bound_push`, `bound_frac`,
535/// and `bound_mult_init_val` to upstream's more-aggressive values
536/// (`10`, `0.2`, `1.0`).
537#[derive(Debug, Clone)]
538pub struct InitOptions {
539    pub bound_push: Number,
540    pub bound_frac: Number,
541    pub slack_bound_push: Number,
542    pub slack_bound_frac: Number,
543    pub constr_mult_init_max: Number,
544    pub bound_mult_init_val: Number,
545    /// `bound_mult_init_method`: `"constant"` (default) or `"mu-based"`
546    /// (matches upstream's `IpDefaultIterateInitializer.cpp`).
547    pub bound_mult_init_method: String,
548    /// `least_square_init_primal` — replace the user's starting `x`
549    /// with the min-norm primal that satisfies the linearized
550    /// constraints. Used by the Mehrotra cascade in `application.rs`
551    /// to drop iter-0 primal infeasibility on LP-shaped problems.
552    /// Mirrors upstream `IpDefaultIterateInitializer.cpp:200-222`.
553    pub least_square_init_primal: bool,
554}
555
556impl Default for InitOptions {
557    fn default() -> Self {
558        Self {
559            bound_push: 1e-2,
560            bound_frac: 1e-2,
561            slack_bound_push: 1e-2,
562            slack_bound_frac: 1e-2,
563            constr_mult_init_max: 1e3,
564            bound_mult_init_val: 1.0,
565            bound_mult_init_method: "constant".into(),
566            least_square_init_primal: false,
567        }
568    }
569}
570
571/// Knobs read off `OptionsList` and baked into
572/// [`WarmStartIterateInitializer`]. Defaults mirror
573/// `IpWarmStartIterateInitializer.cpp:RegisterOptions`.
574///
575/// Wired today: every knob above plus the gh#606 recentering pair.
576/// `warm_start_entire_iterate` / `warm_start_same_structure` are
577/// deliberately *not* here — they name the `GetWarmStartIterate` TNLP
578/// surface pounce does not expose, and are refused by
579/// [`crate::unimplemented_options`] rather than parsed into a field
580/// nothing reads (gh#606).
581#[derive(Debug, Clone)]
582pub struct WarmStartOptions {
583    pub bound_push: Number,
584    pub bound_frac: Number,
585    pub slack_bound_push: Number,
586    pub slack_bound_frac: Number,
587    pub mult_bound_push: Number,
588    pub mult_init_max: Number,
589    pub target_mu: Number,
590    /// The value a NaN-seeded bound multiplier takes: NaN in a
591    /// user-supplied `z`/`v` seed means "unseeded, use the default".
592    /// Threaded from `builder.init.bound_mult_init_val` at build time
593    /// so the Mehrotra override and any user setting stay the single
594    /// source of truth.
595    pub bound_mult_init_val: Number,
596    /// `constr_mult_init_max`, threaded from the init options at build
597    /// time (gh#606). The warm path's reconstruction of an unseeded
598    /// equality-multiplier block runs the *cold* path's least-squares
599    /// solve, so it is capped by the cold path's cap — not by
600    /// `warm_start_mult_init_max`, which caps multipliers a caller
601    /// actually supplied and is three orders looser (1e6 vs 1e3).
602    /// Measured: on `redundant_rows`, whose duplicated equality rows
603    /// make the least-squares system singular, the looser cap let an
604    /// arbitrary estimate through and cost 7 -> 25 iterations.
605    pub constr_mult_init_max: Number,
606    /// `warm_start_recentering` (gh#606). Whether the initializer
607    /// measures the supplied point and adapts μ / the multiplier fills
608    /// to it, or keeps the pre-gh#606 universal constants.
609    pub recentering: WarmStartRecentering,
610}
611
612/// Value of `warm_start_recentering` (gh#606).
613#[derive(Debug, Clone, Copy, PartialEq, Eq)]
614pub enum WarmStartRecentering {
615    /// Pre-gh#606 behaviour: constant pushes and floors, `y` left at
616    /// zero when unseeded, μ untouched unless `warm_start_target_mu`
617    /// is set. The kill switch.
618    None,
619    /// Measure the supplied iterate's residuals and derive μ, the
620    /// bound-multiplier fills, and the equality-multiplier
621    /// reconstruction from them.
622    Residual,
623}
624
625impl WarmStartOptions {
626    /// `mult_init_max` as a usable cap: the registered `0` sentinel
627    /// means "no cap".
628    pub(crate) fn mult_init_max_or_inf(&self) -> Number {
629        if self.mult_init_max > 0.0 {
630            self.mult_init_max
631        } else {
632            Number::INFINITY
633        }
634    }
635}
636
637impl Default for WarmStartOptions {
638    fn default() -> Self {
639        Self {
640            bound_push: 1e-3,
641            bound_frac: 1e-3,
642            slack_bound_push: 1e-3,
643            slack_bound_frac: 1e-3,
644            mult_bound_push: 1e-3,
645            mult_init_max: 1e6,
646            target_mu: 0.0,
647            // seeded from the init options so the default has one
648            // home; build() re-resolves it from the live init options
649            // anyway (see `resolved_warm_options`)
650            bound_mult_init_val: InitOptions::default().bound_mult_init_val,
651            constr_mult_init_max: InitOptions::default().constr_mult_init_max,
652            recentering: WarmStartRecentering::Residual,
653        }
654    }
655}
656
657/// The warm-start options as the initializer actually receives them:
658/// `bound_mult_init_val` and `constr_mult_init_max` come from the
659/// (option-read, Mehrotra-resolved) init options, never from
660/// `WarmStartOptions`'s own copy. Split out of `build()` so the threading is testable.
661pub(crate) fn resolved_warm_options(
662    warm: &WarmStartOptions,
663    init: &InitOptions,
664) -> WarmStartOptions {
665    let mut w = warm.clone();
666    w.bound_mult_init_val = init.bound_mult_init_val;
667    w.constr_mult_init_max = init.constr_mult_init_max;
668    w
669}
670
671/// Knobs read off `OptionsList` and baked into the assembled
672/// `MonotoneMuUpdate` or `AdaptiveMuUpdate`. Defaults mirror
673/// `IpMonotoneMuUpdate.cpp` / `IpAdaptiveMuUpdate.cpp:RegisterOptions`.
674/// `mu_max` defaults to the sentinel `-1`; positive values are baked
675/// into both updaters at build time (adaptive interprets `-1` as
676/// "lazy-init from `mu_max_fact * avrg_compl`").
677#[derive(Debug, Clone)]
678pub struct MuOptions {
679    pub mu_init: Number,
680    pub mu_max: Number,
681    pub mu_max_fact: Number,
682    pub mu_min: Number,
683    pub mu_target: Number,
684    pub mu_linear_decrease_factor: Number,
685    pub mu_superlinear_decrease_power: Number,
686    pub mu_allow_fast_monotone_decrease: bool,
687    pub barrier_tol_factor: Number,
688    /// `tau_min` — floor on the fraction-to-the-boundary parameter
689    /// τ = max(tau_min, 1 − μ). Registered default 0.99, which is what
690    /// both `MonotoneMuUpdate` and `AdaptiveMuUpdate` already carry as
691    /// their struct default, so forwarding it is behaviour-neutral for
692    /// a run that does not set the option (#551 / #677). Consumed by
693    /// both updaters; the adaptive one also uses it in the monotone
694    /// mode and for the post-oracle τ = max(tau_min, 1 − NLP error).
695    pub tau_min: Number,
696    /// `sigma_max` / `sigma_min` — clamp on the centering parameter σ
697    /// chosen by `QualityFunctionMuOracle`. Only consumed when
698    /// `mu_strategy=adaptive` and `mu_oracle=quality-function`.
699    /// Defaults from `IpQualityFunctionMuOracle.cpp:RegisterOptions`.
700    pub sigma_max: Number,
701    pub sigma_min: Number,
702    /// `adaptive_mu_globalization` — globalization strategy for the
703    /// adaptive μ-selection mode. Mirrors
704    /// `IpAdaptiveMuUpdate.cpp:RegisterOptions`. Default is
705    /// `ObjConstrFilter`; the Mehrotra cascade switches to
706    /// `NeverMonotoneMode` to disable globalization entirely.
707    pub adaptive_mu_globalization: crate::mu::adaptive::AdaptiveMuGlobalization,
708    /// `quality_function_norm_type` — norm used inside the quality
709    /// function to aggregate the three KKT components. Forwarded to
710    /// `QualityFunctionMuOracle` when `mu_oracle=quality-function`.
711    pub quality_function_norm_type: crate::mu::oracle::quality_function::NormType,
712    /// `quality_function_centrality` — centrality penalty term added
713    /// to the quality function.
714    pub quality_function_centrality: crate::mu::oracle::quality_function::CentralityType,
715    /// `quality_function_balancing_term` — balancing penalty term in
716    /// the quality function (kicks in when complementarity is far
717    /// below infeasibilities).
718    pub quality_function_balancing_term: crate::mu::oracle::quality_function::BalancingTermType,
719    /// `quality_function_max_section_steps` — cap on golden-section
720    /// iterations when picking σ. Default 8.
721    pub quality_function_max_section_steps: i32,
722    /// `quality_function_section_sigma_tol` — width tolerance in
723    /// σ-space for golden section. Default 1e-2.
724    pub quality_function_section_sigma_tol: Number,
725    /// `quality_function_section_qf_tol` — relative flatness
726    /// tolerance for golden section. Default 0.0.
727    pub quality_function_section_qf_tol: Number,
728    /// `adaptive_mu_safeguard_factor` — guard for the LOQO fallback
729    /// in adaptive mode. Default 0.0.
730    pub adaptive_mu_safeguard_factor: Number,
731    /// `adaptive_mu_monotone_init_factor` — multiplier on the
732    /// average complementarity when seeding monotone mode after a
733    /// free-mode bailout. Default 0.8.
734    pub adaptive_mu_monotone_init_factor: Number,
735    /// `adaptive_mu_restore_previous_iterate` — restore the most
736    /// recent free-mode iterate when switching to fixed mode.
737    /// Default `false`.
738    pub adaptive_mu_restore_previous_iterate: bool,
739    /// `adaptive_mu_max_free_returns` (pounce#749, POUNCE
740    /// extension). Cap on how many times the adaptive strategy may
741    /// leave fixed-mu mode. `-1` = unlimited (upstream behavior).
742    pub adaptive_mu_max_free_returns: i32,
743    /// `adaptive_mu_budget_pin_fraction` (pounce#753, POUNCE
744    /// extension). Fraction of an explicitly-set `max_cpu_time` /
745    /// `max_wall_time` after which the adaptive strategy stops
746    /// returning to free-mu mode and finishes monotone. `1.0`
747    /// disables. Inert unless the caller set a time budget.
748    pub adaptive_mu_budget_pin_fraction: Number,
749    /// `adaptive_mu_kkterror_red_iters` — window length for the
750    /// `KKT_ERROR` globalization history. Default 4.
751    pub adaptive_mu_kkterror_red_iters: usize,
752    /// `adaptive_mu_kkterror_red_fact` — required relative reduction
753    /// of the KKT error over the window. Default 0.9999.
754    pub adaptive_mu_kkterror_red_fact: Number,
755    /// `adaptive_mu_kkt_norm_type` — norm used to score the iterate
756    /// in adaptive globalization decisions.
757    pub adaptive_mu_kkt_norm_type: crate::mu::adaptive::AdaptiveMuKktNorm,
758    /// `filter_margin_fact` — width factor of the margin an entry must
759    /// clear in the `obj-constr-filter` adaptive globalization test
760    /// (`margin = filter_margin_fact * min(filter_max_margin, err)`).
761    /// Only consumed when `mu_strategy=adaptive` and
762    /// `adaptive_mu_globalization=obj-constr-filter` (the default).
763    /// Default 1e-5, from `IpAdaptiveMuUpdate.cpp:RegisterOptions`.
764    pub filter_margin_fact: Number,
765    /// `filter_max_margin` — cap on the margin above. Default 1.0,
766    /// from `IpAdaptiveMuUpdate.cpp:RegisterOptions`.
767    pub filter_max_margin: Number,
768    /// `probing_iterate_quality_factor` (default 1e4, pounce-specific
769    /// — see pounce#58). When the probing (Mehrotra) μ-oracle is
770    /// about to read `curr_avrg_compl()` for its `mu_curr` input, a
771    /// single imbalanced `(s_i, z_i)` pair can inflate the average
772    /// 5+ orders above the stored `data.curr_mu`. The oracle then
773    /// returns `σ · mu_curr` ≫ previous μ, throwing the iterate out
774    /// of the convergence neighborhood. This guard short-circuits
775    /// that case by signalling restoration when the ratio
776    /// `curr_avrg_compl / curr_mu` exceeds the factor. Set to 0 or
777    /// any non-positive value to disable.
778    pub probing_iterate_quality_factor: Number,
779}
780
781impl Default for MuOptions {
782    fn default() -> Self {
783        Self {
784            mu_init: 0.1,
785            mu_max: -1.0,
786            mu_max_fact: 1e3,
787            mu_min: 1e-11,
788            mu_target: 0.0,
789            mu_linear_decrease_factor: 0.2,
790            mu_superlinear_decrease_power: 1.5,
791            mu_allow_fast_monotone_decrease: true,
792            barrier_tol_factor: 10.0,
793            tau_min: 0.99,
794            sigma_max: 1e2,
795            sigma_min: 1e-6,
796            adaptive_mu_globalization:
797                crate::mu::adaptive::AdaptiveMuGlobalization::ObjConstrFilter,
798            quality_function_norm_type:
799                crate::mu::oracle::quality_function::NormType::TwoNormSquared,
800            quality_function_centrality: crate::mu::oracle::quality_function::CentralityType::None,
801            quality_function_balancing_term:
802                crate::mu::oracle::quality_function::BalancingTermType::None,
803            quality_function_max_section_steps: 8,
804            quality_function_section_sigma_tol: 1e-2,
805            quality_function_section_qf_tol: 0.0,
806            adaptive_mu_safeguard_factor: 0.0,
807            adaptive_mu_monotone_init_factor: 0.8,
808            adaptive_mu_restore_previous_iterate: false,
809            adaptive_mu_max_free_returns: -1,
810            adaptive_mu_budget_pin_fraction: 0.75,
811            adaptive_mu_kkterror_red_iters: 4,
812            adaptive_mu_kkterror_red_fact: 0.9999,
813            adaptive_mu_kkt_norm_type: crate::mu::adaptive::AdaptiveMuKktNorm::TwoNormSquared,
814            filter_margin_fact: 1e-5,
815            filter_max_margin: 1.0,
816            probing_iterate_quality_factor: 1e4,
817        }
818    }
819}
820
821/// Knobs baked into the assembled [`BacktrackingLineSearch`]. Defaults
822/// mirror `IpBacktrackingLineSearch.cpp:RegisterOptions`.
823#[derive(Debug, Clone)]
824pub struct LineSearchOptions {
825    /// `alpha_red_factor` — fractional reduction applied to the trial
826    /// step size at every backtracking step
827    /// (`alpha *= alpha_red_factor`). Mirrors upstream's
828    /// `IpBacktrackingLineSearch::alpha_red_factor_`.
829    pub alpha_red_factor: Number,
830    /// `alpha_red_factor_min` — floor on one backtracking reduction,
831    /// which turns the fixed geometric trial sequence into a
832    /// safeguarded quadratic interpolation (gh#818). See
833    /// `BacktrackingLineSearch::next_alpha`.
834    ///
835    /// `None` — the default — means "let the Hessian mode decide", and
836    /// the two modes decide differently:
837    ///
838    /// * **limited-memory → `0.05`** (interpolation on). The
839    ///   quasi-Newton model's *scale* can be wrong by orders of
840    ///   magnitude in any direction its curvature pairs do not span, so
841    ///   the acceptable `alpha` can be far below 1 and the fixed factor
842    ///   spends `log(1/alpha)` objective evaluations walking to it.
843    /// * **exact → off** (`alpha_red_factor`, i.e. upstream's fixed
844    ///   sequence). A Newton step's length is meaningful, the
845    ///   acceptable `alpha` is normally within a few halvings of 1, and
846    ///   the trial sequence is not what costs.
847    ///
848    /// The split is measured, not assumed. Forcing
849    /// `alpha_red_factor_min 0.05` onto the exact path moves 3 of the
850    /// 156 fixture-legs in `scripts/sweep-fixtures.sh`, and the one
851    /// that matters is a **status loss**: `eigena2` goes from
852    /// `SolveSucceeded`/27 to `SolvedToAcceptableLevel`/32. The other
853    /// two are `issue_508_infeasible_gap_1em4` 441 → 385 to the same
854    /// certificate — a gain — and an objective digit on
855    /// `hs13_bigstart`. One fixture giving up a solve is the whole
856    /// argument; a faster infeasibility certificate does not buy it
857    /// back. Before `ALPHA_INTERP_MIN_TRIALS` gated the interpolation
858    /// the same experiment moved 9 legs and cost
859    /// `infeasible_square_scaled_1em4` its infeasibility certificate
860    /// (`InfeasibleProblemDetected`/17 → `ErrorInStepComputation`/12);
861    /// the gate narrowed the damage, it did not remove the reason for
862    /// the split.
863    ///
864    /// An explicit `alpha_red_factor_min` from the user is honoured on
865    /// both paths — the mode-dependence is only in the default.
866    pub alpha_red_factor_min: Option<Number>,
867    pub watchdog_shortened_iter_trigger: Index,
868    pub watchdog_trial_iter_max: Index,
869    /// `soft_resto_pderror_reduction_factor` — required relative
870    /// reduction in the primal-dual error for a soft-resto step.
871    /// `0` disables the soft restoration phase.
872    pub soft_resto_pderror_reduction_factor: Number,
873    /// `max_soft_resto_iters` — cap on consecutive soft-resto
874    /// iterations before full restoration is forced.
875    pub max_soft_resto_iters: Index,
876    /// `accept_every_trial_step` — short-circuits the filter / alpha
877    /// loop and accepts the full fraction-to-the-boundary step every
878    /// outer iteration. Mirrors upstream's
879    /// `IpBacktrackingLineSearch::accept_every_trial_step_`. Drops
880    /// global convergence guarantees; only safe for problems where the
881    /// Newton step is already a descent step (LPs, convex QPs). The
882    /// Mehrotra cascade in `application.rs` flips this on.
883    pub accept_every_trial_step: bool,
884    /// `alpha_for_y` — policy for the equality-multiplier (y_c / y_d)
885    /// step length. Upstream default is `Primal`; the Mehrotra cascade
886    /// switches to `BoundMult`.
887    pub alpha_for_y: crate::line_search::backtracking::AlphaForY,
888    /// `accept_after_max_steps` — accept a trial point once this many
889    /// backtracking steps have been taken, even if it fails the
890    /// acceptor's tests. `-1` (the default) disables it, which is why
891    /// wiring it moves no default trajectory. Mirrors
892    /// `IpBacktrackingLineSearch.cpp:759-770`.
893    pub accept_after_max_steps: Index,
894
895    // Filter switching / Armijo / margin constants baked onto the
896    // assembled [`crate::line_search::filter_acceptor::FilterLsAcceptor`]
897    // (only when `line_search_method = Filter`). All were registered but
898    // never read (#191); defaults mirror `IpFilterLSAcceptor.cpp`.
899    /// `eta_phi` — relaxation factor in the Armijo condition (Eqn. (20)).
900    pub eta_phi: Number,
901    /// `delta` — multiplier on the constraint violation in the filter's
902    /// switching rule (Eqn. (19)); maps to
903    /// [`FilterLsAcceptor::delta_armijo`]. Default 1.0, from
904    /// `IpFilterLSAcceptor.cpp:RegisterOptions`.
905    pub delta: Number,
906    /// `theta_min_fact` — constraint-violation threshold factor in the
907    /// switching rule.
908    pub theta_min_fact: Number,
909    /// `theta_max_fact` — upper-bound factor for constraint violation in
910    /// the filter (Eqn. (21)).
911    pub theta_max_fact: Number,
912    /// `theta_max_row_scale_kappa` — multiplier on the constraint-row
913    /// count used as the floor of the `theta_max` reference.
914    /// **Opt-in**: default `0`, which is upstream's bare
915    /// `max(1, theta_0)` floor bit-for-bit. Set to `1` on a large model
916    /// that stalls from a feasible start. See
917    /// [`FilterLsAcceptor::theta_max_row_scale_kappa`].
918    pub theta_max_row_scale_kappa: Number,
919    /// `theta_max_adaptive_trigger` — consecutive line searches whose
920    /// every trial was refused at the `theta_max` gate before the
921    /// ceiling is raised. `0` disables the rule. See
922    /// [`FilterLsAcceptor::theta_max_adaptive_trigger`] (pounce#546).
923    pub theta_max_adaptive_trigger: u32,
924    /// Geometric factor applied to `theta_max` on each adaptive raise.
925    /// See [`FilterLsAcceptor::theta_max_adaptive_factor`].
926    pub theta_max_adaptive_factor: Number,
927    /// Cap on adaptive raises per solve, which is what keeps `theta_max`
928    /// finite. See [`FilterLsAcceptor::theta_max_adaptive_max_raises`].
929    pub theta_max_adaptive_max_raises: u32,
930    /// `gamma_phi` — filter margin factor for the barrier function
931    /// (Eqn. (18a)).
932    pub gamma_phi: Number,
933    /// `gamma_theta` — filter margin factor for the constraint violation
934    /// (Eqn. (18b)).
935    pub gamma_theta: Number,
936    /// `s_phi` — exponent for the linear barrier model in the switching
937    /// rule (Eqn. (19)).
938    pub s_phi: Number,
939    /// `s_theta` — exponent for the current constraint violation in the
940    /// switching rule (Eqn. (19)).
941    pub s_theta: Number,
942    /// `alpha_min_frac` — safety factor for the minimal step size before
943    /// switching to restoration (gamma_alpha, Eqn. (23)).
944    pub alpha_min_frac: Number,
945    /// `obj_max_inc` — max acceptable increase (orders of magnitude) of
946    /// the barrier objective for a trial point.
947    pub obj_max_inc: Number,
948    /// `max_filter_resets` — maximum number of filter resets allowed
949    /// (`0` disables the reset heuristic).
950    pub max_filter_resets: Index,
951    /// `filter_reset_trigger` — successive filter-rejected iterations that
952    /// trigger a filter reset.
953    pub filter_reset_trigger: Index,
954    /// `filter_theta_roundoff_retry` (gh#945) — whether a line search that
955    /// runs out of `alpha` at an iterate already feasible to round-off gets
956    /// one more pass with the filter's `theta` axis measured against
957    /// `theta`'s own evaluation noise, before the driver hands off to a
958    /// restoration phase that has nothing to minimize. **On by default**;
959    /// see `BacktrackingLineSearch::run_filter_line_search` and
960    /// `IpoptCq::theta_evaluation_noise_floor`.
961    pub filter_theta_roundoff_retry: bool,
962    /// `objective_noise_wolfe` (gh#1016) — whether a solve whose line search
963    /// has accepted a numerical null step also accepts trials by the
964    /// approximate-Wolfe slope test. **On by default**; see
965    /// `BacktrackingLineSearch::objective_noise_wolfe`.
966    pub objective_noise_wolfe: bool,
967
968    // Penalty-acceptor constants baked onto the assembled
969    // [`crate::line_search::penalty_acceptor::PenaltyLsAcceptor`] (only
970    // when `line_search_method = penalty` / `cg-penalty`). Defaults
971    // mirror `IpPenaltyLSAcceptor.cpp:RegisterOptions`.
972    /// `nu_init` — initial value of the penalty parameter ν.
973    pub nu_init: Number,
974    /// `nu_inc` — increment added when ν is bumped.
975    pub nu_inc: Number,
976    /// `rho` — convex-combination weight in the ν update rule.
977    pub rho: Number,
978    /// `eta_penalty` — relaxation factor in the Armijo condition on the
979    /// penalty merit function.
980    pub eta_penalty: Number,
981
982    // Second-order-correction constants baked onto the assembled
983    // [`BacktrackingLineSearch`]. Registered but never read (#191);
984    // defaults mirror `IpBacktrackingLineSearch.cpp`.
985    /// `max_soc` — max second-order-correction trial steps per iteration;
986    /// `0` disables SOC.
987    pub max_soc: Index,
988    /// `kappa_soc` — sufficient-reduction factor for a SOC step to be
989    /// continued.
990    pub kappa_soc: Number,
991    /// `soc_method` — `0` (paper method) or `1` (alpha-on-rhs variant).
992    pub soc_method: Index,
993}
994
995impl Default for LineSearchOptions {
996    fn default() -> Self {
997        Self {
998            alpha_red_factor: 0.5,
999            alpha_red_factor_min: None,
1000            watchdog_shortened_iter_trigger: 10,
1001            watchdog_trial_iter_max: 3,
1002            soft_resto_pderror_reduction_factor: 1.0 - 1e-4,
1003            max_soft_resto_iters: 10,
1004            accept_every_trial_step: false,
1005            alpha_for_y: crate::line_search::backtracking::AlphaForY::Primal,
1006            accept_after_max_steps: -1,
1007            eta_phi: 1e-8,
1008            delta: 1.0,
1009            theta_min_fact: 1e-4,
1010            theta_max_fact: 1e4,
1011            theta_max_row_scale_kappa: 0.0,
1012            theta_max_adaptive_trigger: 3,
1013            theta_max_adaptive_factor: 100.0,
1014            theta_max_adaptive_max_raises: 4,
1015            gamma_phi: 1e-8,
1016            gamma_theta: 1e-5,
1017            s_phi: 2.3,
1018            s_theta: 1.1,
1019            alpha_min_frac: 0.05,
1020            obj_max_inc: 5.0,
1021            max_filter_resets: 5,
1022            filter_reset_trigger: 5,
1023            filter_theta_roundoff_retry: true,
1024            objective_noise_wolfe: true,
1025            nu_init: 1e-6,
1026            nu_inc: 1e-4,
1027            rho: 0.1,
1028            eta_penalty: 1e-8,
1029            max_soc: 4,
1030            kappa_soc: 0.99,
1031            soc_method: 0,
1032        }
1033    }
1034}
1035
1036/// Inertia-correction / regularization knobs baked onto the assembled
1037/// [`crate::kkt::perturbation_handler::PdPerturbationHandler`]. Field
1038/// names use the option names; they map to the handler's `delta_xs_*` /
1039/// `delta_cd_*` fields. Defaults mirror
1040/// `IpPDPerturbationHandler.cpp:RegisterOptions`. All were registered but
1041/// never read (#191).
1042#[derive(Debug, Clone)]
1043pub struct PerturbationOptions {
1044    /// `max_hessian_perturbation` → `delta_xs_max`.
1045    pub max_hessian_perturbation: Number,
1046    /// `min_hessian_perturbation` → `delta_xs_min`.
1047    pub min_hessian_perturbation: Number,
1048    /// `perturb_inc_fact_first` → `delta_xs_first_inc_fact`.
1049    pub perturb_inc_fact_first: Number,
1050    /// `perturb_inc_fact` → `delta_xs_inc_fact`.
1051    pub perturb_inc_fact: Number,
1052    /// `perturb_dec_fact` → `delta_xs_dec_fact`.
1053    pub perturb_dec_fact: Number,
1054    /// `first_hessian_perturbation` → `delta_xs_init`.
1055    pub first_hessian_perturbation: Number,
1056    /// `jacobian_regularization_value` → `delta_cd_val`.
1057    pub jacobian_regularization_value: Number,
1058    /// `jacobian_regularization_exponent` → `delta_cd_exp`.
1059    pub jacobian_regularization_exponent: Number,
1060    /// `perturb_always_cd` — always regularize the c/d (Jacobian) block.
1061    pub perturb_always_cd: bool,
1062    /// `perturb_delta_c_max_rungs` → `delta_c_max_rungs` (pounce gh#592).
1063    pub perturb_delta_c_max_rungs: Index,
1064    /// `perturb_slack_fact` → `delta_s_fact` (pounce gh#1098).
1065    pub perturb_slack_fact: Number,
1066    /// `perturb_slack_max_rows` → `delta_s_max_rows` (pounce gh#1098).
1067    pub perturb_slack_max_rows: Index,
1068}
1069
1070impl Default for PerturbationOptions {
1071    fn default() -> Self {
1072        Self {
1073            max_hessian_perturbation: 1e20,
1074            min_hessian_perturbation: 1e-20,
1075            perturb_inc_fact_first: 100.0,
1076            perturb_inc_fact: 8.0,
1077            perturb_dec_fact: 1.0 / 3.0,
1078            first_hessian_perturbation: 1e-4,
1079            jacobian_regularization_value: 1e-8,
1080            jacobian_regularization_exponent: 0.25,
1081            perturb_always_cd: false,
1082            perturb_delta_c_max_rungs: 3,
1083            perturb_slack_fact: crate::ftb_floor::DEFAULT_PERTURB_SLACK_FACT,
1084            perturb_slack_max_rows: crate::ftb_floor::DEFAULT_PERTURB_SLACK_MAX_ROWS,
1085        }
1086    }
1087}
1088
1089/// Restoration-phase knobs carried on the outer builder and copied into
1090/// the `RestoAlgorithmBuilder` when the restoration factory is minted
1091/// (`pounce-restoration`). The restoration builder is constructed with
1092/// defaults by each frontend and never options-configured, so these were
1093/// registered but never read (#191). Defaults mirror upstream's
1094/// restoration `RegisterOptions`.
1095#[derive(Debug, Clone)]
1096pub struct RestoOptions {
1097    /// `bound_mult_reset_threshold` — reset bound multipliers to 1 after
1098    /// restoration if the largest exceeds this.
1099    pub bound_mult_reset_threshold: Number,
1100    /// `constr_mult_reset_threshold` — ignore the least-square constraint
1101    /// multiplier estimate after restoration if its norm exceeds this
1102    /// (`0` keeps the estimate).
1103    pub constr_mult_reset_threshold: Number,
1104    /// `resto_penalty_parameter` — penalty on the slack 1-norm in the
1105    /// restoration objective (`rho`).
1106    pub resto_penalty_parameter: Number,
1107    /// `resto_proximity_weight` — proximity-term weight (`eta_factor`;
1108    /// `η = eta_factor · sqrt(μ)`).
1109    pub resto_proximity_weight: Number,
1110    /// `required_infeasibility_reduction` — the restoration sub-solve
1111    /// keeps iterating until the *original* NLP's infeasibility has been
1112    /// reduced to at most this fraction of its value at restoration entry
1113    /// (`κ_resto` in `IpRestoConvCheck.cpp:58`). `0` disables the guard,
1114    /// i.e. restoration runs until the sub-NLP itself converges.
1115    pub required_infeasibility_reduction: Number,
1116    /// `evaluate_orig_obj_at_resto_trial` — evaluate the *original*
1117    /// objective at every restoration trial point, so an iterate the
1118    /// restoration problem likes but the original cannot evaluate is
1119    /// rejected there rather than after the phase exits. Upstream default
1120    /// `yes`. `RestoAlgorithmBuilder` has consumed this since it landed;
1121    /// only the read site was missing (gh#483, #191 round 2).
1122    pub evaluate_orig_obj_at_resto_trial: bool,
1123    /// `expect_infeasible_problem` — enter restoration sooner and demand
1124    /// more infeasibility reduction before leaving it. Upstream default
1125    /// `no`. Same story: consumed, never read.
1126    pub expect_infeasible_problem: bool,
1127    /// `start_with_resto` — switch to restoration in the first iteration.
1128    /// Upstream default `no`. Same story.
1129    pub start_with_resto: bool,
1130    /// `max_resto_iter` — cap on *successive* restoration iterations
1131    /// (`IpRestoConvCheck.cpp:144`'s `maximum_resto_iters`). Consumed by
1132    /// `pounce_restoration::conv_check::RestoConvCheckAdapter`, which
1133    /// returns `MaxIterExceeded` once the count is reached; the value
1134    /// used to be the hard-coded `RESTO_MAX_SUCCESSIVE_ITERS` in
1135    /// `resto_inner_solver.rs`, so setting the option did nothing
1136    /// (#551 / #677). The field is named after the option here, but the
1137    /// consumer's field is `maximum_resto_iters` — which is why grepping
1138    /// for the option name found nothing (#551 caution 2).
1139    ///
1140    /// **This default deliberately differs from the registered one.**
1141    /// `upstream_options.rs` registers Ipopt's `3000000`; pounce has
1142    /// enforced `3000` since the cap landed. Wiring the option must not
1143    /// change what an unset option does, so the effective cap stays
1144    /// `3000` and only an explicit `max_resto_iter` moves it. Raising
1145    /// the default to upstream's number is a trajectory change (it
1146    /// lets a restoration that pounce currently cuts off at 3000 keep
1147    /// going) and belongs to a change that measures it.
1148    pub max_resto_iter: i32,
1149}
1150
1151impl Default for RestoOptions {
1152    fn default() -> Self {
1153        Self {
1154            bound_mult_reset_threshold: 1e3,
1155            constr_mult_reset_threshold: 0.0,
1156            resto_penalty_parameter: 1e3,
1157            resto_proximity_weight: 1.0,
1158            required_infeasibility_reduction: 0.9,
1159            evaluate_orig_obj_at_resto_trial: true,
1160            expect_infeasible_problem: false,
1161            start_with_resto: false,
1162            // NOT the registered default (3000000) — see the field docs.
1163            max_resto_iter: 3000,
1164        }
1165    }
1166}
1167
1168/// Iterative-refinement knobs baked onto the assembled
1169/// [`crate::kkt::pd_full_space_solver::PdFullSpaceSolver`]. Defaults
1170/// mirror `IpPDFullSpaceSolver.cpp:RegisterOptions`. All were registered
1171/// but never read (#191).
1172#[derive(Debug, Clone)]
1173pub struct RefinementOptions {
1174    /// `min_refinement_steps` — minimum iterative-refinement steps per
1175    /// linear solve.
1176    pub min_refinement_steps: Index,
1177    /// `max_refinement_steps` — maximum iterative-refinement steps.
1178    pub max_refinement_steps: Index,
1179    /// `residual_ratio_max` — refine until the residual test ratio drops
1180    /// below this (or `max_refinement_steps` is reached).
1181    pub residual_ratio_max: Number,
1182    /// `residual_ratio_singular` — above this ratio after failed
1183    /// refinement, the system is declared singular.
1184    pub residual_ratio_singular: Number,
1185    /// `residual_improvement_factor` — minimum per-step reduction of the
1186    /// residual test ratio before refinement is aborted.
1187    pub residual_improvement_factor: Number,
1188    /// `neg_curv_test_tol` — tolerance α_n of the inertia-free curvature
1189    /// test of Zavala & Chiang (2014). Zero (the registered default)
1190    /// disables the heuristic and keeps the inertia check; positive
1191    /// turns the inertia check off and accepts the factorization only
1192    /// when the computed direction passes the curvature test in
1193    /// `PdFullSpaceSolver::solve_once`.
1194    pub neg_curv_test_tol: Number,
1195    /// `neg_curv_test_reg` — whether the curvature test includes the
1196    /// primal regularization δ_x‖dx‖² + δ_s‖ds‖². Registered default
1197    /// `yes`; `no` reproduces the original Ipopt form that ignores it.
1198    /// Only consulted when `neg_curv_test_tol > 0`.
1199    pub neg_curv_test_reg: bool,
1200}
1201
1202impl Default for RefinementOptions {
1203    fn default() -> Self {
1204        Self {
1205            min_refinement_steps: 1,
1206            max_refinement_steps: 10,
1207            residual_ratio_max: 1e-10,
1208            residual_ratio_singular: 1e-5,
1209            residual_improvement_factor: 0.999_999_999,
1210            neg_curv_test_tol: 0.0,
1211            neg_curv_test_reg: true,
1212        }
1213    }
1214}
1215
1216/// Knobs baked into the assembled [`OrigIterationOutput`]. Defaults
1217/// mirror `IpOrigIterationOutput.cpp:RegisterOptions` /
1218/// `IpAlgorithmRegOp.cpp`.
1219#[derive(Debug, Clone)]
1220pub struct OutputOptions {
1221    pub print_frequency_iter: Index,
1222    pub print_frequency_time: Number,
1223    /// `print_info_string` (default `false`). When on, the iter row
1224    /// ends with the contents of `IpoptData::info_string` so users
1225    /// can read the per-iteration diagnostic tags.
1226    pub print_info_string: bool,
1227    /// `inf_pr_output` — `"original"` (default) prints the unscaled
1228    /// NLP primal infeasibility; `"internal"` prints the internal
1229    /// reformulated violation. Only meaningful once NLP-side scaling
1230    /// is in play; until then both modes produce the same number.
1231    pub inf_pr_output_internal: bool,
1232}
1233
1234impl Default for OutputOptions {
1235    fn default() -> Self {
1236        Self {
1237            print_frequency_iter: 1,
1238            print_frequency_time: 0.0,
1239            print_info_string: false,
1240            inf_pr_output_internal: false,
1241        }
1242    }
1243}
1244
1245impl Default for AlgorithmBuilder {
1246    fn default() -> Self {
1247        Self {
1248            algorithm: AlgorithmChoice::default(),
1249            linear_solver: LinearSolverChoice::Feral,
1250            linear_system_scaling: LinearSystemScalingChoice::None,
1251            linear_scaling_on_demand: true,
1252            mu_strategy: MuStrategyChoice::Monotone,
1253            mu_oracle: MuOracleKind::QualityFunction,
1254            hessian_approximation: HessianApproxChoice::Exact,
1255            partitioned_update_type: UpdateType::Sr1,
1256            partitioned_update_type_was_set: false,
1257            partitioned_max_element: 64,
1258            objective_nonlinear_vars: None,
1259            hessian_declared_pattern: None,
1260            partitioned_curvature_cap: Number::INFINITY,
1261            partitioned_elements: crate::hess::partitioned_quasi_newton::ElementMode::PerConstraint,
1262            partitioned_block_size: 64,
1263            fd_hessian_pattern: crate::hess::fd_hessian::FdPatternSource::Declared,
1264            fd_hessian_coloring: crate::hess::fd_hessian::FdColoring::Cpr,
1265            fd_hessian_reuse_tol: 0.0,
1266            limited_memory_update_type: UpdateType::Bfgs,
1267            limited_memory_max_history: 6,
1268            limited_memory_init_val_max: 1e8,
1269            limited_memory_init_val_min: 1e-8,
1270            limited_memory_initialization: InitialApprox::Scalar1,
1271            limited_memory_init_val: 1.0,
1272            limited_memory_max_skipping: 2,
1273            limited_memory_nonlinear_vars: None,
1274            line_search_method: LineSearchChoice::Filter,
1275            warm_start_init_point: false,
1276            mehrotra_algorithm: false,
1277            fast_step_computation: false,
1278            kappa_sigma: 1e10,
1279            ftb_centrality_floor: crate::ftb_floor::DEFAULT_FTB_CENTRALITY_FLOOR,
1280            recalc_y: false,
1281            recalc_y_feas_tol: 1e-6,
1282            kappa_d: 1e-5,
1283            s_max: 100.0,
1284            tiny_step_tol: 10.0 * Number::EPSILON,
1285            tiny_step_y_tol: 1e-2,
1286            diverging_iterates_tol: 1e20,
1287            dual_divergence_retry_step_tol: 1e-5,
1288            dual_divergence_retry_du_floor: 1e2,
1289            tiny_step_dual_stall_iters: 10,
1290            dual_diverging_streak: 0,
1291            resto_decline_deferrals: 1,
1292            resto_decline_progress_ratio: 0.5,
1293            neg_curv_escapes: 1,
1294            limited_memory_ls_failure_restarts: 0,
1295            kkt_fidelity_tol: 0.0,
1296            conv_check: ConvCheckOptions::default(),
1297            mu: MuOptions::default(),
1298            line_search: LineSearchOptions::default(),
1299            refinement: RefinementOptions::default(),
1300            perturbation: PerturbationOptions::default(),
1301            resto: RestoOptions::default(),
1302            output: OutputOptions::default(),
1303            warm: WarmStartOptions::default(),
1304            sqp: crate::sqp::SqpOptions::default(),
1305            sqp_qp: pounce_qp::QpOptions::sqp_subproblem(),
1306            init: InitOptions::default(),
1307            kkt_schur: None,
1308            kkt_blocks: None,
1309            kkt_blocks_shared: None,
1310            kkt_block_min_size: crate::kkt::block_aug_system_solver::DEFAULT_MIN_BLOCK_SIZE,
1311            kkt_schur_summary_sink: None,
1312            inertia_sink: None,
1313            quality_escalation_counter: None,
1314        }
1315    }
1316}
1317
1318impl AlgorithmBuilder {
1319    pub fn new() -> Self {
1320        Self::default()
1321    }
1322
1323    /// Install a Schur KKT partition (pounce#180 item 2). `schur_indices` are
1324    /// KKT-space indices (`0..dim`, the `x,s,c,d` block order the aug-system
1325    /// solver assembles); `cfg` configures the per-block feral solvers. Only
1326    /// honored on the IPM + feral + exact-Hessian path by
1327    /// [`Self::build_with_backend`]; ignored otherwise.
1328    pub fn set_kkt_schur(&mut self, schur_indices: Vec<usize>, cfg: pounce_feral::FeralConfig) {
1329        self.kkt_schur = Some((schur_indices, cfg));
1330    }
1331
1332    /// Install a block-parallel KKT partition (structured-KKT Phase 5b).
1333    /// `labels` are KKT-space block ids (`< 0` = the shared border); an empty
1334    /// vector asks the solver to detect the structure from the assembled KKT.
1335    pub fn set_kkt_blocks(&mut self, labels: Vec<i32>, cfg: pounce_feral::FeralConfig) {
1336        self.kkt_blocks = Some((labels, cfg));
1337    }
1338
1339    /// Read a partition from `cell` when none is installed directly — the
1340    /// restoration path, see [`Self::kkt_blocks_shared`].
1341    pub fn set_kkt_blocks_cell(&mut self, cell: KktBlocksCell) {
1342        self.kkt_blocks_shared = Some(cell);
1343    }
1344
1345    /// The partition to build with: an installed one first, then the
1346    /// late-bound cell.
1347    fn resolved_kkt_blocks(&self) -> Option<(Vec<i32>, pounce_feral::FeralConfig)> {
1348        self.kkt_blocks.clone().or_else(|| {
1349            self.kkt_blocks_shared
1350                .as_ref()
1351                .and_then(|c| c.lock().ok().and_then(|g| g.clone()))
1352        })
1353    }
1354
1355    /// Route the Schur backend's factorization stats into `sink` (the same
1356    /// sink the standard backend records into).
1357    pub fn set_kkt_schur_summary_sink(
1358        &mut self,
1359        sink: std::sync::Arc<std::sync::Mutex<pounce_linsol::summary::LinearSolverSummary>>,
1360    ) {
1361        self.kkt_schur_summary_sink = Some(sink);
1362    }
1363
1364    /// Assemble the strategy bundle without a search-direction
1365    /// calculator. Used by structural unit tests that don't want to
1366    /// pull in a linear-solver backend.
1367    pub fn build(&self) -> AlgorithmBundle {
1368        self.build_inner(None)
1369    }
1370
1371    /// Same as [`Self::build`] but also constructs the
1372    /// `SymLinearSolver → AugSystemSolver → PdFullSpaceSolver →
1373    /// PdSearchDirCalc` chain via the supplied `factory`.
1374    pub fn build_with_backend(&self, mut factory: LinearBackendFactory) -> AlgorithmBundle {
1375        let backend = factory(self.linear_solver);
1376        let make_scaling = || -> Option<Box<dyn pounce_linsol::TSymScalingMethod>> {
1377            match self.linear_system_scaling {
1378                LinearSystemScalingChoice::None => None,
1379                LinearSystemScalingChoice::Ruiz => {
1380                    Some(Box::new(pounce_linsol::RuizTSymScalingMethod::new()))
1381                }
1382                LinearSystemScalingChoice::Mc19 => {
1383                    tracing::warn!(target: "pounce::algorithm",
1384                        "pounce: linear_system_scaling=mc19 not yet implemented; using no scaling"
1385                    );
1386                    None
1387                }
1388                LinearSystemScalingChoice::SlackBased => {
1389                    Some(Box::new(pounce_linsol::SlackBasedTSymScalingMethod::new()))
1390                }
1391            }
1392        };
1393        let linsol = TSymLinearSolver::new(backend, make_scaling(), self.linear_scaling_on_demand);
1394        let with_inertia_sink = |aug: StdAugSystemSolver| match self.inertia_sink.clone() {
1395            Some(sink) => aug.with_inertia_sink(sink),
1396            None => aug,
1397        };
1398        let inner_aug = with_inertia_sink(StdAugSystemSolver::new(linsol));
1399        // Limited-memory mode publishes the Hessian as a
1400        // `LowRankUpdateSymMatrix`; wrap the standard solver in the
1401        // Sherman-Morrison-Woodbury low-rank solver so the augmented
1402        // system factorizes only the diagonal `B0` and the quasi-Newton
1403        // update is applied as a rank-`m` correction (`O(n·m)` memory).
1404        let is_lbfgs = matches!(
1405            self.hessian_approximation,
1406            HessianApproxChoice::LimitedMemory
1407        );
1408        let aug_solver: Box<dyn AugSystemSolver> = if is_lbfgs {
1409            // A second, independent inner solver for the Hessian-free
1410            // solves. Both see one W shape each for their whole life, so
1411            // neither re-runs the backend's symbolic factorization when
1412            // the other's shape comes round — see
1413            // `LowRankAugSystemSolver::with_bypass_solver` (gh#730).
1414            let bypass_linsol = TSymLinearSolver::new(
1415                factory(self.linear_solver),
1416                make_scaling(),
1417                self.linear_scaling_on_demand,
1418            );
1419            Box::new(LowRankAugSystemSolver::with_bypass_solver(
1420                Box::new(inner_aug),
1421                Box::new(with_inertia_sink(StdAugSystemSolver::new(bypass_linsol))),
1422            ))
1423        } else if let Some((labels, cfg)) = self.resolved_kkt_blocks() {
1424            // Block-parallel KKT path (structured-KKT Phase 5b). Same gates as
1425            // the Schur arm: feral-specific, and the L-BFGS low-rank wrapper
1426            // owns the (2,2) block, so this is the exact-Hessian path only.
1427            if matches!(self.linear_solver, LinearSolverChoice::Feral) {
1428                let blocks = crate::kkt::BlockAugSystemSolver::new(inner_aug, labels, cfg)
1429                    .with_min_block_size(self.kkt_block_min_size);
1430                Box::new(match self.kkt_schur_summary_sink.clone() {
1431                    Some(sink) => blocks.with_summary_sink(sink),
1432                    None => blocks,
1433                })
1434            } else {
1435                Box::new(inner_aug)
1436            }
1437        } else if let Some((indices, cfg)) = self.kkt_schur.clone() {
1438            // Block-triangular / Schur KKT path (pounce#180 item 2). Only on the
1439            // exact-Hessian feral path — the Schur backend is feral-specific,
1440            // and the L-BFGS low-rank Woodbury wrapper owns the (2,2) block.
1441            // The Schur solver falls back to `StdAugSystemSolver` transparently
1442            // when the partition is unsuitable, so a stray hook never breaks a
1443            // solve; we gate on `linear_solver == Feral` here to avoid silently
1444            // ignoring a user's explicit MA57 selection.
1445            if matches!(self.linear_solver, LinearSolverChoice::Feral) {
1446                let schur = crate::kkt::SchurAugSystemSolver::new(inner_aug, indices, cfg);
1447                Box::new(match self.kkt_schur_summary_sink.clone() {
1448                    Some(sink) => schur.with_summary_sink(sink),
1449                    None => schur,
1450                })
1451            } else {
1452                Box::new(inner_aug)
1453            }
1454        } else {
1455            Box::new(inner_aug)
1456        };
1457        // Inertia-correction / Jacobian-regularization constants (#191):
1458        // registered but previously never read. Defaults equal the
1459        // registered defaults. `perturb_always_cd` goes through the setter
1460        // because it also rebuilds the initial jac-degeneracy state.
1461        let mut ph = PdPerturbationHandler::new();
1462        ph.delta_xs_max = self.perturbation.max_hessian_perturbation;
1463        ph.delta_xs_min = self.perturbation.min_hessian_perturbation;
1464        ph.delta_xs_first_inc_fact = self.perturbation.perturb_inc_fact_first;
1465        ph.delta_xs_inc_fact = self.perturbation.perturb_inc_fact;
1466        ph.delta_xs_dec_fact = self.perturbation.perturb_dec_fact;
1467        ph.delta_xs_init = self.perturbation.first_hessian_perturbation;
1468        ph.delta_cd_val = self.perturbation.jacobian_regularization_value;
1469        ph.delta_cd_exp = self.perturbation.jacobian_regularization_exponent;
1470        ph.set_perturb_always_cd(self.perturbation.perturb_always_cd);
1471        ph.delta_c_max_rungs = self.perturbation.perturb_delta_c_max_rungs;
1472        ph.delta_s_fact = self.perturbation.perturb_slack_fact;
1473        ph.delta_s_max_rows = self.perturbation.perturb_slack_max_rows;
1474        let perturb = Rc::new(RefCell::new(ph));
1475        let mut pd_solver = PdFullSpaceSolver::new(aug_solver, perturb);
1476        // Iterative-refinement constants (#191): registered but previously
1477        // never read, so overrides were silently dropped. Defaults equal
1478        // the registered defaults.
1479        pd_solver.min_refinement_steps = self.refinement.min_refinement_steps;
1480        pd_solver.max_refinement_steps = self.refinement.max_refinement_steps;
1481        pd_solver.residual_ratio_max = self.refinement.residual_ratio_max;
1482        pd_solver.residual_ratio_singular = self.refinement.residual_ratio_singular;
1483        pd_solver.residual_improvement_factor = self.refinement.residual_improvement_factor;
1484        // Inertia-free curvature test (#551 / #677). Both were registered
1485        // and never read; `neg_curv_test_tol` defaults to 0, which leaves
1486        // the heuristic off and the inertia check on, so this changes
1487        // nothing for a run that does not set it.
1488        pd_solver.neg_curv_test_tol = self.refinement.neg_curv_test_tol;
1489        pd_solver.neg_curv_test_reg = self.refinement.neg_curv_test_reg;
1490        // gh#857: share the escalation tally with the caller, so the
1491        // restoration sub-solve built from a clone of this builder counts
1492        // into the same total.
1493        if let Some(counter) = self.quality_escalation_counter.as_ref() {
1494            pd_solver.set_quality_escalation_counter(Rc::clone(counter));
1495        }
1496        let mut search_dir = PdSearchDirCalc::new(pd_solver);
1497        search_dir.mehrotra_algorithm = self.mehrotra_algorithm;
1498        search_dir.fast_step_computation = self.fast_step_computation;
1499        self.build_inner(Some(search_dir))
1500    }
1501
1502    /// Phase 5b assembly path for the SQP algorithm. Consults
1503    /// `self.algorithm`: when `ActiveSetSqp`, constructs an
1504    /// `SqpAlgorithm` using the supplied backend factory for the
1505    /// QP subproblem solver; otherwise returns `None` so the
1506    /// caller can fall back to the IPM `build_with_backend`.
1507    ///
1508    /// Sister to `build_with_backend`: the SQP algorithm doesn't
1509    /// share `AlgorithmBundle`'s shape (no mu_update / no IPM
1510    /// line search), so the two paths return different types.
1511    pub fn build_sqp_with_backend(
1512        &self,
1513        mut factory: LinearBackendFactory,
1514    ) -> Option<crate::sqp::SqpAlgorithm> {
1515        if !matches!(self.algorithm, AlgorithmChoice::ActiveSetSqp) {
1516            return None;
1517        }
1518        let backend = factory(self.linear_solver);
1519        let qp_solver = pounce_qp::ParametricActiveSetSolver::new(backend);
1520        Some(
1521            crate::sqp::SqpAlgorithm::new(qp_solver, self.sqp.clone())
1522                .with_qp_options(self.sqp_qp.clone()),
1523        )
1524    }
1525
1526    fn build_inner(&self, search_dir: Option<PdSearchDirCalc>) -> AlgorithmBundle {
1527        let mu_update: Box<dyn crate::mu::r#trait::MuUpdate> = match self.mu_strategy {
1528            MuStrategyChoice::Monotone => {
1529                let mut m = MonotoneMuUpdate::new();
1530                m.mu_init = self.mu.mu_init;
1531                // `mu_max` sentinel `-1` keeps the monotone default
1532                // (1e5); only override on a user-supplied positive.
1533                if self.mu.mu_max > 0.0 {
1534                    m.mu_max = self.mu.mu_max;
1535                }
1536                m.mu_min = self.mu.mu_min;
1537                m.mu_target = self.mu.mu_target;
1538                m.mu_linear_decrease_factor = self.mu.mu_linear_decrease_factor;
1539                m.mu_superlinear_decrease_power = self.mu.mu_superlinear_decrease_power;
1540                m.mu_allow_fast_monotone_decrease = self.mu.mu_allow_fast_monotone_decrease;
1541                m.barrier_tol_factor = self.mu.barrier_tol_factor;
1542                m.tau_min = self.mu.tau_min;
1543                m.compl_inf_tol = self.conv_check.compl_inf_tol;
1544                Box::new(m)
1545            }
1546            MuStrategyChoice::Adaptive => {
1547                let mut adaptive = AdaptiveMuUpdate::new();
1548                adaptive.mu_oracle = self.mu_oracle;
1549                adaptive.mu_init = self.mu.mu_init;
1550                // Adaptive treats `mu_max == -1` as "lazy init from
1551                // `mu_max_fact * curr_avrg_compl`" — forward the
1552                // sentinel as-is.
1553                adaptive.mu_max = self.mu.mu_max;
1554                adaptive.mu_max_fact = self.mu.mu_max_fact;
1555                adaptive.mu_min = self.mu.mu_min;
1556                adaptive.compl_inf_tol = self.conv_check.compl_inf_tol;
1557                adaptive.mu_linear_decrease_factor = self.mu.mu_linear_decrease_factor;
1558                adaptive.mu_superlinear_decrease_power = self.mu.mu_superlinear_decrease_power;
1559                adaptive.barrier_tol_factor = self.mu.barrier_tol_factor;
1560                adaptive.tau_min = self.mu.tau_min;
1561                adaptive.sigma_min = self.mu.sigma_min;
1562                adaptive.sigma_max = self.mu.sigma_max;
1563                adaptive.adaptive_mu_globalization = self.mu.adaptive_mu_globalization;
1564                adaptive.qf_norm_type = self.mu.quality_function_norm_type;
1565                adaptive.qf_centrality_type = self.mu.quality_function_centrality;
1566                adaptive.qf_balancing_term = self.mu.quality_function_balancing_term;
1567                adaptive.qf_max_section_steps = self.mu.quality_function_max_section_steps;
1568                adaptive.qf_section_sigma_tol = self.mu.quality_function_section_sigma_tol;
1569                adaptive.qf_section_qf_tol = self.mu.quality_function_section_qf_tol;
1570                adaptive.probing_iterate_quality_factor = self.mu.probing_iterate_quality_factor;
1571                adaptive.probing_guard_feasible_tol = self.conv_check.tol;
1572                adaptive.adaptive_mu_safeguard_factor = self.mu.adaptive_mu_safeguard_factor;
1573                adaptive.adaptive_mu_monotone_init_factor =
1574                    self.mu.adaptive_mu_monotone_init_factor;
1575                adaptive.restore_accepted_iterate = self.mu.adaptive_mu_restore_previous_iterate;
1576                adaptive.max_free_returns = self.mu.adaptive_mu_max_free_returns;
1577                adaptive.budget_pin_fraction = self.mu.adaptive_mu_budget_pin_fraction;
1578                // The pin measures against the same budget the
1579                // convergence check enforces (pounce#753); the
1580                // `conv_check` copies are the ones the application
1581                // also hands to `Deadline::new`.
1582                adaptive.max_cpu_time = self.conv_check.max_cpu_time;
1583                adaptive.max_wall_time = self.conv_check.max_wall_time;
1584                adaptive.adaptive_mu_kkterror_red_iters = self.mu.adaptive_mu_kkterror_red_iters;
1585                adaptive.adaptive_mu_kkterror_red_fact = self.mu.adaptive_mu_kkterror_red_fact;
1586                adaptive.adaptive_mu_kkt_norm = self.mu.adaptive_mu_kkt_norm_type;
1587                adaptive.filter_margin_fact = self.mu.filter_margin_fact;
1588                adaptive.filter_max_margin = self.mu.filter_max_margin;
1589                Box::new(adaptive)
1590            }
1591        };
1592
1593        let acceptor: Box<dyn BacktrackingLsAcceptor> = match self.line_search_method {
1594            LineSearchChoice::Filter => {
1595                // Filter switching / Armijo / margin constants (#191):
1596                // registered but previously never read. Set them on the
1597                // concrete acceptor before boxing; defaults equal the
1598                // registered defaults, so a run that doesn't set them is
1599                // unchanged.
1600                let mut f = FilterLsAcceptor::default();
1601                f.eta_phi = self.line_search.eta_phi;
1602                f.delta_armijo = self.line_search.delta;
1603                f.theta_min_fact = self.line_search.theta_min_fact;
1604                f.theta_max_fact = self.line_search.theta_max_fact;
1605                f.theta_max_row_scale_kappa = self.line_search.theta_max_row_scale_kappa;
1606                f.theta_max_adaptive_trigger = self.line_search.theta_max_adaptive_trigger;
1607                f.theta_max_adaptive_factor = self.line_search.theta_max_adaptive_factor;
1608                f.theta_max_adaptive_max_raises = self.line_search.theta_max_adaptive_max_raises;
1609                f.gamma_phi = self.line_search.gamma_phi;
1610                f.gamma_theta = self.line_search.gamma_theta;
1611                f.s_phi = self.line_search.s_phi;
1612                f.s_theta = self.line_search.s_theta;
1613                f.alpha_min_frac = self.line_search.alpha_min_frac;
1614                f.obj_max_inc = self.line_search.obj_max_inc;
1615                f.max_filter_resets = self.line_search.max_filter_resets;
1616                f.filter_reset_trigger = self.line_search.filter_reset_trigger;
1617                Box::new(f)
1618            }
1619            // Penalty-acceptor constants: same direct-field pattern as
1620            // the filter arm above. `reset()` re-seeds ν (and `last_nu`)
1621            // from the freshly-set `nu_init`, which `default()` had
1622            // seeded from the registered default.
1623            LineSearchChoice::Penalty | LineSearchChoice::CgPenalty => {
1624                // CG-penalty acceptor lands with the rest of the
1625                // CG-penalty path; fall back to the penalty acceptor's
1626                // surface for now.
1627                let mut p = PenaltyLsAcceptor::default();
1628                p.nu_init = self.line_search.nu_init;
1629                p.nu_inc = self.line_search.nu_inc;
1630                p.rho = self.line_search.rho;
1631                p.eta_penalty = self.line_search.eta_penalty;
1632                p.reset();
1633                Box::new(p)
1634            }
1635        };
1636        let mut line_search = BacktrackingLineSearch::new(acceptor);
1637        line_search.alpha_red_factor = self.line_search.alpha_red_factor;
1638        line_search.filter_theta_roundoff_retry = self.line_search.filter_theta_roundoff_retry;
1639        line_search.objective_noise_wolfe = self.line_search.objective_noise_wolfe;
1640        // Resolve `None` against the Hessian mode; see the field's doc
1641        // for the measurement behind the split (gh#818).
1642        line_search.alpha_red_factor_min =
1643            self.line_search
1644                .alpha_red_factor_min
1645                .unwrap_or(match self.hessian_approximation {
1646                    // The criterion in the field's doc is whether the
1647                    // model's *scale* is trustworthy, not whether it is
1648                    // the exact Hessian. A quasi-Newton `B` can be wrong
1649                    // by orders of magnitude in any direction its
1650                    // curvature pairs do not span, which is as true of
1651                    // the partitioned elements as of the limited-memory
1652                    // ones — they are the same update on a finer
1653                    // decomposition.
1654                    HessianApproxChoice::LimitedMemory | HessianApproxChoice::Partitioned => 0.05,
1655                    // Equal to `alpha_red_factor`, so the clamp in
1656                    // `next_alpha` collapses and the sequence is upstream's.
1657                    //
1658                    // `FiniteDifference` belongs here rather than above:
1659                    // it recovers the Lagrangian Hessian itself by
1660                    // probing the analytic Jacobian, so it carries no
1661                    // curvature history and its step is a Newton step
1662                    // whose length is meaningful. It is the same
1663                    // distinction `hessian_at_current` draws — a pure
1664                    // function of `(x, y)` on one side, a history-carrying
1665                    // `B` on the other. And the measurement behind the
1666                    // split cuts this way too: forcing `0.05` onto a path
1667                    // with a meaningful step length cost `eigena2` a
1668                    // solve.
1669                    HessianApproxChoice::Exact | HessianApproxChoice::FiniteDifference => {
1670                        self.line_search.alpha_red_factor
1671                    }
1672                });
1673        line_search.watchdog_shortened_iter_trigger =
1674            self.line_search.watchdog_shortened_iter_trigger;
1675        line_search.watchdog_trial_iter_max = self.line_search.watchdog_trial_iter_max;
1676        line_search.soft_resto_pderror_reduction_factor =
1677            self.line_search.soft_resto_pderror_reduction_factor;
1678        line_search.max_soft_resto_iters = self.line_search.max_soft_resto_iters;
1679        line_search.accept_every_trial_step = self.line_search.accept_every_trial_step;
1680        line_search.alpha_for_y = self.line_search.alpha_for_y;
1681        line_search.accept_after_max_steps = self.line_search.accept_after_max_steps;
1682        // Second-order-correction constants (#191): registered but
1683        // previously never read. Same direct-field pattern as the
1684        // watchdog knobs above.
1685        line_search.max_soc = self.line_search.max_soc;
1686        line_search.kappa_soc = self.line_search.kappa_soc;
1687        line_search.soc_method = self.line_search.soc_method;
1688
1689        let conv_check: Box<dyn crate::conv_check::r#trait::ConvCheck> =
1690            Box::new(OptErrorConvCheck {
1691                tol: self.conv_check.tol,
1692                dual_inf_tol: self.conv_check.dual_inf_tol,
1693                constr_viol_tol: self.conv_check.constr_viol_tol,
1694                compl_inf_tol: self.conv_check.compl_inf_tol,
1695                acceptable_tol: self.conv_check.acceptable_tol,
1696                acceptable_dual_inf_tol: self.conv_check.acceptable_dual_inf_tol,
1697                acceptable_constr_viol_tol: self.conv_check.acceptable_constr_viol_tol,
1698                acceptable_compl_inf_tol: self.conv_check.acceptable_compl_inf_tol,
1699                acceptable_obj_change_tol: self.conv_check.acceptable_obj_change_tol,
1700                acceptable_iter: self.conv_check.acceptable_iter,
1701                max_iter: self.conv_check.max_iter,
1702                max_cpu_time: self.conv_check.max_cpu_time,
1703                max_wall_time: self.conv_check.max_wall_time,
1704                acceptable_count: 0,
1705                last_acceptable_obj: None,
1706                infeas_stationarity_tol: self.conv_check.infeas_stationarity_tol,
1707                infeas_viol_kappa: self.conv_check.infeas_viol_kappa,
1708                infeas_max_streak: self.conv_check.infeas_max_streak,
1709                infeas_streak: 0,
1710                obj_scale_certificate_threshold: self.conv_check.obj_scale_certificate_threshold,
1711                primal_noise_floor_kappa: self.conv_check.primal_noise_floor_kappa,
1712                acceptable_progress_kappa: self.conv_check.acceptable_progress_kappa,
1713                acceptable_window: std::collections::VecDeque::new(),
1714                acceptable_progress_refusals: 0,
1715                dual_inf_scale_kappa: self.conv_check.dual_inf_scale_kappa,
1716                dual_floor_reported: false,
1717                veto_fired: false,
1718                acceptable_veto_fired: false,
1719                masked_acceptable_veto_fired: false,
1720                veto_extra_iters: 0,
1721                rel_infeas_extra_iters: 0,
1722                prev_rel_viol: f64::NAN,
1723            });
1724
1725        let init: Box<dyn crate::init::r#trait::IterateInitializer> = if self.warm_start_init_point
1726        {
1727            Box::new(WarmStartIterateInitializer::with_options(
1728                resolved_warm_options(&self.warm, &self.init),
1729            ))
1730        } else {
1731            let mut d = DefaultIterateInitializer::with_eq_mult_calculator(Box::new(
1732                LeastSquareMults::new(),
1733            ));
1734            d.bound_push = self.init.bound_push;
1735            d.bound_frac = self.init.bound_frac;
1736            d.slack_bound_push = self.init.slack_bound_push;
1737            d.slack_bound_frac = self.init.slack_bound_frac;
1738            d.constr_mult_init_max = self.init.constr_mult_init_max;
1739            d.bound_mult_init_val = self.init.bound_mult_init_val;
1740            d.bound_mult_init_method = self.init.bound_mult_init_method.clone();
1741            d.least_square_init_primal = self.init.least_square_init_primal;
1742            Box::new(d)
1743        };
1744
1745        let eq_mult: Box<dyn crate::eq_mult::r#trait::EqMultCalculator> =
1746            Box::new(LeastSquareMults::new());
1747
1748        let hess: Box<dyn crate::hess::r#trait::HessianUpdater> = match self.hessian_approximation {
1749            HessianApproxChoice::Exact => Box::new(ExactHessianUpdater::new()),
1750            HessianApproxChoice::LimitedMemory => Box::new(LimMemQuasiNewtonUpdater {
1751                update_type: self.limited_memory_update_type,
1752                max_history: self.limited_memory_max_history,
1753                init_val_max: self.limited_memory_init_val_max,
1754                init_val_min: self.limited_memory_init_val_min,
1755                initial_approx: self.limited_memory_initialization,
1756                init_val: self.limited_memory_init_val,
1757                max_skipping: self.limited_memory_max_skipping,
1758                nonlinear_vars: self.limited_memory_nonlinear_vars.clone(),
1759                ..LimMemQuasiNewtonUpdater::default()
1760            }),
1761            HessianApproxChoice::Partitioned => {
1762                let mut u =
1763                    crate::hess::partitioned_quasi_newton::PartitionedQuasiNewtonUpdater::new(
1764                        self.partitioned_update_type,
1765                    );
1766                u.max_element = self.partitioned_max_element;
1767                u.objective_vars = self.objective_nonlinear_vars.clone();
1768                u.declared_pattern = self.hessian_declared_pattern.clone();
1769                u.curvature_cap = self.partitioned_curvature_cap;
1770                u.mode = self.partitioned_elements;
1771                u.block_size = self.partitioned_block_size;
1772                // Damped BFGS is the right pairing for a Lagrangian
1773                // block: unlike a single constraint's Hessian, the
1774                // Lagrangian's is the object the IPM wants a positive
1775                // definite model of, and the sign problem that makes
1776                // damping wrong per constraint does not arise. Only when
1777                // the caller has not named a formula.
1778                if self.partitioned_elements
1779                    == crate::hess::partitioned_quasi_newton::ElementMode::PrimalBlock
1780                    && !self.partitioned_update_type_was_set
1781                {
1782                    u.update_type = UpdateType::Bfgs;
1783                }
1784                u.init_val_min = self.limited_memory_init_val_min;
1785                u.init_val_max = self.limited_memory_init_val_max;
1786                Box::new(u)
1787            }
1788            HessianApproxChoice::FiniteDifference => {
1789                let mut u = crate::hess::fd_hessian::FdHessianUpdater::new(self.fd_hessian_pattern);
1790                u.coloring = self.fd_hessian_coloring;
1791                u.reuse_tol = self.fd_hessian_reuse_tol;
1792                u.objective_vars = self.objective_nonlinear_vars.clone();
1793                u.nonlinear_vars = self.limited_memory_nonlinear_vars.clone();
1794                Box::new(u)
1795            }
1796        };
1797
1798        let iter_output: Box<dyn crate::output::r#trait::IterationOutput> = {
1799            use crate::output::orig::{InfPrTag, PrintInfoString};
1800            let mut o = OrigIterationOutput::new();
1801            o.print_frequency_iter = self.output.print_frequency_iter;
1802            o.print_frequency_time = self.output.print_frequency_time;
1803            o.print_info_string = if self.output.print_info_string {
1804                PrintInfoString::Yes
1805            } else {
1806                PrintInfoString::No
1807            };
1808            o.inf_pr_output = if self.output.inf_pr_output_internal {
1809                InfPrTag::Internal
1810            } else {
1811                InfPrTag::Original
1812            };
1813            Box::new(o)
1814        };
1815
1816        AlgorithmBundle {
1817            mu_update,
1818            conv_check,
1819            init,
1820            eq_mult,
1821            hess,
1822            line_search,
1823            iter_output,
1824            search_dir,
1825        }
1826    }
1827}
1828
1829#[cfg(test)]
1830mod tests {
1831    use super::*;
1832
1833    #[test]
1834    fn warm_options_take_the_init_default_not_their_own() {
1835        let mut init = InitOptions::default();
1836        init.bound_mult_init_val = 10.0; // the Mehrotra override value
1837        let mut warm = WarmStartOptions::default();
1838        warm.bound_mult_init_val = 123.0; // stale copy must lose
1839        let resolved = resolved_warm_options(&warm, &init);
1840        assert_eq!(resolved.bound_mult_init_val, 10.0);
1841        // everything else passes through untouched
1842        assert_eq!(resolved.mult_bound_push, warm.mult_bound_push);
1843        assert_eq!(resolved.target_mu, warm.target_mu);
1844    }
1845
1846    #[test]
1847    fn default_builder_assembles() {
1848        let bundle = AlgorithmBuilder::new().build();
1849        // Sanity: the placeholder traits compile and the boxed
1850        // strategies don't panic on construction.
1851        let _ = bundle.line_search.acceptor();
1852        assert!(bundle.search_dir.is_none());
1853    }
1854
1855    #[test]
1856    fn build_with_backend_assembles_search_dir_chain() {
1857        // Drive the builder with the FERAL backend factory; the
1858        // resulting bundle should expose a populated `PdSearchDirCalc`.
1859        let factory: LinearBackendFactory = Box::new(|_| {
1860            Box::new(pounce_feral::FeralSolverInterface::new())
1861                as Box<dyn SparseSymLinearSolverInterface>
1862        });
1863        let bundle = AlgorithmBuilder::new().build_with_backend(factory);
1864        assert!(bundle.search_dir.is_some());
1865    }
1866
1867    #[test]
1868    fn limited_memory_sr1_propagates() {
1869        let b = AlgorithmBuilder {
1870            hessian_approximation: HessianApproxChoice::LimitedMemory,
1871            limited_memory_update_type: UpdateType::Sr1,
1872            ..AlgorithmBuilder::default()
1873        };
1874        let _bundle = b.build();
1875    }
1876
1877    #[test]
1878    fn every_strategy_combination_assembles_without_panic() {
1879        let solvers = [LinearSolverChoice::Ma57, LinearSolverChoice::Feral];
1880        let mu = [MuStrategyChoice::Monotone, MuStrategyChoice::Adaptive];
1881        let hess = [
1882            HessianApproxChoice::Exact,
1883            HessianApproxChoice::LimitedMemory,
1884        ];
1885        let ls = [
1886            LineSearchChoice::Filter,
1887            LineSearchChoice::CgPenalty,
1888            LineSearchChoice::Penalty,
1889        ];
1890        for &linear_solver in &solvers {
1891            for &mu_strategy in &mu {
1892                for &hessian_approximation in &hess {
1893                    for &line_search_method in &ls {
1894                        let _ = AlgorithmBuilder {
1895                            algorithm: AlgorithmChoice::default(),
1896                            linear_solver,
1897                            linear_system_scaling: LinearSystemScalingChoice::None,
1898                            linear_scaling_on_demand: true,
1899                            mu_strategy,
1900                            mu_oracle: MuOracleKind::QualityFunction,
1901                            hessian_approximation,
1902                            partitioned_update_type: UpdateType::Sr1,
1903                            partitioned_update_type_was_set: false,
1904                            partitioned_max_element: 64,
1905                            objective_nonlinear_vars: None,
1906                            hessian_declared_pattern: None,
1907                            partitioned_curvature_cap: Number::INFINITY,
1908                            partitioned_elements:
1909                                crate::hess::partitioned_quasi_newton::ElementMode::PerConstraint,
1910                            partitioned_block_size: 64,
1911                            fd_hessian_pattern: crate::hess::fd_hessian::FdPatternSource::Declared,
1912                            fd_hessian_coloring: crate::hess::fd_hessian::FdColoring::Cpr,
1913                            fd_hessian_reuse_tol: 0.0,
1914                            limited_memory_update_type: UpdateType::Bfgs,
1915                            limited_memory_max_history: 6,
1916                            limited_memory_init_val_max: 1e8,
1917                            limited_memory_init_val_min: 1e-8,
1918                            limited_memory_initialization: InitialApprox::Scalar1,
1919                            limited_memory_init_val: 1.0,
1920                            limited_memory_max_skipping: 2,
1921                            limited_memory_nonlinear_vars: None,
1922                            line_search_method,
1923                            warm_start_init_point: false,
1924                            mehrotra_algorithm: false,
1925                            fast_step_computation: false,
1926                            kappa_sigma: 1e10,
1927                            ftb_centrality_floor: crate::ftb_floor::DEFAULT_FTB_CENTRALITY_FLOOR,
1928                            recalc_y: false,
1929                            recalc_y_feas_tol: 1e-6,
1930                            kappa_d: 1e-5,
1931                            s_max: 100.0,
1932                            tiny_step_tol: 10.0 * Number::EPSILON,
1933                            tiny_step_y_tol: 1e-2,
1934                            diverging_iterates_tol: 1e20,
1935                            dual_diverging_streak: 0,
1936                            dual_divergence_retry_step_tol: 1e-5,
1937                            dual_divergence_retry_du_floor: 1e2,
1938                            tiny_step_dual_stall_iters: 10,
1939                            resto_decline_deferrals: 1,
1940                            resto_decline_progress_ratio: 0.5,
1941                            neg_curv_escapes: 1,
1942                            limited_memory_ls_failure_restarts: 0,
1943                            kkt_fidelity_tol: 0.0,
1944                            conv_check: ConvCheckOptions::default(),
1945                            mu: MuOptions::default(),
1946                            line_search: LineSearchOptions::default(),
1947                            refinement: RefinementOptions::default(),
1948                            perturbation: PerturbationOptions::default(),
1949                            resto: RestoOptions::default(),
1950                            output: OutputOptions::default(),
1951                            warm: WarmStartOptions::default(),
1952                            sqp: crate::sqp::SqpOptions::default(),
1953                            sqp_qp: pounce_qp::QpOptions::sqp_subproblem(),
1954                            init: InitOptions::default(),
1955                            kkt_schur: None,
1956                            kkt_blocks: None,
1957                            kkt_blocks_shared: None,
1958                            kkt_block_min_size:
1959                                crate::kkt::block_aug_system_solver::DEFAULT_MIN_BLOCK_SIZE,
1960                            kkt_schur_summary_sink: None,
1961                            inertia_sink: None,
1962                            quality_escalation_counter: None,
1963                        }
1964                        .build();
1965                    }
1966                }
1967            }
1968        }
1969    }
1970}