Skip to main content

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