Skip to main content

pounce_algorithm/
ipopt_cq.rs

1//! Lazy-cache layer — port of
2//! `Algorithm/IpIpoptCalculatedQuantities.{hpp,cpp}`.
3//!
4//! Upstream's CQ object exposes ~80 cached quantities (`curr_f`,
5//! `curr_grad_f`, `curr_jac_c`, `curr_grad_lag_x`, `curr_compl_*`,
6//! `curr_nlp_error`, etc.). All of them are pure derivations from
7//! `(x, s, y_c, y_d, z_l, z_u, v_l, v_u)` and the NLP function
8//! evaluations.
9//!
10//! Phase 5 ships the priority subset needed by the KKT layer
11//! (Phase 6) and the convergence check / line search (Phase 7).
12//! Caching is intentionally deferred — every accessor recomputes its
13//! value on each call. Tag-based invalidation lands once the inner
14//! loop benchmarks justify the bookkeeping; correctness does not
15//! depend on it.
16//!
17//! All accessors take `&self` and return `Rc<dyn Vector>`. NLP
18//! evaluations require a brief `borrow_mut()` on the Nlp handle;
19//! callers must not hold an outstanding `borrow()` across an
20//! accessor call.
21
22use crate::ipopt_data::IpoptDataHandle;
23use crate::ipopt_nlp::IpoptNlp;
24use crate::iterates_vector::IteratesVector;
25use pounce_common::cached::Cache;
26use pounce_common::tagged::TaggedObject;
27use pounce_common::types::Number;
28use pounce_linalg::dense_vector::DenseVector;
29use pounce_linalg::{Matrix, SymMatrix, Vector};
30use std::cell::RefCell;
31use std::rc::Rc;
32
33/// Safety factor on the per-row noise floor of
34/// [`IpoptCalculatedQuantities::row_noise_floor`]. The floor prices one
35/// component of `x` at `eps · ‖x‖_∞` and passes it through the row at
36/// `max_j |a_ij|`; the row's residual accumulates that over all of its
37/// nonzeros, and the linear solve's conditioning widens it further, so the
38/// bare product is short by a problem-dependent factor. `64` covers a typical
39/// sparse row without reaching far enough to swallow a declared magnitude a
40/// model could have meant: at the `‖x‖_∞ ~ 1` of a well-posed problem the
41/// floor sits near
42/// `1.4e-14`, still nine orders under `constr_viol_tol`'s default. Rows it
43/// silences fall back on the absolute feasibility test, which is already
44/// scale-invariant on a row whose declared magnitude is numerically zero.
45///
46/// Measured, and not a knife edge: over gh #446's 15 problems plus the
47/// infeasibility-detection suites (`false_local_infeasibility`,
48/// `infeasible_status_tol_invariance`, `issue_390_nonlinear_equality_scale`),
49/// every value from `8` to `1024` gives the same verdicts. `1` is too small —
50/// QSCSD1's rows are wide enough that the missing nonzero-count factor still
51/// leaves its `2^-53` RHS above the bound — so `64` sits an order of magnitude
52/// inside the band from either edge.
53pub const ROW_NOISE_KAPPA: Number = 64.0;
54
55/// Headroom on the representability floor `calculate_safe_slack` puts under a
56/// slack so that `Σ = z/s` stays inside the double range (gh#655).
57///
58/// The bare requirement is `s ≥ z/f64::MAX`, which bounds `z/s` by `f64::MAX`
59/// exactly — no room for the rounding in the divide itself, and none for the
60/// fact that `Σ_x` *sums* a lower and an upper ratio into the same diagonal
61/// entry. Dividing the floor's budget by `4` bounds each ratio by `MAX/4` and
62/// so their sum by `MAX/2`, which leaves the KKT diagonal finite with a bit
63/// to spare. The factor costs nothing anywhere it is not needed: the floor is
64/// `z_max/4.5e307`, below every slack any non-pathological iterate carries.
65const SIGMA_OVERFLOW_HEADROOM: Number = 4.0;
66
67/// Calculated-quantities object. Holds shared handles on data and the
68/// NLP; per-quantity caches live in `RefCell`s here.
69pub struct IpoptCalculatedQuantities {
70    data: IpoptDataHandle,
71    nlp: Rc<RefCell<dyn IpoptNlp>>,
72
73    /// Optimality scaling cap from `IpOptErrorConvCheck` defaults.
74    pub s_max: Number,
75    /// Damping coefficient for the bound-multiplier complementarity
76    /// term (`kappa_d` in upstream's RegisterOptions).
77    pub kappa_d: Number,
78    /// Correction size for very small slacks (`slack_move` option,
79    /// default `mach_eps^{3/4}`). Drives `calculate_safe_slack`'s
80    /// upper cap on the moved bound — port of upstream's `slack_move_`
81    /// (`IpIpoptCalculatedQuantities.cpp:525`).
82    pub slack_move: Number,
83
84    // Per-iterate caches for the hot accessors used by the KKT solver
85    // dependency-tag check. Without these the PdFullSpaceSolver sees a
86    // fresh tag on every solve (each `curr_slack_*` / `curr_sigma_*`
87    // allocates a new vector with a fresh `TaggedCell`), which forces
88    // an MA57 refactor on every SOC step even though the matrix data
89    // is unchanged. Caches are keyed on the input iterate-vector tag
90    // and survive across calls but are naturally invalidated when the
91    // outer iterate advances (curr.x bump).
92    curr_slack_x_l_cache: RefCell<Cache<Rc<dyn Vector>>>,
93    curr_slack_x_u_cache: RefCell<Cache<Rc<dyn Vector>>>,
94    curr_slack_s_l_cache: RefCell<Cache<Rc<dyn Vector>>>,
95    curr_slack_s_u_cache: RefCell<Cache<Rc<dyn Vector>>>,
96    curr_sigma_x_cache: RefCell<Cache<Rc<dyn Vector>>>,
97    curr_sigma_s_cache: RefCell<Cache<Rc<dyn Vector>>>,
98    // gh #812. Upstream caches both Lagrangian gradients
99    // (`IpIpoptCalculatedQuantities.cpp`: `curr_grad_lag_x_cache_`
100    // with `GetCachedResult5Dep(x, y_c, y_d, z_L, z_U)`,
101    // `curr_grad_lag_s_cache_` with `GetCachedResult3Dep(y_d, v_L,
102    // v_U)`); the port dropped both, so `∇_x L` was reassembled from
103    // scratch on every read — two transposed Jacobian products and
104    // three vector sweeps. On `benchmarks/large_scale/laptime.nl` that
105    // is 806 assemblies for 101 distinct iterates: seven of every
106    // eight reads recompute a value the previous read already had.
107    //
108    // THE X KEY CARRIES `mu`, AND UPSTREAM'S DOES NOT. The five vector
109    // tags are NOT a complete dependency set here, because the premise
110    // they rest on — that `∇f`, `J_c` and `J_d` are functions of `x`
111    // alone — is false for the NLP this CQ is built over during
112    // restoration. `RestoNlp`'s objective carries the proximity term
113    // `ζ/2·‖D_R(x − x_R)‖²` whose `ζ` is a function of the barrier
114    // parameter, so its `∇f` moves when `mu` moves and `x` does not.
115    // Keyed on the five tags alone this cache returns the pre-update
116    // gradient, which is a silent, self-consistent wrong answer: the
117    // solve still converges and still reports the right objective, it
118    // just takes a different route there. Measured, that route is
119    // worse — `scripts/sweep-fixtures.sh` moved 8 of 154 fixture-legs,
120    // `pooling_rt2stp` from 295 to 627 iterations on the lbfgs leg and
121    // `issue_508_infeasible_gap_1em4` from 79 to 224. With `mu` in the
122    // key the sweep is byte-identical across all 154.
123    //
124    // `∇_s L = −y_d − P_L v_L + P_U v_U` evaluates nothing on the NLP,
125    // so its three tags really are complete and it keeps upstream's
126    // key unchanged.
127    curr_grad_lag_x_cache: RefCell<Cache<Rc<dyn Vector>>>,
128    curr_grad_lag_s_cache: RefCell<Cache<Rc<dyn Vector>>>,
129}
130
131/// Helper: convert `Box<dyn Vector>` to `Rc<dyn Vector>`. Cheap; the
132/// box is unwrapped without copying.
133fn rc_from(v: Box<dyn Vector>) -> Rc<dyn Vector> {
134    Rc::from(v)
135}
136
137/// Max-norm of `v` after dividing each entry by its per-row scale factor
138/// (`max_i |v_i / scale_i|`). `scale == None` means "no row scaling" and
139/// returns the plain `v.amax()`; a zero factor for an entry is treated as
140/// the identity (no divide) so a degenerate scale never yields infinities.
141/// Falls back to `v.amax()` for a non-dense backing — POUNCE is dense-only,
142/// so that branch is defensive.
143///
144/// Public because `pounce-restoration`'s locally-infeasible gates compare a
145/// constraint violation against absolute floors (`1e-4` / `1e-3`) and so must
146/// measure it in the same user-facing units this produces — see
147/// `resto_inner_solver::eval_orig_inf_pr_at_inner_curr`. One definition, so
148/// the two call sites cannot drift.
149pub fn unscaled_block_amax(v: &dyn Vector, scale: Option<&[Number]>) -> Number {
150    let Some(s) = scale else {
151        return v.amax();
152    };
153    match v.as_any().downcast_ref::<DenseVector>() {
154        Some(d) => d
155            .values()
156            .iter()
157            .zip(s.iter())
158            .map(|(&x, &f)| if f == 0.0 { x.abs() } else { (x / f).abs() })
159            .fold(0.0, Number::max),
160        None => v.amax(),
161    }
162}
163
164/// Max-norm constraint violation of the **original** NLP, in user units,
165/// for the `c(x)` / `d(x)` blocks `c` and `d` (internally scaled, as
166/// `IpoptNlp::eval_c` / `eval_d` return them). The body of
167/// [`IpoptCalculatedQuantities::curr_unscaled_nlp_constraint_violation_max`],
168/// which documents the definition; free so the restoration phase's iteration
169/// rows can report the same quantity at the restoration iterate's `x` slice
170/// (gh#981) instead of the scaled residual.
171pub fn unscaled_nlp_constraint_violation_max(
172    nlp: &dyn IpoptNlp,
173    c: &dyn Vector,
174    d: &dyn Vector,
175) -> Number {
176    let (dc, dd) = (nlp.c_scale_vec(), nlp.d_scale_vec());
177    let c_max = unscaled_block_amax(c, dc.as_deref());
178
179    if d.dim() == 0 {
180        return c_max;
181    }
182    let (lo, hi, mask_l, mask_u) = {
183        let (mut cl, mut cu) = (nlp.d_l().make_new(), nlp.d_u().make_new());
184        match nlp.declared_d_bounds() {
185            Some((dl, du)) => {
186                let (Some(cld), Some(cud)) = (
187                    cl.as_any_mut().downcast_mut::<DenseVector>(),
188                    cu.as_any_mut().downcast_mut::<DenseVector>(),
189                ) else {
190                    return c_max;
191                };
192                cld.set_values(&dl);
193                cud.set_values(&du);
194            }
195            None => {
196                cl.copy(nlp.d_l());
197                cu.copy(nlp.d_u());
198            }
199        }
200        let mut lo = d.make_new();
201        lo.set(0.0);
202        nlp.pd_l().mult_vector(1.0, &*cl, 0.0, &mut *lo);
203        let mut hi = d.make_new();
204        hi.set(0.0);
205        nlp.pd_u().mult_vector(1.0, &*cu, 0.0, &mut *hi);
206        // A projected 0 is ambiguous — "no bound on this side" and "a
207        // declared zero bound" both read 0 — so project an all-ones
208        // vector through the same expansion to get presence masks.
209        let mut ones_l = nlp.d_l().make_new();
210        ones_l.set(1.0);
211        let mut mask_l = d.make_new();
212        mask_l.set(0.0);
213        nlp.pd_l().mult_vector(1.0, &*ones_l, 0.0, &mut *mask_l);
214        let mut ones_u = nlp.d_u().make_new();
215        ones_u.set(1.0);
216        let mut mask_u = d.make_new();
217        mask_u.set(0.0);
218        nlp.pd_u().mult_vector(1.0, &*ones_u, 0.0, &mut *mask_u);
219        (lo, hi, mask_l, mask_u)
220    };
221    let (Some(dv), Some(lo), Some(hi), Some(ml), Some(mu)) = (
222        d.as_any().downcast_ref::<DenseVector>(),
223        lo.as_any().downcast_ref::<DenseVector>(),
224        hi.as_any().downcast_ref::<DenseVector>(),
225        mask_l.as_any().downcast_ref::<DenseVector>(),
226        mask_u.as_any().downcast_ref::<DenseVector>(),
227    ) else {
228        return c_max;
229    };
230    if !(dv.is_initialized()
231        && lo.is_initialized()
232        && hi.is_initialized()
233        && ml.is_initialized()
234        && mu.is_initialized())
235    {
236        return c_max;
237    }
238    let (dv, lov, hiv, mlv, muv) = (
239        dv.expanded_values(),
240        lo.expanded_values(),
241        hi.expanded_values(),
242        ml.expanded_values(),
243        mu.expanded_values(),
244    );
245    let mut worst = c_max;
246    for i in 0..dv.len() {
247        let mut viol = 0.0_f64;
248        if mlv[i] > 0.5 {
249            viol = viol.max(lov[i] - dv[i]);
250        }
251        if muv[i] > 0.5 {
252            viol = viol.max(dv[i] - hiv[i]);
253        }
254        if viol <= 0.0 || !viol.is_finite() {
255            continue;
256        }
257        // Row scaling is per-row (`d_scaled = dd ⊙ d_user`), so the
258        // violation unscales by the same factor. A zero factor is treated
259        // as the identity, matching `unscaled_block_amax`.
260        let viol = match dd.as_deref() {
261            Some(s) if s[i] != 0.0 => viol / s[i],
262            _ => viol,
263        };
264        worst = worst.max(viol);
265    }
266    worst
267}
268
269/// `‖v‖_∞` over the components that clear their own entry of `floor`;
270/// components at or below it contribute `0`. Used by
271/// [`IpoptCalculatedQuantities::curr_primal_infeasibility_above_noise`], which
272/// documents what the floor means.
273///
274/// A vector that is not dense, is uninitialized, or whose length disagrees
275/// with `floor` falls back to the plain `‖v‖_∞` — no floor can be attributed
276/// component-wise, and over-reporting the residual is the safe direction.
277fn amax_above_floor(v: &dyn Vector, floor: &[Number]) -> Number {
278    let Some(d) = v.as_any().downcast_ref::<DenseVector>() else {
279        return v.amax();
280    };
281    if !d.is_initialized() {
282        return v.amax();
283    }
284    let values = d.expanded_values();
285    if values.len() != floor.len() {
286        return v.amax();
287    }
288    values
289        .iter()
290        .zip(floor.iter())
291        .map(|(&x, &f)| if x.abs() > f { x.abs() } else { 0.0 })
292        .fold(0.0, Number::max)
293}
294
295/// Result of [`IpoptCalculatedQuantities::adjusted_trial_bounds`]: the
296/// new `x_L / x_U / d_L / d_U` to install on the NLP when one or more
297/// trial slacks were corrected by the safe-slack mechanism.
298pub struct AdjustedBounds {
299    /// Total number of slack components corrected across all four blocks.
300    pub adjusted: usize,
301    pub x_l: Box<dyn Vector>,
302    pub x_u: Box<dyn Vector>,
303    pub d_l: Box<dyn Vector>,
304    pub d_u: Box<dyn Vector>,
305}
306
307impl IpoptCalculatedQuantities {
308    pub fn new(data: IpoptDataHandle, nlp: Rc<RefCell<dyn IpoptNlp>>) -> Self {
309        Self {
310            data,
311            nlp,
312            s_max: 100.0,
313            kappa_d: 1e-5,
314            slack_move: f64::EPSILON.powf(0.75),
315            curr_slack_x_l_cache: RefCell::new(Cache::new(1)),
316            curr_slack_x_u_cache: RefCell::new(Cache::new(1)),
317            curr_slack_s_l_cache: RefCell::new(Cache::new(1)),
318            curr_slack_s_u_cache: RefCell::new(Cache::new(1)),
319            curr_sigma_x_cache: RefCell::new(Cache::new(1)),
320            curr_sigma_s_cache: RefCell::new(Cache::new(1)),
321            curr_grad_lag_x_cache: RefCell::new(Cache::new(1)),
322            curr_grad_lag_s_cache: RefCell::new(Cache::new(1)),
323        }
324    }
325
326    pub fn data(&self) -> &IpoptDataHandle {
327        &self.data
328    }
329
330    pub fn nlp(&self) -> &Rc<RefCell<dyn IpoptNlp>> {
331        &self.nlp
332    }
333
334    pub(crate) fn curr_iv(&self) -> IteratesVector {
335        let Some(iv) = self.data.borrow().curr.as_ref().cloned() else {
336            unreachable!("IpoptCalculatedQuantities: curr iterate not set");
337        };
338        iv
339    }
340
341    fn trial_iv(&self) -> IteratesVector {
342        let Some(iv) = self.data.borrow().trial.as_ref().cloned() else {
343            unreachable!("IpoptCalculatedQuantities: trial iterate not set");
344        };
345        iv
346    }
347
348    // --------------------------------------------------------------
349    // Slacks: s_L = P_L^T x - x_L,  s_U = x_U - P_U^T x.
350    // Mirror of `CalcSlack_L` / `CalcSlack_U`
351    // (`IpIpoptCalculatedQuantities.cpp:238-266`).
352    // --------------------------------------------------------------
353
354    fn calc_slack_l_box(p: &dyn Matrix, x: &dyn Vector, x_bound: &dyn Vector) -> Box<dyn Vector> {
355        let mut result = x_bound.make_new();
356        result.copy(x_bound);
357        // result = -1*result + 1*P^T x  ⇒  P^T x - x_bound.
358        p.trans_mult_vector(1.0, x, -1.0, &mut *result);
359        result
360    }
361
362    fn calc_slack_u_box(p: &dyn Matrix, x: &dyn Vector, x_bound: &dyn Vector) -> Box<dyn Vector> {
363        let mut result = x_bound.make_new();
364        result.copy(x_bound);
365        // result = 1*result + (-1)*P^T x  ⇒  x_bound - P^T x.
366        p.trans_mult_vector(-1.0, x, 1.0, &mut *result);
367        result
368    }
369
370    /// Floor a freshly computed slack against machine precision and,
371    /// where it falls below `eps*min(1,mu)`, raise it to a representable
372    /// positive value, returning the number of corrected components.
373    /// Faithful port of `IpoptCalculatedQuantities::CalculateSafeSlack`
374    /// (`IpIpoptCalculatedQuantities.cpp:455-537`): the corrected slack
375    /// is `min(max(mu/multiplier, s_min), slack_move*max(1,|bound|)+slack)`.
376    /// `multiplier` and `mu` are taken from the *current* iterate, exactly
377    /// as upstream does even for trial slacks.
378    ///
379    /// Deviates from upstream in one place: `s_min` also carries a
380    /// representability floor `max_i z_i / (f64::MAX/4)` so that the
381    /// `Σ = z/s` this slack feeds stays inside the double range (gh#655).
382    /// See the comments at the two sites below.
383    fn calculate_safe_slack(
384        &self,
385        slack: &mut dyn Vector,
386        bound: &dyn Vector,
387        multiplier: &dyn Vector,
388        mu: Number,
389    ) -> usize {
390        if slack.dim() == 0 {
391            return 0;
392        }
393        let min_slack = slack.min();
394        // s_min = eps * min(1, mu); if mu drove it to 0, keep it strictly
395        // positive (upstream #212) so the strict `slack < s_min` test and
396        // the barrier term stay well-defined.
397        let mut s_min = f64::EPSILON * mu.min(1.0);
398        if s_min == 0.0 {
399            s_min = f64::MIN_POSITIVE;
400        }
401        // gh#655: `eps*min(1,mu)` floors the *barrier* term, and nothing in it
402        // mentions the multiplier — so a slack can clear it and still be small
403        // enough against its own `z` that `Σ = z/s` leaves the double range.
404        // At `mu = 9.1e-308` the threshold is `2.0e-323`; a slack of
405        // `2.0e-308` sails past it untouched, and `z = 4.5` over that slack is
406        // `2.2e308`, i.e. `inf` on the KKT diagonal under a reported
407        // `SolveSucceeded`. `f64::MIN_POSITIVE` is not the fix either: the
408        // quantity that has to stay finite is `z/s`, so the floor is
409        // `s >= z/f64::MAX` (with `SIGMA_OVERFLOW_HEADROOM` of margin), not
410        // the smallest representable positive double. Divide before
411        // multiplying so a `z` near `f64::MAX` cannot overflow the floor
412        // itself; a non-finite `z` leaves the floor alone and is caught
413        // downstream by the iterate finiteness checks.
414        //
415        // Taken over `max_i z_i` rather than componentwise so one scalar also
416        // serves the `min_slack >= s_min` trigger above. That is conservative
417        // in the harmless direction: it can only raise a flagged slack
418        // further, and raising a slack only lowers `Σ`.
419        let sigma_floor = multiplier.amax() / (f64::MAX / SIGMA_OVERFLOW_HEADROOM);
420        if sigma_floor.is_finite() && sigma_floor > s_min {
421            s_min = sigma_floor;
422        }
423        if min_slack >= s_min {
424            return 0;
425        }
426
427        // t = sign(slack - s_min); then collapse to 1 where slack < s_min,
428        // 0 elsewhere.
429        let mut t = slack.make_new();
430        t.copy(&*slack);
431        t.add_scalar(-s_min);
432        t.element_wise_sgn();
433        let mut zero_vec = t.make_new();
434        zero_vec.set(0.0);
435        t.element_wise_min(&*zero_vec); // -1 if slack < s_min, else 0
436        t.scal(-1.0); //  1 if slack < s_min, else 0
437        let retval = t.asum().round() as usize;
438
439        // Clamp the raw slack to be non-negative before forming the target
440        // (upstream's AW fix for negative slacks producing 0).
441        slack.element_wise_max(&*zero_vec);
442
443        // t2 = max(mu/multiplier, s_min) - slack.
444        let mut t2 = t.make_new();
445        let mut s_min_vec = t2.make_new();
446        s_min_vec.set(s_min);
447        if mu != 0.0 {
448            // mu/0 → +inf here, intentionally capped by t_max below.
449            t2.set(mu);
450            t2.element_wise_divide(multiplier);
451            t2.element_wise_max(&*s_min_vec);
452        } else {
453            // mu == 0: max(0/multiplier, s_min) is s_min everywhere, but a 0/0
454            // (zero multiplier at μ=0) would seed the slack target with NaN and
455            // poison the bound move — pin straight to s_min instead.
456            t2.copy(&*s_min_vec);
457        }
458        t2.axpy(-1.0, &*slack);
459
460        // t = max(mu/multiplier, s_min) where flagged, else slack.
461        t.element_wise_select(&*t2);
462        t.axpy(1.0, &*slack);
463
464        // t_max = slack_move*max(1,|bound|) + slack.
465        let mut t_max = t2; // reuse buffer
466        t_max.set(1.0);
467        let mut abs_bound = bound.make_new();
468        abs_bound.copy(bound);
469        abs_bound.element_wise_abs();
470        t_max.element_wise_max(&*abs_bound);
471        // t_max = 1.0*slack + slack_move*t_max.
472        t_max.add_one_vector(1.0, &*slack, self.slack_move);
473
474        // new slack = min(target, t_max) where flagged, else slack.
475        t.element_wise_min(&*t_max);
476        // gh#655, second half: re-apply the floor *after* the bound-move cap.
477        // `t_max` bounds how far a bound may be nudged, which is a policy the
478        // user sets; a finite `z/s` is not one. The cap sits below `s_min`
479        // only when `slack_move*max(1,|bound|)` does — with the default
480        // `slack_move` that needs `max_i z_i` past `6e295`, and `slack_move = 0`
481        // (the "never move a bound" setting) makes it exact — but where it
482        // does, the min above would hand back the overflowing slack it was
483        // called to repair. Components that were not flagged are `>= s_min`
484        // already, so this is a no-op for them.
485        t.element_wise_max(&*s_min_vec);
486        slack.copy(&*t);
487        retval
488    }
489
490    /// `calc_slack_l` followed by `calculate_safe_slack`, returning the
491    /// (floored) slack plus the number of corrected components. The
492    /// multiplier and `mu` come from the current iterate.
493    fn safe_slack_l(
494        &self,
495        p: &dyn Matrix,
496        x: &dyn Vector,
497        bound: &dyn Vector,
498        multiplier: &dyn Vector,
499    ) -> (Rc<dyn Vector>, usize) {
500        let mu = self.data.borrow().curr_mu;
501        let mut result = Self::calc_slack_l_box(p, x, bound);
502        let n = self.calculate_safe_slack(&mut *result, bound, multiplier, mu);
503        (rc_from(result), n)
504    }
505
506    fn safe_slack_u(
507        &self,
508        p: &dyn Matrix,
509        x: &dyn Vector,
510        bound: &dyn Vector,
511        multiplier: &dyn Vector,
512    ) -> (Rc<dyn Vector>, usize) {
513        let mu = self.data.borrow().curr_mu;
514        let mut result = Self::calc_slack_u_box(p, x, bound);
515        let n = self.calculate_safe_slack(&mut *result, bound, multiplier, mu);
516        (rc_from(result), n)
517    }
518
519    pub fn curr_slack_x_l(&self) -> Rc<dyn Vector> {
520        let iv = self.curr_iv();
521        {
522            let cache = self.curr_slack_x_l_cache.borrow();
523            if let Some(v) = cache.get(&[iv.x.as_tagged()], &[]) {
524                return v;
525            }
526        }
527        let nlp = self.nlp.borrow();
528        let (v, _) = self.safe_slack_l(&*nlp.px_l(), &*iv.x, nlp.x_l(), &*iv.z_l);
529        self.curr_slack_x_l_cache
530            .borrow_mut()
531            .add(v.clone(), &[iv.x.as_tagged()], &[]);
532        v
533    }
534
535    pub fn curr_slack_x_u(&self) -> Rc<dyn Vector> {
536        let iv = self.curr_iv();
537        {
538            let cache = self.curr_slack_x_u_cache.borrow();
539            if let Some(v) = cache.get(&[iv.x.as_tagged()], &[]) {
540                return v;
541            }
542        }
543        let nlp = self.nlp.borrow();
544        let (v, _) = self.safe_slack_u(&*nlp.px_u(), &*iv.x, nlp.x_u(), &*iv.z_u);
545        self.curr_slack_x_u_cache
546            .borrow_mut()
547            .add(v.clone(), &[iv.x.as_tagged()], &[]);
548        v
549    }
550
551    pub fn curr_slack_s_l(&self) -> Rc<dyn Vector> {
552        let iv = self.curr_iv();
553        {
554            let cache = self.curr_slack_s_l_cache.borrow();
555            if let Some(v) = cache.get(&[iv.s.as_tagged()], &[]) {
556                return v;
557            }
558        }
559        let nlp = self.nlp.borrow();
560        let (v, _) = self.safe_slack_l(&*nlp.pd_l(), &*iv.s, nlp.d_l(), &*iv.v_l);
561        self.curr_slack_s_l_cache
562            .borrow_mut()
563            .add(v.clone(), &[iv.s.as_tagged()], &[]);
564        v
565    }
566
567    pub fn curr_slack_s_u(&self) -> Rc<dyn Vector> {
568        let iv = self.curr_iv();
569        {
570            let cache = self.curr_slack_s_u_cache.borrow();
571            if let Some(v) = cache.get(&[iv.s.as_tagged()], &[]) {
572                return v;
573            }
574        }
575        let nlp = self.nlp.borrow();
576        let (v, _) = self.safe_slack_u(&*nlp.pd_u(), &*iv.s, nlp.d_u(), &*iv.v_u);
577        self.curr_slack_s_u_cache
578            .borrow_mut()
579            .add(v.clone(), &[iv.s.as_tagged()], &[]);
580        v
581    }
582
583    pub fn trial_slack_x_l(&self) -> Rc<dyn Vector> {
584        let iv = self.trial_iv();
585        let mult = self.curr_iv();
586        let nlp = self.nlp.borrow();
587        self.safe_slack_l(&*nlp.px_l(), &*iv.x, nlp.x_l(), &*mult.z_l)
588            .0
589    }
590
591    pub fn trial_slack_x_u(&self) -> Rc<dyn Vector> {
592        let iv = self.trial_iv();
593        let mult = self.curr_iv();
594        let nlp = self.nlp.borrow();
595        self.safe_slack_u(&*nlp.px_u(), &*iv.x, nlp.x_u(), &*mult.z_u)
596            .0
597    }
598
599    pub fn trial_slack_s_l(&self) -> Rc<dyn Vector> {
600        let iv = self.trial_iv();
601        let mult = self.curr_iv();
602        let nlp = self.nlp.borrow();
603        self.safe_slack_l(&*nlp.pd_l(), &*iv.s, nlp.d_l(), &*mult.v_l)
604            .0
605    }
606
607    pub fn trial_slack_s_u(&self) -> Rc<dyn Vector> {
608        let iv = self.trial_iv();
609        let mult = self.curr_iv();
610        let nlp = self.nlp.borrow();
611        self.safe_slack_u(&*nlp.pd_u(), &*iv.s, nlp.d_u(), &*mult.v_u)
612            .0
613    }
614
615    /// Compute the four trial slacks with safe-slack flooring and, if any
616    /// component was corrected, the adjusted variable bounds that make the
617    /// trial slacks exactly representable. Port of the bound-adjustment
618    /// block in `IpoptAlgorithm::AcceptTrialPoint`
619    /// (`IpIpoptAlg.cpp:664-706`): `new_x_L = Px_L^T x - safe_slack_x_L`,
620    /// `new_x_U = Px_U^T x + safe_slack_x_U`, likewise for `s`/`d`.
621    /// Returns `None` when no slack needed correcting.
622    pub fn adjusted_trial_bounds(&self) -> Option<AdjustedBounds> {
623        let iv = self.trial_iv();
624        let mult = self.curr_iv();
625        let nlp = self.nlp.borrow();
626
627        let (s_x_l, n_x_l) = self.safe_slack_l(&*nlp.px_l(), &*iv.x, nlp.x_l(), &*mult.z_l);
628        let (s_x_u, n_x_u) = self.safe_slack_u(&*nlp.px_u(), &*iv.x, nlp.x_u(), &*mult.z_u);
629        let (s_s_l, n_s_l) = self.safe_slack_l(&*nlp.pd_l(), &*iv.s, nlp.d_l(), &*mult.v_l);
630        let (s_s_u, n_s_u) = self.safe_slack_u(&*nlp.pd_u(), &*iv.s, nlp.d_u(), &*mult.v_u);
631
632        let adjusted = n_x_l + n_x_u + n_s_l + n_s_u;
633        if adjusted == 0 {
634            return None;
635        }
636
637        // new_x_L = Px_L^T x - safe_slack_x_L
638        let mut new_x_l = nlp.x_l().make_new();
639        nlp.px_l()
640            .trans_mult_vector(1.0, &*iv.x, 0.0, &mut *new_x_l);
641        new_x_l.axpy(-1.0, &*s_x_l);
642        // new_x_U = Px_U^T x + safe_slack_x_U
643        let mut new_x_u = nlp.x_u().make_new();
644        nlp.px_u()
645            .trans_mult_vector(1.0, &*iv.x, 0.0, &mut *new_x_u);
646        new_x_u.axpy(1.0, &*s_x_u);
647        // new_d_L = Pd_L^T s - safe_slack_s_L
648        let mut new_d_l = nlp.d_l().make_new();
649        nlp.pd_l()
650            .trans_mult_vector(1.0, &*iv.s, 0.0, &mut *new_d_l);
651        new_d_l.axpy(-1.0, &*s_s_l);
652        // new_d_U = Pd_U^T s + safe_slack_s_U
653        let mut new_d_u = nlp.d_u().make_new();
654        nlp.pd_u()
655            .trans_mult_vector(1.0, &*iv.s, 0.0, &mut *new_d_u);
656        new_d_u.axpy(1.0, &*s_s_u);
657
658        Some(AdjustedBounds {
659            adjusted,
660            x_l: new_x_l,
661            x_u: new_x_u,
662            d_l: new_d_l,
663            d_u: new_d_u,
664        })
665    }
666
667    // --------------------------------------------------------------
668    // NLP function evaluations.
669    // --------------------------------------------------------------
670
671    pub fn curr_grad_f(&self) -> Rc<dyn Vector> {
672        let iv = self.curr_iv();
673        let mut nlp = self.nlp.borrow_mut();
674        let mut g = iv.x.make_new();
675        nlp.eval_grad_f(&*iv.x, &mut *g);
676        rc_from(g)
677    }
678
679    pub fn trial_grad_f(&self) -> Rc<dyn Vector> {
680        let iv = self.trial_iv();
681        let mut nlp = self.nlp.borrow_mut();
682        let mut g = iv.x.make_new();
683        nlp.eval_grad_f(&*iv.x, &mut *g);
684        rc_from(g)
685    }
686
687    pub fn curr_c(&self) -> Rc<dyn Vector> {
688        let iv = self.curr_iv();
689        let m = self.nlp.borrow().m_eq();
690        let mut nlp = self.nlp.borrow_mut();
691        let mut c = iv.y_c.make_new();
692        debug_assert_eq!(c.dim(), m);
693        nlp.eval_c(&*iv.x, &mut *c);
694        rc_from(c)
695    }
696
697    pub fn trial_c(&self) -> Rc<dyn Vector> {
698        let iv = self.trial_iv();
699        let mut nlp = self.nlp.borrow_mut();
700        let mut c = iv.y_c.make_new();
701        nlp.eval_c(&*iv.x, &mut *c);
702        rc_from(c)
703    }
704
705    pub fn curr_d(&self) -> Rc<dyn Vector> {
706        let iv = self.curr_iv();
707        let mut nlp = self.nlp.borrow_mut();
708        let mut d = iv.s.make_new();
709        nlp.eval_d(&*iv.x, &mut *d);
710        rc_from(d)
711    }
712
713    pub fn trial_d(&self) -> Rc<dyn Vector> {
714        let iv = self.trial_iv();
715        let mut nlp = self.nlp.borrow_mut();
716        let mut d = iv.s.make_new();
717        nlp.eval_d(&*iv.x, &mut *d);
718        rc_from(d)
719    }
720
721    pub fn curr_jac_c(&self) -> Rc<dyn Matrix> {
722        let iv = self.curr_iv();
723        self.nlp.borrow_mut().eval_jac_c(&*iv.x)
724    }
725
726    pub fn curr_jac_d(&self) -> Rc<dyn Matrix> {
727        let iv = self.curr_iv();
728        self.nlp.borrow_mut().eval_jac_d(&*iv.x)
729    }
730
731    pub fn curr_exact_hessian(&self) -> Rc<dyn SymMatrix> {
732        let iv = self.curr_iv();
733        self.nlp
734            .borrow_mut()
735            .eval_h(&*iv.x, 1.0, &*iv.y_c, &*iv.y_d)
736    }
737
738    /// `curr_d - s` — port of `IpIpoptCalculatedQuantities.cpp:1185-1206`.
739    pub fn curr_d_minus_s(&self) -> Rc<dyn Vector> {
740        let iv = self.curr_iv();
741        let d = self.curr_d();
742        let mut tmp = iv.s.make_new();
743        // tmp = 0*tmp + 1*d + (-1)*s
744        tmp.add_two_vectors(1.0, &*d, -1.0, &*iv.s, 0.0);
745        rc_from(tmp)
746    }
747
748    pub fn trial_d_minus_s(&self) -> Rc<dyn Vector> {
749        let iv = self.trial_iv();
750        let d = self.trial_d();
751        let mut tmp = iv.s.make_new();
752        tmp.add_two_vectors(1.0, &*d, -1.0, &*iv.s, 0.0);
753        rc_from(tmp)
754    }
755
756    /// `J_c^T y_c` — for a generic `vec` argument
757    /// (`IpIpoptCalculatedQuantities.cpp:1373-1404`).
758    pub fn curr_jac_c_t_times_vec(&self, vec: &dyn Vector) -> Rc<dyn Vector> {
759        let iv = self.curr_iv();
760        let jac_c = self.curr_jac_c();
761        let mut tmp = iv.x.make_new();
762        jac_c.trans_mult_vector(1.0, vec, 0.0, &mut *tmp);
763        rc_from(tmp)
764    }
765
766    /// `J_d^T y_d` for arbitrary `vec`.
767    pub fn curr_jac_d_t_times_vec(&self, vec: &dyn Vector) -> Rc<dyn Vector> {
768        let iv = self.curr_iv();
769        let jac_d = self.curr_jac_d();
770        let mut tmp = iv.x.make_new();
771        jac_d.trans_mult_vector(1.0, vec, 0.0, &mut *tmp);
772        rc_from(tmp)
773    }
774
775    pub fn curr_jac_c_t_times_curr_y_c(&self) -> Rc<dyn Vector> {
776        let iv = self.curr_iv();
777        self.curr_jac_c_t_times_vec(&*iv.y_c)
778    }
779
780    pub fn curr_jac_d_t_times_curr_y_d(&self) -> Rc<dyn Vector> {
781        let iv = self.curr_iv();
782        self.curr_jac_d_t_times_vec(&*iv.y_d)
783    }
784
785    /// `J_c v` — `IpIpoptCalculatedQuantities.cpp:1303-1321`.
786    pub fn curr_jac_c_times_vec(&self, vec: &dyn Vector) -> Rc<dyn Vector> {
787        let iv = self.curr_iv();
788        let jac_c = self.curr_jac_c();
789        let mut tmp = iv.y_c.make_new();
790        jac_c.mult_vector(1.0, vec, 0.0, &mut *tmp);
791        rc_from(tmp)
792    }
793
794    /// `J_d v` — `IpIpoptCalculatedQuantities.cpp:1323-1343`.
795    pub fn curr_jac_d_times_vec(&self, vec: &dyn Vector) -> Rc<dyn Vector> {
796        let iv = self.curr_iv();
797        let jac_d = self.curr_jac_d();
798        let mut tmp = iv.s.make_new();
799        jac_d.mult_vector(1.0, vec, 0.0, &mut *tmp);
800        rc_from(tmp)
801    }
802
803    // --------------------------------------------------------------
804    // Lagrangian gradients
805    // --------------------------------------------------------------
806
807    /// `∇_x L = ∇f(x) + J_c^T y_c + J_d^T y_d - P_L z_L + P_U z_U`
808    /// per `IpIpoptCalculatedQuantities.cpp:1993-2030`.
809    pub fn curr_grad_lag_x(&self) -> Rc<dyn Vector> {
810        let iv = self.curr_iv();
811        let deps: [&dyn TaggedObject; 5] = [
812            iv.x.as_tagged(),
813            iv.y_c.as_tagged(),
814            iv.y_d.as_tagged(),
815            iv.z_l.as_tagged(),
816            iv.z_u.as_tagged(),
817        ];
818        let mu = self.data.borrow().curr_mu;
819        {
820            let cache = self.curr_grad_lag_x_cache.borrow();
821            if let Some(v) = cache.get(&deps, &[mu]) {
822                return v;
823            }
824        }
825        let grad_f = self.curr_grad_f();
826        let jc_t_y_c = self.curr_jac_c_t_times_curr_y_c();
827        let jd_t_y_d = self.curr_jac_d_t_times_curr_y_d();
828
829        let mut tmp = iv.x.make_new();
830        tmp.copy(&*grad_f);
831        tmp.add_two_vectors(1.0, &*jc_t_y_c, 1.0, &*jd_t_y_d, 1.0);
832
833        let nlp = self.nlp.borrow();
834        nlp.px_l().mult_vector(-1.0, &*iv.z_l, 1.0, &mut *tmp);
835        nlp.px_u().mult_vector(1.0, &*iv.z_u, 1.0, &mut *tmp);
836        let v = rc_from(tmp);
837        self.curr_grad_lag_x_cache
838            .borrow_mut()
839            .add(v.clone(), &deps, &[mu]);
840        v
841    }
842
843    /// `∇_s L = -y_d - P_L v_L + P_U v_U`
844    /// (`IpIpoptCalculatedQuantities.cpp:2069-2098`).
845    pub fn curr_grad_lag_s(&self) -> Rc<dyn Vector> {
846        let iv = self.curr_iv();
847        let deps: [&dyn TaggedObject; 3] =
848            [iv.y_d.as_tagged(), iv.v_l.as_tagged(), iv.v_u.as_tagged()];
849        {
850            let cache = self.curr_grad_lag_s_cache.borrow();
851            if let Some(v) = cache.get(&deps, &[]) {
852                return v;
853            }
854        }
855        let mut tmp = iv.y_d.make_new();
856        let nlp = self.nlp.borrow();
857        // tmp = P_U v_U
858        nlp.pd_u().mult_vector(1.0, &*iv.v_u, 0.0, &mut *tmp);
859        // tmp = tmp - P_L v_L
860        nlp.pd_l().mult_vector(-1.0, &*iv.v_l, 1.0, &mut *tmp);
861        // tmp = tmp - y_d
862        tmp.axpy(-1.0, &*iv.y_d);
863        drop(nlp);
864        let v = rc_from(tmp);
865        self.curr_grad_lag_s_cache
866            .borrow_mut()
867            .add(v.clone(), &deps, &[]);
868        v
869    }
870
871    // --------------------------------------------------------------
872    // Complementarity (slack ⊙ multiplier)
873    // --------------------------------------------------------------
874
875    fn calc_compl(slack: &dyn Vector, mult: &dyn Vector) -> Rc<dyn Vector> {
876        let mut result = slack.make_new();
877        result.copy(slack);
878        result.element_wise_multiply(mult);
879        rc_from(result)
880    }
881
882    pub fn curr_compl_x_l(&self) -> Rc<dyn Vector> {
883        let slack = self.curr_slack_x_l();
884        let z_l = self.curr_iv().z_l;
885        Self::calc_compl(&*slack, &*z_l)
886    }
887
888    pub fn curr_compl_x_u(&self) -> Rc<dyn Vector> {
889        let slack = self.curr_slack_x_u();
890        let z_u = self.curr_iv().z_u;
891        Self::calc_compl(&*slack, &*z_u)
892    }
893
894    pub fn curr_compl_s_l(&self) -> Rc<dyn Vector> {
895        let slack = self.curr_slack_s_l();
896        let v_l = self.curr_iv().v_l;
897        Self::calc_compl(&*slack, &*v_l)
898    }
899
900    pub fn curr_compl_s_u(&self) -> Rc<dyn Vector> {
901        let slack = self.curr_slack_s_u();
902        let v_u = self.curr_iv().v_u;
903        Self::calc_compl(&*slack, &*v_u)
904    }
905
906    /// `s_L .* z_L - mu` — relaxed complementarity used in the KKT
907    /// RHS. `IpIpoptCalculatedQuantities.cpp:2406-2430`.
908    pub fn curr_relaxed_compl_x_l(&self) -> Rc<dyn Vector> {
909        let mu = self.data.borrow().curr_mu;
910        let mut r = self.curr_compl_x_l().make_new();
911        r.copy(&*self.curr_compl_x_l());
912        r.add_scalar(-mu);
913        rc_from(r)
914    }
915
916    pub fn curr_relaxed_compl_x_u(&self) -> Rc<dyn Vector> {
917        let mu = self.data.borrow().curr_mu;
918        let mut r = self.curr_compl_x_u().make_new();
919        r.copy(&*self.curr_compl_x_u());
920        r.add_scalar(-mu);
921        rc_from(r)
922    }
923
924    pub fn curr_relaxed_compl_s_l(&self) -> Rc<dyn Vector> {
925        let mu = self.data.borrow().curr_mu;
926        let mut r = self.curr_compl_s_l().make_new();
927        r.copy(&*self.curr_compl_s_l());
928        r.add_scalar(-mu);
929        rc_from(r)
930    }
931
932    pub fn curr_relaxed_compl_s_u(&self) -> Rc<dyn Vector> {
933        let mu = self.data.borrow().curr_mu;
934        let mut r = self.curr_compl_s_u().make_new();
935        r.copy(&*self.curr_compl_s_u());
936        r.add_scalar(-mu);
937        rc_from(r)
938    }
939
940    // --------------------------------------------------------------
941    // Σ_x / Σ_s (barrier-Hessian diagonals fed to the augmented system)
942    // `IpIpoptCalculatedQuantities.cpp:3501-3551`.
943    //
944    //   Σ_x = P_L · diag(z_L / s_L) · P_L^T + P_U · diag(z_U / s_U) · P_U^T
945    //   Σ_s = P_L · diag(v_L / s_L) · P_L^T + P_U · diag(v_U / s_U) · P_U^T
946    // --------------------------------------------------------------
947
948    pub fn curr_sigma_x(&self) -> Rc<dyn Vector> {
949        let iv = self.curr_iv();
950        {
951            let cache = self.curr_sigma_x_cache.borrow();
952            if let Some(v) = cache.get(
953                &[iv.x.as_tagged(), iv.z_l.as_tagged(), iv.z_u.as_tagged()],
954                &[],
955            ) {
956                return v;
957            }
958        }
959        let slack_l = self.curr_slack_x_l();
960        let slack_u = self.curr_slack_x_u();
961
962        let mut sigma = iv.x.make_new();
963        sigma.set(0.0);
964
965        let nlp = self.nlp.borrow();
966        nlp.px_l()
967            .add_m_sinv_z(1.0, &*slack_l, &*iv.z_l, &mut *sigma);
968        nlp.px_u()
969            .add_m_sinv_z(1.0, &*slack_u, &*iv.z_u, &mut *sigma);
970        let v = rc_from(sigma);
971        self.curr_sigma_x_cache.borrow_mut().add(
972            v.clone(),
973            &[iv.x.as_tagged(), iv.z_l.as_tagged(), iv.z_u.as_tagged()],
974            &[],
975        );
976        v
977    }
978
979    /// Slack-based symmetric scaling factors for the `s` block —
980    /// `min(Pd_L · slack_s_L + Pd_U · slack_s_U, 1)`.
981    ///
982    /// Port of `IpSlackBasedTSymScalingMethod.cpp:ComputeSymTScalingFactors`,
983    /// which builds the whole augmented-system scaling vector as
984    /// `[1 (x block) | this (s block) | 1 (y_c, y_d blocks)]`. Only the
985    /// `s` block is computed here; the surrounding ones are constants
986    /// the scaling method writes itself.
987    ///
988    /// Upstream's method is an algorithm-strategy object with direct
989    /// access to `IpCq()`/`IpNLP()`. pounce's `TSymScalingMethod` lives
990    /// in `pounce-linsol`, which cannot see the iterate, so the quantity
991    /// is computed here and pushed down before the factorization. That
992    /// is why this is a CQ method rather than logic inside the scaling
993    /// method itself.
994    ///
995    /// The cap at 1 is upstream's `slack_scale_max`. A component whose
996    /// `d` row has no bound at all contributes nothing to either
997    /// product and would scale that row by zero, which would wipe the
998    /// row out of the factorization; the floor guards that. It cannot
999    /// arise from a well-formed NLP — an inequality row has at least one
1000    /// bound or it would not be an inequality — but the augmented system
1001    /// is assembled from whatever the caller passes.
1002    pub fn curr_slack_based_s_scaling(&self) -> Option<Vec<Number>> {
1003        let iv = self.curr_iv();
1004        let slack_l = self.curr_slack_s_l();
1005        let slack_u = self.curr_slack_s_u();
1006        let nlp = self.nlp.borrow();
1007
1008        let mut tmp = iv.s.make_new();
1009        nlp.pd_l().mult_vector(1.0, &*slack_l, 0.0, &mut *tmp);
1010        nlp.pd_u().mult_vector(1.0, &*slack_u, 1.0, &mut *tmp);
1011
1012        let mut cap = iv.s.make_new();
1013        cap.set(1.0);
1014        tmp.element_wise_min(&*cap);
1015
1016        // The `Vector` trait exposes no generic value read, so this
1017        // downcasts. `s` is dense on the main solve; the restoration
1018        // sub-IPM's primal is a 5-block `CompoundVector` whose `s` is a
1019        // different space, and slack-based scaling is not wired there.
1020        // Returning `None` rather than panicking means an unexpected
1021        // vector type costs the scaling, not the solve.
1022        let dense = tmp.as_any().downcast_ref::<DenseVector>()?;
1023        let mut out = dense.expanded_values();
1024        for v in out.iter_mut() {
1025            // Guard the zero case described above, and any NaN.
1026            if !(*v > 0.0) {
1027                *v = 1.0;
1028            }
1029        }
1030        Some(out)
1031    }
1032
1033    pub fn curr_sigma_s(&self) -> Rc<dyn Vector> {
1034        let iv = self.curr_iv();
1035        {
1036            let cache = self.curr_sigma_s_cache.borrow();
1037            if let Some(v) = cache.get(
1038                &[iv.s.as_tagged(), iv.v_l.as_tagged(), iv.v_u.as_tagged()],
1039                &[],
1040            ) {
1041                return v;
1042            }
1043        }
1044        let slack_l = self.curr_slack_s_l();
1045        let slack_u = self.curr_slack_s_u();
1046
1047        let mut sigma = iv.s.make_new();
1048        sigma.set(0.0);
1049
1050        let nlp = self.nlp.borrow();
1051        nlp.pd_l()
1052            .add_m_sinv_z(1.0, &*slack_l, &*iv.v_l, &mut *sigma);
1053        nlp.pd_u()
1054            .add_m_sinv_z(1.0, &*slack_u, &*iv.v_u, &mut *sigma);
1055        let v = rc_from(sigma);
1056        self.curr_sigma_s_cache.borrow_mut().add(
1057            v.clone(),
1058            &[iv.s.as_tagged(), iv.v_l.as_tagged(), iv.v_u.as_tagged()],
1059            &[],
1060        );
1061        v
1062    }
1063
1064    // --------------------------------------------------------------
1065    // Objective f and barrier objective phi
1066    // (`IpIpoptCalculatedQuantities.cpp:CalcBarrierTerm`,
1067    //  lines 870-1042 in upstream).
1068    //
1069    //   phi(x,s) = f(x)
1070    //              − μ · [Σ ln(s_x_L) + Σ ln(s_x_U)
1071    //                   + Σ ln(s_s_L) + Σ ln(s_s_U)]
1072    //              + κ_d · μ · [s_x_L · 1_singly_x_L
1073    //                          + s_x_U · 1_singly_x_U
1074    //                          + s_s_L · 1_singly_s_L
1075    //                          + s_s_U · 1_singly_s_U]
1076    //
1077    // The damping piece vanishes when `kappa_d == 0` (default).
1078    // --------------------------------------------------------------
1079
1080    pub fn curr_f(&self) -> Number {
1081        let iv = self.curr_iv();
1082        let mut nlp = self.nlp.borrow_mut();
1083        nlp.eval_f(&*iv.x)
1084    }
1085
1086    /// Unscaled objective at the current iterate. `curr_f` returns the
1087    /// internally scaled value (`f · df_`); upstream IPOPT prints the
1088    /// unscaled objective in its iteration log, so this divides the
1089    /// scaling back out. Mirrors `IpoptCalculatedQuantities::
1090    /// unscaled_curr_f`. A zero factor (scaling never determined) is
1091    /// treated as the identity.
1092    pub fn unscaled_curr_f(&self) -> Number {
1093        let scaled = self.curr_f();
1094        let factor = self.nlp.borrow().obj_scaling_factor();
1095        if factor == 0.0 {
1096            scaled
1097        } else {
1098            scaled / factor
1099        }
1100    }
1101
1102    /// Max-norm dual infeasibility in the **unscaled** (user-original)
1103    /// space. [`Self::curr_dual_infeasibility_max`] is evaluated in the
1104    /// internally-scaled NLP space (objective × `df`, constraints × `dc`);
1105    /// because POUNCE applies no variable scaling, every term of the
1106    /// Lagrangian gradient `∇f + Jᵀy − z` carries the same objective
1107    /// factor `df`, so the unscaling is a single divide by
1108    /// `df = obj_scaling_factor`. A zero or unit factor returns the scaled
1109    /// value unchanged — the common no-scaling path stays division-free.
1110    pub fn curr_unscaled_dual_infeasibility_max(&self) -> Number {
1111        let df = self.nlp.borrow().obj_scaling_factor();
1112        let scaled = self.curr_dual_infeasibility_max();
1113        // `df` is SIGNED — `obj_scaling_factor = -1` is the documented way to
1114        // pose a maximization — while `scaled` is a max-norm. Dividing by the
1115        // signed factor returned a NEGATIVE "max-norm", which then sailed under
1116        // every `<= tol` comparison: it disabled the gh #200 veto on
1117        // maximization, and defeated the unscaled residual gate added for
1118        // pounce#173 there as well. Magnitude is what the unscaling means.
1119        let df = df.abs();
1120        if df == 0.0 || df == 1.0 {
1121            scaled
1122        } else {
1123            scaled / df
1124        }
1125    }
1126
1127    /// Max-norm complementarity in the **unscaled** space. Each bound block
1128    /// `s · z` scales uniformly by `df`: the slack's `dc`/`dd` factor and
1129    /// the multiplier's `df/dc` (`df/dd`) factor cancel in the product,
1130    /// leaving `df`. So this is the scaled max-norm divided by `df`. See
1131    /// [`Self::curr_unscaled_dual_infeasibility_max`].
1132    pub fn curr_unscaled_complementarity_max(&self) -> Number {
1133        let df = self.nlp.borrow().obj_scaling_factor();
1134        let scaled = self.curr_complementarity_max();
1135        // `df` is SIGNED — `obj_scaling_factor = -1` is the documented way to
1136        // pose a maximization — while `scaled` is a max-norm. Dividing by the
1137        // signed factor returned a NEGATIVE "max-norm", which then sailed under
1138        // every `<= tol` comparison: it disabled the gh #200 veto on
1139        // maximization, and defeated the unscaled residual gate added for
1140        // pounce#173 there as well. Magnitude is what the unscaling means.
1141        let df = df.abs();
1142        if df == 0.0 || df == 1.0 {
1143            scaled
1144        } else {
1145            scaled / df
1146        }
1147    }
1148
1149    /// Max-norm primal infeasibility in the **unscaled** space. Unlike the
1150    /// dual/complementarity terms the constraint scaling is per-row
1151    /// (`c_scaled = dc ⊙ c_user`, `(d−s)_scaled = dd ⊙ (d−s)_user`), so each
1152    /// block is unscaled element-by-element before the max-norm. When no row
1153    /// scaling is active (`c_scale_vec`/`d_scale_vec` both `None` — the
1154    /// common case) this is exactly [`Self::curr_primal_infeasibility_max`].
1155    pub fn curr_unscaled_primal_infeasibility_max(&self) -> Number {
1156        let (dc, dd) = {
1157            let nlp = self.nlp.borrow();
1158            (nlp.c_scale_vec(), nlp.d_scale_vec())
1159        };
1160        if dc.is_none() && dd.is_none() {
1161            return self.curr_primal_infeasibility_max();
1162        }
1163        let c_max = unscaled_block_amax(&*self.curr_c(), dc.as_deref());
1164        let dms_max = unscaled_block_amax(&*self.curr_d_minus_s(), dd.as_deref());
1165        c_max.max(dms_max)
1166    }
1167
1168    /// Max-norm constraint violation of the **original** NLP, in user units:
1169    /// `|c_i|` over the equality block and `max(0, d_l_i − d_i, d_i − d_u_i)`
1170    /// over the inequality block. This is what upstream's
1171    /// `inf_pr_output = original` — its *default* — prints in the `inf_pr`
1172    /// column, and what its end-of-run "Constraint violation" line reports.
1173    /// Mirrors `IpIpoptCalculatedQuantities.cpp:unscaled_curr_nlp_constraint_violation`.
1174    ///
1175    /// Deliberately **not** [`Self::curr_primal_infeasibility_max`], which is
1176    /// `max(‖c‖_∞, ‖d − s‖_∞)` — the violation of the *internal* slack
1177    /// reformulation. The two diverge whenever the slack drifts from `d(x)`:
1178    /// `s` is confined to `[d_l, d_u]`, so `d = s + (d − s)` with `d − s > 0`
1179    /// clears a lower bound however large that gap grows. On a model that is
1180    /// all inequalities the gap *is* the whole number — on Mittelmann's
1181    /// `robot_a` POUNCE reported 2.79e4 at an iterate where Ipopt reported
1182    /// `0.00e+00` and every original row was in fact satisfied (pounce#476).
1183    ///
1184    /// Display only. The filter's `theta`, the barrier-parameter strategies
1185    /// and the convergence test all stay on the internal measure — that split
1186    /// is upstream's, not a shortcut.
1187    ///
1188    /// Judged against the **declared** bounds where the NLP tracks them, so
1189    /// the `bound_relax_factor` widening cannot forgive a violation the user
1190    /// would still see (same reasoning as
1191    /// [`Self::relative_d_infeasibility_max`]).
1192    pub fn curr_unscaled_nlp_constraint_violation_max(&self) -> Number {
1193        let c = self.curr_c();
1194        let d = self.curr_d();
1195        unscaled_nlp_constraint_violation_max(&*self.nlp.borrow(), &*c, &*d)
1196    }
1197
1198    /// The primal violation of the model **as declared** — before the
1199    /// `bound_relax_factor` widening `OrigIpoptNlp::relax_bounds` applied.
1200    ///
1201    /// [`Self::curr_unscaled_nlp_constraint_violation_max`] already judges the
1202    /// `c` and `d` blocks against the declared bounds. What nothing else
1203    /// measured is the **variable box**, which the widening moves too; that
1204    /// term comes from `Nlp::declared_box_violation`, which owns the lift out
1205    /// of the compressed bound spaces.
1206    ///
1207    /// This is not what any gate reads and must not become one. The barrier
1208    /// genuinely solves the widened model — a feasible-iterate log-barrier
1209    /// needs `x` strictly inside its bounds — and `final_constr_viol` reports
1210    /// the internal slack measure the convergence test uses. The point of this
1211    /// number is that the two can differ by orders and a caller could not
1212    /// previously see it: on netlib `wood1p` this arm reports `1.71e-14` at a
1213    /// point `7.96e-09` outside the declared rows and `9.84e-09` outside the
1214    /// declared box, and returns an objective `4.4e-05` from the optimum
1215    /// HiGHS reports.
1216    pub fn curr_declared_primal_violation_max(&self) -> Number {
1217        let rows = self.curr_unscaled_nlp_constraint_violation_max();
1218        rows.max(self.curr_declared_box_violation_max())
1219    }
1220
1221    /// How far the current iterate sits outside the **declared** variable box
1222    /// — the box the user wrote, before the `bound_relax_factor` widening.
1223    ///
1224    /// The box half of [`Self::curr_declared_primal_violation_max`] on its
1225    /// own, because that is the quantity Ipopt's summary block reports as
1226    /// `Variable bound violation` and the aggregate cannot answer it: maxed
1227    /// together with the row term, a box violation and a row violation are
1228    /// indistinguishable. POUNCE printed a hardcoded `0.0` on that line until
1229    /// this existed, which is the correct value on an unwidened solve and a
1230    /// false reassurance on exactly the class where the line earns its keep —
1231    /// the toy `min 1e8·x + x²/2 s.t. x ≥ 0` returns `x = −1e-8` at
1232    /// `bound_relax_factor = 1e-8`, an objective of `−1` for a quantity that
1233    /// cannot go below `0`, under `Optimal Solution Found`.
1234    ///
1235    /// `0.0` when the NLP does not track a declared box
1236    /// (`Nlp::declared_box_violation` returns `None`). That is not a fallback
1237    /// stand-in: `relax_bounds` snapshots the box on every solve of this arm
1238    /// *whether or not* it then widens it, so an untracked box means no
1239    /// widening pass ran at all, the declared box and the live one are the
1240    /// same object, and a feasible-iterate log-barrier keeps `x` strictly
1241    /// inside the live one by construction.
1242    ///
1243    /// Measured on the iterate, not on the finalized `x`: with
1244    /// `honor_original_bounds` the reported point is projected back into the
1245    /// declared box, so reading it there would report `0` for every solve and
1246    /// say nothing about the point the objective above it was evaluated at.
1247    /// Upstream reports the same pre-projection quantity.
1248    pub fn curr_declared_box_violation_max(&self) -> Number {
1249        let iv = self.curr_iv();
1250        let nlp = self.nlp.borrow();
1251        nlp.declared_box_violation(&*iv.x).unwrap_or(0.0)
1252    }
1253
1254    /// Largest primal infeasibility of a constraint row **relative to that
1255    /// row's own magnitude** — `|c_i| / |b_i|` over the equality block and
1256    /// `dist(d_i, [d_l_i, d_u_i]) / max(|d_l_i|, |d_u_i|)` over the
1257    /// inequality block, whichever is worse.
1258    ///
1259    /// See [`Self::relative_d_infeasibility_max`] and
1260    /// [`Self::relative_c_infeasibility_max`] for the two blocks; both use
1261    /// the row's **declared** magnitude, never a live or relaxed stand-in,
1262    /// and both abstain (contribute nothing) on a row that has no declared
1263    /// magnitude to be relative to.
1264    pub fn curr_relative_primal_infeasibility_max(&self) -> Number {
1265        self.relative_d_infeasibility_max()
1266            .max(self.relative_c_infeasibility_max())
1267    }
1268
1269    /// The equality-block half of
1270    /// [`Self::curr_relative_primal_infeasibility_max`]: `max_i |c_i| / |b_i|`,
1271    /// where `b_i` is the row's declared right-hand side
1272    /// ([`IpoptNlp::declared_c_rhs`]).
1273    ///
1274    /// POUNCE folds `g_i(x) == b_i` into `c_i(x) = 0`, so `|c_i|` *is* the
1275    /// violation and by itself carries no magnitude to be judged against —
1276    /// which is why every runtime feasibility decision on an equality row was
1277    /// an absolute one, and why down-scaling such a row shrank `|c_i|` under
1278    /// the absolute tolerance and flipped a true infeasibility verdict to
1279    /// `Solve_Succeeded` (gh #390, residual of #387). Dividing by the pre-fold
1280    /// RHS restores it: `s·g(x) == s·b` has residual `s·(g(x) − b)` and RHS
1281    /// `s·b`, so the ratio is the same at every `s` — the point.
1282    ///
1283    /// Both numerator and denominator are taken in the internally-scaled
1284    /// space, so the solver's own row scaling `dc_i` cancels too.
1285    ///
1286    /// A **homogeneous** row (`b_i = 0`) contributes nothing. It has no
1287    /// declared magnitude to be relative to, and needs none: `s·g(x) == 0` is
1288    /// the same row at every `s`, so the absolute test is already invariant
1289    /// there. Dividing by zero — or by a fabricated floor — would turn
1290    /// float-noise residuals into 100% "violations" on the single most common
1291    /// equality row there is. Non-finite entries likewise contribute nothing:
1292    /// an unjudgeable row must not fabricate a relative verdict. When the NLP
1293    /// does not track the RHS at all (`declared_c_rhs` is `None` — e.g. the
1294    /// restoration NLP, whose `c` block is not the user's rows), the whole
1295    /// block abstains.
1296    ///
1297    /// "Homogeneous" is judged **numerically**, not by `b_i == 0` exactly: a
1298    /// row abstains once `|b_i|` sinks under its own
1299    /// [noise floor](`Self::row_noise_floor`). An exact-zero test is the
1300    /// right idea measured with the wrong instrument — a converter that emits
1301    /// `2^-53` where the model says `0` (Maros-Mészáros `QSC*`/`QSCFXM*`, and
1302    /// every one of the 15 problems in gh #446, carry equality rows with an
1303    /// RHS at `1e-17`–`1e-16`) declares a magnitude that is pure rounding
1304    /// residue — a target no iterate could be positioned finely enough to hit.
1305    /// `|c_i|` cannot be driven below the same floor either, so the
1306    /// ratio was noise over noise: QSCSD1 read 81× violated at a converged KKT
1307    /// point whose absolute violation was `9.2e-15`, which vetoed its success
1308    /// certificate and then armed the rapid-infeasibility pre-filter — a
1309    /// feasible convex QP reported `Converged to a point of local
1310    /// infeasibility`. Comparing against the row's own noise floor keeps the
1311    /// scale invariance that is the whole point of the measure (both sides
1312    /// carry `dc_i`), which an absolute cutoff on `|b_i|` would have thrown
1313    /// away.
1314    pub fn relative_c_infeasibility_max(&self) -> Number {
1315        let c = self.curr_c();
1316        if c.dim() == 0 {
1317            return 0.0;
1318        }
1319        let Some(rhs) = self.nlp.borrow().declared_c_rhs() else {
1320            return 0.0;
1321        };
1322        let noise = self.row_noise_floor(&*self.curr_jac_c(), &*c);
1323        let Some(c) = c.as_any().downcast_ref::<DenseVector>() else {
1324            return 0.0;
1325        };
1326        if !c.is_initialized() {
1327            return 0.0;
1328        }
1329        let cv = c.expanded_values();
1330        if cv.len() != rhs.len() {
1331            return 0.0;
1332        }
1333        let mut worst = 0.0_f64;
1334        for (i, (&ci, &bi)) in cv.iter().zip(rhs.iter()).enumerate() {
1335            let mag = bi.abs();
1336            // `0.0` when no floor could be computed, which reproduces the
1337            // former `mag > 0.0` gate exactly.
1338            let floor = noise.as_ref().map_or(0.0, |n| n[i]);
1339            if mag > floor && mag.is_finite() && ci.is_finite() {
1340                worst = worst.max(ci.abs() / mag);
1341            }
1342        }
1343        worst
1344    }
1345
1346    /// Per-row noise floor of a constraint block: the finest residual the
1347    /// solver could drive that row to, in the same internally scaled units as
1348    /// the block's residual and declared bounds. `jac` is the block's Jacobian
1349    /// and `template` any vector in the block's space.
1350    ///
1351    /// The quantity being modelled is **how finely the solver can place `x`**,
1352    /// not how accurately a row evaluates. A Newton step comes from a linear
1353    /// solve whose backward error is norm-wise, so every component of `x` is
1354    /// positioned to roughly `eps · ‖x‖_∞` in absolute terms — a variable at
1355    /// `1e-8` inside a vector of norm `2.7` is still only resolved to
1356    /// `~6e-16`, not to `~2e-24`. A row responds to `x` at rate
1357    /// `max_j |∂g_i/∂x_j|`, so the finest residual it can be driven to is
1358    /// `max_j |∂g_i/∂x_j| · eps · ‖x‖_∞`, with [`ROW_NOISE_KAPPA`] covering
1359    /// accumulation across the row's nonzeros and conditioning slop. A
1360    /// declared magnitude under that is a target the solver could not hit even
1361    /// in exact arithmetic on the model as written.
1362    ///
1363    /// `‖x‖_∞` is global, and that is the point rather than a compromise: `x`
1364    /// is one vector solved for jointly, so a large variable anywhere really
1365    /// does coarsen the resolution of every other. The per-row alternative,
1366    /// the exact term sum `Σ_j |a_ij x_j|` via `|J|·|x|`, was implemented and
1367    /// measured, and it is strictly worse — it models the row's *evaluation*
1368    /// error, which is not what limits the residual. It regressed QETAMACR,
1369    /// QSCORPIO and QPILOTNO of gh #446's 15: QSCORPIO's row 93 has all its
1370    /// variables parked near a zero bound at `~1e-8`, giving a term sum of
1371    /// `6e-8` and a floor of `8.5e-22`, so its `−5.6e-17` of rounding residue
1372    /// read as real data again — while the iterate it is judging is only
1373    /// resolved to `~6e-16`. Do not "improve" this to the term sum without
1374    /// re-running those three.
1375    ///
1376    /// Scale-invariant by construction. Under a row scaling `dc_i` the
1377    /// Jacobian row carries `dc_i` exactly as the residual and the declared
1378    /// bounds do (the scaling is applied in `eval_jac_c`/`eval_jac_d`), so the
1379    /// floor moves with the quantities it gates and the abstention verdict is
1380    /// the same at every `s`.
1381    ///
1382    /// A row with an **empty** Jacobian gets an infinite floor, so it always
1383    /// abstains. Every variable it mentions has been fixed and substituted
1384    /// out, which leaves a constant row `0 = b` that no iterate can move: it
1385    /// is a statement about the *model*, and judging the *iterate* by it is a
1386    /// category error. That is presolve's question, answered up front by
1387    /// `presolve_infeasibility_proof` with a certificate, not a residual. The
1388    /// runtime measure abstaining costs no detection that matters — the
1389    /// absolute `constr_viol_tol` arm still sees the row, and an empty row
1390    /// violated by anything a caller would recognise as infeasible is orders
1391    /// above it. QPILOTNO is why: five variables fixed at `0` reduce row 150
1392    /// to `0 = −2.22e-16`, its own rounding residue, and a measure that
1393    /// insists the iterate is 100% in violation of it will never let any
1394    /// iterate succeed (gh #446).
1395    ///
1396    /// `None` — meaning "no floor", i.e. only an exactly-zero magnitude
1397    /// abstains — when the reference cannot be formed: `x = 0` (every term is
1398    /// exactly zero, so the row carries no rounding error to speak of), a
1399    /// non-finite iterate, or a vector type that is not dense.
1400    fn row_noise_floor(&self, jac: &dyn Matrix, template: &dyn Vector) -> Option<Vec<Number>> {
1401        let x_amax = self.curr_iv().x.amax();
1402        if x_amax <= 0.0 || !x_amax.is_finite() {
1403            return None;
1404        }
1405        let mut rows = template.make_new();
1406        jac.compute_row_amax(&mut *rows, true);
1407        let rows = rows.as_any().downcast_ref::<DenseVector>()?;
1408        if !rows.is_initialized() {
1409            return None;
1410        }
1411        Some(
1412            rows.expanded_values()
1413                .iter()
1414                .map(|&a| {
1415                    if a > 0.0 {
1416                        ROW_NOISE_KAPPA * Number::EPSILON * a * x_amax
1417                    } else {
1418                        Number::INFINITY
1419                    }
1420                })
1421                .collect(),
1422        )
1423    }
1424
1425    /// [`Self::curr_primal_infeasibility_max`] — `max(‖c‖_∞, ‖d − s‖_∞)` —
1426    /// counting each row only where its residual rises above the finest value
1427    /// that residual can take in floating point (gh #528).
1428    ///
1429    /// Both residuals are *differences of quantities the row's own size*:
1430    /// `c_i = g_i(x) − b_i` and `d_i − s_i` with `s_i` confined to `d_i`'s
1431    /// bounds. A difference of doubles of magnitude `m` is quantised in units
1432    /// of `eps · m`, so no iterate can place either residual strictly between
1433    /// `0` and `eps · m_i` — it lands on an exact `0` or on a multiple of the
1434    /// quantum, and which of the two is arithmetic luck. Once `eps · m_i`
1435    /// exceeds `tol` that luck decides whether a fully converged solve gets a
1436    /// certificate: on gh #528's LPs (`|b| ~ 1e8`, so one ulp is `1.5e-8`
1437    /// against the default `tol = 1e-8`) the KKT error was pinned one ulp
1438    /// above the tolerance at the exact optimum, the solve kept iterating at a
1439    /// point it could not improve, and it exited
1440    /// `Search_Direction_Becomes_Too_Small` with the right answer in hand.
1441    ///
1442    /// The floor per row is the larger of two irreducible effects, both
1443    /// carrying [`ROW_NOISE_KAPPA`] for the same reason
1444    /// [`Self::row_noise_floor`] does (accumulation over the row's nonzeros
1445    /// and the linear solve's conditioning):
1446    ///
1447    /// * **Placing `x`** — [`Self::row_noise_floor`], `eps · ‖x‖_∞` passed
1448    ///   through the row at `max_j |∂g_i/∂x_j|`. A row whose Jacobian is
1449    ///   empty gets `INFINITY` there, meaning "abstain", which is the safe
1450    ///   direction for the *relative* measures that floor was written for and
1451    ///   the unsafe one here — silencing a constant row `0 = b` would forgive
1452    ///   a genuine infeasibility outright. Non-finite floors are therefore
1453    ///   read as `0`: such a row is judged on its residual alone.
1454    /// * **Forming the residual** — `eps · m_i`, with `m_i` the magnitude of
1455    ///   the quantities subtracted: the declared right-hand side `|b_i|` on
1456    ///   the equality block (the value `c_i` was formed against), and
1457    ///   `max(|d_i|, |s_i|)` on the inequality block. A block with no declared
1458    ///   magnitude to hand (the restoration NLP's `c`, whose rows are not the
1459    ///   user's) contributes nothing here and is left to the placement floor.
1460    ///
1461    /// A row's residual is counted in full or not at all, matching how
1462    /// [`Self::relative_c_infeasibility_max`] and
1463    /// [`Self::relative_d_infeasibility_max`] use their floors: the question
1464    /// is whether the row says anything, not how much of it to subtract.
1465    pub fn curr_primal_infeasibility_above_noise(&self, kappa: Number) -> Number {
1466        let c = self.curr_c();
1467        let dms = self.curr_d_minus_s();
1468
1469        let c_above = if c.dim() == 0 {
1470            0.0
1471        } else {
1472            let mag = self
1473                .nlp
1474                .borrow()
1475                .declared_c_rhs()
1476                .map(|rhs| rhs.iter().map(|b| b.abs()).collect::<Vec<_>>());
1477            let floor = self.primal_residual_noise_floor(
1478                &*self.curr_jac_c(),
1479                &*c,
1480                mag.as_deref(),
1481                c.dim() as usize,
1482                kappa,
1483            );
1484            amax_above_floor(&*c, &floor)
1485        };
1486
1487        let d_above = if dms.dim() == 0 {
1488            0.0
1489        } else {
1490            let d = self.curr_d();
1491            let s = self.curr_iv().s;
1492            let mag = match (
1493                d.as_any().downcast_ref::<DenseVector>(),
1494                s.as_any().downcast_ref::<DenseVector>(),
1495            ) {
1496                (Some(d), Some(s)) if d.is_initialized() && s.is_initialized() => {
1497                    let (dv, sv) = (d.expanded_values(), s.expanded_values());
1498                    (dv.len() == sv.len()).then(|| {
1499                        dv.iter()
1500                            .zip(&sv)
1501                            .map(|(a, b)| a.abs().max(b.abs()))
1502                            .collect::<Vec<_>>()
1503                    })
1504                }
1505                _ => None,
1506            };
1507            let floor = self.primal_residual_noise_floor(
1508                &*self.curr_jac_d(),
1509                &*dms,
1510                mag.as_deref(),
1511                dms.dim() as usize,
1512                kappa,
1513            );
1514            amax_above_floor(&*dms, &floor)
1515        };
1516
1517        c_above.max(d_above)
1518    }
1519
1520    /// Per-row floor for [`Self::curr_primal_infeasibility_above_noise`]:
1521    /// `max(placement floor, ROW_NOISE_KAPPA · eps · magnitude_i)`, with a
1522    /// finite value on every row (`0` where nothing can be said, so that row
1523    /// is judged on its residual alone). See that method for the derivation.
1524    fn primal_residual_noise_floor(
1525        &self,
1526        jac: &dyn Matrix,
1527        residual: &dyn Vector,
1528        magnitude: Option<&[Number]>,
1529        dim: usize,
1530        kappa: Number,
1531    ) -> Vec<Number> {
1532        // `row_noise_floor` bakes in `ROW_NOISE_KAPPA`; rescale it so both
1533        // contributions carry the caller's `kappa` and nothing else changes
1534        // for the relative measures that share that helper.
1535        let rescale = kappa / ROW_NOISE_KAPPA;
1536        let placement = self.row_noise_floor(jac, residual);
1537        let finite_or_zero = |v: Number| if v.is_finite() && v > 0.0 { v } else { 0.0 };
1538        (0..dim)
1539            .map(|i| {
1540                let from_placement = placement
1541                    .as_ref()
1542                    .and_then(|p| p.get(i))
1543                    .copied()
1544                    .unwrap_or(0.0);
1545                let from_placement = from_placement * rescale;
1546                let from_formation = magnitude
1547                    .and_then(|m| m.get(i))
1548                    .map_or(0.0, |&m| kappa * Number::EPSILON * m);
1549                finite_or_zero(from_placement).max(finite_or_zero(from_formation))
1550            })
1551            .collect()
1552    }
1553
1554    /// The inequality-block half of
1555    /// [`Self::curr_relative_primal_infeasibility_max`]:
1556    /// `max_i |d_i − s_i| / max(|d_i|, |d_l_i|, |d_u_i|)`.
1557    ///
1558    /// This is the scale-free companion to
1559    /// [`Self::curr_unscaled_primal_infeasibility_max`]. An absolute violation
1560    /// measure cannot tell "satisfied" from "violated by 10% of everything the
1561    /// row is" once the row's numbers are small — `x >= 0.7` written as
1562    /// `1e-12·x >= 0.7e-12` has an absolute violation of `1e-13` at `x = 0.6`,
1563    /// under every absolute tolerance, while the row is violated by a seventh
1564    /// of its own right-hand side. The ratio is `0.14` at every writing of the
1565    /// row.
1566    ///
1567    /// Computed entirely in the internally-scaled space: numerator and
1568    /// denominator both carry the row scaling `dd_i`, so it cancels and the
1569    /// ratio is invariant under it — which is the point.
1570    ///
1571    /// The magnitude comes from the row's **declared bounds only** — the
1572    /// current value `d_i` is deliberately excluded. On an *active* row the
1573    /// value converges to the bound, so for a zero-bound row (`g(x) >= 0`,
1574    /// ubiquitous) both the violation and `|d_i|` go to zero together and
1575    /// their ratio hovers near 1 at a perfectly converged point — including
1576    /// `|d_i|` made HS13's genuine solution read as 100% violated and vetoed
1577    /// its certificate. A zero bound also needs no relative treatment in the
1578    /// first place: `s·g >= 0` is the same row at every `s`, so the absolute
1579    /// test is already invariant there. Rows whose bounds are all zero or
1580    /// non-finite therefore contribute nothing (the relative measure
1581    /// abstains) — "zero" measured against the row's own
1582    /// [noise floor](`Self::row_noise_floor`) rather than exactly, for the
1583    /// reason spelled out on [`Self::relative_c_infeasibility_max`]: a
1584    /// converter that writes `2^-53` where the model says `0` otherwise hands
1585    /// a bound made of rounding residue to a measure that then reads the row
1586    /// as 100% violated. QPILOTNO carries 43 such inequality bounds at
1587    /// `1e-17`–`1e-15`, and one of them — a row sitting at exactly `d(x) = 0`
1588    /// against a declared bound of `1.1e-16` — pinned `rel_viol` at `1.0` for
1589    /// the whole run and drove the gh #446 local-infeasibility verdict from
1590    /// this block. Equality rows are judged by
1591    /// [`Self::relative_c_infeasibility_max`], which plumbs the pre-fold RHS
1592    /// back to supply the magnitude the fold into `c(x) = 0` erased.
1593    ///
1594    /// The violation judged is the **distance of `d(x)` outside the declared
1595    /// box** — NOT the lifted residual `|d − s|` the absolute measure uses.
1596    /// `|d − s|` only bounds the true violation from above: mid-solve the
1597    /// slack lags `d` while `d` is comfortably inside its bounds, so a
1598    /// slack-lag of 1% of a small row's magnitude read as "violated" at
1599    /// points that are genuinely feasible. That armed the rapid-infeasibility
1600    /// pre-filter at degenerate QP endgames, where the no-descent
1601    /// confirmation is vacuous (the violation is already ~0, so no materially
1602    /// less-violating point exists) — and 18 feasible CUTEr QPs were reported
1603    /// locally infeasible. Measured, not hypothetical.
1604    pub fn relative_d_infeasibility_max(&self) -> Number {
1605        let dms = self.curr_d_minus_s();
1606        if dms.dim() == 0 {
1607            return 0.0;
1608        }
1609        let d = self.curr_d();
1610        let (lo, hi, mask_l, mask_u) = {
1611            let nlp = self.nlp.borrow();
1612            // The *declared* bounds where the NLP tracks them: the live
1613            // `d_l`/`d_u` carry the `bound_relax_factor` widening, under which
1614            // a declared-zero bound reads as `~1e-8` — a fabricated magnitude
1615            // for a row that has none (that misread both vetoed HS13's genuine
1616            // solution and manufactured "relative" verdicts out of thin air).
1617            let (mut cl, mut cu) = (nlp.d_l().make_new(), nlp.d_u().make_new());
1618            match nlp.declared_d_bounds() {
1619                Some((dl, du)) => {
1620                    let (Some(cld), Some(cud)) = (
1621                        cl.as_any_mut().downcast_mut::<DenseVector>(),
1622                        cu.as_any_mut().downcast_mut::<DenseVector>(),
1623                    ) else {
1624                        return 0.0;
1625                    };
1626                    cld.set_values(&dl);
1627                    cud.set_values(&du);
1628                }
1629                None => {
1630                    cl.copy(nlp.d_l());
1631                    cu.copy(nlp.d_u());
1632                }
1633            }
1634            let mut lo = dms.make_new();
1635            lo.set(0.0);
1636            nlp.pd_l().mult_vector(1.0, &*cl, 0.0, &mut *lo);
1637            let mut hi = dms.make_new();
1638            hi.set(0.0);
1639            nlp.pd_u().mult_vector(1.0, &*cu, 0.0, &mut *hi);
1640            // A projected 0 is ambiguous — "no bound on this side" and "a
1641            // declared zero bound" both read 0 — so project an all-ones
1642            // vector through the same expansion to get presence masks.
1643            let mut ones_l = nlp.d_l().make_new();
1644            ones_l.set(1.0);
1645            let mut mask_l = dms.make_new();
1646            mask_l.set(0.0);
1647            nlp.pd_l().mult_vector(1.0, &*ones_l, 0.0, &mut *mask_l);
1648            let mut ones_u = nlp.d_u().make_new();
1649            ones_u.set(1.0);
1650            let mut mask_u = dms.make_new();
1651            mask_u.set(0.0);
1652            nlp.pd_u().mult_vector(1.0, &*ones_u, 0.0, &mut *mask_u);
1653            (lo, hi, mask_l, mask_u)
1654        };
1655        let noise = self.row_noise_floor(&*self.curr_jac_d(), &*dms);
1656        let (Some(d), Some(lo), Some(hi), Some(mask_l), Some(mask_u)) = (
1657            d.as_any().downcast_ref::<DenseVector>(),
1658            lo.as_any().downcast_ref::<DenseVector>(),
1659            hi.as_any().downcast_ref::<DenseVector>(),
1660            mask_l.as_any().downcast_ref::<DenseVector>(),
1661            mask_u.as_any().downcast_ref::<DenseVector>(),
1662        ) else {
1663            return 0.0;
1664        };
1665        if !(d.is_initialized()
1666            && lo.is_initialized()
1667            && hi.is_initialized()
1668            && mask_l.is_initialized()
1669            && mask_u.is_initialized())
1670        {
1671            return 0.0;
1672        }
1673        let dv = d.expanded_values();
1674        let lov = lo.expanded_values();
1675        let hiv = hi.expanded_values();
1676        let mlv = mask_l.expanded_values();
1677        let muv = mask_u.expanded_values();
1678        let mut worst = 0.0_f64;
1679        for i in 0..dv.len() {
1680            let (has_l, has_u) = (mlv[i] > 0.5, muv[i] > 0.5);
1681            let mut viol = 0.0_f64;
1682            let mut mag = 0.0_f64;
1683            if has_l {
1684                viol = viol.max(lov[i] - dv[i]);
1685                mag = mag.max(lov[i].abs());
1686            }
1687            if has_u {
1688                viol = viol.max(dv[i] - hiv[i]);
1689                mag = mag.max(hiv[i].abs());
1690            }
1691            // `0.0` when no floor could be computed, which reproduces the
1692            // former `mag > 0.0` gate exactly.
1693            let floor = noise.as_ref().map_or(0.0, |n| n[i]);
1694            if mag > floor && mag.is_finite() && viol.is_finite() && viol > 0.0 {
1695                worst = worst.max(viol / mag);
1696            }
1697        }
1698        worst
1699    }
1700
1701    /// The objective scaling factor `df` currently in force (`1.0` when no
1702    /// objective scaling is active).
1703    ///
1704    /// Exposed because the termination logic must be able to tell an honest
1705    /// certificate from one an extreme scale has masked (gh #200): the scale
1706    /// factor itself is the discriminating signal, not the error.
1707    pub fn obj_scaling_factor(&self) -> Number {
1708        self.nlp.borrow().obj_scaling_factor()
1709    }
1710
1711    /// The solver-computed part of the objective scale — see
1712    /// [`IpoptNlp::computed_obj_scaling_factor`]. The masked-certificate test
1713    /// keys on this, not on the product, so a user who deliberately scales a
1714    /// well-conditioned objective down is not second-guessed.
1715    pub fn computed_obj_scaling_factor(&self) -> Number {
1716        self.nlp.borrow().computed_obj_scaling_factor()
1717    }
1718
1719    /// See [`IpoptNlp::start_obj_gradient_max`].
1720    pub fn start_obj_gradient_max(&self) -> Number {
1721        self.nlp.borrow().start_obj_gradient_max()
1722    }
1723
1724    /// Overall **unscaled** max-norm KKT error — `max` of the unscaled dual
1725    /// infeasibility, primal infeasibility, and complementarity. This is the
1726    /// honest "distance from a KKT point in the user's own units", as
1727    /// opposed to [`Self::curr_nlp_error`], which additionally applies the
1728    /// `s_d`/`s_c` optimality scaling. Used by the status-fidelity gate and
1729    /// surfaced to callers that must independently verify a returned
1730    /// certificate (pounce#173).
1731    pub fn curr_unscaled_nlp_error(&self) -> Number {
1732        self.curr_unscaled_dual_infeasibility_max()
1733            .max(self.curr_unscaled_primal_infeasibility_max())
1734            .max(self.curr_unscaled_complementarity_max())
1735    }
1736
1737    pub fn trial_f(&self) -> Number {
1738        let iv = self.trial_iv();
1739        let mut nlp = self.nlp.borrow_mut();
1740        nlp.eval_f(&*iv.x)
1741    }
1742
1743    fn barrier_obj_at(
1744        &self,
1745        f: Number,
1746        s_x_l: &dyn Vector,
1747        s_x_u: &dyn Vector,
1748        s_s_l: &dyn Vector,
1749        s_s_u: &dyn Vector,
1750    ) -> Number {
1751        let mu = self.data.borrow().curr_mu;
1752        let log_sum = s_x_l.sum_logs() + s_x_u.sum_logs() + s_s_l.sum_logs() + s_s_u.sum_logs();
1753        let mut phi = f - mu * log_sum;
1754        if self.kappa_d > 0.0 {
1755            let di = self.damping_indicators();
1756            phi += self.kappa_d * mu * s_x_l.dot(&*di.x_l);
1757            phi += self.kappa_d * mu * s_x_u.dot(&*di.x_u);
1758            phi += self.kappa_d * mu * s_s_l.dot(&*di.s_l);
1759            phi += self.kappa_d * mu * s_s_u.dot(&*di.s_u);
1760        }
1761        phi
1762    }
1763
1764    pub fn curr_barrier_obj(&self) -> Number {
1765        let f = self.curr_f();
1766        let s_x_l = self.curr_slack_x_l();
1767        let s_x_u = self.curr_slack_x_u();
1768        let s_s_l = self.curr_slack_s_l();
1769        let s_s_u = self.curr_slack_s_u();
1770        self.barrier_obj_at(f, &*s_x_l, &*s_x_u, &*s_s_l, &*s_s_u)
1771    }
1772
1773    pub fn trial_barrier_obj(&self) -> Number {
1774        let f = self.trial_f();
1775        let s_x_l = self.trial_slack_x_l();
1776        let s_x_u = self.trial_slack_x_u();
1777        let s_s_l = self.trial_slack_s_l();
1778        let s_s_u = self.trial_slack_s_u();
1779        self.barrier_obj_at(f, &*s_x_l, &*s_x_u, &*s_s_l, &*s_s_u)
1780    }
1781
1782    /// Gradient of the barrier objective wrt `x`:
1783    ///   ∇_x φ = ∇f(x) − μ · [P_L · (1/s_L) − P_U · (1/s_U)] + damping
1784    /// Mirrors `IpIpoptCalculatedQuantities.cpp:CalcGradBarrierObjectiveX`.
1785    pub fn curr_grad_barrier_obj_x(&self) -> Rc<dyn Vector> {
1786        let iv = self.curr_iv();
1787        let mu = self.data.borrow().curr_mu;
1788        let s_l = self.curr_slack_x_l();
1789        let s_u = self.curr_slack_x_u();
1790
1791        let mut inv_s_l = s_l.make_new();
1792        inv_s_l.copy(&*s_l);
1793        inv_s_l.element_wise_reciprocal();
1794        let mut inv_s_u = s_u.make_new();
1795        inv_s_u.copy(&*s_u);
1796        inv_s_u.element_wise_reciprocal();
1797
1798        let grad_f = self.curr_grad_f();
1799        let mut tmp = iv.x.make_new();
1800        tmp.copy(&*grad_f);
1801        let nlp = self.nlp.borrow();
1802        // tmp -= μ · P_L · inv_s_l
1803        nlp.px_l().mult_vector(-mu, &*inv_s_l, 1.0, &mut *tmp);
1804        // tmp += μ · P_U · inv_s_u
1805        nlp.px_u().mult_vector(mu, &*inv_s_u, 1.0, &mut *tmp);
1806
1807        if self.kappa_d > 0.0 {
1808            let di = self.damping_indicators();
1809            // + κ_d μ · P_L · 1_singly_x_L
1810            nlp.px_l()
1811                .mult_vector(self.kappa_d * mu, &*di.x_l, 1.0, &mut *tmp);
1812            // − κ_d μ · P_U · 1_singly_x_U
1813            nlp.px_u()
1814                .mult_vector(-self.kappa_d * mu, &*di.x_u, 1.0, &mut *tmp);
1815        }
1816        rc_from(tmp)
1817    }
1818
1819    /// [`Self::curr_grad_barrier_obj_x`] at the **trial** iterate. One
1820    /// objective-gradient evaluation. Used only by the line search's
1821    /// noise-limited acceptance test (gh#1016), which needs the slope of
1822    /// `phi` along the step at the trial point.
1823    pub fn trial_grad_barrier_obj_x(&self) -> Rc<dyn Vector> {
1824        let iv = self.trial_iv();
1825        let mu = self.data.borrow().curr_mu;
1826        let s_l = self.trial_slack_x_l();
1827        let s_u = self.trial_slack_x_u();
1828
1829        let mut inv_s_l = s_l.make_new();
1830        inv_s_l.copy(&*s_l);
1831        inv_s_l.element_wise_reciprocal();
1832        let mut inv_s_u = s_u.make_new();
1833        inv_s_u.copy(&*s_u);
1834        inv_s_u.element_wise_reciprocal();
1835
1836        let grad_f = self.trial_grad_f();
1837        let mut tmp = iv.x.make_new();
1838        tmp.copy(&*grad_f);
1839        let nlp = self.nlp.borrow();
1840        nlp.px_l().mult_vector(-mu, &*inv_s_l, 1.0, &mut *tmp);
1841        nlp.px_u().mult_vector(mu, &*inv_s_u, 1.0, &mut *tmp);
1842
1843        if self.kappa_d > 0.0 {
1844            let di = self.damping_indicators();
1845            nlp.px_l()
1846                .mult_vector(self.kappa_d * mu, &*di.x_l, 1.0, &mut *tmp);
1847            nlp.px_u()
1848                .mult_vector(-self.kappa_d * mu, &*di.x_u, 1.0, &mut *tmp);
1849        }
1850        rc_from(tmp)
1851    }
1852
1853    /// [`Self::curr_grad_barrier_obj_s`] at the **trial** iterate.
1854    pub fn trial_grad_barrier_obj_s(&self) -> Rc<dyn Vector> {
1855        let iv = self.trial_iv();
1856        let mu = self.data.borrow().curr_mu;
1857        let s_l = self.trial_slack_s_l();
1858        let s_u = self.trial_slack_s_u();
1859
1860        let mut inv_s_l = s_l.make_new();
1861        inv_s_l.copy(&*s_l);
1862        inv_s_l.element_wise_reciprocal();
1863        let mut inv_s_u = s_u.make_new();
1864        inv_s_u.copy(&*s_u);
1865        inv_s_u.element_wise_reciprocal();
1866
1867        let mut tmp = iv.s.make_new();
1868        tmp.set(0.0);
1869        let nlp = self.nlp.borrow();
1870        nlp.pd_l().mult_vector(-mu, &*inv_s_l, 1.0, &mut *tmp);
1871        nlp.pd_u().mult_vector(mu, &*inv_s_u, 1.0, &mut *tmp);
1872
1873        if self.kappa_d > 0.0 {
1874            let di = self.damping_indicators();
1875            nlp.pd_l()
1876                .mult_vector(self.kappa_d * mu, &*di.s_l, 1.0, &mut *tmp);
1877            nlp.pd_u()
1878                .mult_vector(-self.kappa_d * mu, &*di.s_u, 1.0, &mut *tmp);
1879        }
1880        rc_from(tmp)
1881    }
1882
1883    /// Gradient of the barrier objective wrt `s`:
1884    ///   ∇_s φ = − μ · [P_L · (1/s_s_L) − P_U · (1/s_s_U)] + damping
1885    pub fn curr_grad_barrier_obj_s(&self) -> Rc<dyn Vector> {
1886        let iv = self.curr_iv();
1887        let mu = self.data.borrow().curr_mu;
1888        let s_l = self.curr_slack_s_l();
1889        let s_u = self.curr_slack_s_u();
1890
1891        let mut inv_s_l = s_l.make_new();
1892        inv_s_l.copy(&*s_l);
1893        inv_s_l.element_wise_reciprocal();
1894        let mut inv_s_u = s_u.make_new();
1895        inv_s_u.copy(&*s_u);
1896        inv_s_u.element_wise_reciprocal();
1897
1898        let mut tmp = iv.s.make_new();
1899        tmp.set(0.0);
1900        let nlp = self.nlp.borrow();
1901        nlp.pd_l().mult_vector(-mu, &*inv_s_l, 1.0, &mut *tmp);
1902        nlp.pd_u().mult_vector(mu, &*inv_s_u, 1.0, &mut *tmp);
1903
1904        if self.kappa_d > 0.0 {
1905            let di = self.damping_indicators();
1906            nlp.pd_l()
1907                .mult_vector(self.kappa_d * mu, &*di.s_l, 1.0, &mut *tmp);
1908            nlp.pd_u()
1909                .mult_vector(-self.kappa_d * mu, &*di.s_u, 1.0, &mut *tmp);
1910        }
1911        rc_from(tmp)
1912    }
1913
1914    // --------------------------------------------------------------
1915    // Step-aware quadratic-model quantities — used by the penalty
1916    // line-search acceptor's pred/ared test and by the quality-
1917    // function mu oracle's q(σ) evaluator.
1918    // --------------------------------------------------------------
1919
1920    /// Directional derivative of the barrier objective along `(δx, δs)`:
1921    /// `gradBarrTDelta = ∇_x φ · δx + ∇_s φ · δs`. Port of
1922    /// `IpIpoptCalculatedQuantities.cpp:CurrGradBarrTDelta` (called
1923    /// `IpCq().curr_gradBarrTDelta()` in upstream after the search dir
1924    /// has been computed).
1925    pub fn curr_grad_barr_t_delta(&self, delta_x: &dyn Vector, delta_s: &dyn Vector) -> Number {
1926        let g_x = self.curr_grad_barrier_obj_x();
1927        let g_s = self.curr_grad_barrier_obj_s();
1928        g_x.dot(delta_x) + g_s.dot(delta_s)
1929    }
1930
1931    /// `δᵀ(W + Σ_x + δ_pert_x I)δ_x + δ_sᵀ(Σ_s + δ_pert_s I)δ_s` —
1932    /// the quadratic-model term used by `IpPenaltyLSAcceptor.cpp:
1933    /// InitThisLineSearch:101-129`. Reads `W` and the active PD
1934    /// perturbations from [`crate::ipopt_data::IpoptData`].
1935    /// Returns 0 if the result would be negative (matching upstream's
1936    /// `if dWd <= 0 then dWd = 0` guard at line 133).
1937    pub fn curr_dwd(&self, delta_x: &dyn Vector, delta_s: &dyn Vector) -> Number {
1938        let mut dwd: Number = 0.0;
1939
1940        // δ_xᵀ W δ_x.
1941        if let Some(w) = self.data.borrow().w.clone() {
1942            let mut wd = delta_x.make_new();
1943            w.mult_vector(1.0, delta_x, 0.0, &mut *wd);
1944            dwd += wd.dot(delta_x);
1945        }
1946
1947        // δ_xᵀ Σ_x δ_x.
1948        let sigma_x = self.curr_sigma_x();
1949        let mut tmp_x = delta_x.make_new();
1950        tmp_x.copy(delta_x);
1951        tmp_x.element_wise_multiply(&*sigma_x);
1952        dwd += tmp_x.dot(delta_x);
1953
1954        // δ_sᵀ Σ_s δ_s.
1955        let sigma_s = self.curr_sigma_s();
1956        let mut tmp_s = delta_s.make_new();
1957        tmp_s.copy(delta_s);
1958        tmp_s.element_wise_multiply(&*sigma_s);
1959        dwd += tmp_s.dot(delta_s);
1960
1961        // PD perturbations.
1962        let pert = self.data.borrow().perturbations;
1963        if pert.delta_x != 0.0 {
1964            let nx = delta_x.nrm2();
1965            dwd += pert.delta_x * nx * nx;
1966        }
1967        if pert.delta_s != 0.0 {
1968            let ns = delta_s.nrm2();
1969            dwd += pert.delta_s * ns * ns;
1970        }
1971
1972        dwd.max(0.0)
1973    }
1974
1975    // --------------------------------------------------------------
1976    // Constraint violation theta — port of
1977    // `IpIpoptCalculatedQuantities.cpp:CurrConstraintViolation`.
1978    // Default norm is 1-norm (option `constraint_violation_norm`,
1979    // default "1-norm" upstream); we hardwire 1-norm in v1.0.
1980    // --------------------------------------------------------------
1981
1982    pub fn curr_constraint_violation(&self) -> Number {
1983        let c = self.curr_c();
1984        let dms = self.curr_d_minus_s();
1985        c.asum() + dms.asum()
1986    }
1987
1988    /// The round-off floor of [`Self::curr_constraint_violation`] at this
1989    /// iterate — the magnitude below which a difference in `theta` is an
1990    /// artefact of having evaluated `c` in floating point rather than a
1991    /// difference in feasibility (gh#945).
1992    ///
1993    /// The standard forward-error bound for a floating-point sum is `eps`
1994    /// times the magnitudes of the terms summed, and for row `i` of `c`
1995    /// those terms are the `J_ij x_j`. Bounding a row's terms by its largest
1996    /// Jacobian entry times `‖x‖∞` gives
1997    ///
1998    /// ```text
1999    ///   eps · ( max_i rowmax|J_i| · ‖x‖∞  +  ‖s‖∞ )
2000    /// ```
2001    ///
2002    /// with the `d − s` rows contributing `‖s‖∞`, since they subtract `s`
2003    /// from `d(x)` and carry its magnitude into the cancellation
2004    /// independently of the Jacobian.
2005    ///
2006    /// **Two deliberate under-estimates, in the same direction.** `theta` is
2007    /// a 1-norm, so its round-off is the *sum* of the rows' rather than the
2008    /// largest; and `max_j |J_ij| · ‖x‖∞` is itself below `Σ_j |J_ij x_j|`
2009    /// by roughly the row's nonzero count. Both are taken on purpose. The
2010    /// caller — [`crate::line_search::backtracking::BacktrackingLineSearch`]'s
2011    /// gh#945 retry — reads this as "is the iterate feasible to its own
2012    /// evaluation noise, so the restoration phase has nothing to minimize",
2013    /// and answering *yes* when the answer is no reroutes a solve that was
2014    /// working, while answering *no* when the answer is yes costs nothing
2015    /// but upstream's behaviour. Measured: the 1-norm form reads 2.0e-15 on
2016    /// MacMPEC's `qpec_small` against a failure at `theta = 1.746e-15` and
2017    /// takes that fixture's answer away; the ∞-norm form reads 6.66e-16 at
2018    /// the same point, 2.6× under it, and leaves the trajectory
2019    /// byte-identical.
2020    ///
2021    /// There is no safety factor on `eps` for the same reason. A factor of
2022    /// 10 — `compare_le`'s — puts `qpec_small`'s 1.746e-15 failure inside
2023    /// the band and costs it the same way.
2024    ///
2025    /// Why it cannot be a constant: the quantity it bounds moves with the
2026    /// iterate. On gh#945's model (`c = Σx`, `‖x‖∞ ≈ 1`) it is ~1.2e-15 and
2027    /// the `theta` values the filter was ranking — 1.1e-16 against 5.6e-16 —
2028    /// sit inside it. On MacMPEC's `ralph1` at `x = [6.1e-10, 3.8e-8]` it is
2029    /// ~1.7e-23, and that model's 5.8e-16 / 1.1e-15 / 2.4e-15 sit orders
2030    /// *above* it — real differences in violation, which the filter is right
2031    /// to rank on. An absolute `eps` cannot tell those apart; this does,
2032    /// without knowing anything about either model.
2033    ///
2034    /// **This is not [`Self::row_noise_floor`] and must not be folded into
2035    /// it.** That one carries `ROW_NOISE_KAPPA = 64` and a global `‖x‖∞`
2036    /// on purpose, and its own doc records the measurement that rejected the
2037    /// per-row term sum for it. The two answer opposite questions and are
2038    /// conservative in opposite directions: `row_noise_floor` decides
2039    /// whether a residual is too small to be *real*, where being generous
2040    /// avoids claiming a convergence you have not got; this decides whether
2041    /// an iterate is feasible enough that restoration is pointless, where
2042    /// being generous overrides filter decisions that carry information.
2043    /// Hence one at `64 · eps` and one at `eps`.
2044    pub fn theta_evaluation_noise_floor(&self) -> Number {
2045        let iv = self.curr_iv();
2046        let x_amax = iv.x.amax();
2047        if !x_amax.is_finite() {
2048            return 0.0;
2049        }
2050
2051        let mut jac_amax: Number = 0.0;
2052        let jac_c = self.curr_jac_c();
2053        if jac_c.n_rows() > 0 {
2054            let mut rows = iv.y_c.make_new();
2055            jac_c.compute_row_amax(&mut *rows, true);
2056            jac_amax = jac_amax.max(rows.amax());
2057        }
2058        let jac_d = self.curr_jac_d();
2059        if jac_d.n_rows() > 0 {
2060            let mut rows = iv.s.make_new();
2061            jac_d.compute_row_amax(&mut *rows, true);
2062            jac_amax = jac_amax.max(rows.amax());
2063        }
2064
2065        // The `d − s` rows subtract `s` from `d(x)`, so `s` carries its own
2066        // magnitude into the cancellation independently of the Jacobian.
2067        let slack_scale = iv.s.amax();
2068
2069        let floor = Number::EPSILON * (jac_amax * x_amax + slack_scale);
2070        if floor.is_finite() {
2071            floor.max(0.0)
2072        } else {
2073            0.0
2074        }
2075    }
2076
2077    /// Number of constraint rows backing the 1-norm above, i.e.
2078    /// `dim(c) + dim(d - s)`. Upstream never needs this because it
2079    /// treats `theta` as a bare scalar, but any threshold expressed in
2080    /// `theta` units is a *sum* over this many rows — a `theta` of `T`
2081    /// is a mean per-row residual of `T / rows`. The filter acceptor
2082    /// uses it to floor the `theta_max` reference so the ceiling means
2083    /// the same thing on a 10-row and a 50 000-row model.
2084    pub fn constraint_violation_rows(&self) -> usize {
2085        let c = self.curr_c();
2086        let dms = self.curr_d_minus_s();
2087        (c.dim() as usize) + (dms.dim() as usize)
2088    }
2089
2090    pub fn trial_constraint_violation(&self) -> Number {
2091        let c = self.trial_c();
2092        let dms = self.trial_d_minus_s();
2093        c.asum() + dms.asum()
2094    }
2095
2096    /// Max-norm primal infeasibility — `max(||c||_∞, ||d − s||_∞)`. Used
2097    /// by the iteration output's `inf_pr` column when
2098    /// `inf_pr_output == INTERNAL`. Mirrors
2099    /// `IpIpoptCalculatedQuantities.cpp:CurrPrimalInfeasibility(NORM_MAX)`.
2100    pub fn curr_primal_infeasibility_max(&self) -> Number {
2101        let c = self.curr_c();
2102        let dms = self.curr_d_minus_s();
2103        c.amax().max(dms.amax())
2104    }
2105
2106    /// Max-norm dual infeasibility — `max(||∇_x L||_∞, ||∇_s L||_∞)`.
2107    /// Mirrors `IpIpoptCalculatedQuantities.cpp:CurrDualInfeasibility(NORM_MAX)`.
2108    pub fn curr_dual_infeasibility_max(&self) -> Number {
2109        let glx = self.curr_grad_lag_x();
2110        let gls = self.curr_grad_lag_s();
2111        glx.amax().max(gls.amax())
2112    }
2113
2114    /// Magnitude of the largest **term** the Lagrangian gradient is assembled
2115    /// from — the scale [`Self::curr_dual_infeasibility_max`] is a residual
2116    /// *of* (gh #532).
2117    ///
2118    /// ```text
2119    ///   D = max( ‖∇f‖_∞ , ‖J_cᵀ y_c‖_∞ , ‖J_dᵀ y_d‖_∞ ,
2120    ///            ‖P_L z_L‖_∞ , ‖P_U z_U‖_∞ ,
2121    ///            ‖y_d‖_∞ , ‖P_L v_L‖_∞ , ‖P_U v_U‖_∞ )
2122    /// ```
2123    ///
2124    /// `∇L` is the *sum* of exactly these terms, so `dual_inf / D` is the
2125    /// fraction of them that failed to cancel: `1` at a point where nothing
2126    /// cancelled (`min -exp(x) s.t. x >= 0` running away, `∇f = −8.8e47` with
2127    /// no multiplier to meet it), and `~eps` at a point where the cancellation
2128    /// was as complete as the arithmetic allows. That ratio is the
2129    /// scale-invariant statement of stationarity: it is unchanged by
2130    /// multiplying the objective — and hence every multiplier — by a positive
2131    /// constant, which is the map an absolute bound on `dual_inf` is not
2132    /// invariant under.
2133    ///
2134    /// The projections are applied rather than assumed away: `P_L`/`P_U` are
2135    /// 0/1 expansion matrices in the main NLP, where the scatter leaves the
2136    /// max-norm alone, but the term's own norm is what this measures and the
2137    /// restoration NLP supplies its own operators.
2138    ///
2139    /// No `has_valid_numbers` sweep, unlike [`Self::curr_nlp_error`] (gh #292):
2140    /// `amax` drops NaN, so a NaN gradient reads here as a finite scale. That
2141    /// cannot launder anything, because the only caller pairs this with the
2142    /// aggregate `nlp_err <= tol` test, and `nlp_err` carries that sweep — a
2143    /// NaN anywhere in `∇L` makes it NaN, and `NaN <= tol` is false.
2144    ///
2145    /// Repeats the `∇f` and the two transpose products
2146    /// [`Self::curr_grad_lag_x`] already performs on the same iterate, plus
2147    /// four scatters. The evaluations themselves hit `OrigIpoptNLP`'s
2148    /// per-iterate caches, so the marginal cost is the products — but it is
2149    /// still a second pass, and the caller reads this only where a termination
2150    /// certificate is otherwise on the table. See
2151    /// `OptErrorConvCheck::dual_inf_bound`.
2152    pub fn curr_dual_infeasibility_scale_max(&self) -> Number {
2153        let iv = self.curr_iv();
2154        let mut scale = self
2155            .curr_grad_f()
2156            .amax()
2157            .max(self.curr_jac_c_t_times_curr_y_c().amax())
2158            .max(self.curr_jac_d_t_times_curr_y_d().amax())
2159            .max(iv.y_d.amax());
2160
2161        let nlp = self.nlp.borrow();
2162        let mut tmp_x = iv.x.make_new();
2163        nlp.px_l().mult_vector(1.0, &*iv.z_l, 0.0, &mut *tmp_x);
2164        scale = scale.max(tmp_x.amax());
2165        nlp.px_u().mult_vector(1.0, &*iv.z_u, 0.0, &mut *tmp_x);
2166        scale = scale.max(tmp_x.amax());
2167
2168        let mut tmp_s = iv.y_d.make_new();
2169        nlp.pd_l().mult_vector(1.0, &*iv.v_l, 0.0, &mut *tmp_s);
2170        scale = scale.max(tmp_s.amax());
2171        nlp.pd_u().mult_vector(1.0, &*iv.v_u, 0.0, &mut *tmp_s);
2172        scale.max(tmp_s.amax())
2173    }
2174
2175    /// [`Self::curr_dual_infeasibility_scale_max`] in the **unscaled**
2176    /// (user-original) space. Every term of the scaled Lagrangian gradient is
2177    /// `df` times its user-space counterpart — `∇f_scaled = df·∇f`,
2178    /// `J_cᵀ_scaled y_c_scaled = Jᵀ(dc ⊙ y_c_scaled) = df·Jᵀ y_c` since
2179    /// `dc ⊙ y_scaled = df·y_user`, and likewise for the bound blocks, POUNCE
2180    /// applying no variable scaling — so the unscaling is the single divide by
2181    /// `|df|` that [`Self::curr_unscaled_dual_infeasibility_max`] performs on
2182    /// the residual, term for term and row scaling included. Magnitude, for
2183    /// the reason documented there: `df` is signed, a max-norm is not.
2184    pub fn curr_unscaled_dual_infeasibility_scale_max(&self) -> Number {
2185        let df = self.nlp.borrow().obj_scaling_factor().abs();
2186        let scaled = self.curr_dual_infeasibility_scale_max();
2187        if df == 0.0 || df == 1.0 {
2188            scaled
2189        } else {
2190            scaled / df
2191        }
2192    }
2193
2194    /// Scaled stationarity of the infeasibility measure `½‖(c, d−s)‖²`
2195    /// — `‖J_cᵀ c + J_dᵀ (d−s)‖_∞ / max(1, ‖(c, d−s)‖_∞)`. The
2196    /// numerator is the x-gradient of the squared constraint
2197    /// violation; a value near zero with the violation itself bounded
2198    /// away from zero marks an iterate converging to a stationary
2199    /// point of the infeasibility — i.e. a locally infeasible problem.
2200    /// No linear solve: two transpose-products. Mirrors the gradient
2201    /// term behind Ipopt's `IpRestoConvCheck.cpp` `LOCALLY_INFEASIBLE`
2202    /// test, applied here in the main loop.
2203    /// Does a short step along `−∇θ` actually reduce the constraint violation?
2204    ///
2205    /// `LocalInfeasibility` asserts the iterate has converged to a **stationary
2206    /// point of the constraint violation** — that no local move reduces it. That
2207    /// is a checkable claim, and this checks it directly instead of trusting a
2208    /// threshold on a proxy.
2209    ///
2210    /// Why a probe rather than a better proxy: the detector's surrogate is
2211    /// `‖Jᵀc‖ / max(1, ‖c‖)` against an absolute tolerance, and no variant of it
2212    /// separates the cases. Measured over 800 MINLPLib models plus targeted
2213    /// infeasible problems, the scaled form produces a confirmed false verdict
2214    /// (HS13 from `x₀ = (1e4, 1e4)`, where the constraint scaling `dc ≈ 3.3e-7`
2215    /// drives the surrogate to `5e-14` at a point whose violation is 0.51); the
2216    /// unscaled form needs a tolerance ≥ 1e-2 to fire at all, which introduces
2217    /// new false infeasibility on 3+ corpus models while still losing 2 correct
2218    /// detections; and a scale-invariant `‖Jᵀc‖ / ‖c‖²` is not separable even on
2219    /// the targeted set. A single absolute threshold on a surrogate cannot do
2220    /// this job.
2221    ///
2222    /// Comparing `θ` at two points is scale-free by construction — the row
2223    /// scaling cancels out of the ratio — so this needs no calibration at all.
2224    ///
2225    /// Costs one `eval_c`/`eval_d` pair per probed step, and runs only where the
2226    /// detector was about to fire (both gates already passed for a full streak),
2227    /// which is rare. Steps are clamped to the variable bounds, so descent that
2228    /// only exists outside the box is correctly not counted — that direction
2229    /// would suppress a *correct* infeasibility verdict.
2230    ///
2231    /// Returns `true` when descent is available, i.e. the iterate is **not**
2232    /// stationary and `LocalInfeasibility` must not be declared.
2233    pub fn infeasibility_descent_available(&self) -> bool {
2234        use pounce_linalg::DenseVector;
2235
2236        let theta_curr = self.curr_primal_infeasibility_max();
2237        if theta_curr <= 0.0 {
2238            return false;
2239        }
2240        // -grad of 1/2||(c, d-s)||^2 w.r.t. x.
2241        let c = self.curr_c();
2242        let dms = self.curr_d_minus_s();
2243        let jc_t_c = self.curr_jac_c_t_times_vec(&*c);
2244        let jd_t_dms = self.curr_jac_d_t_times_vec(&*dms);
2245        let mut grad = jc_t_c.make_new();
2246        grad.add_two_vectors(1.0, &*jc_t_c, 1.0, &*jd_t_dms, 0.0);
2247        let gnorm = grad.amax();
2248        if !(gnorm > 0.0) || !gnorm.is_finite() {
2249            // A vanishing gradient is the stationary case this exists to
2250            // confirm; a non-finite one gives us nothing to probe with.
2251            return false;
2252        }
2253
2254        let x = self.curr_iv().x.clone();
2255        let nlp = self.nlp.borrow();
2256
2257        // Full-length bound values and finite-bound indicators, lifted through
2258        // the expansion matrices (same pattern as the divergence guard).
2259        let mut ones_l = nlp.x_l().make_new();
2260        ones_l.set(1.0);
2261        let mut has_lb = x.make_new();
2262        nlp.px_l().mult_vector(1.0, &*ones_l, 0.0, &mut *has_lb);
2263        let mut lb = x.make_new();
2264        nlp.px_l().mult_vector(1.0, nlp.x_l(), 0.0, &mut *lb);
2265
2266        let mut ones_u = nlp.x_u().make_new();
2267        ones_u.set(1.0);
2268        let mut has_ub = x.make_new();
2269        nlp.px_u().mult_vector(1.0, &*ones_u, 0.0, &mut *has_ub);
2270        let mut ub = x.make_new();
2271        nlp.px_u().mult_vector(1.0, nlp.x_u(), 0.0, &mut *ub);
2272        drop(nlp);
2273
2274        let dense = |v: &dyn Vector| -> Option<Vec<Number>> {
2275            v.as_any()
2276                .downcast_ref::<DenseVector>()
2277                .map(|d| d.expanded_values())
2278        };
2279        let (Some(xv), Some(gv), Some(lbv), Some(ubv), Some(hl), Some(hu)) = (
2280            dense(&*x),
2281            dense(&*grad),
2282            dense(&*lb),
2283            dense(&*ub),
2284            dense(&*has_lb),
2285            dense(&*has_ub),
2286        ) else {
2287            // Non-dense backing: no probe possible. Report "no descent" so the
2288            // caller falls back to the surrogate's verdict rather than silently
2289            // suppressing every infeasibility conclusion.
2290            return false;
2291        };
2292
2293        // Relative step lengths, so the probe is independent of problem scale.
2294        let xnorm = xv.iter().fold(0.0_f64, |a, &v| a.max(v.abs())).max(1.0);
2295        let base = xnorm / gnorm;
2296
2297        let mut trial = x.make_new();
2298        for k in 0..Self::INFEAS_PROBE_STEPS {
2299            let alpha = base * 10f64.powi(-(k as i32));
2300            {
2301                let Some(t) = trial.as_any_mut().downcast_mut::<DenseVector>() else {
2302                    return false;
2303                };
2304                for (i, slot) in t.values_mut().iter_mut().enumerate() {
2305                    let mut xi = xv[i] - alpha * gv[i];
2306                    if hl[i] != 0.0 {
2307                        xi = xi.max(lbv[i]);
2308                    }
2309                    if hu[i] != 0.0 {
2310                        xi = xi.min(ubv[i]);
2311                    }
2312                    *slot = xi;
2313                }
2314            }
2315            if let Some(theta) = self.theta_at(&*trial) {
2316                if theta.is_finite() && theta < theta_curr * (1.0 - Self::INFEAS_PROBE_MARGIN) {
2317                    return true;
2318                }
2319            }
2320        }
2321        false
2322    }
2323
2324    /// Number of geometrically decreasing step lengths the descent probe tries.
2325    const INFEAS_PROBE_STEPS: usize = 6;
2326    /// Relative reduction in `θ` a probe step must achieve before it counts as
2327    /// descent and vetoes the verdict.
2328    ///
2329    /// Deliberately coarse. The question is not "is this the exact minimiser of
2330    /// the violation" — an interior-point iterate converging toward one always
2331    /// has some infinitesimal descent left, and a tight margin would veto
2332    /// forever and never let a genuine infeasibility be declared. The question
2333    /// is whether a *materially* less-violating point sits nearby, which is what
2334    /// distinguishes "converging to an infeasible stationary point" from
2335    /// "nowhere near stationary".
2336    ///
2337    /// The two regimes are far apart, so the exact value is not delicate. On the
2338    /// genuinely infeasible `x³+y³ == 1 ∧ == 2`, iterates near the least-squares
2339    /// point have only ~0.07 % descent available. On HS13's false verdict, one
2340    /// step takes `θ` from 0.51 to **zero** — a 100 % reduction. Anything between
2341    /// a few percent and most of the way separates them; 10 % sits in the middle.
2342    const INFEAS_PROBE_MARGIN: Number = 0.1;
2343
2344    /// Max-norm constraint violation at an arbitrary `x`, evaluated on scratch
2345    /// vectors so the algorithm's `curr`/`trial` state is untouched. `None` if
2346    /// the evaluation is unusable.
2347    fn theta_at(&self, x: &dyn Vector) -> Option<Number> {
2348        let iv = self.curr_iv();
2349        let mut nlp = self.nlp.borrow_mut();
2350        let mut c = iv.y_c.make_new();
2351        nlp.eval_c(x, &mut *c);
2352        let mut d = iv.s.make_new();
2353        nlp.eval_d(x, &mut *d);
2354        // `d - s` against the CURRENT slacks, matching how `curr_d_minus_s`
2355        // measures the violation: the probe moves x only.
2356        let mut dms = iv.s.make_new();
2357        dms.add_two_vectors(1.0, &*d, -1.0, &*iv.s, 0.0);
2358        let t = c.amax().max(dms.amax());
2359        t.is_finite().then_some(t)
2360    }
2361
2362    pub fn curr_infeasibility_stationarity(&self) -> Number {
2363        let c = self.curr_c();
2364        let dms = self.curr_d_minus_s();
2365        let jc_t_c = self.curr_jac_c_t_times_vec(&*c);
2366        let jd_t_dms = self.curr_jac_d_t_times_vec(&*dms);
2367        let mut grad = jc_t_c.make_new();
2368        grad.add_two_vectors(1.0, &*jc_t_c, 1.0, &*jd_t_dms, 0.0);
2369        let viol = c.amax().max(dms.amax());
2370        grad.amax() / viol.max(1.0)
2371    }
2372
2373    // --------------------------------------------------------------
2374    // Average / scalar complementarity
2375    // --------------------------------------------------------------
2376
2377    /// `(z_L · s_L + z_U · s_U + v_L · s_L^d + v_U · s_U^d) / N`
2378    /// where `N` is the total number of bound multipliers
2379    /// (`IpIpoptCalculatedQuantities.cpp:3553-3606`).
2380    pub fn curr_avrg_compl(&self) -> Number {
2381        let iv = self.curr_iv();
2382        let n = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2383        if n == 0 {
2384            return 0.0;
2385        }
2386        let s_x_l = self.curr_slack_x_l();
2387        let s_x_u = self.curr_slack_x_u();
2388        let s_s_l = self.curr_slack_s_l();
2389        let s_s_u = self.curr_slack_s_u();
2390        let mut acc = iv.z_l.dot(&*s_x_l);
2391        acc += iv.z_u.dot(&*s_x_u);
2392        acc += iv.v_l.dot(&*s_s_l);
2393        acc += iv.v_u.dot(&*s_s_u);
2394        acc / Number::from(n)
2395    }
2396
2397    /// `min_i (s_i · z_i)` over all four bound complementarity blocks.
2398    /// Mirrors `IpIpoptCalculatedQuantities.cpp:CurrComplxMin`
2399    /// (lines 3608-3640) — the smallest pairwise product `s · z`,
2400    /// signalling how close the iterate is to the central path.
2401    /// Empty bound sets contribute `+∞`; returns `0` if no bounds at
2402    /// all.
2403    pub fn curr_complementarity_min(&self) -> Number {
2404        let cxl = self.curr_compl_x_l();
2405        let cxu = self.curr_compl_x_u();
2406        let csl = self.curr_compl_s_l();
2407        let csu = self.curr_compl_s_u();
2408        let m = |v: &Rc<dyn Vector>| {
2409            if v.dim() == 0 {
2410                Number::INFINITY
2411            } else {
2412                v.min()
2413            }
2414        };
2415        let acc = m(&cxl).min(m(&cxu)).min(m(&csl)).min(m(&csu));
2416        if acc.is_infinite() { 0.0 } else { acc }
2417    }
2418
2419    /// Max-norm of the unbarriered complementarity blocks
2420    /// `max_i |s_i · z_i|` across all four `(x_L, x_U, s_L, s_U)`
2421    /// pairs. Mirrors upstream
2422    /// `IpIpoptCalculatedQuantities.cpp:CurrComplementarity(0., NORM_MAX)`
2423    /// — used by `OptimalityErrorConvergenceCheck` to gate the
2424    /// per-component `compl_inf_tol` test independently of the scaled
2425    /// scalar `curr_nlp_error`.
2426    pub fn curr_complementarity_max(&self) -> Number {
2427        self.curr_compl_x_l()
2428            .amax()
2429            .max(self.curr_compl_x_u().amax())
2430            .max(self.curr_compl_s_l().amax())
2431            .max(self.curr_compl_s_u().amax())
2432    }
2433
2434    /// Centrality measure `ξ = min_i(s_i z_i) / avrg(s · z)`. Mirrors
2435    /// `IpIpoptCalculatedQuantities.cpp:CurrCentralityMeasure`. Used
2436    /// by [`crate::mu::oracle::loqo::LoqoMuOracle`] to bias σ toward
2437    /// the central path when the iterate is unbalanced. Returns `1.0`
2438    /// (perfectly central) when there are no bound multipliers.
2439    pub fn curr_centrality_measure(&self) -> Number {
2440        let avrg = self.curr_avrg_compl();
2441        if avrg <= 0.0 {
2442            return 1.0;
2443        }
2444        self.curr_complementarity_min() / avrg
2445    }
2446
2447    /// Barriered KKT error `E_μ(x,y,z)` — port of
2448    /// `IpIpoptCalculatedQuantities.cpp:CurrBarrierError`. Same as
2449    /// [`Self::curr_nlp_error`] but uses the *relaxed* complementarity
2450    /// `s ⊙ z − μ` so the residual is zero when the iterate sits on the
2451    /// μ-perturbed central path. The monotone barrier-update strategy
2452    /// reduces μ only once this error drops below
2453    /// `barrier_tol_factor · μ`.
2454    pub fn curr_barrier_error(&self) -> Number {
2455        let iv = self.curr_iv();
2456        let (s_d, s_c) = self.optimality_error_scaling(&iv);
2457
2458        let glx = self.curr_grad_lag_x();
2459        let gls = self.curr_grad_lag_s();
2460        let dual = glx.amax().max(gls.amax()) / s_d;
2461
2462        let c = self.curr_c();
2463        let dms = self.curr_d_minus_s();
2464        let primal = c.amax().max(dms.amax());
2465
2466        let compl = self
2467            .curr_relaxed_compl_x_l()
2468            .amax()
2469            .max(self.curr_relaxed_compl_x_u().amax())
2470            .max(self.curr_relaxed_compl_s_l().amax())
2471            .max(self.curr_relaxed_compl_s_u().amax())
2472            / s_c;
2473
2474        dual.max(primal).max(compl)
2475    }
2476
2477    /// Optimality-scaled max-norm KKT error — port of
2478    /// `IpIpoptCalculatedQuantities.cpp:3050-3104`.
2479    ///
2480    /// ```text
2481    ///   E = max( ||∇_x L, ∇_s L||_∞ / s_d ,
2482    ///            ||c, d − s||_∞ ,
2483    ///            ||compl||_∞ / s_c )
2484    /// ```
2485    ///
2486    /// where `s_d` / `s_c` are the asum-based scalings from
2487    /// `ComputeOptimalityErrorScaling` (see §4 of `MAIN_LOOP.md`).
2488    /// Uses `mu_target = 0` (the unbarriered KKT residual). The
2489    /// barriered variant is `curr_barrier_error` (TODO in Phase 7).
2490    pub fn curr_nlp_error(&self) -> Number {
2491        self.nlp_error(None)
2492    }
2493
2494    /// [`Self::curr_nlp_error`] with the primal-infeasibility term replaced by
2495    /// [`Self::curr_primal_infeasibility_above_noise`] — i.e. counting a
2496    /// constraint row's residual only where it rises above the finest value
2497    /// that row's residual can take in floating point (gh #528).
2498    ///
2499    /// Never larger than [`Self::curr_nlp_error`], and equal to it whenever no
2500    /// row is at its own resolution limit — which is every problem whose data
2501    /// is `O(1)`, so the common path is unchanged. It exists because the other
2502    /// two terms of the KKT error are already normalised (`s_d`, `s_c`) while
2503    /// the primal one is a bare absolute residual: `‖c‖_∞` and `‖d − s‖_∞` are
2504    /// quantised in units of `eps ·` the rows' own magnitude, so on a model
2505    /// whose constraint values reach `~1e8` the smallest *nonzero* value the
2506    /// term can take already exceeds the default `tol = 1e-8`. Judging that
2507    /// term absolutely there asks for a residual no iterate can represent.
2508    ///
2509    /// Read only by the **strict** convergence gate, which pairs it with the
2510    /// unscaled `constr_viol_tol` test on the full, unfloored residual — so
2511    /// what this admits is bounded by the user's own feasibility tolerance,
2512    /// never by the noise floor alone.
2513    ///
2514    /// `kappa` is the safety factor on the per-row floor —
2515    /// [`ROW_NOISE_KAPPA`] by default, from the `primal_noise_floor_kappa`
2516    /// option. **`0` switches the floor off entirely**, making this identical
2517    /// to [`Self::curr_nlp_error`] and the strict gate bit-for-bit upstream's.
2518    pub fn curr_nlp_error_above_primal_noise(&self, kappa: Number) -> Number {
2519        self.nlp_error(Some(kappa))
2520    }
2521
2522    /// [`Self::curr_nlp_error`] with the complementarity term supplied by the
2523    /// caller instead of read off the iterate, keeping the `s_c` normalisation
2524    /// and the other two terms exactly as they are.
2525    ///
2526    /// One caller: the crossover phase (#612). Its returned point sits
2527    /// *exactly* on the active constraints of the problem **as the user
2528    /// declared it**, which is `bound_relax_factor` inside the widened bounds
2529    /// this object measures against — so the iterate-derived complementarity
2530    /// reads `|multiplier| · δ`, around `1e-8` for a unit multiplier, where
2531    /// the truth in the frame that was solved is zero. Left alone that put a
2532    /// converged run's `Overall NLP error` above `tol` and let the opt-in
2533    /// `kkt_fidelity_tol` gate downgrade a strictly better point (#646).
2534    ///
2535    /// `compl_raw` is the un-normalised max-norm `max_i |s_i · z_i|`, the same
2536    /// quantity [`Self::curr_complementarity_max`] returns; the `s_c` divide
2537    /// happens here. `kappa` follows
2538    /// [`Self::curr_nlp_error_above_primal_noise`], `0` disabling the floor.
2539    ///
2540    /// This is a *reporting* substitution and nothing more — no convergence
2541    /// decision reads it, because crossover runs after the status is already
2542    /// settled.
2543    pub fn curr_nlp_error_with_complementarity(&self, compl_raw: Number, kappa: Number) -> Number {
2544        let floor = (kappa > 0.0).then_some(kappa);
2545        self.nlp_error_inner(floor, Some(compl_raw))
2546    }
2547
2548    /// `above_primal_noise` carries the floor's `kappa` when the primal term is
2549    /// to be floored, and is `None` for the plain upstream aggregate.
2550    fn nlp_error(&self, above_primal_noise: Option<Number>) -> Number {
2551        self.nlp_error_inner(above_primal_noise, None)
2552    }
2553
2554    /// `compl_override` replaces the iterate-derived complementarity max-norm
2555    /// before the `s_c` divide; see
2556    /// [`Self::curr_nlp_error_with_complementarity`]. The NaN guard below
2557    /// still inspects the iterate's own complementarity vectors either way —
2558    /// an override is a change of *frame*, not a licence to stop looking at
2559    /// the iterate for non-finite numbers.
2560    fn nlp_error_inner(
2561        &self,
2562        above_primal_noise: Option<Number>,
2563        compl_override: Option<Number>,
2564    ) -> Number {
2565        let iv = self.curr_iv();
2566        let (s_d, s_c) = self.optimality_error_scaling(&iv);
2567
2568        // dual infeasibility (max-norm of grad_lag_x and grad_lag_s)
2569        let glx = self.curr_grad_lag_x();
2570        let gls = self.curr_grad_lag_s();
2571
2572        // primal: max(||c||, ||d-s||)
2573        let c = self.curr_c();
2574        let dms = self.curr_d_minus_s();
2575
2576        // unbarriered complementarity (mu_target = 0 → just ||compl||)
2577        let cxl = self.curr_compl_x_l();
2578        let cxu = self.curr_compl_x_u();
2579        let csl = self.curr_compl_s_l();
2580        let csu = self.curr_compl_s_u();
2581
2582        // #292: the max-norm (`amax`/BLAS `iamax`) behind every term below
2583        // silently *drops* NaN — `NaN > m` is `false`, so a NaN component
2584        // leaves the running max untouched and is laundered into a finite
2585        // (typically `0.0`) KKT error. A NaN gradient, NaN constraint Jacobian
2586        // (via `∇_x L`'s `Jᵀy` term), or NaN residual would then read as an
2587        // *optimal* solve and return `Solve_Succeeded`. Detect any non-finite
2588        // component here — through the NaN-propagating `asum` behind
2589        // `has_valid_numbers`, not `amax` — and surface it as a non-finite KKT
2590        // error so the caller's existing `!nlp_err.is_finite()` guard fires
2591        // `Invalid_Number_Detected`. This is confined to the convergence/error
2592        // measure; the general `amax` semantics that step-size selection, the
2593        // line search, and the divergence detectors rely on are untouched.
2594        // (Inf is *not* laundered — `Inf > m` is true — so it already
2595        // propagated; this closes only the NaN hole, and Inf for free.)
2596        for v in [&glx, &gls, &c, &dms, &cxl, &cxu, &csl, &csu] {
2597            if !v.has_valid_numbers() {
2598                return Number::NAN;
2599            }
2600        }
2601
2602        let dual = glx.amax().max(gls.amax()) / s_d;
2603        let primal = match above_primal_noise {
2604            Some(kappa) if kappa > 0.0 => self.curr_primal_infeasibility_above_noise(kappa),
2605            _ => c.amax().max(dms.amax()),
2606        };
2607        let compl_raw = compl_override
2608            .unwrap_or_else(|| cxl.amax().max(cxu.amax()).max(csl.amax()).max(csu.amax()));
2609        let compl = compl_raw / s_c;
2610
2611        dual.max(primal).max(compl)
2612    }
2613
2614    /// `(s_d, s_c)` per `ComputeOptimalityErrorScaling`
2615    /// (`IpIpoptCalculatedQuantities.cpp:3663-3700`).
2616    fn optimality_error_scaling(&self, iv: &IteratesVector) -> (Number, Number) {
2617        let s_max = self.s_max;
2618
2619        // s_c: mean asum of all bound multipliers, capped at s_max,
2620        //      divided by s_max.
2621        let n_c = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2622        let s_c = if n_c == 0 {
2623            1.0
2624        } else {
2625            let asum = iv.z_l.asum() + iv.z_u.asum() + iv.v_l.asum() + iv.v_u.asum();
2626            (s_max.max(asum / Number::from(n_c))) / s_max
2627        };
2628
2629        // s_d: mean asum of all dual multipliers, capped, divided.
2630        let n_d =
2631            iv.y_c.dim() + iv.y_d.dim() + iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2632        let s_d = if n_d == 0 {
2633            1.0
2634        } else {
2635            let asum = iv.y_c.asum()
2636                + iv.y_d.asum()
2637                + iv.z_l.asum()
2638                + iv.z_u.asum()
2639                + iv.v_l.asum()
2640                + iv.v_u.asum();
2641            (s_max.max(asum / Number::from(n_d))) / s_max
2642        };
2643
2644        (s_d, s_c)
2645    }
2646
2647    // --------------------------------------------------------------
2648    // Trial-side Lagrangian gradient / complementarity — needed by
2649    // the soft restoration phase's primal-dual error test. Each is a
2650    // line-for-line analog of the `curr_*` method above, reading the
2651    // `trial` iterate instead of `curr`.
2652    // --------------------------------------------------------------
2653
2654    pub fn trial_jac_c(&self) -> Rc<dyn Matrix> {
2655        let iv = self.trial_iv();
2656        self.nlp.borrow_mut().eval_jac_c(&*iv.x)
2657    }
2658
2659    pub fn trial_jac_d(&self) -> Rc<dyn Matrix> {
2660        let iv = self.trial_iv();
2661        self.nlp.borrow_mut().eval_jac_d(&*iv.x)
2662    }
2663
2664    /// `∇_x L` at the trial iterate — analog of [`Self::curr_grad_lag_x`].
2665    pub fn trial_grad_lag_x(&self) -> Rc<dyn Vector> {
2666        let iv = self.trial_iv();
2667        let grad_f = self.trial_grad_f();
2668        let jac_c = self.trial_jac_c();
2669        let jac_d = self.trial_jac_d();
2670
2671        let mut jc_t = iv.x.make_new();
2672        jac_c.trans_mult_vector(1.0, &*iv.y_c, 0.0, &mut *jc_t);
2673        let mut jd_t = iv.x.make_new();
2674        jac_d.trans_mult_vector(1.0, &*iv.y_d, 0.0, &mut *jd_t);
2675
2676        let mut tmp = iv.x.make_new();
2677        tmp.copy(&*grad_f);
2678        tmp.add_two_vectors(1.0, &*jc_t, 1.0, &*jd_t, 1.0);
2679
2680        let nlp = self.nlp.borrow();
2681        nlp.px_l().mult_vector(-1.0, &*iv.z_l, 1.0, &mut *tmp);
2682        nlp.px_u().mult_vector(1.0, &*iv.z_u, 1.0, &mut *tmp);
2683        rc_from(tmp)
2684    }
2685
2686    /// `∇_s L` at the trial iterate — analog of [`Self::curr_grad_lag_s`].
2687    pub fn trial_grad_lag_s(&self) -> Rc<dyn Vector> {
2688        let iv = self.trial_iv();
2689        let mut tmp = iv.y_d.make_new();
2690        let nlp = self.nlp.borrow();
2691        nlp.pd_u().mult_vector(1.0, &*iv.v_u, 0.0, &mut *tmp);
2692        nlp.pd_l().mult_vector(-1.0, &*iv.v_l, 1.0, &mut *tmp);
2693        tmp.axpy(-1.0, &*iv.y_d);
2694        rc_from(tmp)
2695    }
2696
2697    pub fn trial_compl_x_l(&self) -> Rc<dyn Vector> {
2698        Self::calc_compl(&*self.trial_slack_x_l(), &*self.trial_iv().z_l)
2699    }
2700
2701    pub fn trial_compl_x_u(&self) -> Rc<dyn Vector> {
2702        Self::calc_compl(&*self.trial_slack_x_u(), &*self.trial_iv().z_u)
2703    }
2704
2705    pub fn trial_compl_s_l(&self) -> Rc<dyn Vector> {
2706        Self::calc_compl(&*self.trial_slack_s_l(), &*self.trial_iv().v_l)
2707    }
2708
2709    pub fn trial_compl_s_u(&self) -> Rc<dyn Vector> {
2710        Self::calc_compl(&*self.trial_slack_s_u(), &*self.trial_iv().v_u)
2711    }
2712
2713    /// `||s ⊙ z − μ||₁` summed over the four complementarity blocks.
2714    fn relaxed_compl_asum(blocks: &[Rc<dyn Vector>], mu: Number) -> Number {
2715        let mut acc = 0.0;
2716        for compl in blocks {
2717            if compl.dim() == 0 {
2718                continue;
2719            }
2720            let mut r = compl.make_new();
2721            r.copy(&**compl);
2722            r.add_scalar(-mu);
2723            acc += r.asum();
2724        }
2725        acc
2726    }
2727
2728    /// Unscaled primal-dual KKT system error at the current iterate —
2729    /// port of
2730    /// `IpIpoptCalculatedQuantities.cpp:curr_primal_dual_system_error`.
2731    /// Each block uses the 1-norm scaled by its entry count; the result
2732    /// is the sum of the dual-infeasibility, primal-infeasibility, and
2733    /// complementarity terms. Used by the soft restoration phase's
2734    /// sufficient-reduction test.
2735    pub fn curr_primal_dual_system_error(&self, mu: Number) -> Number {
2736        let iv = self.curr_iv();
2737        let n_dual = iv.x.dim() + iv.s.dim();
2738        let dual_inf =
2739            (self.curr_grad_lag_x().asum() + self.curr_grad_lag_s().asum()) / Number::from(n_dual);
2740
2741        let n_primal = iv.y_c.dim() + iv.y_d.dim();
2742        let primal_inf = if n_primal > 0 {
2743            (self.curr_c().asum() + self.curr_d_minus_s().asum()) / Number::from(n_primal)
2744        } else {
2745            0.0
2746        };
2747
2748        let n_cmpl = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2749        let cmpl = if n_cmpl > 0 {
2750            Self::relaxed_compl_asum(
2751                &[
2752                    self.curr_compl_x_l(),
2753                    self.curr_compl_x_u(),
2754                    self.curr_compl_s_l(),
2755                    self.curr_compl_s_u(),
2756                ],
2757                mu,
2758            ) / Number::from(n_cmpl)
2759        } else {
2760            0.0
2761        };
2762
2763        dual_inf + primal_inf + cmpl
2764    }
2765
2766    /// Unscaled primal-dual KKT system error at the trial iterate —
2767    /// trial-side analog of [`Self::curr_primal_dual_system_error`].
2768    pub fn trial_primal_dual_system_error(&self, mu: Number) -> Number {
2769        let iv = self.trial_iv();
2770        let n_dual = iv.x.dim() + iv.s.dim();
2771        let dual_inf = (self.trial_grad_lag_x().asum() + self.trial_grad_lag_s().asum())
2772            / Number::from(n_dual);
2773
2774        let n_primal = iv.y_c.dim() + iv.y_d.dim();
2775        let primal_inf = if n_primal > 0 {
2776            (self.trial_c().asum() + self.trial_d_minus_s().asum()) / Number::from(n_primal)
2777        } else {
2778            0.0
2779        };
2780
2781        let n_cmpl = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2782        let cmpl = if n_cmpl > 0 {
2783            Self::relaxed_compl_asum(
2784                &[
2785                    self.trial_compl_x_l(),
2786                    self.trial_compl_x_u(),
2787                    self.trial_compl_s_l(),
2788                    self.trial_compl_s_u(),
2789                ],
2790                mu,
2791            ) / Number::from(n_cmpl)
2792        } else {
2793            0.0
2794        };
2795
2796        dual_inf + primal_inf + cmpl
2797    }
2798
2799    // --------------------------------------------------------------
2800    // Damping indicators — `IpIpoptCalculatedQuantities.cpp:1044-1092`.
2801    //
2802    //   Tmp_x = P_L · 1 − P_U · 1   (per primal: +1 lower-only,
2803    //                                 −1 upper-only, 0 two-sided,
2804    //                                 0 unbounded)
2805    //   dampind_x_L =  P_L^T · Tmp_x   (1 on lower-only bounds)
2806    //   dampind_x_U = −P_U^T · Tmp_x   (1 on upper-only bounds)
2807    // --------------------------------------------------------------
2808
2809    fn damping_indicators(&self) -> DampingIndicators {
2810        let nlp = self.nlp.borrow();
2811
2812        let mut tmp_x_l = nlp.x_l().make_new();
2813        tmp_x_l.set(1.0);
2814        let mut tmp_x_u = nlp.x_u().make_new();
2815        tmp_x_u.set(1.0);
2816        let mut tmp_x = self.curr_iv().x.make_new();
2817        nlp.px_l().mult_vector(1.0, &*tmp_x_l, 0.0, &mut *tmp_x);
2818        nlp.px_u().mult_vector(-1.0, &*tmp_x_u, 1.0, &mut *tmp_x);
2819        let mut d_x_l = nlp.x_l().make_new();
2820        nlp.px_l().trans_mult_vector(1.0, &*tmp_x, 0.0, &mut *d_x_l);
2821        let mut d_x_u = nlp.x_u().make_new();
2822        nlp.px_u()
2823            .trans_mult_vector(-1.0, &*tmp_x, 0.0, &mut *d_x_u);
2824
2825        let mut tmp_s_l = nlp.d_l().make_new();
2826        tmp_s_l.set(1.0);
2827        let mut tmp_s_u = nlp.d_u().make_new();
2828        tmp_s_u.set(1.0);
2829        let mut tmp_s = self.curr_iv().s.make_new();
2830        nlp.pd_l().mult_vector(1.0, &*tmp_s_l, 0.0, &mut *tmp_s);
2831        nlp.pd_u().mult_vector(-1.0, &*tmp_s_u, 1.0, &mut *tmp_s);
2832        let mut d_s_l = nlp.d_l().make_new();
2833        nlp.pd_l().trans_mult_vector(1.0, &*tmp_s, 0.0, &mut *d_s_l);
2834        let mut d_s_u = nlp.d_u().make_new();
2835        nlp.pd_u()
2836            .trans_mult_vector(-1.0, &*tmp_s, 0.0, &mut *d_s_u);
2837
2838        DampingIndicators {
2839            x_l: rc_from(d_x_l),
2840            x_u: rc_from(d_x_u),
2841            s_l: rc_from(d_s_l),
2842            s_u: rc_from(d_s_u),
2843        }
2844    }
2845
2846    /// `curr_grad_lag_x` plus the `kappa_d · μ · (Px_L · 1 − Px_U · 1)`
2847    /// damping term on singly-bounded primals — port of
2848    /// `IpIpoptCalculatedQuantities.cpp:2131-2180`. When `kappa_d == 0`
2849    /// returns the un-damped gradient.
2850    pub fn curr_grad_lag_with_damping_x(&self) -> Rc<dyn Vector> {
2851        if self.kappa_d == 0.0 {
2852            return self.curr_grad_lag_x();
2853        }
2854        let mu = self.data.borrow().curr_mu;
2855        let di = self.damping_indicators();
2856        let (d_x_l, d_x_u) = (di.x_l, di.x_u);
2857        let glx = self.curr_grad_lag_x();
2858        let mut tmp = glx.make_new();
2859        tmp.copy(&*glx);
2860        let nlp = self.nlp.borrow();
2861        nlp.px_l()
2862            .mult_vector(self.kappa_d * mu, &*d_x_l, 1.0, &mut *tmp);
2863        nlp.px_u()
2864            .mult_vector(-self.kappa_d * mu, &*d_x_u, 1.0, &mut *tmp);
2865        rc_from(tmp)
2866    }
2867
2868    pub fn curr_grad_lag_with_damping_s(&self) -> Rc<dyn Vector> {
2869        if self.kappa_d == 0.0 {
2870            return self.curr_grad_lag_s();
2871        }
2872        let mu = self.data.borrow().curr_mu;
2873        let di = self.damping_indicators();
2874        let (d_s_l, d_s_u) = (di.s_l, di.s_u);
2875        let gls = self.curr_grad_lag_s();
2876        let mut tmp = gls.make_new();
2877        tmp.copy(&*gls);
2878        let nlp = self.nlp.borrow();
2879        nlp.pd_l()
2880            .mult_vector(self.kappa_d * mu, &*d_s_l, 1.0, &mut *tmp);
2881        nlp.pd_u()
2882            .mult_vector(-self.kappa_d * mu, &*d_s_u, 1.0, &mut *tmp);
2883        rc_from(tmp)
2884    }
2885
2886    /// `kappa_d · (P_L · damping_l − P_U · damping_u)` in the full x
2887    /// space — port of `IpIpoptCalculatedQuantities.cpp::grad_kappa_times_damping_x`
2888    /// (lines 912-949). Unlike `curr_grad_lag_with_damping_x` this does
2889    /// NOT include `grad_lag_x` and is NOT scaled by `mu`; the centering
2890    /// RHS in the quality-function oracle multiplies the returned vector
2891    /// by `-avrg_compl` per upstream `IpQualityFunctionMuOracle.cpp:229`.
2892    pub fn grad_kappa_times_damping_x(&self) -> Rc<dyn Vector> {
2893        let mut tmp = self.curr_iv().x.make_new();
2894        tmp.set(0.0);
2895        if self.kappa_d > 0.0 {
2896            let di = self.damping_indicators();
2897            let nlp = self.nlp.borrow();
2898            nlp.px_l()
2899                .mult_vector(self.kappa_d, &*di.x_l, 0.0, &mut *tmp);
2900            nlp.px_u()
2901                .mult_vector(-self.kappa_d, &*di.x_u, 1.0, &mut *tmp);
2902        }
2903        rc_from(tmp)
2904    }
2905
2906    pub fn grad_kappa_times_damping_s(&self) -> Rc<dyn Vector> {
2907        let mut tmp = self.curr_iv().s.make_new();
2908        tmp.set(0.0);
2909        if self.kappa_d > 0.0 {
2910            let di = self.damping_indicators();
2911            let nlp = self.nlp.borrow();
2912            nlp.pd_l()
2913                .mult_vector(self.kappa_d, &*di.s_l, 0.0, &mut *tmp);
2914            nlp.pd_u()
2915                .mult_vector(-self.kappa_d, &*di.s_u, 1.0, &mut *tmp);
2916        }
2917        rc_from(tmp)
2918    }
2919
2920    // --------------------------------------------------------------
2921    // Affine (predictor) step helpers — port of upstream
2922    // `IpIpoptCalculatedQuantities.cpp:CurrAvrgCompl`/`AffMaxAlpha…`
2923    // used by the Mehrotra probing oracle and the quality-function
2924    // oracle's σ-search.
2925    // --------------------------------------------------------------
2926
2927    /// Max primal step that keeps `s + α · Δs > 0` for the four slack
2928    /// blocks (x_L, x_U, s_L, s_U), bounded by the fraction-to-the-
2929    /// boundary parameter `τ ∈ (0, 1]`. Mirrors
2930    /// `CalcFracToBound` against the projected step `P_L^T Δx`,
2931    /// `−P_U^T Δx`, `P_L^T Δs`, `−P_U^T Δs`.
2932    pub fn aff_step_alpha_primal_max(&self, delta_aff: &IteratesVector, tau: Number) -> Number {
2933        let nlp = self.nlp.borrow();
2934        let s_x_l = self.curr_slack_x_l();
2935        let s_x_u = self.curr_slack_x_u();
2936        let s_s_l = self.curr_slack_s_l();
2937        let s_s_u = self.curr_slack_s_u();
2938
2939        // Project Δx / Δs onto each bound subspace with the right sign.
2940        let mut step_x_l = s_x_l.make_new();
2941        nlp.px_l()
2942            .trans_mult_vector(1.0, &*delta_aff.x, 0.0, &mut *step_x_l);
2943        let mut step_x_u = s_x_u.make_new();
2944        nlp.px_u()
2945            .trans_mult_vector(-1.0, &*delta_aff.x, 0.0, &mut *step_x_u);
2946        let mut step_s_l = s_s_l.make_new();
2947        nlp.pd_l()
2948            .trans_mult_vector(1.0, &*delta_aff.s, 0.0, &mut *step_s_l);
2949        let mut step_s_u = s_s_u.make_new();
2950        nlp.pd_u()
2951            .trans_mult_vector(-1.0, &*delta_aff.s, 0.0, &mut *step_s_u);
2952
2953        s_x_l
2954            .frac_to_bound(&*step_x_l, tau)
2955            .min(s_x_u.frac_to_bound(&*step_x_u, tau))
2956            .min(s_s_l.frac_to_bound(&*step_s_l, tau))
2957            .min(s_s_u.frac_to_bound(&*step_s_u, tau))
2958    }
2959
2960    /// Max dual step that keeps `z + α · Δz > 0` (and same for v).
2961    pub fn aff_step_alpha_dual_max(&self, delta_aff: &IteratesVector, tau: Number) -> Number {
2962        let iv = self.curr_iv();
2963        iv.z_l
2964            .frac_to_bound(&*delta_aff.z_l, tau)
2965            .min(iv.z_u.frac_to_bound(&*delta_aff.z_u, tau))
2966            .min(iv.v_l.frac_to_bound(&*delta_aff.v_l, tau))
2967            .min(iv.v_u.frac_to_bound(&*delta_aff.v_u, tau))
2968    }
2969
2970    /// Predicted average complementarity after the affine step:
2971    /// `(1/N) · Σ (s + α_pri · Δs) · (z + α_du · Δz)` summed over the
2972    /// four bound blocks. Returns `0` when there are no bounds.
2973    pub fn aff_step_compl_avrg(
2974        &self,
2975        delta_aff: &IteratesVector,
2976        alpha_primal: Number,
2977        alpha_dual: Number,
2978    ) -> Number {
2979        let iv = self.curr_iv();
2980        let n = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2981        if n == 0 {
2982            return 0.0;
2983        }
2984        let nlp = self.nlp.borrow();
2985
2986        // s_X_L_aff = s_X_L + α_pri · P_L^T Δx
2987        let s_x_l = self.curr_slack_x_l();
2988        let mut s_x_l_aff = s_x_l.make_new();
2989        s_x_l_aff.copy(&*s_x_l);
2990        let mut tmp = s_x_l.make_new();
2991        nlp.px_l()
2992            .trans_mult_vector(1.0, &*delta_aff.x, 0.0, &mut *tmp);
2993        s_x_l_aff.axpy(alpha_primal, &*tmp);
2994        // z_L_aff = z_L + α_du · Δz_L
2995        let mut z_l_aff = iv.z_l.make_new();
2996        z_l_aff.copy(&*iv.z_l);
2997        z_l_aff.axpy(alpha_dual, &*delta_aff.z_l);
2998        let mut acc = s_x_l_aff.dot(&*z_l_aff);
2999
3000        // s_X_U_aff = s_X_U − α_pri · P_U^T Δx
3001        let s_x_u = self.curr_slack_x_u();
3002        let mut s_x_u_aff = s_x_u.make_new();
3003        s_x_u_aff.copy(&*s_x_u);
3004        let mut tmp = s_x_u.make_new();
3005        nlp.px_u()
3006            .trans_mult_vector(-1.0, &*delta_aff.x, 0.0, &mut *tmp);
3007        s_x_u_aff.axpy(alpha_primal, &*tmp);
3008        let mut z_u_aff = iv.z_u.make_new();
3009        z_u_aff.copy(&*iv.z_u);
3010        z_u_aff.axpy(alpha_dual, &*delta_aff.z_u);
3011        acc += s_x_u_aff.dot(&*z_u_aff);
3012
3013        // s_S_L_aff = s_S_L + α_pri · P_dL^T Δs
3014        let s_s_l = self.curr_slack_s_l();
3015        let mut s_s_l_aff = s_s_l.make_new();
3016        s_s_l_aff.copy(&*s_s_l);
3017        let mut tmp = s_s_l.make_new();
3018        nlp.pd_l()
3019            .trans_mult_vector(1.0, &*delta_aff.s, 0.0, &mut *tmp);
3020        s_s_l_aff.axpy(alpha_primal, &*tmp);
3021        let mut v_l_aff = iv.v_l.make_new();
3022        v_l_aff.copy(&*iv.v_l);
3023        v_l_aff.axpy(alpha_dual, &*delta_aff.v_l);
3024        acc += s_s_l_aff.dot(&*v_l_aff);
3025
3026        // s_S_U_aff = s_S_U − α_pri · P_dU^T Δs
3027        let s_s_u = self.curr_slack_s_u();
3028        let mut s_s_u_aff = s_s_u.make_new();
3029        s_s_u_aff.copy(&*s_s_u);
3030        let mut tmp = s_s_u.make_new();
3031        nlp.pd_u()
3032            .trans_mult_vector(-1.0, &*delta_aff.s, 0.0, &mut *tmp);
3033        s_s_u_aff.axpy(alpha_primal, &*tmp);
3034        let mut v_u_aff = iv.v_u.make_new();
3035        v_u_aff.copy(&*iv.v_u);
3036        v_u_aff.axpy(alpha_dual, &*delta_aff.v_u);
3037        acc += s_s_u_aff.dot(&*v_u_aff);
3038
3039        acc / Number::from(n)
3040    }
3041}
3042
3043/// Convenience handle. Mirrors upstream's `SmartPtr<CQ>` flow.
3044pub type IpoptCqHandle = Rc<RefCell<IpoptCalculatedQuantities>>;
3045
3046/// Bundle of damping indicators for the four bound spaces — kept
3047/// internal because `kappa_d == 0` makes them dead in the default
3048/// configuration.
3049struct DampingIndicators {
3050    x_l: Rc<dyn Vector>,
3051    x_u: Rc<dyn Vector>,
3052    s_l: Rc<dyn Vector>,
3053    s_u: Rc<dyn Vector>,
3054}
3055
3056#[cfg(test)]
3057mod tests {
3058    use super::*;
3059    use crate::ipopt_data::IpoptData;
3060    use crate::iterates_vector::IteratesVector;
3061    use pounce_common::types::Index;
3062    use pounce_linalg::dense_vector::{DenseVector, DenseVectorSpace};
3063    use pounce_linalg::expansion_matrix::{ExpansionMatrix, ExpansionMatrixSpace};
3064    use pounce_linalg::triplet::{GenTMatrix, GenTMatrixSpace};
3065    use std::rc::Rc as StdRc;
3066
3067    fn dvec(values: &[Number]) -> DenseVector {
3068        let space = DenseVectorSpace::new(values.len() as Index);
3069        let mut v = space.make_new_dense();
3070        v.values_mut().copy_from_slice(values);
3071        v
3072    }
3073
3074    fn rcv(values: &[Number]) -> Rc<dyn Vector> {
3075        StdRc::new(dvec(values))
3076    }
3077
3078    /// Mock IpoptNlp covering: 2 vars, 1 equality, 1 inequality.
3079    /// Bounds: x[0] ≥ 0, x[1] ≤ 5, d ≥ 1.
3080    /// f(x) = x[0]^2 + x[1]^2; ∇f = (2x[0], 2x[1])
3081    /// c(x) = x[0] + x[1] - 1
3082    /// d(x) = x[0]
3083    struct MockNlp {
3084        x_l: DenseVector,
3085        x_u: DenseVector,
3086        d_l: DenseVector,
3087        d_u: DenseVector,
3088        px_l: Rc<dyn Matrix>,
3089        px_u: Rc<dyn Matrix>,
3090        pd_l: Rc<dyn Matrix>,
3091        pd_u: Rc<dyn Matrix>,
3092        // NLP scaling factors. Identity by default; `with_scaling`
3093        // installs non-trivial ones to exercise the unscaled accessors.
3094        // (The mock does not actually apply these in `eval_*`; the tests
3095        // verify the unscaling *arithmetic*, not end-to-end scaling.)
3096        obj_scale: Number,
3097        c_scale: Option<Vec<Number>>,
3098        d_scale: Option<Vec<Number>>,
3099        // #292: inject a non-finite component into the gradient / constraint
3100        // Jacobian to exercise the finiteness guard in `curr_nlp_error`.
3101        nan_grad: bool,
3102        nan_jac_c: bool,
3103        empty_jac_c: bool,
3104        // gh#390: the declared equality RHS the c-block relative measure
3105        // divides by. `None` (the default) is the "not tracked" contract.
3106        c_rhs: Option<Vec<Number>>,
3107        // pounce#476: force `c(x)` to a fixed value so a test can isolate the
3108        // inequality block (the default `x0 + x1 - 1` is 4 at the fixture's
3109        // point, which dominates any d-block difference under a max-norm).
3110        c_override: Option<Number>,
3111        // gh#812: stand in for `RestoNlp`, whose objective carries the
3112        // proximity term `ζ/2·‖D_R(x − x_R)‖²` and therefore has a `∇f`
3113        // that moves with the barrier parameter at fixed `x`. When set,
3114        // `eval_grad_f` adds `curr_mu` read from this handle — the same
3115        // coupling, in one line.
3116        mu_source: Option<IpoptDataHandle>,
3117    }
3118
3119    impl MockNlp {
3120        fn with_c(mut self, v: Number) -> Self {
3121            self.c_override = Some(v);
3122            self
3123        }
3124
3125        fn with_c_rhs(mut self, rhs: Option<Vec<Number>>) -> Self {
3126            self.c_rhs = rhs;
3127            self
3128        }
3129
3130        fn with_nan_grad(mut self) -> Self {
3131            self.nan_grad = true;
3132            self
3133        }
3134
3135        fn with_nan_jac_c(mut self) -> Self {
3136            self.nan_jac_c = true;
3137            self
3138        }
3139
3140        /// Every variable of the equality row fixed and substituted out, so
3141        /// the row reduces to the constant `0 = b` — what
3142        /// `IpoptCalculatedQuantities::row_noise_floor` calls a row no iterate
3143        /// can move.
3144        fn with_empty_jac_c(mut self) -> Self {
3145            self.empty_jac_c = true;
3146            self
3147        }
3148
3149        /// Re-declare the single `d` row as the box `[−mag, +mag]`, so every
3150        /// bound it has is of the chosen magnitude — the default fixture's
3151        /// lower bound of `1` would otherwise supply the magnitude by itself.
3152        /// `d(x) = x0 = 2` sits outside it, violating by `2 − mag`.
3153        fn with_d_box(mut self, mag: Number) -> Self {
3154            self.d_l = dvec(&[-mag]);
3155            self.d_u = dvec(&[mag]);
3156            self.pd_u = StdRc::new(ExpansionMatrix::new(ExpansionMatrixSpace::new(
3157                1,
3158                1,
3159                &[0],
3160                0,
3161            )));
3162            self
3163        }
3164
3165        fn with_scaling(
3166            mut self,
3167            obj_scale: Number,
3168            c_scale: Option<Vec<Number>>,
3169            d_scale: Option<Vec<Number>>,
3170        ) -> Self {
3171            self.obj_scale = obj_scale;
3172            self.c_scale = c_scale;
3173            self.d_scale = d_scale;
3174            self
3175        }
3176
3177        fn new() -> Self {
3178            // x_L holds finite lower bounds; here only x[0] has one (=0).
3179            let x_l = dvec(&[0.0]);
3180            // x_U holds finite upper bounds; here only x[1] has one (=5).
3181            let x_u = dvec(&[5.0]);
3182            // d has one finite lower bound (d ≥ 1) and no finite upper.
3183            let d_l = dvec(&[1.0]);
3184            let d_u = dvec(&[]);
3185
3186            let px_l_space = ExpansionMatrixSpace::new(2, 1, &[0], 0);
3187            let px_u_space = ExpansionMatrixSpace::new(2, 1, &[1], 0);
3188            let pd_l_space = ExpansionMatrixSpace::new(1, 1, &[0], 0);
3189            let pd_u_space = ExpansionMatrixSpace::new(1, 0, &[], 0);
3190
3191            Self {
3192                x_l,
3193                x_u,
3194                d_l,
3195                d_u,
3196                px_l: StdRc::new(ExpansionMatrix::new(px_l_space)),
3197                px_u: StdRc::new(ExpansionMatrix::new(px_u_space)),
3198                pd_l: StdRc::new(ExpansionMatrix::new(pd_l_space)),
3199                pd_u: StdRc::new(ExpansionMatrix::new(pd_u_space)),
3200                obj_scale: 1.0,
3201                c_scale: None,
3202                d_scale: None,
3203                nan_grad: false,
3204                nan_jac_c: false,
3205                empty_jac_c: false,
3206                c_rhs: None,
3207                c_override: None,
3208                mu_source: None,
3209            }
3210        }
3211    }
3212
3213    impl crate::ipopt_nlp::Nlp for MockNlp {
3214        fn n(&self) -> Index {
3215            2
3216        }
3217        fn m_eq(&self) -> Index {
3218            1
3219        }
3220        fn m_ineq(&self) -> Index {
3221            1
3222        }
3223        fn eval_f(&mut self, x: &dyn Vector) -> Number {
3224            // f(x) = x[0]^2 + x[1]^2
3225            let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
3226            xx.values()[0] * xx.values()[0] + xx.values()[1] * xx.values()[1]
3227        }
3228        fn eval_grad_f(&mut self, x: &dyn Vector, g: &mut dyn Vector) {
3229            // grad f = (2 x[0], 2 x[1])
3230            let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
3231            let gg = g.as_any_mut().downcast_mut::<DenseVector>().unwrap();
3232            gg.values_mut()[0] = 2.0 * xx.values()[0];
3233            gg.values_mut()[1] = 2.0 * xx.values()[1];
3234            if let Some(d) = self.mu_source.as_ref() {
3235                let mu = d.borrow().curr_mu;
3236                gg.values_mut()[0] += mu;
3237                gg.values_mut()[1] += mu;
3238            }
3239            if self.nan_grad {
3240                gg.values_mut()[0] = Number::NAN;
3241            }
3242        }
3243        fn eval_c(&mut self, x: &dyn Vector, c: &mut dyn Vector) {
3244            let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
3245            let cc = c.as_any_mut().downcast_mut::<DenseVector>().unwrap();
3246            cc.values_mut()[0] = match self.c_override {
3247                Some(v) => v,
3248                None => xx.values()[0] + xx.values()[1] - 1.0,
3249            };
3250        }
3251        fn eval_d(&mut self, x: &dyn Vector, d: &mut dyn Vector) {
3252            let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
3253            let dd = d.as_any_mut().downcast_mut::<DenseVector>().unwrap();
3254            dd.values_mut()[0] = xx.values()[0];
3255        }
3256        fn eval_jac_c(&mut self, _x: &dyn Vector) -> Rc<dyn Matrix> {
3257            if self.empty_jac_c {
3258                // No entries at all: the row carries no variable.
3259                let space = GenTMatrixSpace::new(1, 2, vec![], vec![]);
3260                let mut jac = GenTMatrix::new(space);
3261                jac.set_values(&[]);
3262                return StdRc::new(jac);
3263            }
3264            // c(x) = x0 + x1 - 1 → Jc = [1, 1] (1×2), nonzeros (1,1),(1,2).
3265            let space = GenTMatrixSpace::new(1, 2, vec![1, 1], vec![1, 2]);
3266            let mut jac = GenTMatrix::new(space);
3267            if self.nan_jac_c {
3268                jac.set_values(&[Number::NAN, 1.0]);
3269            } else {
3270                jac.set_values(&[1.0, 1.0]);
3271            }
3272            StdRc::new(jac)
3273        }
3274        fn eval_jac_d(&mut self, _x: &dyn Vector) -> Rc<dyn Matrix> {
3275            // d(x) = x0 → Jd = [1, 0] (1×2), single nonzero (1,1).
3276            let space = GenTMatrixSpace::new(1, 2, vec![1], vec![1]);
3277            let mut jac = GenTMatrix::new(space);
3278            jac.set_values(&[1.0]);
3279            StdRc::new(jac)
3280        }
3281        fn eval_h(
3282            &mut self,
3283            _x: &dyn Vector,
3284            _obj_factor: Number,
3285            _y_c: &dyn Vector,
3286            _y_d: &dyn Vector,
3287        ) -> Rc<dyn SymMatrix> {
3288            unimplemented!()
3289        }
3290    }
3291
3292    impl IpoptNlp for MockNlp {
3293        fn x_l(&self) -> &dyn Vector {
3294            &self.x_l
3295        }
3296        fn x_u(&self) -> &dyn Vector {
3297            &self.x_u
3298        }
3299        fn d_l(&self) -> &dyn Vector {
3300            &self.d_l
3301        }
3302        fn d_u(&self) -> &dyn Vector {
3303            &self.d_u
3304        }
3305        fn px_l(&self) -> Rc<dyn Matrix> {
3306            self.px_l.clone()
3307        }
3308        fn px_u(&self) -> Rc<dyn Matrix> {
3309            self.px_u.clone()
3310        }
3311        fn pd_l(&self) -> Rc<dyn Matrix> {
3312            self.pd_l.clone()
3313        }
3314        fn pd_u(&self) -> Rc<dyn Matrix> {
3315            self.pd_u.clone()
3316        }
3317        fn obj_scaling_factor(&self) -> Number {
3318            self.obj_scale
3319        }
3320        fn c_scale_vec(&self) -> Option<Vec<Number>> {
3321            self.c_scale.clone()
3322        }
3323        fn d_scale_vec(&self) -> Option<Vec<Number>> {
3324            self.d_scale.clone()
3325        }
3326        fn declared_c_rhs(&self) -> Option<Vec<Number>> {
3327            self.c_rhs.clone()
3328        }
3329    }
3330
3331    fn fixture() -> IpoptCalculatedQuantities {
3332        fixture_with(MockNlp::new())
3333    }
3334
3335    fn fixture_with(nlp: MockNlp) -> IpoptCalculatedQuantities {
3336        fixture_with_x(nlp, &[2.0, 3.0])
3337    }
3338
3339    fn fixture_with_x(nlp: MockNlp, x: &[Number]) -> IpoptCalculatedQuantities {
3340        let mut data = IpoptData::new();
3341        data.curr_mu = 0.1;
3342        // Iterate: x as given (2, 3 by default); s = (4); y_c = (1); y_d = (1);
3343        // z_L = (0.5) [bound on x[0]], z_U = (0.7) [bound on x[1]],
3344        // v_L = (0.3), v_U = ().
3345        let iv = IteratesVector::new(
3346            rcv(x),
3347            rcv(&[4.0]),
3348            rcv(&[1.0]),
3349            rcv(&[1.0]),
3350            rcv(&[0.5]),
3351            rcv(&[0.7]),
3352            rcv(&[0.3]),
3353            rcv(&[]),
3354        );
3355        data.set_curr(iv);
3356        let data_handle = StdRc::new(RefCell::new(data));
3357        let nlp: StdRc<RefCell<dyn IpoptNlp>> = StdRc::new(RefCell::new(nlp));
3358        let mut cq = IpoptCalculatedQuantities::new(data_handle, nlp);
3359        // Disable damping for clean unit-test expectations.
3360        cq.kappa_d = 0.0;
3361        cq
3362    }
3363
3364    /// gh#812 — `mu` is part of the `curr_grad_lag_x` cache key, and
3365    /// removing it is a silent trajectory regression.
3366    ///
3367    /// The five vector tags upstream keys this cache on (`x`, `y_c`,
3368    /// `y_d`, `z_L`, `z_U`) are a complete dependency set only while
3369    /// `∇f` is a function of `x` alone. It is not during restoration:
3370    /// `RestoNlp`'s proximity term scales with `ζ(mu)`, so its `∇f`
3371    /// moves while every one of those five tags stands still. A cache
3372    /// that misses `mu` then hands back the pre-update gradient — an
3373    /// answer that is self-consistent, converges, and reports the
3374    /// right objective, while taking a measurably worse route: drop
3375    /// `mu` from the key and `scripts/sweep-fixtures.sh` moves 8 of
3376    /// 154 fixture-legs, `pooling_rt2stp` 295 → 627 iterations on the
3377    /// lbfgs leg.
3378    ///
3379    /// MUTATION CHECK: delete `&[mu]` from the `get`/`add` pair in
3380    /// `curr_grad_lag_x` and this test fails — the second read returns
3381    /// the first read's vector unchanged.
3382    #[test]
3383    fn grad_lag_x_cache_reruns_when_only_mu_moves() {
3384        let mut data = IpoptData::new();
3385        data.curr_mu = 0.1;
3386        data.set_curr(IteratesVector::new(
3387            rcv(&[2.0, 3.0]),
3388            rcv(&[4.0]),
3389            rcv(&[1.0]),
3390            rcv(&[1.0]),
3391            rcv(&[0.5]),
3392            rcv(&[0.7]),
3393            rcv(&[0.3]),
3394            rcv(&[]),
3395        ));
3396        let data_handle = StdRc::new(RefCell::new(data));
3397        let mut nlp = MockNlp::new();
3398        nlp.mu_source = Some(StdRc::clone(&data_handle));
3399        let nlp: StdRc<RefCell<dyn IpoptNlp>> = StdRc::new(RefCell::new(nlp));
3400        let mut cq = IpoptCalculatedQuantities::new(StdRc::clone(&data_handle), nlp);
3401        cq.kappa_d = 0.0;
3402
3403        let before = dense_vals(&cq.curr_grad_lag_x());
3404        // A repeat read at unchanged `mu` must hit the cache and agree
3405        // exactly — otherwise the test below proves nothing about the
3406        // key and everything about a non-deterministic mock.
3407        assert_eq!(before, dense_vals(&cq.curr_grad_lag_x()));
3408
3409        // Move ONLY `mu`. Every iterate vector — and so every one of
3410        // the five tags upstream keys on — is untouched.
3411        data_handle.borrow_mut().curr_mu = 0.5;
3412        let after = dense_vals(&cq.curr_grad_lag_x());
3413
3414        // The mock adds `mu` to both gradient components, so the whole
3415        // Lagrangian gradient shifts by exactly the change in `mu`.
3416        assert_eq!(before.len(), after.len());
3417        for (b, a) in before.iter().zip(after.iter()) {
3418            assert!(
3419                (a - b - 0.4).abs() < 1e-12,
3420                "grad_lag_x did not follow mu: {b} -> {a}, expected +0.4"
3421            );
3422        }
3423    }
3424
3425    fn dense_vals(v: &Rc<dyn Vector>) -> Vec<Number> {
3426        v.as_any()
3427            .downcast_ref::<DenseVector>()
3428            .unwrap()
3429            .values()
3430            .to_vec()
3431    }
3432
3433    #[test]
3434    fn slack_x_lower_is_x0_minus_x_l() {
3435        // P_L^T x = [x[0]] = [2]; x_L = [0]; slack = 2 - 0 = 2.
3436        let cq = fixture();
3437        assert_eq!(dense_vals(&cq.curr_slack_x_l()), vec![2.0]);
3438    }
3439
3440    #[test]
3441    fn slack_x_upper_is_x_u_minus_x1() {
3442        // x_U = [5]; P_U^T x = [3]; slack = 5 - 3 = 2.
3443        let cq = fixture();
3444        assert_eq!(dense_vals(&cq.curr_slack_x_u()), vec![2.0]);
3445    }
3446
3447    #[test]
3448    fn slack_s_lower() {
3449        // d_L = [1]; P_L^T s = [4]; slack = 4 - 1 = 3.
3450        let cq = fixture();
3451        assert_eq!(dense_vals(&cq.curr_slack_s_l()), vec![3.0]);
3452    }
3453
3454    #[test]
3455    fn grad_f_is_twice_x() {
3456        let cq = fixture();
3457        assert_eq!(dense_vals(&cq.curr_grad_f()), vec![4.0, 6.0]);
3458    }
3459
3460    #[test]
3461    fn compl_x_l_is_slack_times_z() {
3462        // slack_x_L = [2]; z_L = [0.5]; compl = [1.0]
3463        let cq = fixture();
3464        assert_eq!(dense_vals(&cq.curr_compl_x_l()), vec![1.0]);
3465    }
3466
3467    #[test]
3468    fn relaxed_compl_x_l_subtracts_mu() {
3469        // compl = 1.0; mu = 0.1; relaxed = 0.9.
3470        let cq = fixture();
3471        assert!((dense_vals(&cq.curr_relaxed_compl_x_l())[0] - 0.9).abs() < 1e-15);
3472    }
3473
3474    #[test]
3475    fn sigma_x_routes_z_over_slack_through_p() {
3476        // P_L lifts (z_L/s_L) = (0.5/2 = 0.25) into x[0] slot.
3477        // P_U lifts (z_U/s_U) = (0.7/2 = 0.35) into x[1] slot.
3478        // sigma = (0.25, 0.35)
3479        let cq = fixture();
3480        let s = dense_vals(&cq.curr_sigma_x());
3481        assert!((s[0] - 0.25).abs() < 1e-15);
3482        assert!((s[1] - 0.35).abs() < 1e-15);
3483    }
3484
3485    /// gh#655 fixture. `x_L[0] = 0`, so the lower-bound block of `x` carries
3486    /// slack `x0` against multiplier `z_l`, at barrier parameter `mu`. The
3487    /// rest of the iterate is the default fixture's.
3488    fn fixture_at_mu(x0: Number, z_l: Number, mu: Number) -> IpoptCalculatedQuantities {
3489        let mut data = IpoptData::new();
3490        data.curr_mu = mu;
3491        let iv = IteratesVector::new(
3492            rcv(&[x0, 3.0]),
3493            rcv(&[4.0]),
3494            rcv(&[1.0]),
3495            rcv(&[1.0]),
3496            rcv(&[z_l]),
3497            rcv(&[0.7]),
3498            rcv(&[0.3]),
3499            rcv(&[]),
3500        );
3501        data.set_curr(iv);
3502        let data_handle = StdRc::new(RefCell::new(data));
3503        let nlp: StdRc<RefCell<dyn IpoptNlp>> = StdRc::new(RefCell::new(MockNlp::new()));
3504        let mut cq = IpoptCalculatedQuantities::new(data_handle, nlp);
3505        cq.kappa_d = 0.0;
3506        cq
3507    }
3508
3509    /// gh#655. The reported point, verbatim: `mu = 9.0909e-308`, a subnormal
3510    /// slack of `2.0202e-308` against `z = 4.5`, reached under a
3511    /// `SolveSucceeded`. The old floor never even fired here — `eps*mu` is
3512    /// `2.0e-323`, still a representable subnormal rather than the `0` that
3513    /// would have substituted `f64::MIN_POSITIVE`, so the slack cleared the
3514    /// threshold untouched and `4.5 / 2.0202e-308 = 2.2e308` overflowed.
3515    #[test]
3516    fn subnormal_slack_does_not_overflow_sigma() {
3517        let mu: Number = 9.0909e-308;
3518        let slack: Number = 2.0202e-308;
3519        let z: Number = 4.5;
3520        // The premise: the barrier-side threshold does not catch this point.
3521        assert!(f64::EPSILON * mu.min(1.0) > 0.0);
3522        assert!(slack > f64::EPSILON * mu.min(1.0));
3523        assert!(!(z / slack).is_finite());
3524
3525        let cq = fixture_at_mu(slack, z, mu);
3526        let s = dense_vals(&cq.curr_sigma_x());
3527        assert!(s[0].is_finite(), "Sigma_x[0] = {} is not finite", s[0]);
3528        // Floored at z/(MAX/4), so the ratio lands at MAX/4 at worst.
3529        assert!(s[0] <= f64::MAX / SIGMA_OVERFLOW_HEADROOM);
3530        // The slack itself was raised to the floor, not to f64::MIN_POSITIVE.
3531        assert!(dense_vals(&cq.curr_slack_x_l())[0] >= z / f64::MAX);
3532        // The untouched upper block still reads (5 - 3) against z_U = 0.7.
3533        assert!((s[1] - 0.35).abs() < 1e-15);
3534    }
3535
3536    /// gh#655, the half the trigger alone does not cover: a multiplier large
3537    /// enough that the bound-move cap (`slack_move*max(1,|bound|) + slack`)
3538    /// sits *below* the representability floor. Capping there would hand back
3539    /// a slack that still overflows, so the floor is re-applied after the cap.
3540    #[test]
3541    fn representability_floor_survives_the_bound_move_cap() {
3542        let cq = fixture_at_mu(1e-300, 1e300, 1e-8);
3543        // Premise: the cap really is the binding constraint here.
3544        assert!(cq.slack_move * 1.0 + 1e-300 < 1e300 / (f64::MAX / SIGMA_OVERFLOW_HEADROOM));
3545        let s = dense_vals(&cq.curr_sigma_x());
3546        assert!(s[0].is_finite(), "Sigma_x[0] = {} is not finite", s[0]);
3547        assert!(s[0] <= f64::MAX / SIGMA_OVERFLOW_HEADROOM);
3548    }
3549
3550    /// The floor is `z_max/4.5e307`; a slack twelve orders of magnitude above
3551    /// anything subnormal is nowhere near it, and must come back bit-identical
3552    /// — the correction is meant to be invisible off the overflow edge.
3553    #[test]
3554    fn ordinary_small_slack_is_left_exactly_alone() {
3555        let cq = fixture_at_mu(1e-20, 0.5, 1e-8);
3556        assert_eq!(dense_vals(&cq.curr_slack_x_l()), vec![1e-20]);
3557        assert_eq!(dense_vals(&cq.curr_sigma_x())[0], 0.5 / 1e-20);
3558    }
3559
3560    #[test]
3561    fn sigma_s_lower_only() {
3562        // P_L lifts (v_L/s_L) = (0.3/3 = 0.1).
3563        let cq = fixture();
3564        let s = dense_vals(&cq.curr_sigma_s());
3565        assert!((s[0] - 0.1).abs() < 1e-15);
3566    }
3567
3568    #[test]
3569    fn avrg_compl_averages_over_active_bounds() {
3570        // z_L·s_L + z_U·s_U + v_L·s_s_L + v_U·s_s_U
3571        // = 0.5*2 + 0.7*2 + 0.3*3 + 0
3572        // = 1 + 1.4 + 0.9 = 3.3
3573        // N = 1 + 1 + 1 + 0 = 3 → 1.1
3574        let cq = fixture();
3575        assert!((cq.curr_avrg_compl() - 1.1).abs() < 1e-15);
3576    }
3577
3578    #[test]
3579    fn complementarity_min_takes_min_over_active_pairs() {
3580        // compl entries: z_L·s_L=1.0, z_U·s_U=1.4, v_L·s_s_L=0.9.
3581        // v_U is empty (skipped). Min = 0.9.
3582        let cq = fixture();
3583        assert!((cq.curr_complementarity_min() - 0.9).abs() < 1e-15);
3584    }
3585
3586    #[test]
3587    fn centrality_measure_is_min_over_avrg() {
3588        // min/avrg = 0.9 / 1.1 ≈ 0.81818…
3589        let cq = fixture();
3590        let xi = cq.curr_centrality_measure();
3591        assert!((xi - 0.9 / 1.1).abs() < 1e-15);
3592    }
3593
3594    #[test]
3595    fn curr_f_evaluates_objective() {
3596        // f(x) = x[0]^2 + x[1]^2 at x = (2, 3) → 4 + 9 = 13.
3597        let cq = fixture();
3598        assert!((cq.curr_f() - 13.0).abs() < 1e-15);
3599    }
3600
3601    #[test]
3602    fn curr_barrier_obj_subtracts_mu_log_slacks() {
3603        // f = 13; slacks = (s_x_L=2, s_x_U=2, s_s_L=3, s_s_U=∅).
3604        // log_sum = ln 2 + ln 2 + ln 3 + 0 = 2 ln 2 + ln 3.
3605        // mu = 0.1 → phi = 13 - 0.1*(2 ln 2 + ln 3).
3606        let cq = fixture();
3607        let expected = 13.0 - 0.1 * (2.0 * 2.0_f64.ln() + 3.0_f64.ln());
3608        assert!((cq.curr_barrier_obj() - expected).abs() < 1e-13);
3609    }
3610
3611    /// pounce#476. `inf_pr_output = original` (upstream's default) must report
3612    /// the violation of the **original** rows, not of the internal slack
3613    /// reformulation. The fixture is exactly the case that made the two
3614    /// diverge on Mittelmann's `robot_a`: `d(x) = 2` against `d >= 1` — the
3615    /// original row is *satisfied*, so the original-NLP violation is 0 — while
3616    /// the slack has drifted to `s = 4`, so `|d − s| = 2` and the internal
3617    /// measure reads 2. Reporting the internal number made feasible iterates
3618    /// look badly infeasible (2.79e4 where Ipopt printed 0.00e+00).
3619    ///
3620    /// The equality row is genuinely violated (`c = 4`), and both measures
3621    /// must still see it — the fix must not swallow real infeasibility.
3622    #[test]
3623    fn original_nlp_violation_ignores_slack_drift_but_not_a_violated_row() {
3624        let cq = fixture();
3625        // Internal: max(|c|, |d − s|) = max(4, 2) = 4.
3626        assert_eq!(cq.curr_primal_infeasibility_max(), 4.0);
3627        // Original: max(|c|, dist(d, [d_l, d_u])) = max(4, 0) = 4 — the
3628        // equality violation survives, the slack drift does not contribute.
3629        assert_eq!(cq.curr_unscaled_nlp_constraint_violation_max(), 4.0);
3630    }
3631
3632    /// The other half of pounce#476: with the equality block satisfied, the
3633    /// two measures disagree outright — internal still sees the slack drift,
3634    /// original sees a feasible point.
3635    #[test]
3636    fn original_nlp_violation_is_zero_when_only_the_slack_has_drifted() {
3637        let cq = fixture_with(MockNlp::new().with_c(0.0));
3638        assert_eq!(cq.curr_primal_infeasibility_max(), 2.0);
3639        assert_eq!(cq.curr_unscaled_nlp_constraint_violation_max(), 0.0);
3640    }
3641
3642    /// …and the `inf_pr` column must actually be *wired* to the right one.
3643    /// The two tests above pass whichever accessor `OrigIterationOutput`
3644    /// picks, so without this the exact regression — a one-line match arm
3645    /// reaching for `curr_primal_infeasibility_max` — goes unnoticed.
3646    /// `InfPrTag::Original` is upstream's default, so this is what the column
3647    /// prints unless the user asks for `internal`.
3648    #[test]
3649    fn inf_pr_column_prints_the_original_violation_under_the_default_tag() {
3650        use crate::ipopt_data::IpoptData;
3651        use crate::output::orig::{InfPrTag, OrigIterationOutput};
3652        use crate::output::r#trait::IterationOutput;
3653
3654        // Slack drift only: internal reads 2, original reads 0.
3655        let cq: IpoptCqHandle = Rc::new(RefCell::new(fixture_with(MockNlp::new().with_c(0.0))));
3656        let data: IpoptDataHandle = Rc::new(RefCell::new(IpoptData::default()));
3657
3658        let field = |tag| {
3659            let mut out = OrigIterationOutput::new();
3660            out.inf_pr_output = tag;
3661            // Column 2 of the row is `inf_pr` (iter, objective, inf_pr, …).
3662            out.format_row(&data, &cq)
3663                .split_whitespace()
3664                .nth(2)
3665                .unwrap()
3666                .to_string()
3667        };
3668        assert_eq!(field(InfPrTag::Original), "0.00e+00");
3669        assert_eq!(field(InfPrTag::Internal), "2.00e+00");
3670    }
3671
3672    #[test]
3673    fn curr_constraint_violation_is_one_norm() {
3674        // c(x) = x[0]+x[1]-1 = 4 ⇒ |c| = 4.
3675        // d(x)=x[0]=2; s=4 ⇒ d-s = -2 ⇒ |d-s| = 2.
3676        // theta = 4 + 2 = 6.
3677        let cq = fixture();
3678        assert!((cq.curr_constraint_violation() - 6.0).abs() < 1e-13);
3679    }
3680
3681    /// gh#390. The fixture's equality row is `x0 + x1 == 1` at `x = (2, 3)`,
3682    /// so `c = 4`. Judged against a declared RHS of 2 that is a 200% violation
3683    /// — and it is 200% however the row is written, which is the point.
3684    #[test]
3685    fn relative_c_infeasibility_is_residual_over_declared_rhs() {
3686        let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![2.0])));
3687        assert_eq!(cq.relative_c_infeasibility_max(), 2.0);
3688        // The fixture's inequality row (`d = 2` against `d >= 1`) is satisfied,
3689        // so the combined measure is the equality block's verdict.
3690        assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
3691        assert_eq!(cq.curr_relative_primal_infeasibility_max(), 2.0);
3692    }
3693
3694    /// An NLP that does not track the pre-fold RHS (the trait default, e.g.
3695    /// the restoration NLP) must abstain rather than invent a magnitude.
3696    #[test]
3697    fn relative_c_infeasibility_abstains_without_declared_rhs() {
3698        let cq = fixture();
3699        assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3700        assert_eq!(cq.curr_relative_primal_infeasibility_max(), 0.0);
3701    }
3702
3703    /// A homogeneous row (`g(x) == 0`) has no declared magnitude and needs
3704    /// none — `s·g(x) == 0` is the same row at every `s`. Dividing by its zero
3705    /// RHS would report every float-noise residual as an infinite violation.
3706    #[test]
3707    fn relative_c_infeasibility_abstains_on_homogeneous_row() {
3708        let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![0.0])));
3709        assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3710    }
3711
3712    /// An unjudgeable row must not fabricate a relative verdict.
3713    #[test]
3714    fn relative_c_infeasibility_abstains_on_non_finite_rhs() {
3715        let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::INFINITY])));
3716        assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3717        let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::NAN])));
3718        assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3719    }
3720
3721    /// gh #446. "Homogeneous" has to be judged numerically. The fixture's row
3722    /// is `x0 + x1 == b` at `x = (2, 3)`, so its noise floor is
3723    /// `ROW_NOISE_KAPPA · eps · 1 · 3 ≈ 4.3e-14`: an RHS under that is
3724    /// rounding residue — a converter writing `2^-53` where the model says
3725    /// `0` — and the row must abstain exactly as a declared zero does. Above
3726    /// the floor the RHS is real data and is judged, however small.
3727    #[test]
3728    fn relative_c_infeasibility_abstains_on_rhs_below_the_row_noise_floor() {
3729        let floor = ROW_NOISE_KAPPA * Number::EPSILON * 3.0;
3730        // The QSCSD1 value: an RHS of exactly one machine epsilon.
3731        let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::EPSILON])));
3732        assert!(Number::EPSILON < floor);
3733        assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3734        // Just above the floor the row still carries a magnitude, and a
3735        // residual of 4 against it is judged on its merits.
3736        let rhs = 2.0 * floor;
3737        let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![rhs])));
3738        assert_eq!(cq.relative_c_infeasibility_max(), 4.0 / rhs);
3739    }
3740
3741    /// gh #446. Every variable of the row fixed and substituted out leaves
3742    /// `0 = b`, which no iterate can move — a statement about the model, for
3743    /// presolve to certify, not a residual to judge an iterate by. QPILOTNO's
3744    /// row 150 reduces to `0 = −2.22e-16` this way and pinned the relative
3745    /// measure at 100% for the entire run.
3746    #[test]
3747    fn relative_c_infeasibility_abstains_on_a_row_no_iterate_can_move() {
3748        let cq = fixture_with(
3749            MockNlp::new()
3750                .with_empty_jac_c()
3751                .with_c_rhs(Some(vec![Number::EPSILON])),
3752        );
3753        assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3754        // Not a licence to ignore a real one: the absolute `constr_viol_tol`
3755        // arm still sees the row, and it is what governs here.
3756        assert_eq!(cq.curr_primal_infeasibility_max(), 4.0);
3757    }
3758
3759    /// gh #446. The inequality block draws its magnitude from the declared
3760    /// bounds, and needs the same numeric reading of "zero" — QPILOTNO carries
3761    /// 43 bounds at `1e-17`–`1e-15`. `d(x) = x0 = 2` against an upper bound
3762    /// under the row's noise floor is 2e14 times its magnitude by the old
3763    /// arithmetic, and unjudgeable by the new.
3764    #[test]
3765    fn relative_d_infeasibility_abstains_on_bound_below_the_row_noise_floor() {
3766        let floor = ROW_NOISE_KAPPA * Number::EPSILON * 3.0;
3767        let cq = fixture_with(MockNlp::new().with_d_box(Number::EPSILON));
3768        assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
3769        // A bound above the floor is real, and `d = 2` violates it hugely.
3770        let bound = 2.0 * floor;
3771        let cq = fixture_with(MockNlp::new().with_d_box(bound));
3772        assert_eq!(cq.relative_d_infeasibility_max(), (2.0 - bound) / bound);
3773    }
3774
3775    /// The floor tracks `‖x‖_∞` **deliberately**, and this pins it. `x` is one
3776    /// vector produced by a linear solve with norm-wise backward error, so a
3777    /// large variable anywhere really does coarsen how finely every other
3778    /// component can be placed — and a declared magnitude finer than that is a
3779    /// target no iterate could hit. The per-row alternative, `Σ_j |a_ij x_j|`
3780    /// via `|J|·|x|`, looks more precise and measures the wrong thing (a row's
3781    /// *evaluation* error, not what limits its residual); it was implemented
3782    /// and it regressed QETAMACR, QSCORPIO and QPILOTNO of gh #446's 15. Re-run
3783    /// those three before changing this.
3784    #[test]
3785    fn row_noise_floor_tracks_the_iterate_norm() {
3786        // `d(x) = x0` against a declared box of ±1e-9.
3787        let bound = 1e-9;
3788        // At ‖x‖_∞ = 3 the floor is ~4.3e-14: the bound is real data, judged.
3789        let cq = fixture_with(MockNlp::new().with_d_box(bound));
3790        assert_eq!(cq.relative_d_infeasibility_max(), (2.0 - bound) / bound);
3791        // At ‖x‖_∞ = 1e8 the floor is ~1.4e-6 and the same bound is finer than
3792        // the iterate can be resolved, so the row abstains.
3793        let cq = fixture_with_x(MockNlp::new().with_d_box(bound), &[2.0, 1e8]);
3794        assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
3795    }
3796
3797    /// A row-count mismatch means the RHS does not describe this `c` block;
3798    /// pairing them up anyway would judge rows against other rows' magnitudes.
3799    #[test]
3800    fn relative_c_infeasibility_abstains_on_length_mismatch() {
3801        let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![2.0, 2.0])));
3802        assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3803    }
3804
3805    #[test]
3806    fn grad_barrier_obj_x_subtracts_mu_inv_slack() {
3807        // grad_f = (4, 6).
3808        // P_L lifts -mu*(1/s_x_L) = -0.1*(1/2)=-0.05 into x[0].
3809        // P_U lifts +mu*(1/s_x_U) = +0.1*(1/2)=+0.05 into x[1].
3810        // result = (4 - 0.05, 6 + 0.05) = (3.95, 6.05).
3811        let cq = fixture();
3812        let g = dense_vals(&cq.curr_grad_barrier_obj_x());
3813        assert!((g[0] - 3.95).abs() < 1e-13);
3814        assert!((g[1] - 6.05).abs() < 1e-13);
3815    }
3816
3817    #[test]
3818    fn grad_lag_s_is_minus_y_d_minus_pl_v_l_plus_pu_v_u() {
3819        // tmp = P_U v_U = (zero-dim contrib) → 0
3820        // tmp -= P_L v_L → tmp = -[0.3]
3821        // tmp -= y_d = -[0.3] - [1.0] = [-1.3]
3822        let cq = fixture();
3823        assert!((dense_vals(&cq.curr_grad_lag_s())[0] + 1.3).abs() < 1e-15);
3824    }
3825
3826    fn zero_iv_like(iv: &IteratesVector) -> IteratesVector {
3827        // Materialize explicit zeros for every component so the
3828        // affine-step tests can compose direct-sum updates.
3829        IteratesVector::new(
3830            rcv(&vec![0.0; iv.x.dim() as usize]),
3831            rcv(&vec![0.0; iv.s.dim() as usize]),
3832            rcv(&vec![0.0; iv.y_c.dim() as usize]),
3833            rcv(&vec![0.0; iv.y_d.dim() as usize]),
3834            rcv(&vec![0.0; iv.z_l.dim() as usize]),
3835            rcv(&vec![0.0; iv.z_u.dim() as usize]),
3836            rcv(&vec![0.0; iv.v_l.dim() as usize]),
3837            rcv(&vec![0.0; iv.v_u.dim() as usize]),
3838        )
3839    }
3840
3841    #[test]
3842    fn aff_step_compl_avrg_with_zero_step_matches_curr_avrg_compl() {
3843        // Δ_aff = 0 ⇒ predicted compl ≡ current compl.
3844        // s_X_L · z_L = 2·0.5=1, s_X_U·z_U=2·0.7=1.4, s_S_L·v_L=3·0.3=0.9.
3845        // Total = 3.3; N = 3 (z_l + z_u + v_l, v_u empty); avrg = 1.1.
3846        let cq = fixture();
3847        let iv = cq.curr_iv();
3848        let zero = zero_iv_like(&iv);
3849        let m = cq.aff_step_compl_avrg(&zero, 1.0, 1.0);
3850        assert!((m - 1.1).abs() < 1e-13);
3851        assert!((cq.curr_avrg_compl() - 1.1).abs() < 1e-13);
3852    }
3853
3854    #[test]
3855    fn aff_step_compl_avrg_responds_to_primal_step() {
3856        // Δ_aff.x = (1, 0), α_pri = 1, others = 0.
3857        // s_X_L_aff = 2 + 1·1 = 3; s_X_U_aff = 2 (P_U^T·dx = 0); s_S_L_aff = 3.
3858        // (3·0.5 + 2·0.7 + 3·0.3) / 3 = (1.5 + 1.4 + 0.9) / 3 = 1.2667.
3859        let cq = fixture();
3860        let iv = cq.curr_iv();
3861        let mut z = zero_iv_like(&iv);
3862        z.x = rcv(&[1.0, 0.0]);
3863        let m = cq.aff_step_compl_avrg(&z, 1.0, 1.0);
3864        assert!((m - 1.2666666666666666).abs() < 1e-13);
3865    }
3866
3867    #[test]
3868    fn aff_step_alpha_primal_truncates_to_x_lower_bound() {
3869        // Δ_aff.x = (-3, 0); s_X_L = 2; tau = 1 ⇒ α_max = 2/3.
3870        let cq = fixture();
3871        let iv = cq.curr_iv();
3872        let mut z = zero_iv_like(&iv);
3873        z.x = rcv(&[-3.0, 0.0]);
3874        let a = cq.aff_step_alpha_primal_max(&z, 1.0);
3875        assert!((a - 2.0 / 3.0).abs() < 1e-13);
3876    }
3877
3878    #[test]
3879    fn aff_step_alpha_dual_truncates_to_z_lower_bound() {
3880        // Δ_aff.z_L = (-1); z_L = 0.5; tau = 1 ⇒ α_max = 0.5.
3881        let cq = fixture();
3882        let iv = cq.curr_iv();
3883        let mut z = zero_iv_like(&iv);
3884        z.z_l = rcv(&[-1.0]);
3885        let a = cq.aff_step_alpha_dual_max(&z, 1.0);
3886        assert!((a - 0.5).abs() < 1e-13);
3887    }
3888
3889    #[test]
3890    fn grad_barr_t_delta_dots_barrier_grads_with_step() {
3891        // ∇_x φ = (3.95, 6.05); ∇_s φ = (-mu/s_s_L) = -0.1/3 ≈ -0.03333…
3892        // δx = (1, 2); δs = (3): result = 3.95·1 + 6.05·2 + (-0.0333…)·3
3893        //                              = 3.95 + 12.10 − 0.1 = 15.95.
3894        let cq = fixture();
3895        let dx = dvec(&[1.0, 2.0]);
3896        let ds = dvec(&[3.0]);
3897        let r = cq.curr_grad_barr_t_delta(&dx, &ds);
3898        let expected = 3.95 + 12.10 - 0.1;
3899        assert!((r - expected).abs() < 1e-13, "r = {r}");
3900    }
3901
3902    #[test]
3903    fn dwd_with_no_w_collapses_to_sigma_quadratic() {
3904        // W is None in the fixture (no Hessian seeded), perts default to 0.
3905        // σ_x = (0.25, 0.35); σ_s = (0.1).
3906        // δx = (2, -1); δs = (3) ⇒ dWd = 0.25·4 + 0.35·1 + 0.1·9
3907        //                              = 1.00 + 0.35 + 0.90 = 2.25.
3908        let cq = fixture();
3909        let dx = dvec(&[2.0, -1.0]);
3910        let ds = dvec(&[3.0]);
3911        let r = cq.curr_dwd(&dx, &ds);
3912        assert!((r - 2.25).abs() < 1e-13, "r = {r}");
3913    }
3914
3915    #[test]
3916    fn dwd_includes_pd_perturbations() {
3917        // Without perts: dWd = 0.25·4 + 0.35·1 + 0.1·9 = 2.25.
3918        // δ_pert_x = 0.5, δ_pert_s = 0.25:
3919        //   add δ_pert_x · ‖δx‖² + δ_pert_s · ‖δs‖²
3920        //     = 0.5·(4+1) + 0.25·9 = 2.5 + 2.25 = 4.75.
3921        // Total = 7.00.
3922        let cq = fixture();
3923        {
3924            let mut d = cq.data.borrow_mut();
3925            d.perturbations.delta_x = 0.5;
3926            d.perturbations.delta_s = 0.25;
3927        }
3928        let dx = dvec(&[2.0, -1.0]);
3929        let ds = dvec(&[3.0]);
3930        let r = cq.curr_dwd(&dx, &ds);
3931        assert!((r - 7.00).abs() < 1e-13, "r = {r}");
3932    }
3933
3934    // ---- #292: NaN gradient / Jacobian must not launder to a finite KKT error
3935
3936    #[test]
3937    fn nlp_error_is_finite_for_a_finite_iterate() {
3938        // Baseline: the well-formed fixture produces a finite, positive KKT
3939        // error (this iterate is not a KKT point). The finiteness guard added
3940        // for #292 must not perturb this normal path.
3941        let cq = fixture();
3942        let err = cq.curr_nlp_error();
3943        assert!(err.is_finite() && err > 0.0, "err = {err}");
3944    }
3945
3946    #[test]
3947    fn nlp_error_is_non_finite_when_gradient_has_nan() {
3948        // A NaN gradient component reaches ∇_x L, whose max-norm (`amax`)
3949        // silently drops NaN and would launder the dual infeasibility to a
3950        // finite value → bogus `Solve_Succeeded` (#292). `curr_nlp_error` must
3951        // instead surface a non-finite error so the caller's
3952        // `!nlp_err.is_finite()` guard fires `Invalid_Number_Detected`.
3953        let cq = fixture_with(MockNlp::new().with_nan_grad());
3954        assert!(
3955            !cq.curr_nlp_error().is_finite(),
3956            "NaN gradient laundered to finite KKT error: {}",
3957            cq.curr_nlp_error()
3958        );
3959    }
3960
3961    #[test]
3962    fn nlp_error_is_non_finite_when_constraint_jacobian_has_nan() {
3963        // A NaN in the constraint Jacobian enters ∇_x L through the Jᵀy term
3964        // and is likewise laundered by `amax` on the fixture's nonzero
3965        // multipliers. Must read as a non-finite KKT error, not `Optimal`.
3966        let cq = fixture_with(MockNlp::new().with_nan_jac_c());
3967        assert!(
3968            !cq.curr_nlp_error().is_finite(),
3969            "NaN constraint Jacobian laundered to finite KKT error: {}",
3970            cq.curr_nlp_error()
3971        );
3972    }
3973
3974    // ---- Unscaled (user-space) KKT residuals — pounce#173 -------------
3975
3976    #[test]
3977    fn unscaled_dual_inf_is_scaled_over_df() {
3978        // df = 2: every Lagrangian-gradient term carries the objective
3979        // factor, so the unscaled dual infeasibility is the scaled one
3980        // divided by df.
3981        let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
3982        let scaled = cq.curr_dual_infeasibility_max();
3983        let unscaled = cq.curr_unscaled_dual_infeasibility_max();
3984        assert!(scaled > 0.0, "fixture should have nonzero dual inf");
3985        assert!(
3986            (unscaled - scaled / 2.0).abs() < 1e-12,
3987            "unscaled {unscaled} != scaled/df {}",
3988            scaled / 2.0
3989        );
3990    }
3991
3992    /// gh #532. The dual *scale* is the largest single term `∇L` is assembled
3993    /// from, so the strict gate can ask what fraction of those terms failed to
3994    /// cancel instead of comparing a residual against an absolute constant.
3995    #[test]
3996    fn dual_inf_scale_is_the_largest_lagrangian_term() {
3997        // Fixture at x = (2, 3): ∇f = (4, 6); J_cᵀ y_c = (1, 1); J_dᵀ y_d =
3998        // (1, 0); y_d = 1; P_L z_L = 0.5; P_U z_U = 0.7; P_L v_L = 0.3; v_U is
3999        // empty. The largest is ‖∇f‖_∞ = 6.
4000        let cq = fixture();
4001        assert_eq!(cq.curr_dual_infeasibility_scale_max(), 6.0);
4002        // No scaling → the unscaled accessor is the identity, as for every
4003        // other residual on the common path.
4004        assert_eq!(
4005            cq.curr_unscaled_dual_infeasibility_scale_max(),
4006            cq.curr_dual_infeasibility_scale_max()
4007        );
4008    }
4009
4010    /// The scale unscales exactly as the residual it is the scale of: every
4011    /// term of the scaled Lagrangian gradient carries `df`, so both are the
4012    /// scaled value over `|df|`. If the two ever divided differently the ratio
4013    /// the strict gate tests would silently pick up a factor of `df`.
4014    #[test]
4015    fn unscaled_dual_inf_scale_is_scaled_over_df() {
4016        let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
4017        assert_eq!(cq.curr_unscaled_dual_infeasibility_scale_max(), 3.0);
4018        // A negative factor is the documented way to pose a maximization; a
4019        // max-norm has no business coming back negative (the sign trap that
4020        // defeated the unscaled dual residual gate).
4021        let neg = fixture_with(MockNlp::new().with_scaling(-2.0, None, None));
4022        assert_eq!(neg.curr_unscaled_dual_infeasibility_scale_max(), 3.0);
4023    }
4024
4025    #[test]
4026    fn unscaled_residuals_are_identity_without_scaling() {
4027        // df = 1, no row scaling → unscaled accessors return exactly the
4028        // scaled values (the common no-scaling path).
4029        let cq = fixture();
4030        assert_eq!(
4031            cq.curr_unscaled_dual_infeasibility_max(),
4032            cq.curr_dual_infeasibility_max()
4033        );
4034        assert_eq!(
4035            cq.curr_unscaled_complementarity_max(),
4036            cq.curr_complementarity_max()
4037        );
4038        assert_eq!(
4039            cq.curr_unscaled_primal_infeasibility_max(),
4040            cq.curr_primal_infeasibility_max()
4041        );
4042    }
4043
4044    #[test]
4045    fn unscaled_compl_is_scaled_over_df() {
4046        let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
4047        let scaled = cq.curr_complementarity_max();
4048        let unscaled = cq.curr_unscaled_complementarity_max();
4049        assert!(scaled > 0.0);
4050        assert!((unscaled - scaled / 2.0).abs() < 1e-12);
4051    }
4052
4053    #[test]
4054    fn unscaled_primal_divides_each_row_by_its_factor() {
4055        // Fixture residuals: c = x0+x1-1 = 4; d-s = x0 - s = 2 - 4 = -2.
4056        // Scaled max-norm primal = max(|4|, |-2|) = 4.
4057        // With dc = [4], dd = [2]: unscaled = max(|4/4|, |-2/2|) = 1.
4058        let cq = fixture_with(MockNlp::new().with_scaling(1.0, Some(vec![4.0]), Some(vec![2.0])));
4059        assert!((cq.curr_primal_infeasibility_max() - 4.0).abs() < 1e-12);
4060        assert!(
4061            (cq.curr_unscaled_primal_infeasibility_max() - 1.0).abs() < 1e-12,
4062            "got {}",
4063            cq.curr_unscaled_primal_infeasibility_max()
4064        );
4065    }
4066
4067    #[test]
4068    fn unscaled_nlp_error_is_max_of_unscaled_components() {
4069        let cq = fixture_with(MockNlp::new().with_scaling(2.0, Some(vec![4.0]), Some(vec![2.0])));
4070        let expected = cq
4071            .curr_unscaled_dual_infeasibility_max()
4072            .max(cq.curr_unscaled_primal_infeasibility_max())
4073            .max(cq.curr_unscaled_complementarity_max());
4074        assert_eq!(cq.curr_unscaled_nlp_error(), expected);
4075    }
4076
4077    /// gh #528. A component at or below its own floor drops out; everything
4078    /// above it is counted in full, not net of the floor — the question the
4079    /// floor answers is whether the row says anything at all.
4080    #[test]
4081    fn amax_above_floor_drops_only_sub_floor_components() {
4082        let v = dvec(&[1e-9, -3e-7, 5e-3]);
4083        assert_eq!(amax_above_floor(&v, &[1e-8, 1e-8, 1e-8]), 5e-3);
4084        // The largest component is the only one under its floor: the max comes
4085        // from what remains, not from the vector's own `amax`.
4086        assert_eq!(amax_above_floor(&v, &[1e-8, 1e-8, 1.0]), 3e-7);
4087        // Everything silenced.
4088        assert_eq!(amax_above_floor(&v, &[1.0, 1.0, 1.0]), 0.0);
4089        // Exactly at the floor is silenced (`>`, not `>=`).
4090        assert_eq!(amax_above_floor(&dvec(&[1e-8]), &[1e-8]), 0.0);
4091    }
4092
4093    /// A floor that cannot be attributed component-wise must not silence
4094    /// anything: over-reporting the residual is the safe direction.
4095    #[test]
4096    fn amax_above_floor_falls_back_on_a_length_mismatch() {
4097        let v = dvec(&[1e-9, -3e-7]);
4098        assert_eq!(amax_above_floor(&v, &[1.0]), 3e-7);
4099        assert_eq!(amax_above_floor(&v, &[]), 3e-7);
4100    }
4101
4102    /// The floored aggregate is never larger than the raw one, and on a
4103    /// fixture whose residuals (`c = 4`, `d − s = −2`) are nowhere near any
4104    /// resolution limit the two are identical — the common path is untouched.
4105    #[test]
4106    fn nlp_error_above_primal_noise_matches_on_ordinary_residuals() {
4107        let cq = fixture_with(MockNlp::new());
4108        assert_eq!(
4109            cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4110            cq.curr_primal_infeasibility_max()
4111        );
4112        assert_eq!(
4113            cq.curr_nlp_error_above_primal_noise(ROW_NOISE_KAPPA),
4114            cq.curr_nlp_error()
4115        );
4116    }
4117
4118    /// gh #528, **equality block**, through the real accessor rather than a
4119    /// hand-supplied floor. The integration LP is all-inequality (`g_u = 2e19`,
4120    /// so `c.dim() == 0`), so this is the only cover the `declared_c_rhs()`
4121    /// branch has.
4122    ///
4123    /// `x = (4, 3)` puts `d = x0 = 4` on top of `s = 4`, so the inequality
4124    /// block's residual is an exact `0` and what the accessor returns is the
4125    /// `c` block alone.
4126    #[test]
4127    fn a_sub_quantum_equality_residual_is_silenced_and_a_coarser_one_is_not() {
4128        let rhs = 1e8;
4129        let floor = ROW_NOISE_KAPPA * Number::EPSILON * rhs;
4130        let cq_for = |c: Number| {
4131            fixture_with_x(
4132                MockNlp::new().with_c_rhs(Some(vec![rhs])).with_c(c),
4133                &[4.0, 3.0],
4134            )
4135        };
4136
4137        // Under the quantum of `g(x) − b` at `|b| = 1e8`: no iterate could
4138        // have placed the residual here, so the row says nothing.
4139        let cq = cq_for(floor * 0.5);
4140        assert_eq!(cq.curr_primal_infeasibility_max(), floor * 0.5);
4141        assert_eq!(
4142            cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4143            0.0
4144        );
4145
4146        // Above it: counted in full, not net of the floor.
4147        let cq = cq_for(floor * 2.0);
4148        assert_eq!(
4149            cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4150            floor * 2.0
4151        );
4152
4153        // The placement floor alone would not have silenced anything here —
4154        // at ‖x‖_∞ = 4 through a row of `max_j |∂c/∂x_j| = 1` it is ~5.7e-14,
4155        // eight decades under the formation floor. The `c` branch's own
4156        // magnitude is what does the work.
4157        let cq = fixture_with_x(MockNlp::new().with_c(floor * 0.5), &[4.0, 3.0]);
4158        assert_eq!(
4159            cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4160            floor * 0.5
4161        );
4162    }
4163
4164    /// The `primal_noise_floor_kappa = 0` escape hatch: every floor collapses
4165    /// to `0`, so every residual is counted and the floored aggregate is the
4166    /// raw one — the strict gate is bit-for-bit upstream Ipopt's again. Pinned
4167    /// on a fixture where the floor otherwise *does* silence the row, so this
4168    /// cannot pass by the two agreeing anyway.
4169    #[test]
4170    fn a_zero_kappa_switches_the_floor_off_completely() {
4171        let rhs = 1e8;
4172        let residual = ROW_NOISE_KAPPA * Number::EPSILON * rhs * 0.5;
4173        let cq = fixture_with_x(
4174            MockNlp::new().with_c_rhs(Some(vec![rhs])).with_c(residual),
4175            &[4.0, 3.0],
4176        );
4177        // The floor is live at the default kappa …
4178        assert_eq!(
4179            cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4180            0.0
4181        );
4182        // … and gone at zero.
4183        assert_eq!(
4184            cq.curr_primal_infeasibility_above_noise(0.0),
4185            cq.curr_primal_infeasibility_max()
4186        );
4187        assert_eq!(
4188            cq.curr_nlp_error_above_primal_noise(0.0),
4189            cq.curr_nlp_error()
4190        );
4191    }
4192
4193    /// The equality floor rides the row scaling, because both sides of the
4194    /// comparison do: `declared_c_rhs()` reapplies `c_scale` (pinned by
4195    /// `declared_c_rhs_carries_the_row_scaling` in `orig_ipopt_nlp.rs`) and
4196    /// `curr_c()` is the scaled residual `dc · (g(x) − b)`. Scaling a row by
4197    /// `k` scales its residual and its floor together, so the verdict is
4198    /// invariant — which is what makes it legitimate to compare a floor built
4199    /// from the declared RHS against `curr_c()` at all.
4200    #[test]
4201    fn the_equality_floor_rides_the_row_scaling() {
4202        let rhs = 1e8;
4203        let quantum = ROW_NOISE_KAPPA * Number::EPSILON * rhs;
4204        for k in [1.0, 4.0, 0.25] {
4205            let cq_for = |c: Number| {
4206                fixture_with_x(
4207                    MockNlp::new()
4208                        .with_scaling(1.0, Some(vec![k]), None)
4209                        .with_c_rhs(Some(vec![k * rhs]))
4210                        .with_c(k * c),
4211                    &[4.0, 3.0],
4212                )
4213            };
4214            assert_eq!(
4215                cq_for(quantum * 0.5).curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4216                0.0,
4217                "sub-quantum residual must stay silenced at row scaling {k}",
4218            );
4219            assert_eq!(
4220                cq_for(quantum * 2.0).curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4221                k * quantum * 2.0,
4222                "above-quantum residual must survive at row scaling {k}",
4223            );
4224        }
4225    }
4226}