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 /// The per-iteration hook (the user's `intermediate_callback`) returned
73 /// `false`. Maps to `User_Requested_Stop`.
74 UserRequestedStop,
75}
76
77impl fmt::Display for SqpStatus {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 match self {
80 SqpStatus::Optimal => write!(f, "optimal"),
81 SqpStatus::MaxIter => write!(f, "max-iter"),
82 SqpStatus::InfeasibleSubproblem => write!(f, "infeasible-subproblem"),
83 SqpStatus::LineSearchFailed => write!(f, "line-search-failed"),
84 SqpStatus::QpStepFailed => write!(f, "qp-step-failed"),
85 SqpStatus::QpIterationLimit => write!(f, "qp-iteration-limit"),
86 SqpStatus::Unbounded => write!(f, "unbounded"),
87 SqpStatus::InvalidNumber => write!(f, "invalid-number"),
88 SqpStatus::UserRequestedStop => write!(f, "user-requested-stop"),
89 }
90 }
91}
92
93#[derive(Debug)]
94pub enum SqpError {
95 /// Hard QP-solver failure (singular, dimension mismatch, etc.).
96 QpFailure(QpError),
97 /// Caller-supplied dimensions disagree.
98 DimensionMismatch(String),
99}
100
101impl fmt::Display for SqpError {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 match self {
104 SqpError::QpFailure(e) => write!(f, "QP subproblem failure: {e}"),
105 SqpError::DimensionMismatch(s) => write!(f, "dimension mismatch: {s}"),
106 }
107 }
108}
109
110impl From<QpError> for SqpError {
111 fn from(e: QpError) -> Self {
112 SqpError::QpFailure(e)
113 }
114}
115
116#[derive(Debug, Clone)]
117pub struct SqpResult {
118 pub x: Vec<Number>,
119 pub lambda_g: Vec<Number>,
120 pub lambda_x: Vec<Number>,
121 pub obj: Number,
122 pub status: SqpStatus,
123 pub n_iter: u32,
124 pub n_qp_solves: u32,
125 /// Active-set changes (adds + drops) summed over every step QP
126 /// solved during this call — the inner work a working-set warm
127 /// start exists to avoid. Reported separately from `n_iter`
128 /// because the two move independently: on a QP-shaped NLP the
129 /// outer loop always terminates in one iteration, so the entire
130 /// warm-start effect shows up here and nowhere else.
131 ///
132 /// Excludes second-order-correction QPs, whose stats the line
133 /// search does not surface.
134 pub n_qp_working_set_changes: u32,
135 /// Final stationarity residual (max-norm of `∇f + Jᵀ λ_g + λ_x`).
136 pub final_stationarity: Number,
137 /// Final constraint violation (max-norm of `c(x*)` for
138 /// equalities plus bound-violation slack).
139 pub final_constr_viol: Number,
140 /// Final QP working set, suitable for warm-starting the next
141 /// `optimize_with_warm_start` call (§6 design-note contract).
142 /// `None` only when no QP was solved (e.g. cold-start declared
143 /// the iterate optimal at the very first KKT check).
144 pub working_set: Option<WorkingSet>,
145}