pounce_algorithm/sqp/result.rs
1//! `SqpResult` / `SqpStatus` / `SqpError` — return types for
2//! `SqpAlgorithm::optimize`.
3
4use pounce_common::Number;
5use pounce_qp::{QpError, WorkingSet};
6use std::fmt;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum SqpStatus {
10 /// KKT residuals all below their tolerances.
11 Optimal,
12 /// `max_iter` reached without convergence.
13 MaxIter,
14 /// QP subproblem returned an `Infeasible` status (elastic
15 /// mode certified the QP infeasible).
16 InfeasibleSubproblem,
17 /// Line search failed to find an acceptable step (Phase 5b
18 /// commit 5+; not produced by the c3 always-full-step loop).
19 LineSearchFailed,
20 /// The QP subproblem solver neither produced a usable step nor
21 /// certified infeasibility — it hit its own iteration limit or a
22 /// numerical breakdown (e.g. the extreme m/n ≫ 1 degenerate phase-1
23 /// of #282). This is an HONEST non-committal failure: the SQP could
24 /// not compute a search direction, but — unlike `InfeasibleSubproblem`
25 /// — it makes no infeasibility claim it cannot back with a
26 /// certificate. Maps to `Search_Direction_Becomes_Too_Small`.
27 QpStepFailed,
28 /// The QP subproblem exhausted its own iteration budget
29 /// ([`QpOptions::max_iter`], the `sqp_qp_max_iter` option) without
30 /// converging or certifying anything.
31 ///
32 /// Split out from [`QpStepFailed`](Self::QpStepFailed) because the two
33 /// call for opposite remedies and the merged status actively misled.
34 /// A budget exhaustion is *actionable* — raise the limit — whereas
35 /// `Search_Direction_Becomes_Too_Small` reads as a numerical stall with
36 /// nothing to turn. On the Maros-Mészáros set the merged mapping hid the
37 /// single largest failure class: the cold-start active-set method needs
38 /// roughly one iteration per active-set change, so the flat default of
39 /// 200 is below what a few hundred constraints require, and dozens of
40 /// problems reported a step-size failure when they had simply run out of
41 /// budget. `DUALC1` (n=9, m=215) is the type case — it exits here at the
42 /// default and solves exactly, in one outer iteration, at a larger limit.
43 ///
44 /// Maps to `Maximum_Iterations_Exceeded`.
45 QpIterationLimit,
46 /// The problem is unbounded below: the step QP returned a certified
47 /// recession ray (zero curvature, feasible for every step length,
48 /// strict descent) *and* that ray was re-verified against the true
49 /// NLP — feasible points along it drive `f` toward `−∞` at (at
50 /// least) half the linear rate out to `1e12·‖d‖`. Maps to
51 /// `Diverging_Iterates`, POUNCE's (Ipopt's) unboundedness verdict,
52 /// the same status the IPM paths report on an unbounded model
53 /// (gh #388). An *unverified* unbounded step QP is a statement about
54 /// the local model only and falls back to
55 /// [`QpStepFailed`](Self::QpStepFailed).
56 Unbounded,
57 /// The KKT residuals at the current iterate are not finite: an iterate
58 /// or a constraint value went `NaN`/`±inf`, so nothing computed from it
59 /// means anything. Maps to `Invalid_Number_Detected`, which is what the
60 /// interior-point arm already reports for the same condition
61 /// (`ipopt_alg.rs`, `if !nlp_err.is_finite()`).
62 ///
63 /// This exists because the alternative is worse than an unhelpful
64 /// status. `check_kkt` reduced its residuals with `fold(0.0, f64::max)`,
65 /// and `f64::max` *ignores* `NaN` — so an all-`NaN` stationarity vector
66 /// reduced to a perfect `0.0`, cleared `<= tol`, and the arm reported
67 /// `Optimal` with `Objective nan` printed one line above it (gh #876).
68 /// Making the residuals honest already stops the false `Optimal`; naming
69 /// the condition is what stops it being reported as a *budget* problem
70 /// the user could fix by raising `max_iter`.
71 InvalidNumber,
72}
73
74impl fmt::Display for SqpStatus {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 match self {
77 SqpStatus::Optimal => write!(f, "optimal"),
78 SqpStatus::MaxIter => write!(f, "max-iter"),
79 SqpStatus::InfeasibleSubproblem => write!(f, "infeasible-subproblem"),
80 SqpStatus::LineSearchFailed => write!(f, "line-search-failed"),
81 SqpStatus::QpStepFailed => write!(f, "qp-step-failed"),
82 SqpStatus::QpIterationLimit => write!(f, "qp-iteration-limit"),
83 SqpStatus::Unbounded => write!(f, "unbounded"),
84 SqpStatus::InvalidNumber => write!(f, "invalid-number"),
85 }
86 }
87}
88
89#[derive(Debug)]
90pub enum SqpError {
91 /// Hard QP-solver failure (singular, dimension mismatch, etc.).
92 QpFailure(QpError),
93 /// Caller-supplied dimensions disagree.
94 DimensionMismatch(String),
95}
96
97impl fmt::Display for SqpError {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match self {
100 SqpError::QpFailure(e) => write!(f, "QP subproblem failure: {e}"),
101 SqpError::DimensionMismatch(s) => write!(f, "dimension mismatch: {s}"),
102 }
103 }
104}
105
106impl From<QpError> for SqpError {
107 fn from(e: QpError) -> Self {
108 SqpError::QpFailure(e)
109 }
110}
111
112#[derive(Debug, Clone)]
113pub struct SqpResult {
114 pub x: Vec<Number>,
115 pub lambda_g: Vec<Number>,
116 pub lambda_x: Vec<Number>,
117 pub obj: Number,
118 pub status: SqpStatus,
119 pub n_iter: u32,
120 pub n_qp_solves: u32,
121 /// Active-set changes (adds + drops) summed over every step QP
122 /// solved during this call — the inner work a working-set warm
123 /// start exists to avoid. Reported separately from `n_iter`
124 /// because the two move independently: on a QP-shaped NLP the
125 /// outer loop always terminates in one iteration, so the entire
126 /// warm-start effect shows up here and nowhere else.
127 ///
128 /// Excludes second-order-correction QPs, whose stats the line
129 /// search does not surface.
130 pub n_qp_working_set_changes: u32,
131 /// Final stationarity residual (max-norm of `∇f + Jᵀ λ_g + λ_x`).
132 pub final_stationarity: Number,
133 /// Final constraint violation (max-norm of `c(x*)` for
134 /// equalities plus bound-violation slack).
135 pub final_constr_viol: Number,
136 /// Final QP working set, suitable for warm-starting the next
137 /// `optimize_with_warm_start` call (§6 design-note contract).
138 /// `None` only when no QP was solved (e.g. cold-start declared
139 /// the iterate optimal at the very first KKT check).
140 pub working_set: Option<WorkingSet>,
141}