Skip to main content

pounce_algorithm/kkt/
aug_system_solver.rs

1//! Augmented-system solver trait — port of `IpAugSystemSolver.hpp`.
2//!
3//! Solves the symmetric saddle-point system
4//!
5//! ```text
6//!   [ W·factor + Σ_x + δ_x I       0          J_c^T   J_d^T ] [ dx ]   [ rx ]
7//!   [          0           Σ_s + δ_s I        0       -I    ] [ ds ] = [ rs ]
8//!   [         J_c                  0       -Σ_c-δ_c    0    ] [ dyc]   [ rc ]
9//!   [         J_d                 -I            0   -Σ_d-δ_d] [ dyd]   [ rd ]
10//! ```
11//!
12//! See `KKT_SYSTEM.md` §3 for the sign convention. `Σ_x = D_x`, `Σ_s
13//! = D_s`, `Σ_c = D_c`, `Σ_d = D_d` are the diagonal weights pulled
14//! from `IpoptCalculatedQuantities`. Any of the `D_*` may be `None`,
15//! interpreted as zero. `delta_*` are the perturbations driven by the
16//! `PerturbationHandler`.
17
18use pounce_common::timing::TimingStatistics;
19use pounce_common::types::{Index, Number};
20use pounce_linalg::{Matrix, SymMatrix, Vector};
21use pounce_linsol::{ESymSolverStatus, FactorPattern};
22use std::rc::Rc;
23
24/// Bundle of the matrices/vectors that define one augmented-system
25/// instance. Lives only for the duration of the call. Mirrors the
26/// long argument list of upstream `AugSystemSolver::Solve`.
27pub struct AugSysCoeffs<'a> {
28    /// Hessian-of-Lagrangian block. `None` means W = 0 (used by
29    /// `LeastSquareMults` and the resto-NLP equality multiplier
30    /// estimate).
31    pub w: Option<&'a dyn SymMatrix>,
32    /// Multiplier on `W` (typically 1.0; restoration uses ζ).
33    pub w_factor: Number,
34    /// `D_x`, the (1,1) primal weight diagonal. `None` means zero.
35    pub d_x: Option<&'a dyn Vector>,
36    pub delta_x: Number,
37    /// `D_s`, the (2,2) slack weight diagonal. `None` means zero.
38    pub d_s: Option<&'a dyn Vector>,
39    pub delta_s: Number,
40    /// Equality-constraint Jacobian, `m_c × n_x`.
41    pub j_c: &'a dyn Matrix,
42    /// `D_c`, the (3,3) diagonal weight. `None` means zero. Goes in
43    /// with a *negative* sign, matching upstream.
44    pub d_c: Option<&'a dyn Vector>,
45    pub delta_c: Number,
46    /// Inequality-constraint Jacobian, `m_d × n_x`.
47    pub j_d: &'a dyn Matrix,
48    /// `D_d`, the (4,4) diagonal weight. `None` means zero. Goes in
49    /// with a *negative* sign, matching upstream.
50    pub d_d: Option<&'a dyn Vector>,
51    pub delta_d: Number,
52}
53
54/// Right-hand sides for one solve. All four slices are required;
55/// upstream always provides all four (even if some are zero).
56pub struct AugSysRhs<'a> {
57    pub rhs_x: &'a dyn Vector,
58    pub rhs_s: &'a dyn Vector,
59    pub rhs_c: &'a dyn Vector,
60    pub rhs_d: &'a dyn Vector,
61}
62
63/// Solution slots, written in place. Must already be sized to match
64/// the corresponding RHS dim.
65pub struct AugSysSol<'a> {
66    pub sol_x: &'a mut dyn Vector,
67    pub sol_s: &'a mut dyn Vector,
68    pub sol_c: &'a mut dyn Vector,
69    pub sol_d: &'a mut dyn Vector,
70}
71
72/// Trait surface mirroring `Ipopt::AugSystemSolver`.
73pub trait AugSystemSolver {
74    /// Whether the underlying linear solver reports inertia.
75    fn provides_inertia(&self) -> bool;
76
77    /// Number of negative eigenvalues observed in the most recent
78    /// factorization. Caller checks `provides_inertia()` first.
79    fn number_of_neg_evals(&self) -> Index;
80
81    /// Dimension of the assembled augmented (KKT) system. Used by the
82    /// interactive debugger to report inertia; default 0 for backends
83    /// that don't track it.
84    fn system_dim(&self) -> Index {
85        0
86    }
87
88    /// Triplets of the assembled KKT matrix `(dim, irn, jcn, vals)`
89    /// (1-based lower triangle), for the debugger's `viz kkt`. Default
90    /// `None` for backends that don't expose them.
91    fn kkt_triplets(&self) -> Option<(Index, Vec<Index>, Vec<Index>, Vec<Number>)> {
92        None
93    }
94
95    /// The `LDLᵀ` factor pattern (and optionally values) of the most
96    /// recent factorization, for the debugger's `viz L`. Default `None`.
97    fn l_factor(&self, _want_values: bool) -> Option<FactorPattern> {
98        None
99    }
100
101    /// Ask the underlying solver for higher-quality pivoting.
102    fn increase_quality(&mut self) -> bool;
103
104    /// Status of the most recent `solve` call.
105    fn last_solve_status(&self) -> ESymSolverStatus;
106
107    /// Install the shared per-solve `TimingStatistics` so the
108    /// linear-system factor/back-solve calls are attributed to
109    /// `linear_system_factorization` / `linear_system_back_solve`.
110    /// Default impl is a no-op (timing disabled); the standard
111    /// solver overrides to record both fields, and composite solvers
112    /// (LowRank) forward to their inner solver.
113    fn set_timing_stats(&mut self, _timing: Rc<TimingStatistics>) {}
114
115    /// Install the shared per-solve diagnostics state so KKT-dump
116    /// sites can consult per-iter gating. Default impl is a no-op
117    /// (diagnostics disabled); the standard solver overrides to wire
118    /// in the dump path.
119    fn set_diagnostics(&mut self, _diag: Rc<pounce_common::diagnostics::DiagnosticsState>) {}
120
121    /// Push the per-iterate part of `linear_system_scaling=slack-based`
122    /// down to the linear solver's scaling method. Default no-op;
123    /// `StdAugSystemSolver` forwards to its `TSymLinearSolver`, and
124    /// composite solvers forward to their inner solver.
125    ///
126    /// Called once per iteration rather than once per solve: the
127    /// quantity is a function of the iterate and several augmented
128    /// solves share one. See `IpoptCq::curr_slack_based_s_scaling`.
129    fn set_slack_scaling(&mut self, _nx: Index, _s_scale: &[Number]) {}
130
131    /// Whether this solver can consume a `LowRankUpdateSymMatrix` as
132    /// `coeffs.w` directly, applying it by Sherman-Morrison-Woodbury
133    /// rather than needing an assembled triplet matrix.
134    ///
135    /// Default `false`: a triplet-based backend must be handed triplets.
136    /// `LowRankAugSystemSolver` overrides it, and composite solvers
137    /// forward their inner solver's answer.
138    ///
139    /// Exists so restoration can ask before choosing between handing its
140    /// orig block over in factored form and densifying it — the dense
141    /// form is `O(n²)` and aborts the process at 60k variables (#684).
142    fn handles_low_rank_w(&self) -> bool {
143        false
144    }
145
146    /// One factor + back-substitution for the full 4×4 block system.
147    /// `check_neg_evals=true` asks the linsol to verify that the
148    /// observed inertia equals `num_neg_evals`; on mismatch the
149    /// status is `WrongInertia` and the solution is left untouched.
150    fn solve(
151        &mut self,
152        coeffs: &AugSysCoeffs<'_>,
153        rhs: &AugSysRhs<'_>,
154        sol: &mut AugSysSol<'_>,
155        check_neg_evals: bool,
156        num_neg_evals: Index,
157    ) -> ESymSolverStatus;
158
159    /// Back-substitution only, reusing the factorization from the most
160    /// recent successful `solve`. Caller must guarantee the augmented
161    /// matrix is byte-identical to that solve (same W, J_c, J_d, all
162    /// diagonals, all perturbations, same pivot tolerance). Used by
163    /// `PdFullSpaceSolver`'s iterative-refinement loop and same-matrix
164    /// fast path to avoid the per-iter MA57BD refactor that dominates
165    /// pounce-ma57 wall time on long-iter problems (e.g. cont5_2_4_l
166    /// drops from 97s → ~30s once refactor-per-refinement is gone).
167    ///
168    /// Default impl falls through to `solve` (correct but slow);
169    /// `StdAugSystemSolver` overrides to skip `refill_values` and pass
170    /// `new_matrix=false` to the linear solver.
171    fn resolve(
172        &mut self,
173        coeffs: &AugSysCoeffs<'_>,
174        rhs: &AugSysRhs<'_>,
175        sol: &mut AugSysSol<'_>,
176    ) -> ESymSolverStatus {
177        self.solve(coeffs, rhs, sol, false, 0)
178    }
179
180    /// Solve the same KKT system for `nrhs` right-hand sides. Default
181    /// impl loops [`solve`]; concrete backends override only when they
182    /// can amortize factorization across calls. Mirrors upstream's
183    /// `AugSystemSolver::MultiSolve` (`IpAugSystemSolver.hpp:113-150`).
184    ///
185    /// `rhs_list` and `sol_list` must have the same length; each pair
186    /// describes one independent solve. The same `coeffs` are used for
187    /// every column.
188    fn multi_solve(
189        &mut self,
190        coeffs: &AugSysCoeffs<'_>,
191        rhs_list: &[&AugSysRhs<'_>],
192        sol_list: &mut [&mut AugSysSol<'_>],
193        check_neg_evals: bool,
194        num_neg_evals: Index,
195    ) -> ESymSolverStatus {
196        debug_assert_eq!(rhs_list.len(), sol_list.len());
197        for (rhs, sol) in rhs_list.iter().zip(sol_list.iter_mut()) {
198            let status = self.solve(coeffs, rhs, *sol, check_neg_evals, num_neg_evals);
199            if status != ESymSolverStatus::Success {
200                return status;
201            }
202        }
203        ESymSolverStatus::Success
204    }
205
206    /// Back-substitution only against the cached factor for
207    /// `nrhs` right-hand sides, packed in **column-major** layout in
208    /// `packed_rhs`. Each column has length `dim = n_x + n_s + n_y_c +
209    /// n_y_d` (the aug-system dim — z/v blocks are not part of this
210    /// path; callers expand them via `expand_bound_multipliers` after
211    /// the fact). Solutions overwrite `packed_rhs` in place.
212    ///
213    /// Returns `None` when the backend does not support this fast
214    /// path; the caller should then fall back to a per-RHS loop over
215    /// [`resolve`]. The contract on `coeffs` and `have_factor` matches
216    /// [`resolve`]'s.
217    ///
218    /// `StdAugSystemSolver` overrides this to forward to
219    /// `pounce_linsol::TSymLinearSolver::multi_solve` with `nrhs > 1`,
220    /// which lets the underlying backend (FERAL / MA57 / LAPACK)
221    /// amortize per-call setup and, where supported, block the
222    /// triangular solves. Used by `pounce-sensitivity` for the JaxProblem
223    /// `jacrev` backward, where every cotangent re-solves against the
224    /// same converged factor (pounce#77 follow-up).
225    fn try_resolve_many_flat(
226        &mut self,
227        _coeffs: &AugSysCoeffs<'_>,
228        _packed_rhs: &mut [Number],
229        _nrhs: usize,
230    ) -> Option<ESymSolverStatus> {
231        None
232    }
233
234    /// Factorize **and** solve `nrhs` right-hand sides in a single
235    /// backend call, with `packed_rhs` in the same column-major layout
236    /// [`Self::try_resolve_many_flat`] uses. Solutions overwrite
237    /// `packed_rhs` in place.
238    ///
239    /// This is the factorizing counterpart of `try_resolve_many_flat`,
240    /// and it exists to reproduce upstream's single
241    /// `AugSystemSolver::MultiSolve` (`IpLowRankAugSystemSolver.cpp:487`)
242    /// in one step rather than two. Splitting that call into a
243    /// single-RHS `solve` followed by a batched `try_resolve_many_flat`
244    /// costs one **extra full traversal of the factor**: a sparse
245    /// triangular solve streams the whole factor once per call and then
246    /// applies it to every column, so its cost is `F + nrhs·W` with `F`
247    /// several times `W` on a large KKT. Merging the two calls removes
248    /// one `F` per Sherman-Morrison-Woodbury update.
249    ///
250    /// Returns `None` when the backend does not support the path, in
251    /// which case the caller keeps the split. Inertia bookkeeping
252    /// (`check_neg_evals` / `num_neg_evals`) matches [`Self::solve`].
253    fn try_solve_many_flat(
254        &mut self,
255        _coeffs: &AugSysCoeffs<'_>,
256        _packed_rhs: &mut [Number],
257        _nrhs: usize,
258        _check_neg_evals: bool,
259        _num_neg_evals: Index,
260    ) -> Option<ESymSolverStatus> {
261        None
262    }
263
264    /// Whether [`Self::try_resolve_many_flat`] with `nrhs` columns returns
265    /// **bit-identical** results to `nrhs` separate [`Self::resolve`] calls.
266    ///
267    /// Consulted only by callers that batch as a pure optimization inside an
268    /// iteration whose trajectory must not move — today that is
269    /// `LowRankAugSystemSolver`'s SMW correction block (gh#729). A caller
270    /// batching independent questions (`pounce-sensitivity`'s `jacrev`
271    /// backward) has no such constraint and does not ask.
272    ///
273    /// Defaults to `false`, the conservative answer. `StdAugSystemSolver`
274    /// forwards it to the linear-solver backend; see
275    /// `SparseSymLinearSolverInterface::multi_solve_matches_single_solve`
276    /// for why the answer depends on `nrhs`.
277    fn multi_solve_matches_single_solve(&self, _nrhs: usize) -> bool {
278        false
279    }
280}