Skip to main content

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    /// `max_wall_time` ran out ([`crate::sqp::SqpOptions::deadline`]),
76    /// either between outer iterations or inside a step QP. Maps to
77    /// `Maximum_WallTime_Exceeded`, as on the interior-point arm.
78    ///
79    /// Before gh#1054 neither time limit reached this arm at all: an
80    /// active-set solve that stalled in its first QP ran until something
81    /// outside POUNCE killed it.
82    WallTimeExceeded,
83    /// `max_cpu_time` ran out. Maps to `Maximum_CpuTime_Exceeded`.
84    CpuTimeExceeded,
85}
86
87impl fmt::Display for SqpStatus {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        match self {
90            SqpStatus::Optimal => write!(f, "optimal"),
91            SqpStatus::MaxIter => write!(f, "max-iter"),
92            SqpStatus::InfeasibleSubproblem => write!(f, "infeasible-subproblem"),
93            SqpStatus::LineSearchFailed => write!(f, "line-search-failed"),
94            SqpStatus::QpStepFailed => write!(f, "qp-step-failed"),
95            SqpStatus::QpIterationLimit => write!(f, "qp-iteration-limit"),
96            SqpStatus::Unbounded => write!(f, "unbounded"),
97            SqpStatus::InvalidNumber => write!(f, "invalid-number"),
98            SqpStatus::UserRequestedStop => write!(f, "user-requested-stop"),
99            SqpStatus::WallTimeExceeded => write!(f, "wall-time-exceeded"),
100            SqpStatus::CpuTimeExceeded => write!(f, "cpu-time-exceeded"),
101        }
102    }
103}
104
105#[derive(Debug)]
106pub enum SqpError {
107    /// Hard QP-solver failure (singular, dimension mismatch, etc.).
108    QpFailure(QpError),
109    /// Caller-supplied dimensions disagree.
110    DimensionMismatch(String),
111}
112
113impl fmt::Display for SqpError {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        match self {
116            SqpError::QpFailure(e) => write!(f, "QP subproblem failure: {e}"),
117            SqpError::DimensionMismatch(s) => write!(f, "dimension mismatch: {s}"),
118        }
119    }
120}
121
122impl From<pounce_common::timing::DeadlineKind> for SqpStatus {
123    fn from(kind: pounce_common::timing::DeadlineKind) -> Self {
124        match kind {
125            pounce_common::timing::DeadlineKind::Wall => SqpStatus::WallTimeExceeded,
126            pounce_common::timing::DeadlineKind::Cpu => SqpStatus::CpuTimeExceeded,
127        }
128    }
129}
130
131impl From<QpError> for SqpError {
132    fn from(e: QpError) -> Self {
133        SqpError::QpFailure(e)
134    }
135}
136
137#[derive(Debug, Clone)]
138pub struct SqpResult {
139    pub x: Vec<Number>,
140    pub lambda_g: Vec<Number>,
141    pub lambda_x: Vec<Number>,
142    pub obj: Number,
143    pub status: SqpStatus,
144    pub n_iter: u32,
145    pub n_qp_solves: u32,
146    /// Active-set changes (adds + drops) summed over every step QP
147    /// solved during this call — the inner work a working-set warm
148    /// start exists to avoid. Reported separately from `n_iter`
149    /// because the two move independently: on a QP-shaped NLP the
150    /// outer loop always terminates in one iteration, so the entire
151    /// warm-start effect shows up here and nowhere else.
152    ///
153    /// Excludes second-order-correction QPs, whose stats the line
154    /// search does not surface.
155    pub n_qp_working_set_changes: u32,
156    /// Final stationarity residual (max-norm of `∇f + Jᵀ λ_g + λ_x`).
157    pub final_stationarity: Number,
158    /// Final constraint violation (max-norm of `c(x*)` for
159    /// equalities plus bound-violation slack).
160    pub final_constr_viol: Number,
161    /// Final QP working set, suitable for warm-starting the next
162    /// `optimize_with_warm_start` call (§6 design-note contract).
163    /// `None` only when no QP was solved (e.g. cold-start declared
164    /// the iterate optimal at the very first KKT check).
165    pub working_set: Option<WorkingSet>,
166}