pounce_algorithm/ipopt_data.rs
1//! Mutable algorithm state — port of `Algorithm/IpIpoptData.{hpp,cpp}`.
2//!
3//! Holds the iterate trio (`curr` / `trial` / `delta`), the affine
4//! step `delta_aff`, current barrier parameter `mu`, fraction-to-the-
5//! boundary `tau`, iteration count, tolerances, and the four PD
6//! perturbations. No additional-data plug in v1.0 (CG penalty is
7//! deferred to Phase 10).
8//!
9//! Phase 5 ships the full state holder; concrete strategies (line
10//! search, mu update, etc.) read/write fields here as their inputs
11//! and outputs.
12
13use crate::inf_pr_floor::InfPrFloor;
14use crate::init::warm_start::WarmStartDiagnostics;
15use crate::iterates_vector::IteratesVector;
16use pounce_common::timing::{Deadline, TimingStatistics};
17use pounce_common::types::{Index, Number};
18use pounce_linalg::SymMatrix;
19use std::cell::RefCell;
20use std::rc::Rc;
21
22/// Primal-dual perturbation triple (`delta_x`, `delta_s`, `delta_c`,
23/// `delta_d`) — port of the four `current_perturbation` fields in
24/// `IpIpoptData.hpp`.
25#[derive(Debug, Default, Clone, Copy)]
26pub struct PdPerturbations {
27 pub delta_x: Number,
28 pub delta_s: Number,
29 pub delta_c: Number,
30 pub delta_d: Number,
31}
32
33/// KKT-factorization diagnostics captured for the interactive debugger
34/// after a search-direction solve. Only populated when a debugger is
35/// installed (see `IpoptAlgorithm`); inspected via `DebugCtx::kkt`.
36#[derive(Clone, Debug, Default)]
37pub struct KktDebug {
38 /// The outer iteration this factorization was assembled at. Lets the
39 /// debugger label `viz kkt` / `viz L` with the iteration the system
40 /// actually came from — at an `iter_start` pause that's the *previous*
41 /// iteration (the step that produced the current point), not the
42 /// iterate you're standing on.
43 pub iter: i32,
44 /// Dimension of the augmented system (n + m).
45 pub dim: i32,
46 /// Negative eigenvalues reported by the factorization (-1 if the
47 /// backend doesn't provide inertia).
48 pub n_neg: i32,
49 /// Whether the backend reports inertia at all.
50 pub provides_inertia: bool,
51 /// Debug string of the last factorization status.
52 pub status: String,
53 /// Assembled KKT triplets `(dim, irn, jcn, vals)`, 1-based lower
54 /// triangle — for `viz kkt`. Captured when a debugger is attached.
55 pub matrix: Option<(i32, Vec<i32>, Vec<i32>, Vec<f64>)>,
56 /// `LDLᵀ` factor pattern (+ values) — for `viz L`. Captured only
57 /// after the debugger opts in (it's the expensive piece).
58 pub l_factor: Option<pounce_linsol::FactorPattern>,
59}
60
61/// Mutable state passed down through the algorithm. Owned by
62/// `IpoptAlgorithm`; strategies access via `Rc<RefCell<IpoptData>>`.
63pub struct IpoptData {
64 pub curr: Option<IteratesVector>,
65 pub trial: Option<IteratesVector>,
66 pub delta: Option<IteratesVector>,
67 pub delta_aff: Option<IteratesVector>,
68 /// Pure centering step — solution of the primal-dual system with
69 /// RHS `(0, 0, 0, 0, μ̄·1, μ̄·1, μ̄·1, μ̄·1)` (where μ̄ = avrg_compl)
70 /// per upstream `IpQualityFunctionMuOracle.cpp:227-247`. Used by
71 /// the quality-function oracle to assemble σ-step trial points
72 /// without re-factorising for each candidate σ.
73 pub delta_cen: Option<IteratesVector>,
74
75 /// Hessian of the Lagrangian for the *current* iterate. Set by
76 /// `HessianUpdater` (exact or quasi-Newton). Mirrors `IpIpoptData::W_`.
77 pub w: Option<Rc<dyn SymMatrix>>,
78
79 pub iter_count: Index,
80 pub curr_mu: Number,
81 pub curr_tau: Number,
82 pub tol: Number,
83
84 pub perturbations: PdPerturbations,
85
86 /// KKT-factorization diagnostics for the debugger (set after a
87 /// search-direction solve when a debugger is installed). The full
88 /// matrix triplets and `LDLᵀ` factor are captured here whenever the
89 /// debugger is stepping (see `DebugHook::wants_kkt_capture`) and
90 /// dropped when it detaches, so `viz kkt` / `viz L` always have the
91 /// previous iteration's system to look back at without paying the
92 /// O(nnz) assembly during a free run.
93 pub kkt_debug: Option<KktDebug>,
94
95 /// Set after a successful trial-acceptance step in the line
96 /// search. Cleared on accept.
97 pub info_alpha_primal: Number,
98 pub info_alpha_dual: Number,
99
100 /// Mirrors `IpIpoptData::info_regu_x_`.
101 pub info_regu_x: Number,
102
103 /// Mirrors `IpIpoptData::info_skip_output_`.
104 pub info_skip_output: bool,
105
106 /// Mirrors `IpIpoptData::info_string_`. Free-form text the
107 /// iteration output appends to its line.
108 pub info_string: String,
109
110 /// Mirrors `IpIpoptData::tiny_step_flag_`. Set by the line search
111 /// when an alpha→0 trial is detected; the main loop reads it on
112 /// the next pass to decide between "tiny step accept" and bail.
113 pub tiny_step_flag: bool,
114
115 /// Emergency restoration request from the μ-update layer. Set by
116 /// [`AdaptiveMuUpdate`] when the probing oracle's input iterate
117 /// is corrupted (`curr_avrg_compl` ≫ `curr_mu`) so the main loop
118 /// invokes restoration instead of letting the oracle snap μ up
119 /// many orders of magnitude. Pounce-specific guard; no upstream
120 /// counterpart. See pounce#58.
121 pub request_resto: bool,
122
123 /// How long this solve has sat at a constraint violation it could
124 /// not get below (gh#661, gh#664). Fed once per outer iteration from
125 /// the `inf_pr` the iteration output already computes.
126 ///
127 /// Read by restoration's divergence guard, which needs to know
128 /// whether the solve had *demonstrated* a floor before its
129 /// restoration sub-solve blew up — the premise the reconstructed
130 /// locally-infeasible gates assert and never tested. The evidence
131 /// lives here rather than in restoration because the trajectory that
132 /// carries it is the outer one: the sub-solves themselves run a
133 /// handful of iterations. Pounce-specific; no upstream counterpart.
134 pub inf_pr_floor: InfPrFloor,
135
136 /// What the warm-start initializer accepted, reconstructed, or
137 /// discarded from the supplied iterate, and the residuals it based
138 /// those calls on (gh#606). `None` on the cold path, which has no
139 /// supplied iterate to report on. Read back after a solve through
140 /// [`crate::application::IpoptApplication::warm_start_diagnostics`].
141 pub warm_start_diagnostics: Option<WarmStartDiagnostics>,
142
143 /// `curr` was installed by the post-convergence crossover phase
144 /// (gh#612) rather than produced by the interior iteration.
145 ///
146 /// The distinction is not bookkeeping: a crossed-over point sits
147 /// *on* the bounds the user declared, which is `bound_relax_factor`
148 /// **inside** the widened box the barrier quantities are measured
149 /// against, so every slack at an active bound reads exactly `δ`
150 /// where an interior iterate would have carried `μ/z` (gh#646,
151 /// gh#654). Anything that reads `curr` through the barrier — the
152 /// residual report, the sensitivity path's `Σ = z/s` — has to know
153 /// which of the two frames the iterate belongs to before it can
154 /// pick the bounds to measure against. Nothing inside the
155 /// algorithm reads this: the flag is set after `optimize()` has
156 /// returned and no further step is taken.
157 pub curr_from_crossover: bool,
158
159 /// Line-search reset request from the μ-update layer (pounce#510).
160 /// Upstream's μ updates hold a `linesearch_` handle and call
161 /// `linesearch_->Reset()` themselves at fixed points
162 /// (`IpAdaptiveMuUpdate.cpp:339, 386, 431`,
163 /// `IpMonotoneMuUpdate.cpp:165`); pounce's [`MuUpdate`] trait has no
164 /// such handle, so the updates raise this flag instead and the main
165 /// loop performs the reset immediately after
166 /// `update_barrier_parameter` returns. Consuming the flag clears it.
167 ///
168 /// [`MuUpdate`]: crate::mu::MuUpdate
169 pub request_ls_reset: bool,
170
171 /// Tiny-step termination request from the μ-update layer (pounce#512).
172 /// Upstream signals "problem solved to best possible numerical
173 /// accuracy" by throwing `TINY_STEP_DETECTED` from inside
174 /// `UpdateBarrierParameter`; a Rust port returns a μ instead, so the
175 /// two throw sites in `IpAdaptiveMuUpdate.cpp` (`:330-333` fixed
176 /// mode, `:377-380` on the free→fixed switch) raise this flag and
177 /// the main loop turns it into `SolverReturn::StopAtTinyStep`.
178 ///
179 /// The flag exists because the throw's exact branch matters:
180 /// "a tiny step was flagged and μ came back unchanged" is also true
181 /// on adaptive paths where upstream does *not* throw (the no-bounds
182 /// short-circuit, and a free-mode oracle that happens to re-pick the
183 /// current μ), so it cannot be reconstructed from the μ values alone.
184 /// [`MonotoneMuUpdate`](crate::mu::monotone::MonotoneMuUpdate) has a
185 /// single throw site covering its whole update and is served by the
186 /// main loop's `terminates_on_tiny_step()` μ-comparison instead.
187 pub request_tiny_step_stop: bool,
188
189 /// One-char marker the iteration output puts in front of
190 /// `alpha_primal` (e.g. `'f'` for filter, `'r'` for restoration,
191 /// `'h'` for the very first iterate). Mirrors
192 /// `IpIpoptData::info_alpha_primal_char_`.
193 pub info_alpha_primal_char: char,
194
195 /// Number of trial points evaluated in the most recent line
196 /// search. Mirrors `IpIpoptData::info_ls_count_`.
197 pub info_ls_count: Index,
198
199 /// The wall-clock at the last `OrigIterationOutput::WriteOutput`
200 /// pass. Phase 7 uses this to decide whether to re-print the
201 /// header. Mirrors `IpIpoptData::info_last_output_`.
202 pub info_last_output: Number,
203
204 /// Iterations since the iteration header was last printed. Phase
205 /// 7 reprints every `print_frequency_iter` lines. Mirrors
206 /// `IpIpoptData::info_iters_since_header_`.
207 pub info_iters_since_header: Index,
208
209 /// Shared per-subsystem timing accumulator. Mirrors upstream's
210 /// `IpoptData::TimingStats_`. `IpoptApplication` constructs a single
211 /// instance per solve and shares it (via `Rc`) with the algorithm,
212 /// NLP, and KKT solver so each can record its own contribution.
213 /// Defaults to a fresh empty instance for the structural unit tests
214 /// that don't go through `IpoptApplication`.
215 pub timing: Rc<TimingStatistics>,
216
217 /// Shared wall/CPU-time deadline for the whole solve (pounce#242).
218 /// `IpoptApplication` installs one at solve start from the
219 /// `max_wall_time` / `max_cpu_time` options, and the restoration inner
220 /// IPM copies the *same* deadline onto its own `IpoptData` so the
221 /// nested solve is bounded by the caller's global budget rather than
222 /// running unbounded (its fresh `timing.overall_alg` is never
223 /// started). When present it is the authoritative time gate — checked
224 /// at the granularity of the expensive inner steps (KKT factorization,
225 /// each line-search trial), not only between outer iterations. `None`
226 /// for direct-driver / unit-test paths, which fall back to the
227 /// `overall_alg` timer in [`crate::conv_check`].
228 pub deadline: Option<Deadline>,
229}
230
231impl Default for IpoptData {
232 fn default() -> Self {
233 Self::new()
234 }
235}
236
237impl IpoptData {
238 pub fn new() -> Self {
239 Self {
240 curr: None,
241 trial: None,
242 delta: None,
243 delta_aff: None,
244 delta_cen: None,
245 w: None,
246 iter_count: 0,
247 curr_mu: 0.1,
248 curr_tau: 0.99,
249 tol: 1e-8,
250 perturbations: PdPerturbations::default(),
251 kkt_debug: None,
252 info_alpha_primal: 0.0,
253 info_alpha_dual: 0.0,
254 info_regu_x: 0.0,
255 info_skip_output: false,
256 info_string: String::new(),
257 tiny_step_flag: false,
258 request_resto: false,
259 inf_pr_floor: InfPrFloor::default(),
260 warm_start_diagnostics: None,
261 curr_from_crossover: false,
262 request_ls_reset: false,
263 request_tiny_step_stop: false,
264 info_alpha_primal_char: ' ',
265 info_ls_count: 0,
266 info_last_output: -1.0,
267 info_iters_since_header: 0,
268 timing: Rc::new(TimingStatistics::new()),
269 deadline: None,
270 }
271 }
272
273 /// Append text to `info_string`. Mirrors `IpIpoptData::Append_info_string`.
274 pub fn append_info_string(&mut self, s: &str) {
275 self.info_string.push_str(s);
276 }
277
278 /// Reset per-iteration info fields. Mirrors the top of
279 /// `IpoptAlgorithm::Optimize`'s loop body.
280 pub fn reset_info(&mut self) {
281 self.info_string.clear();
282 self.info_skip_output = false;
283 self.info_alpha_primal_char = ' ';
284 self.info_ls_count = 0;
285 self.info_regu_x = 0.0;
286 }
287
288 /// Replace `curr` with the previously-set `trial`. Mirrors
289 /// `IpIpoptData::AcceptTrialPoint`, which `DBG_ASSERT`s a trial is
290 /// staged before promoting it (upstream always runs a line search that
291 /// stages one). pounce additionally supports a bookkeeping-only
292 /// `iterate()` path (no NLP + no search_dir, per the module docs) that
293 /// runs the per-iteration bookkeeping without computing a step, so
294 /// `trial` may be unset here. Promoting `None` would null out `curr`
295 /// and make the next iteration's CQ accessor (`IpoptCq::curr_iv`) hit
296 /// `unreachable!`; preserve `curr` when nothing is staged.
297 pub fn accept_trial_point(&mut self) {
298 if let Some(trial) = self.trial.take() {
299 self.curr = Some(trial);
300 }
301 }
302
303 /// Set the trial iterate from a primal step `delta_x`/`delta_s`
304 /// scaled by `alpha_p` and a dual step scaled by `alpha_d`.
305 /// Phase 5 ships only the structural plumbing; the actual
306 /// arithmetic is implemented once the line search lands in
307 /// Phase 7.
308 pub fn set_trial(&mut self, trial: IteratesVector) {
309 self.trial = Some(trial);
310 }
311
312 pub fn set_curr(&mut self, curr: IteratesVector) {
313 self.curr = Some(curr);
314 }
315
316 pub fn set_delta(&mut self, d: IteratesVector) {
317 self.delta = Some(d);
318 }
319
320 pub fn set_delta_aff(&mut self, d: IteratesVector) {
321 self.delta_aff = Some(d);
322 }
323
324 pub fn set_delta_cen(&mut self, d: IteratesVector) {
325 self.delta_cen = Some(d);
326 }
327}
328
329/// Convenience handle. Mirrors how upstream passes the data object
330/// around as `SmartPtr<IpoptData>`.
331pub type IpoptDataHandle = Rc<RefCell<IpoptData>>;
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336 use crate::iterates_vector::IteratesVector;
337 use pounce_linalg::Vector;
338 use pounce_linalg::dense_vector::DenseVectorSpace;
339 use std::rc::Rc as StdRc;
340
341 fn zero_iv() -> IteratesVector {
342 let z = |n| StdRc::new(DenseVectorSpace::new(n).make_new_dense()) as StdRc<dyn Vector>;
343 IteratesVector::new(z(2), z(1), z(1), z(1), z(2), z(2), z(1), z(1))
344 }
345
346 #[test]
347 fn accept_trial_point_promotes_trial_to_curr() {
348 let mut d = IpoptData::new();
349 d.set_trial(zero_iv());
350 assert!(d.curr.is_none());
351 d.accept_trial_point();
352 assert!(d.curr.is_some());
353 assert!(d.trial.is_none());
354 }
355
356 // Regression for M2 (dev-notes/code-review-2026-06.md): in the
357 // bookkeeping-only `iterate()` path (no NLP + no search_dir), step 5
358 // is skipped so no trial is staged, yet `accept_trial_point()` is still
359 // called. The old `curr = trial.take()` then nulled out `curr`, and the
360 // next iteration's CQ accessor (`ipopt_cq.rs` `curr_iv`) hit
361 // `unreachable!`. With no trial staged, `curr` must be preserved.
362 #[test]
363 fn accept_trial_point_preserves_curr_when_no_trial_staged() {
364 let mut d = IpoptData::new();
365 d.set_curr(zero_iv());
366 assert!(d.curr.is_some());
367 assert!(d.trial.is_none());
368 d.accept_trial_point();
369 // Must NOT destroy the current iterate when nothing is staged.
370 assert!(
371 d.curr.is_some(),
372 "accept_trial_point() nulled curr with no trial staged"
373 );
374 assert!(d.trial.is_none());
375 }
376}