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 /// `θ` here is the violation of the **model**, not of the slack
2223 /// reformulation, and in user units:
2224 /// [`unscaled_nlp_constraint_violation_max`] — `|c(x)|` and
2225 /// `dist(d(x), [d_l, d_u])` against the declared bounds, each row
2226 /// unscaled. Both halves of that matter, and both were measured wrong
2227 /// once (gh#1146):
2228 ///
2229 /// * **Slack-free.** The verdict claims no nearby `x` violates the
2230 /// *model* less. Measured as `‖(c, d − s)‖` with `s` held fixed, every
2231 /// probe step also opens a gap `Δx` on each inequality row whose slack
2232 /// currently sits exactly on `d(x)` — rows that are satisfied, and stay
2233 /// satisfied, for any small move. On the gh#1146 model (`x ≥ 0.1`,
2234 /// `0.25 ≤ x`, `log x ≥ −1`, exact Hessian, `x0 = 0`) that turned a
2235 /// step of `+0.1` — which makes the model **feasible** — into a
2236 /// 17 000-fold *increase*, and the verdict went out at `x = 0.349`, one
2237 /// Newton step from a solution.
2238 /// * **Per-row unscaled.** A ratio of max-norms is scale-free only when
2239 /// one row dominates both. Under row scaling `(1, 1, 1e-8)` — the `log`
2240 /// row, scaled at `x0 = 0` where its derivative is infinite — the
2241 /// `0.057` violation that the verdict was about counted as `5.7e-10`,
2242 /// below roundoff on every other row.
2243 ///
2244 /// A model-feasible point (`θ = 0`) has nothing to certify, and reports
2245 /// descent — the caller must not convict it.
2246 ///
2247 /// Costs one `eval_c`/`eval_d` pair per probed step, and runs only where the
2248 /// detector was about to fire (both gates already passed for a full streak),
2249 /// which is rare. Steps are clamped to the variable bounds, so descent that
2250 /// only exists outside the box is correctly not counted — that direction
2251 /// would suppress a *correct* infeasibility verdict.
2252 ///
2253 /// Returns `true` when descent is available, i.e. the iterate is **not**
2254 /// stationary and `LocalInfeasibility` must not be declared.
2255 pub fn infeasibility_descent_available(&self) -> bool {
2256 use pounce_linalg::DenseVector;
2257
2258 let theta_curr = self.curr_unscaled_nlp_constraint_violation_max();
2259 if !theta_curr.is_finite() {
2260 return false;
2261 }
2262 if theta_curr <= 0.0 {
2263 // Feasible as declared: no infeasibility to confirm.
2264 return true;
2265 }
2266 // -grad of 1/2||(c, d-s)||^2 w.r.t. x. Only the direction is used;
2267 // the probe below measures the model's violation along it.
2268 let c = self.curr_c();
2269 let dms = self.curr_d_minus_s();
2270 let jc_t_c = self.curr_jac_c_t_times_vec(&*c);
2271 let jd_t_dms = self.curr_jac_d_t_times_vec(&*dms);
2272 let mut grad = jc_t_c.make_new();
2273 grad.add_two_vectors(1.0, &*jc_t_c, 1.0, &*jd_t_dms, 0.0);
2274 let gnorm = grad.amax();
2275 if !(gnorm > 0.0) || !gnorm.is_finite() {
2276 // A vanishing gradient is the stationary case this exists to
2277 // confirm; a non-finite one gives us nothing to probe with.
2278 return false;
2279 }
2280
2281 let x = self.curr_iv().x.clone();
2282 let nlp = self.nlp.borrow();
2283
2284 // Full-length bound values and finite-bound indicators, lifted through
2285 // the expansion matrices (same pattern as the divergence guard).
2286 let mut ones_l = nlp.x_l().make_new();
2287 ones_l.set(1.0);
2288 let mut has_lb = x.make_new();
2289 nlp.px_l().mult_vector(1.0, &*ones_l, 0.0, &mut *has_lb);
2290 let mut lb = x.make_new();
2291 nlp.px_l().mult_vector(1.0, nlp.x_l(), 0.0, &mut *lb);
2292
2293 let mut ones_u = nlp.x_u().make_new();
2294 ones_u.set(1.0);
2295 let mut has_ub = x.make_new();
2296 nlp.px_u().mult_vector(1.0, &*ones_u, 0.0, &mut *has_ub);
2297 let mut ub = x.make_new();
2298 nlp.px_u().mult_vector(1.0, nlp.x_u(), 0.0, &mut *ub);
2299 drop(nlp);
2300
2301 let dense = |v: &dyn Vector| -> Option<Vec<Number>> {
2302 v.as_any()
2303 .downcast_ref::<DenseVector>()
2304 .map(|d| d.expanded_values())
2305 };
2306 let (Some(xv), Some(gv), Some(lbv), Some(ubv), Some(hl), Some(hu)) = (
2307 dense(&*x),
2308 dense(&*grad),
2309 dense(&*lb),
2310 dense(&*ub),
2311 dense(&*has_lb),
2312 dense(&*has_ub),
2313 ) else {
2314 // Non-dense backing: no probe possible. Report "no descent" so the
2315 // caller falls back to the surrogate's verdict rather than silently
2316 // suppressing every infeasibility conclusion.
2317 return false;
2318 };
2319
2320 // Relative step lengths, so the probe is independent of problem scale.
2321 let xnorm = xv.iter().fold(0.0_f64, |a, &v| a.max(v.abs())).max(1.0);
2322 let base = xnorm / gnorm;
2323
2324 let mut trial = x.make_new();
2325 for k in 0..Self::INFEAS_PROBE_STEPS {
2326 let alpha = base * 10f64.powi(-(k as i32));
2327 {
2328 let Some(t) = trial.as_any_mut().downcast_mut::<DenseVector>() else {
2329 return false;
2330 };
2331 for (i, slot) in t.values_mut().iter_mut().enumerate() {
2332 let mut xi = xv[i] - alpha * gv[i];
2333 if hl[i] != 0.0 {
2334 xi = xi.max(lbv[i]);
2335 }
2336 if hu[i] != 0.0 {
2337 xi = xi.min(ubv[i]);
2338 }
2339 *slot = xi;
2340 }
2341 }
2342 if let Some(theta) = self.theta_at(&*trial) {
2343 if theta.is_finite() && theta < theta_curr * (1.0 - Self::INFEAS_PROBE_MARGIN) {
2344 return true;
2345 }
2346 }
2347 }
2348 false
2349 }
2350
2351 /// Number of geometrically decreasing step lengths the descent probe tries.
2352 const INFEAS_PROBE_STEPS: usize = 6;
2353 /// Relative reduction in `θ` a probe step must achieve before it counts as
2354 /// descent and vetoes the verdict.
2355 ///
2356 /// Deliberately coarse. The question is not "is this the exact minimiser of
2357 /// the violation" — an interior-point iterate converging toward one always
2358 /// has some infinitesimal descent left, and a tight margin would veto
2359 /// forever and never let a genuine infeasibility be declared. The question
2360 /// is whether a *materially* less-violating point sits nearby, which is what
2361 /// distinguishes "converging to an infeasible stationary point" from
2362 /// "nowhere near stationary".
2363 ///
2364 /// The two regimes are far apart, so the exact value is not delicate. On the
2365 /// genuinely infeasible `x³+y³ == 1 ∧ == 2`, iterates near the least-squares
2366 /// point have only ~0.07 % descent available. On HS13's false verdict, one
2367 /// step takes `θ` from 0.51 to **zero** — a 100 % reduction. Anything between
2368 /// a few percent and most of the way separates them; 10 % sits in the middle.
2369 const INFEAS_PROBE_MARGIN: Number = 0.1;
2370
2371 /// The model's max-norm constraint violation at an arbitrary `x`, in user
2372 /// units ([`unscaled_nlp_constraint_violation_max`], the measure
2373 /// [`Self::infeasibility_descent_available`] compares against), evaluated
2374 /// on scratch vectors so the algorithm's `curr`/`trial` state is
2375 /// untouched. `None` if the evaluation is unusable.
2376 fn theta_at(&self, x: &dyn Vector) -> Option<Number> {
2377 let iv = self.curr_iv();
2378 let mut nlp = self.nlp.borrow_mut();
2379 let mut c = iv.y_c.make_new();
2380 nlp.eval_c(x, &mut *c);
2381 let mut d = iv.s.make_new();
2382 nlp.eval_d(x, &mut *d);
2383 let t = unscaled_nlp_constraint_violation_max(&*nlp, &*c, &*d);
2384 t.is_finite().then_some(t)
2385 }
2386
2387 pub fn curr_infeasibility_stationarity(&self) -> Number {
2388 let c = self.curr_c();
2389 let dms = self.curr_d_minus_s();
2390 let jc_t_c = self.curr_jac_c_t_times_vec(&*c);
2391 let jd_t_dms = self.curr_jac_d_t_times_vec(&*dms);
2392 let mut grad = jc_t_c.make_new();
2393 grad.add_two_vectors(1.0, &*jc_t_c, 1.0, &*jd_t_dms, 0.0);
2394 let viol = c.amax().max(dms.amax());
2395 grad.amax() / viol.max(1.0)
2396 }
2397
2398 // --------------------------------------------------------------
2399 // Average / scalar complementarity
2400 // --------------------------------------------------------------
2401
2402 /// `(z_L · s_L + z_U · s_U + v_L · s_L^d + v_U · s_U^d) / N`
2403 /// where `N` is the total number of bound multipliers
2404 /// (`IpIpoptCalculatedQuantities.cpp:3553-3606`).
2405 pub fn curr_avrg_compl(&self) -> Number {
2406 let iv = self.curr_iv();
2407 let n = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2408 if n == 0 {
2409 return 0.0;
2410 }
2411 let s_x_l = self.curr_slack_x_l();
2412 let s_x_u = self.curr_slack_x_u();
2413 let s_s_l = self.curr_slack_s_l();
2414 let s_s_u = self.curr_slack_s_u();
2415 let mut acc = iv.z_l.dot(&*s_x_l);
2416 acc += iv.z_u.dot(&*s_x_u);
2417 acc += iv.v_l.dot(&*s_s_l);
2418 acc += iv.v_u.dot(&*s_s_u);
2419 acc / Number::from(n)
2420 }
2421
2422 /// `min_i (s_i · z_i)` over all four bound complementarity blocks.
2423 /// Mirrors `IpIpoptCalculatedQuantities.cpp:CurrComplxMin`
2424 /// (lines 3608-3640) — the smallest pairwise product `s · z`,
2425 /// signalling how close the iterate is to the central path.
2426 /// Empty bound sets contribute `+∞`; returns `0` if no bounds at
2427 /// all.
2428 pub fn curr_complementarity_min(&self) -> Number {
2429 let cxl = self.curr_compl_x_l();
2430 let cxu = self.curr_compl_x_u();
2431 let csl = self.curr_compl_s_l();
2432 let csu = self.curr_compl_s_u();
2433 let m = |v: &Rc<dyn Vector>| {
2434 if v.dim() == 0 {
2435 Number::INFINITY
2436 } else {
2437 v.min()
2438 }
2439 };
2440 let acc = m(&cxl).min(m(&cxu)).min(m(&csl)).min(m(&csu));
2441 if acc.is_infinite() { 0.0 } else { acc }
2442 }
2443
2444 /// Max-norm of the unbarriered complementarity blocks
2445 /// `max_i |s_i · z_i|` across all four `(x_L, x_U, s_L, s_U)`
2446 /// pairs. Mirrors upstream
2447 /// `IpIpoptCalculatedQuantities.cpp:CurrComplementarity(0., NORM_MAX)`
2448 /// — used by `OptimalityErrorConvergenceCheck` to gate the
2449 /// per-component `compl_inf_tol` test independently of the scaled
2450 /// scalar `curr_nlp_error`.
2451 pub fn curr_complementarity_max(&self) -> Number {
2452 self.curr_compl_x_l()
2453 .amax()
2454 .max(self.curr_compl_x_u().amax())
2455 .max(self.curr_compl_s_l().amax())
2456 .max(self.curr_compl_s_u().amax())
2457 }
2458
2459 /// Centrality measure `ξ = min_i(s_i z_i) / avrg(s · z)`. Mirrors
2460 /// `IpIpoptCalculatedQuantities.cpp:CurrCentralityMeasure`. Used
2461 /// by [`crate::mu::oracle::loqo::LoqoMuOracle`] to bias σ toward
2462 /// the central path when the iterate is unbalanced. Returns `1.0`
2463 /// (perfectly central) when there are no bound multipliers.
2464 pub fn curr_centrality_measure(&self) -> Number {
2465 let avrg = self.curr_avrg_compl();
2466 if avrg <= 0.0 {
2467 return 1.0;
2468 }
2469 self.curr_complementarity_min() / avrg
2470 }
2471
2472 /// Barriered KKT error `E_μ(x,y,z)` — port of
2473 /// `IpIpoptCalculatedQuantities.cpp:CurrBarrierError`. Same as
2474 /// [`Self::curr_nlp_error`] but uses the *relaxed* complementarity
2475 /// `s ⊙ z − μ` so the residual is zero when the iterate sits on the
2476 /// μ-perturbed central path. The monotone barrier-update strategy
2477 /// reduces μ only once this error drops below
2478 /// `barrier_tol_factor · μ`.
2479 pub fn curr_barrier_error(&self) -> Number {
2480 let iv = self.curr_iv();
2481 let (s_d, s_c) = self.optimality_error_scaling(&iv);
2482
2483 let glx = self.curr_grad_lag_x();
2484 let gls = self.curr_grad_lag_s();
2485 let dual = glx.amax().max(gls.amax()) / s_d;
2486
2487 let c = self.curr_c();
2488 let dms = self.curr_d_minus_s();
2489 let primal = c.amax().max(dms.amax());
2490
2491 let compl = self
2492 .curr_relaxed_compl_x_l()
2493 .amax()
2494 .max(self.curr_relaxed_compl_x_u().amax())
2495 .max(self.curr_relaxed_compl_s_l().amax())
2496 .max(self.curr_relaxed_compl_s_u().amax())
2497 / s_c;
2498
2499 dual.max(primal).max(compl)
2500 }
2501
2502 /// Optimality-scaled max-norm KKT error — port of
2503 /// `IpIpoptCalculatedQuantities.cpp:3050-3104`.
2504 ///
2505 /// ```text
2506 /// E = max( ||∇_x L, ∇_s L||_∞ / s_d ,
2507 /// ||c, d − s||_∞ ,
2508 /// ||compl||_∞ / s_c )
2509 /// ```
2510 ///
2511 /// where `s_d` / `s_c` are the asum-based scalings from
2512 /// `ComputeOptimalityErrorScaling` (see §4 of `MAIN_LOOP.md`).
2513 /// Uses `mu_target = 0` (the unbarriered KKT residual). The
2514 /// barriered variant is `curr_barrier_error` (TODO in Phase 7).
2515 pub fn curr_nlp_error(&self) -> Number {
2516 self.nlp_error(None)
2517 }
2518
2519 /// [`Self::curr_nlp_error`] with the primal-infeasibility term replaced by
2520 /// [`Self::curr_primal_infeasibility_above_noise`] — i.e. counting a
2521 /// constraint row's residual only where it rises above the finest value
2522 /// that row's residual can take in floating point (gh #528).
2523 ///
2524 /// Never larger than [`Self::curr_nlp_error`], and equal to it whenever no
2525 /// row is at its own resolution limit — which is every problem whose data
2526 /// is `O(1)`, so the common path is unchanged. It exists because the other
2527 /// two terms of the KKT error are already normalised (`s_d`, `s_c`) while
2528 /// the primal one is a bare absolute residual: `‖c‖_∞` and `‖d − s‖_∞` are
2529 /// quantised in units of `eps ·` the rows' own magnitude, so on a model
2530 /// whose constraint values reach `~1e8` the smallest *nonzero* value the
2531 /// term can take already exceeds the default `tol = 1e-8`. Judging that
2532 /// term absolutely there asks for a residual no iterate can represent.
2533 ///
2534 /// Read only by the **strict** convergence gate, which pairs it with the
2535 /// unscaled `constr_viol_tol` test on the full, unfloored residual — so
2536 /// what this admits is bounded by the user's own feasibility tolerance,
2537 /// never by the noise floor alone.
2538 ///
2539 /// `kappa` is the safety factor on the per-row floor —
2540 /// [`ROW_NOISE_KAPPA`] by default, from the `primal_noise_floor_kappa`
2541 /// option. **`0` switches the floor off entirely**, making this identical
2542 /// to [`Self::curr_nlp_error`] and the strict gate bit-for-bit upstream's.
2543 pub fn curr_nlp_error_above_primal_noise(&self, kappa: Number) -> Number {
2544 self.nlp_error(Some(kappa))
2545 }
2546
2547 /// [`Self::curr_nlp_error`] with the complementarity term supplied by the
2548 /// caller instead of read off the iterate, keeping the `s_c` normalisation
2549 /// and the other two terms exactly as they are.
2550 ///
2551 /// One caller: the crossover phase (#612). Its returned point sits
2552 /// *exactly* on the active constraints of the problem **as the user
2553 /// declared it**, which is `bound_relax_factor` inside the widened bounds
2554 /// this object measures against — so the iterate-derived complementarity
2555 /// reads `|multiplier| · δ`, around `1e-8` for a unit multiplier, where
2556 /// the truth in the frame that was solved is zero. Left alone that put a
2557 /// converged run's `Overall NLP error` above `tol` and let the opt-in
2558 /// `kkt_fidelity_tol` gate downgrade a strictly better point (#646).
2559 ///
2560 /// `compl_raw` is the un-normalised max-norm `max_i |s_i · z_i|`, the same
2561 /// quantity [`Self::curr_complementarity_max`] returns; the `s_c` divide
2562 /// happens here. `kappa` follows
2563 /// [`Self::curr_nlp_error_above_primal_noise`], `0` disabling the floor.
2564 ///
2565 /// This is a *reporting* substitution and nothing more — no convergence
2566 /// decision reads it, because crossover runs after the status is already
2567 /// settled.
2568 pub fn curr_nlp_error_with_complementarity(&self, compl_raw: Number, kappa: Number) -> Number {
2569 let floor = (kappa > 0.0).then_some(kappa);
2570 self.nlp_error_inner(floor, Some(compl_raw))
2571 }
2572
2573 /// `above_primal_noise` carries the floor's `kappa` when the primal term is
2574 /// to be floored, and is `None` for the plain upstream aggregate.
2575 fn nlp_error(&self, above_primal_noise: Option<Number>) -> Number {
2576 self.nlp_error_inner(above_primal_noise, None)
2577 }
2578
2579 /// `compl_override` replaces the iterate-derived complementarity max-norm
2580 /// before the `s_c` divide; see
2581 /// [`Self::curr_nlp_error_with_complementarity`]. The NaN guard below
2582 /// still inspects the iterate's own complementarity vectors either way —
2583 /// an override is a change of *frame*, not a licence to stop looking at
2584 /// the iterate for non-finite numbers.
2585 fn nlp_error_inner(
2586 &self,
2587 above_primal_noise: Option<Number>,
2588 compl_override: Option<Number>,
2589 ) -> Number {
2590 let iv = self.curr_iv();
2591 let (s_d, s_c) = self.optimality_error_scaling(&iv);
2592
2593 // dual infeasibility (max-norm of grad_lag_x and grad_lag_s)
2594 let glx = self.curr_grad_lag_x();
2595 let gls = self.curr_grad_lag_s();
2596
2597 // primal: max(||c||, ||d-s||)
2598 let c = self.curr_c();
2599 let dms = self.curr_d_minus_s();
2600
2601 // unbarriered complementarity (mu_target = 0 → just ||compl||)
2602 let cxl = self.curr_compl_x_l();
2603 let cxu = self.curr_compl_x_u();
2604 let csl = self.curr_compl_s_l();
2605 let csu = self.curr_compl_s_u();
2606
2607 // #292: the max-norm (`amax`/BLAS `iamax`) behind every term below
2608 // silently *drops* NaN — `NaN > m` is `false`, so a NaN component
2609 // leaves the running max untouched and is laundered into a finite
2610 // (typically `0.0`) KKT error. A NaN gradient, NaN constraint Jacobian
2611 // (via `∇_x L`'s `Jᵀy` term), or NaN residual would then read as an
2612 // *optimal* solve and return `Solve_Succeeded`. Detect any non-finite
2613 // component here — through the NaN-propagating `asum` behind
2614 // `has_valid_numbers`, not `amax` — and surface it as a non-finite KKT
2615 // error so the caller's existing `!nlp_err.is_finite()` guard fires
2616 // `Invalid_Number_Detected`. This is confined to the convergence/error
2617 // measure; the general `amax` semantics that step-size selection, the
2618 // line search, and the divergence detectors rely on are untouched.
2619 // (Inf is *not* laundered — `Inf > m` is true — so it already
2620 // propagated; this closes only the NaN hole, and Inf for free.)
2621 for v in [&glx, &gls, &c, &dms, &cxl, &cxu, &csl, &csu] {
2622 if !v.has_valid_numbers() {
2623 return Number::NAN;
2624 }
2625 }
2626
2627 let dual = glx.amax().max(gls.amax()) / s_d;
2628 let primal = match above_primal_noise {
2629 Some(kappa) if kappa > 0.0 => self.curr_primal_infeasibility_above_noise(kappa),
2630 _ => c.amax().max(dms.amax()),
2631 };
2632 let compl_raw = compl_override
2633 .unwrap_or_else(|| cxl.amax().max(cxu.amax()).max(csl.amax()).max(csu.amax()));
2634 let compl = compl_raw / s_c;
2635
2636 dual.max(primal).max(compl)
2637 }
2638
2639 /// `(s_d, s_c)` per `ComputeOptimalityErrorScaling`
2640 /// (`IpIpoptCalculatedQuantities.cpp:3663-3700`).
2641 fn optimality_error_scaling(&self, iv: &IteratesVector) -> (Number, Number) {
2642 let s_max = self.s_max;
2643
2644 // s_c: mean asum of all bound multipliers, capped at s_max,
2645 // divided by s_max.
2646 let n_c = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2647 let s_c = if n_c == 0 {
2648 1.0
2649 } else {
2650 let asum = iv.z_l.asum() + iv.z_u.asum() + iv.v_l.asum() + iv.v_u.asum();
2651 (s_max.max(asum / Number::from(n_c))) / s_max
2652 };
2653
2654 // s_d: mean asum of all dual multipliers, capped, divided.
2655 let n_d =
2656 iv.y_c.dim() + iv.y_d.dim() + iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2657 let s_d = if n_d == 0 {
2658 1.0
2659 } else {
2660 let asum = iv.y_c.asum()
2661 + iv.y_d.asum()
2662 + iv.z_l.asum()
2663 + iv.z_u.asum()
2664 + iv.v_l.asum()
2665 + iv.v_u.asum();
2666 (s_max.max(asum / Number::from(n_d))) / s_max
2667 };
2668
2669 (s_d, s_c)
2670 }
2671
2672 // --------------------------------------------------------------
2673 // Trial-side Lagrangian gradient / complementarity — needed by
2674 // the soft restoration phase's primal-dual error test. Each is a
2675 // line-for-line analog of the `curr_*` method above, reading the
2676 // `trial` iterate instead of `curr`.
2677 // --------------------------------------------------------------
2678
2679 pub fn trial_jac_c(&self) -> Rc<dyn Matrix> {
2680 let iv = self.trial_iv();
2681 self.nlp.borrow_mut().eval_jac_c(&*iv.x)
2682 }
2683
2684 pub fn trial_jac_d(&self) -> Rc<dyn Matrix> {
2685 let iv = self.trial_iv();
2686 self.nlp.borrow_mut().eval_jac_d(&*iv.x)
2687 }
2688
2689 /// `∇_x L` at the trial iterate — analog of [`Self::curr_grad_lag_x`].
2690 pub fn trial_grad_lag_x(&self) -> Rc<dyn Vector> {
2691 let iv = self.trial_iv();
2692 let grad_f = self.trial_grad_f();
2693 let jac_c = self.trial_jac_c();
2694 let jac_d = self.trial_jac_d();
2695
2696 let mut jc_t = iv.x.make_new();
2697 jac_c.trans_mult_vector(1.0, &*iv.y_c, 0.0, &mut *jc_t);
2698 let mut jd_t = iv.x.make_new();
2699 jac_d.trans_mult_vector(1.0, &*iv.y_d, 0.0, &mut *jd_t);
2700
2701 let mut tmp = iv.x.make_new();
2702 tmp.copy(&*grad_f);
2703 tmp.add_two_vectors(1.0, &*jc_t, 1.0, &*jd_t, 1.0);
2704
2705 let nlp = self.nlp.borrow();
2706 nlp.px_l().mult_vector(-1.0, &*iv.z_l, 1.0, &mut *tmp);
2707 nlp.px_u().mult_vector(1.0, &*iv.z_u, 1.0, &mut *tmp);
2708 rc_from(tmp)
2709 }
2710
2711 /// `∇_s L` at the trial iterate — analog of [`Self::curr_grad_lag_s`].
2712 pub fn trial_grad_lag_s(&self) -> Rc<dyn Vector> {
2713 let iv = self.trial_iv();
2714 let mut tmp = iv.y_d.make_new();
2715 let nlp = self.nlp.borrow();
2716 nlp.pd_u().mult_vector(1.0, &*iv.v_u, 0.0, &mut *tmp);
2717 nlp.pd_l().mult_vector(-1.0, &*iv.v_l, 1.0, &mut *tmp);
2718 tmp.axpy(-1.0, &*iv.y_d);
2719 rc_from(tmp)
2720 }
2721
2722 pub fn trial_compl_x_l(&self) -> Rc<dyn Vector> {
2723 Self::calc_compl(&*self.trial_slack_x_l(), &*self.trial_iv().z_l)
2724 }
2725
2726 pub fn trial_compl_x_u(&self) -> Rc<dyn Vector> {
2727 Self::calc_compl(&*self.trial_slack_x_u(), &*self.trial_iv().z_u)
2728 }
2729
2730 pub fn trial_compl_s_l(&self) -> Rc<dyn Vector> {
2731 Self::calc_compl(&*self.trial_slack_s_l(), &*self.trial_iv().v_l)
2732 }
2733
2734 pub fn trial_compl_s_u(&self) -> Rc<dyn Vector> {
2735 Self::calc_compl(&*self.trial_slack_s_u(), &*self.trial_iv().v_u)
2736 }
2737
2738 /// `||s ⊙ z − μ||₁` summed over the four complementarity blocks.
2739 fn relaxed_compl_asum(blocks: &[Rc<dyn Vector>], mu: Number) -> Number {
2740 let mut acc = 0.0;
2741 for compl in blocks {
2742 if compl.dim() == 0 {
2743 continue;
2744 }
2745 let mut r = compl.make_new();
2746 r.copy(&**compl);
2747 r.add_scalar(-mu);
2748 acc += r.asum();
2749 }
2750 acc
2751 }
2752
2753 /// Unscaled primal-dual KKT system error at the current iterate —
2754 /// port of
2755 /// `IpIpoptCalculatedQuantities.cpp:curr_primal_dual_system_error`.
2756 /// Each block uses the 1-norm scaled by its entry count; the result
2757 /// is the sum of the dual-infeasibility, primal-infeasibility, and
2758 /// complementarity terms. Used by the soft restoration phase's
2759 /// sufficient-reduction test.
2760 pub fn curr_primal_dual_system_error(&self, mu: Number) -> Number {
2761 let iv = self.curr_iv();
2762 let n_dual = iv.x.dim() + iv.s.dim();
2763 let dual_inf =
2764 (self.curr_grad_lag_x().asum() + self.curr_grad_lag_s().asum()) / Number::from(n_dual);
2765
2766 let n_primal = iv.y_c.dim() + iv.y_d.dim();
2767 let primal_inf = if n_primal > 0 {
2768 (self.curr_c().asum() + self.curr_d_minus_s().asum()) / Number::from(n_primal)
2769 } else {
2770 0.0
2771 };
2772
2773 let n_cmpl = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2774 let cmpl = if n_cmpl > 0 {
2775 Self::relaxed_compl_asum(
2776 &[
2777 self.curr_compl_x_l(),
2778 self.curr_compl_x_u(),
2779 self.curr_compl_s_l(),
2780 self.curr_compl_s_u(),
2781 ],
2782 mu,
2783 ) / Number::from(n_cmpl)
2784 } else {
2785 0.0
2786 };
2787
2788 dual_inf + primal_inf + cmpl
2789 }
2790
2791 /// Unscaled primal-dual KKT system error at the trial iterate —
2792 /// trial-side analog of [`Self::curr_primal_dual_system_error`].
2793 pub fn trial_primal_dual_system_error(&self, mu: Number) -> Number {
2794 let iv = self.trial_iv();
2795 let n_dual = iv.x.dim() + iv.s.dim();
2796 let dual_inf = (self.trial_grad_lag_x().asum() + self.trial_grad_lag_s().asum())
2797 / Number::from(n_dual);
2798
2799 let n_primal = iv.y_c.dim() + iv.y_d.dim();
2800 let primal_inf = if n_primal > 0 {
2801 (self.trial_c().asum() + self.trial_d_minus_s().asum()) / Number::from(n_primal)
2802 } else {
2803 0.0
2804 };
2805
2806 let n_cmpl = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
2807 let cmpl = if n_cmpl > 0 {
2808 Self::relaxed_compl_asum(
2809 &[
2810 self.trial_compl_x_l(),
2811 self.trial_compl_x_u(),
2812 self.trial_compl_s_l(),
2813 self.trial_compl_s_u(),
2814 ],
2815 mu,
2816 ) / Number::from(n_cmpl)
2817 } else {
2818 0.0
2819 };
2820
2821 dual_inf + primal_inf + cmpl
2822 }
2823
2824 // --------------------------------------------------------------
2825 // Damping indicators — `IpIpoptCalculatedQuantities.cpp:1044-1092`.
2826 //
2827 // Tmp_x = P_L · 1 − P_U · 1 (per primal: +1 lower-only,
2828 // −1 upper-only, 0 two-sided,
2829 // 0 unbounded)
2830 // dampind_x_L = P_L^T · Tmp_x (1 on lower-only bounds)
2831 // dampind_x_U = −P_U^T · Tmp_x (1 on upper-only bounds)
2832 // --------------------------------------------------------------
2833
2834 fn damping_indicators(&self) -> DampingIndicators {
2835 let nlp = self.nlp.borrow();
2836
2837 let mut tmp_x_l = nlp.x_l().make_new();
2838 tmp_x_l.set(1.0);
2839 let mut tmp_x_u = nlp.x_u().make_new();
2840 tmp_x_u.set(1.0);
2841 let mut tmp_x = self.curr_iv().x.make_new();
2842 nlp.px_l().mult_vector(1.0, &*tmp_x_l, 0.0, &mut *tmp_x);
2843 nlp.px_u().mult_vector(-1.0, &*tmp_x_u, 1.0, &mut *tmp_x);
2844 let mut d_x_l = nlp.x_l().make_new();
2845 nlp.px_l().trans_mult_vector(1.0, &*tmp_x, 0.0, &mut *d_x_l);
2846 let mut d_x_u = nlp.x_u().make_new();
2847 nlp.px_u()
2848 .trans_mult_vector(-1.0, &*tmp_x, 0.0, &mut *d_x_u);
2849
2850 let mut tmp_s_l = nlp.d_l().make_new();
2851 tmp_s_l.set(1.0);
2852 let mut tmp_s_u = nlp.d_u().make_new();
2853 tmp_s_u.set(1.0);
2854 let mut tmp_s = self.curr_iv().s.make_new();
2855 nlp.pd_l().mult_vector(1.0, &*tmp_s_l, 0.0, &mut *tmp_s);
2856 nlp.pd_u().mult_vector(-1.0, &*tmp_s_u, 1.0, &mut *tmp_s);
2857 let mut d_s_l = nlp.d_l().make_new();
2858 nlp.pd_l().trans_mult_vector(1.0, &*tmp_s, 0.0, &mut *d_s_l);
2859 let mut d_s_u = nlp.d_u().make_new();
2860 nlp.pd_u()
2861 .trans_mult_vector(-1.0, &*tmp_s, 0.0, &mut *d_s_u);
2862
2863 DampingIndicators {
2864 x_l: rc_from(d_x_l),
2865 x_u: rc_from(d_x_u),
2866 s_l: rc_from(d_s_l),
2867 s_u: rc_from(d_s_u),
2868 }
2869 }
2870
2871 /// `curr_grad_lag_x` plus the `kappa_d · μ · (Px_L · 1 − Px_U · 1)`
2872 /// damping term on singly-bounded primals — port of
2873 /// `IpIpoptCalculatedQuantities.cpp:2131-2180`. When `kappa_d == 0`
2874 /// returns the un-damped gradient.
2875 pub fn curr_grad_lag_with_damping_x(&self) -> Rc<dyn Vector> {
2876 if self.kappa_d == 0.0 {
2877 return self.curr_grad_lag_x();
2878 }
2879 let mu = self.data.borrow().curr_mu;
2880 let di = self.damping_indicators();
2881 let (d_x_l, d_x_u) = (di.x_l, di.x_u);
2882 let glx = self.curr_grad_lag_x();
2883 let mut tmp = glx.make_new();
2884 tmp.copy(&*glx);
2885 let nlp = self.nlp.borrow();
2886 nlp.px_l()
2887 .mult_vector(self.kappa_d * mu, &*d_x_l, 1.0, &mut *tmp);
2888 nlp.px_u()
2889 .mult_vector(-self.kappa_d * mu, &*d_x_u, 1.0, &mut *tmp);
2890 rc_from(tmp)
2891 }
2892
2893 pub fn curr_grad_lag_with_damping_s(&self) -> Rc<dyn Vector> {
2894 if self.kappa_d == 0.0 {
2895 return self.curr_grad_lag_s();
2896 }
2897 let mu = self.data.borrow().curr_mu;
2898 let di = self.damping_indicators();
2899 let (d_s_l, d_s_u) = (di.s_l, di.s_u);
2900 let gls = self.curr_grad_lag_s();
2901 let mut tmp = gls.make_new();
2902 tmp.copy(&*gls);
2903 let nlp = self.nlp.borrow();
2904 nlp.pd_l()
2905 .mult_vector(self.kappa_d * mu, &*d_s_l, 1.0, &mut *tmp);
2906 nlp.pd_u()
2907 .mult_vector(-self.kappa_d * mu, &*d_s_u, 1.0, &mut *tmp);
2908 rc_from(tmp)
2909 }
2910
2911 /// `kappa_d · (P_L · damping_l − P_U · damping_u)` in the full x
2912 /// space — port of `IpIpoptCalculatedQuantities.cpp::grad_kappa_times_damping_x`
2913 /// (lines 912-949). Unlike `curr_grad_lag_with_damping_x` this does
2914 /// NOT include `grad_lag_x` and is NOT scaled by `mu`; the centering
2915 /// RHS in the quality-function oracle multiplies the returned vector
2916 /// by `-avrg_compl` per upstream `IpQualityFunctionMuOracle.cpp:229`.
2917 pub fn grad_kappa_times_damping_x(&self) -> Rc<dyn Vector> {
2918 let mut tmp = self.curr_iv().x.make_new();
2919 tmp.set(0.0);
2920 if self.kappa_d > 0.0 {
2921 let di = self.damping_indicators();
2922 let nlp = self.nlp.borrow();
2923 nlp.px_l()
2924 .mult_vector(self.kappa_d, &*di.x_l, 0.0, &mut *tmp);
2925 nlp.px_u()
2926 .mult_vector(-self.kappa_d, &*di.x_u, 1.0, &mut *tmp);
2927 }
2928 rc_from(tmp)
2929 }
2930
2931 pub fn grad_kappa_times_damping_s(&self) -> Rc<dyn Vector> {
2932 let mut tmp = self.curr_iv().s.make_new();
2933 tmp.set(0.0);
2934 if self.kappa_d > 0.0 {
2935 let di = self.damping_indicators();
2936 let nlp = self.nlp.borrow();
2937 nlp.pd_l()
2938 .mult_vector(self.kappa_d, &*di.s_l, 0.0, &mut *tmp);
2939 nlp.pd_u()
2940 .mult_vector(-self.kappa_d, &*di.s_u, 1.0, &mut *tmp);
2941 }
2942 rc_from(tmp)
2943 }
2944
2945 // --------------------------------------------------------------
2946 // Affine (predictor) step helpers — port of upstream
2947 // `IpIpoptCalculatedQuantities.cpp:CurrAvrgCompl`/`AffMaxAlpha…`
2948 // used by the Mehrotra probing oracle and the quality-function
2949 // oracle's σ-search.
2950 // --------------------------------------------------------------
2951
2952 /// Max primal step that keeps `s + α · Δs > 0` for the four slack
2953 /// blocks (x_L, x_U, s_L, s_U), bounded by the fraction-to-the-
2954 /// boundary parameter `τ ∈ (0, 1]`. Mirrors
2955 /// `CalcFracToBound` against the projected step `P_L^T Δx`,
2956 /// `−P_U^T Δx`, `P_L^T Δs`, `−P_U^T Δs`.
2957 pub fn aff_step_alpha_primal_max(&self, delta_aff: &IteratesVector, tau: Number) -> Number {
2958 let nlp = self.nlp.borrow();
2959 let s_x_l = self.curr_slack_x_l();
2960 let s_x_u = self.curr_slack_x_u();
2961 let s_s_l = self.curr_slack_s_l();
2962 let s_s_u = self.curr_slack_s_u();
2963
2964 // Project Δx / Δs onto each bound subspace with the right sign.
2965 let mut step_x_l = s_x_l.make_new();
2966 nlp.px_l()
2967 .trans_mult_vector(1.0, &*delta_aff.x, 0.0, &mut *step_x_l);
2968 let mut step_x_u = s_x_u.make_new();
2969 nlp.px_u()
2970 .trans_mult_vector(-1.0, &*delta_aff.x, 0.0, &mut *step_x_u);
2971 let mut step_s_l = s_s_l.make_new();
2972 nlp.pd_l()
2973 .trans_mult_vector(1.0, &*delta_aff.s, 0.0, &mut *step_s_l);
2974 let mut step_s_u = s_s_u.make_new();
2975 nlp.pd_u()
2976 .trans_mult_vector(-1.0, &*delta_aff.s, 0.0, &mut *step_s_u);
2977
2978 s_x_l
2979 .frac_to_bound(&*step_x_l, tau)
2980 .min(s_x_u.frac_to_bound(&*step_x_u, tau))
2981 .min(s_s_l.frac_to_bound(&*step_s_l, tau))
2982 .min(s_s_u.frac_to_bound(&*step_s_u, tau))
2983 }
2984
2985 /// Max dual step that keeps `z + α · Δz > 0` (and same for v).
2986 pub fn aff_step_alpha_dual_max(&self, delta_aff: &IteratesVector, tau: Number) -> Number {
2987 let iv = self.curr_iv();
2988 iv.z_l
2989 .frac_to_bound(&*delta_aff.z_l, tau)
2990 .min(iv.z_u.frac_to_bound(&*delta_aff.z_u, tau))
2991 .min(iv.v_l.frac_to_bound(&*delta_aff.v_l, tau))
2992 .min(iv.v_u.frac_to_bound(&*delta_aff.v_u, tau))
2993 }
2994
2995 /// Predicted average complementarity after the affine step:
2996 /// `(1/N) · Σ (s + α_pri · Δs) · (z + α_du · Δz)` summed over the
2997 /// four bound blocks. Returns `0` when there are no bounds.
2998 pub fn aff_step_compl_avrg(
2999 &self,
3000 delta_aff: &IteratesVector,
3001 alpha_primal: Number,
3002 alpha_dual: Number,
3003 ) -> Number {
3004 let iv = self.curr_iv();
3005 let n = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
3006 if n == 0 {
3007 return 0.0;
3008 }
3009 let nlp = self.nlp.borrow();
3010
3011 // s_X_L_aff = s_X_L + α_pri · P_L^T Δx
3012 let s_x_l = self.curr_slack_x_l();
3013 let mut s_x_l_aff = s_x_l.make_new();
3014 s_x_l_aff.copy(&*s_x_l);
3015 let mut tmp = s_x_l.make_new();
3016 nlp.px_l()
3017 .trans_mult_vector(1.0, &*delta_aff.x, 0.0, &mut *tmp);
3018 s_x_l_aff.axpy(alpha_primal, &*tmp);
3019 // z_L_aff = z_L + α_du · Δz_L
3020 let mut z_l_aff = iv.z_l.make_new();
3021 z_l_aff.copy(&*iv.z_l);
3022 z_l_aff.axpy(alpha_dual, &*delta_aff.z_l);
3023 let mut acc = s_x_l_aff.dot(&*z_l_aff);
3024
3025 // s_X_U_aff = s_X_U − α_pri · P_U^T Δx
3026 let s_x_u = self.curr_slack_x_u();
3027 let mut s_x_u_aff = s_x_u.make_new();
3028 s_x_u_aff.copy(&*s_x_u);
3029 let mut tmp = s_x_u.make_new();
3030 nlp.px_u()
3031 .trans_mult_vector(-1.0, &*delta_aff.x, 0.0, &mut *tmp);
3032 s_x_u_aff.axpy(alpha_primal, &*tmp);
3033 let mut z_u_aff = iv.z_u.make_new();
3034 z_u_aff.copy(&*iv.z_u);
3035 z_u_aff.axpy(alpha_dual, &*delta_aff.z_u);
3036 acc += s_x_u_aff.dot(&*z_u_aff);
3037
3038 // s_S_L_aff = s_S_L + α_pri · P_dL^T Δs
3039 let s_s_l = self.curr_slack_s_l();
3040 let mut s_s_l_aff = s_s_l.make_new();
3041 s_s_l_aff.copy(&*s_s_l);
3042 let mut tmp = s_s_l.make_new();
3043 nlp.pd_l()
3044 .trans_mult_vector(1.0, &*delta_aff.s, 0.0, &mut *tmp);
3045 s_s_l_aff.axpy(alpha_primal, &*tmp);
3046 let mut v_l_aff = iv.v_l.make_new();
3047 v_l_aff.copy(&*iv.v_l);
3048 v_l_aff.axpy(alpha_dual, &*delta_aff.v_l);
3049 acc += s_s_l_aff.dot(&*v_l_aff);
3050
3051 // s_S_U_aff = s_S_U − α_pri · P_dU^T Δs
3052 let s_s_u = self.curr_slack_s_u();
3053 let mut s_s_u_aff = s_s_u.make_new();
3054 s_s_u_aff.copy(&*s_s_u);
3055 let mut tmp = s_s_u.make_new();
3056 nlp.pd_u()
3057 .trans_mult_vector(-1.0, &*delta_aff.s, 0.0, &mut *tmp);
3058 s_s_u_aff.axpy(alpha_primal, &*tmp);
3059 let mut v_u_aff = iv.v_u.make_new();
3060 v_u_aff.copy(&*iv.v_u);
3061 v_u_aff.axpy(alpha_dual, &*delta_aff.v_u);
3062 acc += s_s_u_aff.dot(&*v_u_aff);
3063
3064 acc / Number::from(n)
3065 }
3066}
3067
3068/// Convenience handle. Mirrors upstream's `SmartPtr<CQ>` flow.
3069pub type IpoptCqHandle = Rc<RefCell<IpoptCalculatedQuantities>>;
3070
3071/// Bundle of damping indicators for the four bound spaces — kept
3072/// internal because `kappa_d == 0` makes them dead in the default
3073/// configuration.
3074struct DampingIndicators {
3075 x_l: Rc<dyn Vector>,
3076 x_u: Rc<dyn Vector>,
3077 s_l: Rc<dyn Vector>,
3078 s_u: Rc<dyn Vector>,
3079}
3080
3081#[cfg(test)]
3082mod tests {
3083 use super::*;
3084 use crate::ipopt_data::IpoptData;
3085 use crate::iterates_vector::IteratesVector;
3086 use pounce_common::types::Index;
3087 use pounce_linalg::dense_vector::{DenseVector, DenseVectorSpace};
3088 use pounce_linalg::expansion_matrix::{ExpansionMatrix, ExpansionMatrixSpace};
3089 use pounce_linalg::triplet::{GenTMatrix, GenTMatrixSpace};
3090 use std::rc::Rc as StdRc;
3091
3092 fn dvec(values: &[Number]) -> DenseVector {
3093 let space = DenseVectorSpace::new(values.len() as Index);
3094 let mut v = space.make_new_dense();
3095 v.values_mut().copy_from_slice(values);
3096 v
3097 }
3098
3099 fn rcv(values: &[Number]) -> Rc<dyn Vector> {
3100 StdRc::new(dvec(values))
3101 }
3102
3103 /// Mock IpoptNlp covering: 2 vars, 1 equality, 1 inequality.
3104 /// Bounds: x[0] ≥ 0, x[1] ≤ 5, d ≥ 1.
3105 /// f(x) = x[0]^2 + x[1]^2; ∇f = (2x[0], 2x[1])
3106 /// c(x) = x[0] + x[1] - 1
3107 /// d(x) = x[0]
3108 struct MockNlp {
3109 x_l: DenseVector,
3110 x_u: DenseVector,
3111 d_l: DenseVector,
3112 d_u: DenseVector,
3113 px_l: Rc<dyn Matrix>,
3114 px_u: Rc<dyn Matrix>,
3115 pd_l: Rc<dyn Matrix>,
3116 pd_u: Rc<dyn Matrix>,
3117 // NLP scaling factors. Identity by default; `with_scaling`
3118 // installs non-trivial ones to exercise the unscaled accessors.
3119 // (The mock does not actually apply these in `eval_*`; the tests
3120 // verify the unscaling *arithmetic*, not end-to-end scaling.)
3121 obj_scale: Number,
3122 c_scale: Option<Vec<Number>>,
3123 d_scale: Option<Vec<Number>>,
3124 // #292: inject a non-finite component into the gradient / constraint
3125 // Jacobian to exercise the finiteness guard in `curr_nlp_error`.
3126 nan_grad: bool,
3127 nan_jac_c: bool,
3128 empty_jac_c: bool,
3129 // gh#390: the declared equality RHS the c-block relative measure
3130 // divides by. `None` (the default) is the "not tracked" contract.
3131 c_rhs: Option<Vec<Number>>,
3132 // pounce#476: force `c(x)` to a fixed value so a test can isolate the
3133 // inequality block (the default `x0 + x1 - 1` is 4 at the fixture's
3134 // point, which dominates any d-block difference under a max-norm).
3135 c_override: Option<Number>,
3136 // gh#812: stand in for `RestoNlp`, whose objective carries the
3137 // proximity term `ζ/2·‖D_R(x − x_R)‖²` and therefore has a `∇f`
3138 // that moves with the barrier parameter at fixed `x`. When set,
3139 // `eval_grad_f` adds `curr_mu` read from this handle — the same
3140 // coupling, in one line.
3141 mu_source: Option<IpoptDataHandle>,
3142 }
3143
3144 impl MockNlp {
3145 fn with_c(mut self, v: Number) -> Self {
3146 self.c_override = Some(v);
3147 self
3148 }
3149
3150 fn with_c_rhs(mut self, rhs: Option<Vec<Number>>) -> Self {
3151 self.c_rhs = rhs;
3152 self
3153 }
3154
3155 fn with_nan_grad(mut self) -> Self {
3156 self.nan_grad = true;
3157 self
3158 }
3159
3160 fn with_nan_jac_c(mut self) -> Self {
3161 self.nan_jac_c = true;
3162 self
3163 }
3164
3165 /// Every variable of the equality row fixed and substituted out, so
3166 /// the row reduces to the constant `0 = b` — what
3167 /// `IpoptCalculatedQuantities::row_noise_floor` calls a row no iterate
3168 /// can move.
3169 fn with_empty_jac_c(mut self) -> Self {
3170 self.empty_jac_c = true;
3171 self
3172 }
3173
3174 /// Re-declare the single `d` row as the box `[−mag, +mag]`, so every
3175 /// bound it has is of the chosen magnitude — the default fixture's
3176 /// lower bound of `1` would otherwise supply the magnitude by itself.
3177 /// `d(x) = x0 = 2` sits outside it, violating by `2 − mag`.
3178 fn with_d_box(mut self, mag: Number) -> Self {
3179 self.d_l = dvec(&[-mag]);
3180 self.d_u = dvec(&[mag]);
3181 self.pd_u = StdRc::new(ExpansionMatrix::new(ExpansionMatrixSpace::new(
3182 1,
3183 1,
3184 &[0],
3185 0,
3186 )));
3187 self
3188 }
3189
3190 fn with_scaling(
3191 mut self,
3192 obj_scale: Number,
3193 c_scale: Option<Vec<Number>>,
3194 d_scale: Option<Vec<Number>>,
3195 ) -> Self {
3196 self.obj_scale = obj_scale;
3197 self.c_scale = c_scale;
3198 self.d_scale = d_scale;
3199 self
3200 }
3201
3202 fn new() -> Self {
3203 // x_L holds finite lower bounds; here only x[0] has one (=0).
3204 let x_l = dvec(&[0.0]);
3205 // x_U holds finite upper bounds; here only x[1] has one (=5).
3206 let x_u = dvec(&[5.0]);
3207 // d has one finite lower bound (d ≥ 1) and no finite upper.
3208 let d_l = dvec(&[1.0]);
3209 let d_u = dvec(&[]);
3210
3211 let px_l_space = ExpansionMatrixSpace::new(2, 1, &[0], 0);
3212 let px_u_space = ExpansionMatrixSpace::new(2, 1, &[1], 0);
3213 let pd_l_space = ExpansionMatrixSpace::new(1, 1, &[0], 0);
3214 let pd_u_space = ExpansionMatrixSpace::new(1, 0, &[], 0);
3215
3216 Self {
3217 x_l,
3218 x_u,
3219 d_l,
3220 d_u,
3221 px_l: StdRc::new(ExpansionMatrix::new(px_l_space)),
3222 px_u: StdRc::new(ExpansionMatrix::new(px_u_space)),
3223 pd_l: StdRc::new(ExpansionMatrix::new(pd_l_space)),
3224 pd_u: StdRc::new(ExpansionMatrix::new(pd_u_space)),
3225 obj_scale: 1.0,
3226 c_scale: None,
3227 d_scale: None,
3228 nan_grad: false,
3229 nan_jac_c: false,
3230 empty_jac_c: false,
3231 c_rhs: None,
3232 c_override: None,
3233 mu_source: None,
3234 }
3235 }
3236 }
3237
3238 impl crate::ipopt_nlp::Nlp for MockNlp {
3239 fn n(&self) -> Index {
3240 2
3241 }
3242 fn m_eq(&self) -> Index {
3243 1
3244 }
3245 fn m_ineq(&self) -> Index {
3246 1
3247 }
3248 fn eval_f(&mut self, x: &dyn Vector) -> Number {
3249 // f(x) = x[0]^2 + x[1]^2
3250 let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
3251 xx.values()[0] * xx.values()[0] + xx.values()[1] * xx.values()[1]
3252 }
3253 fn eval_grad_f(&mut self, x: &dyn Vector, g: &mut dyn Vector) {
3254 // grad f = (2 x[0], 2 x[1])
3255 let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
3256 let gg = g.as_any_mut().downcast_mut::<DenseVector>().unwrap();
3257 gg.values_mut()[0] = 2.0 * xx.values()[0];
3258 gg.values_mut()[1] = 2.0 * xx.values()[1];
3259 if let Some(d) = self.mu_source.as_ref() {
3260 let mu = d.borrow().curr_mu;
3261 gg.values_mut()[0] += mu;
3262 gg.values_mut()[1] += mu;
3263 }
3264 if self.nan_grad {
3265 gg.values_mut()[0] = Number::NAN;
3266 }
3267 }
3268 fn eval_c(&mut self, x: &dyn Vector, c: &mut dyn Vector) {
3269 let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
3270 let cc = c.as_any_mut().downcast_mut::<DenseVector>().unwrap();
3271 cc.values_mut()[0] = match self.c_override {
3272 Some(v) => v,
3273 None => xx.values()[0] + xx.values()[1] - 1.0,
3274 };
3275 }
3276 fn eval_d(&mut self, x: &dyn Vector, d: &mut dyn Vector) {
3277 let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
3278 let dd = d.as_any_mut().downcast_mut::<DenseVector>().unwrap();
3279 dd.values_mut()[0] = xx.values()[0];
3280 }
3281 fn eval_jac_c(&mut self, _x: &dyn Vector) -> Rc<dyn Matrix> {
3282 if self.empty_jac_c {
3283 // No entries at all: the row carries no variable.
3284 let space = GenTMatrixSpace::new(1, 2, vec![], vec![]);
3285 let mut jac = GenTMatrix::new(space);
3286 jac.set_values(&[]);
3287 return StdRc::new(jac);
3288 }
3289 // c(x) = x0 + x1 - 1 → Jc = [1, 1] (1×2), nonzeros (1,1),(1,2).
3290 let space = GenTMatrixSpace::new(1, 2, vec![1, 1], vec![1, 2]);
3291 let mut jac = GenTMatrix::new(space);
3292 if self.nan_jac_c {
3293 jac.set_values(&[Number::NAN, 1.0]);
3294 } else {
3295 jac.set_values(&[1.0, 1.0]);
3296 }
3297 StdRc::new(jac)
3298 }
3299 fn eval_jac_d(&mut self, _x: &dyn Vector) -> Rc<dyn Matrix> {
3300 // d(x) = x0 → Jd = [1, 0] (1×2), single nonzero (1,1).
3301 let space = GenTMatrixSpace::new(1, 2, vec![1], vec![1]);
3302 let mut jac = GenTMatrix::new(space);
3303 jac.set_values(&[1.0]);
3304 StdRc::new(jac)
3305 }
3306 fn eval_h(
3307 &mut self,
3308 _x: &dyn Vector,
3309 _obj_factor: Number,
3310 _y_c: &dyn Vector,
3311 _y_d: &dyn Vector,
3312 ) -> Rc<dyn SymMatrix> {
3313 unimplemented!()
3314 }
3315 }
3316
3317 impl IpoptNlp for MockNlp {
3318 fn x_l(&self) -> &dyn Vector {
3319 &self.x_l
3320 }
3321 fn x_u(&self) -> &dyn Vector {
3322 &self.x_u
3323 }
3324 fn d_l(&self) -> &dyn Vector {
3325 &self.d_l
3326 }
3327 fn d_u(&self) -> &dyn Vector {
3328 &self.d_u
3329 }
3330 fn px_l(&self) -> Rc<dyn Matrix> {
3331 self.px_l.clone()
3332 }
3333 fn px_u(&self) -> Rc<dyn Matrix> {
3334 self.px_u.clone()
3335 }
3336 fn pd_l(&self) -> Rc<dyn Matrix> {
3337 self.pd_l.clone()
3338 }
3339 fn pd_u(&self) -> Rc<dyn Matrix> {
3340 self.pd_u.clone()
3341 }
3342 fn obj_scaling_factor(&self) -> Number {
3343 self.obj_scale
3344 }
3345 fn c_scale_vec(&self) -> Option<Vec<Number>> {
3346 self.c_scale.clone()
3347 }
3348 fn d_scale_vec(&self) -> Option<Vec<Number>> {
3349 self.d_scale.clone()
3350 }
3351 fn declared_c_rhs(&self) -> Option<Vec<Number>> {
3352 self.c_rhs.clone()
3353 }
3354 }
3355
3356 fn fixture() -> IpoptCalculatedQuantities {
3357 fixture_with(MockNlp::new())
3358 }
3359
3360 fn fixture_with(nlp: MockNlp) -> IpoptCalculatedQuantities {
3361 fixture_with_x(nlp, &[2.0, 3.0])
3362 }
3363
3364 fn fixture_with_x(nlp: MockNlp, x: &[Number]) -> IpoptCalculatedQuantities {
3365 let mut data = IpoptData::new();
3366 data.curr_mu = 0.1;
3367 // Iterate: x as given (2, 3 by default); s = (4); y_c = (1); y_d = (1);
3368 // z_L = (0.5) [bound on x[0]], z_U = (0.7) [bound on x[1]],
3369 // v_L = (0.3), v_U = ().
3370 let iv = IteratesVector::new(
3371 rcv(x),
3372 rcv(&[4.0]),
3373 rcv(&[1.0]),
3374 rcv(&[1.0]),
3375 rcv(&[0.5]),
3376 rcv(&[0.7]),
3377 rcv(&[0.3]),
3378 rcv(&[]),
3379 );
3380 data.set_curr(iv);
3381 let data_handle = StdRc::new(RefCell::new(data));
3382 let nlp: StdRc<RefCell<dyn IpoptNlp>> = StdRc::new(RefCell::new(nlp));
3383 let mut cq = IpoptCalculatedQuantities::new(data_handle, nlp);
3384 // Disable damping for clean unit-test expectations.
3385 cq.kappa_d = 0.0;
3386 cq
3387 }
3388
3389 /// gh#812 — `mu` is part of the `curr_grad_lag_x` cache key, and
3390 /// removing it is a silent trajectory regression.
3391 ///
3392 /// The five vector tags upstream keys this cache on (`x`, `y_c`,
3393 /// `y_d`, `z_L`, `z_U`) are a complete dependency set only while
3394 /// `∇f` is a function of `x` alone. It is not during restoration:
3395 /// `RestoNlp`'s proximity term scales with `ζ(mu)`, so its `∇f`
3396 /// moves while every one of those five tags stands still. A cache
3397 /// that misses `mu` then hands back the pre-update gradient — an
3398 /// answer that is self-consistent, converges, and reports the
3399 /// right objective, while taking a measurably worse route: drop
3400 /// `mu` from the key and `scripts/sweep-fixtures.sh` moves 8 of
3401 /// 154 fixture-legs, `pooling_rt2stp` 295 → 627 iterations on the
3402 /// lbfgs leg.
3403 ///
3404 /// MUTATION CHECK: delete `&[mu]` from the `get`/`add` pair in
3405 /// `curr_grad_lag_x` and this test fails — the second read returns
3406 /// the first read's vector unchanged.
3407 #[test]
3408 fn grad_lag_x_cache_reruns_when_only_mu_moves() {
3409 let mut data = IpoptData::new();
3410 data.curr_mu = 0.1;
3411 data.set_curr(IteratesVector::new(
3412 rcv(&[2.0, 3.0]),
3413 rcv(&[4.0]),
3414 rcv(&[1.0]),
3415 rcv(&[1.0]),
3416 rcv(&[0.5]),
3417 rcv(&[0.7]),
3418 rcv(&[0.3]),
3419 rcv(&[]),
3420 ));
3421 let data_handle = StdRc::new(RefCell::new(data));
3422 let mut nlp = MockNlp::new();
3423 nlp.mu_source = Some(StdRc::clone(&data_handle));
3424 let nlp: StdRc<RefCell<dyn IpoptNlp>> = StdRc::new(RefCell::new(nlp));
3425 let mut cq = IpoptCalculatedQuantities::new(StdRc::clone(&data_handle), nlp);
3426 cq.kappa_d = 0.0;
3427
3428 let before = dense_vals(&cq.curr_grad_lag_x());
3429 // A repeat read at unchanged `mu` must hit the cache and agree
3430 // exactly — otherwise the test below proves nothing about the
3431 // key and everything about a non-deterministic mock.
3432 assert_eq!(before, dense_vals(&cq.curr_grad_lag_x()));
3433
3434 // Move ONLY `mu`. Every iterate vector — and so every one of
3435 // the five tags upstream keys on — is untouched.
3436 data_handle.borrow_mut().curr_mu = 0.5;
3437 let after = dense_vals(&cq.curr_grad_lag_x());
3438
3439 // The mock adds `mu` to both gradient components, so the whole
3440 // Lagrangian gradient shifts by exactly the change in `mu`.
3441 assert_eq!(before.len(), after.len());
3442 for (b, a) in before.iter().zip(after.iter()) {
3443 assert!(
3444 (a - b - 0.4).abs() < 1e-12,
3445 "grad_lag_x did not follow mu: {b} -> {a}, expected +0.4"
3446 );
3447 }
3448 }
3449
3450 fn dense_vals(v: &Rc<dyn Vector>) -> Vec<Number> {
3451 v.as_any()
3452 .downcast_ref::<DenseVector>()
3453 .unwrap()
3454 .values()
3455 .to_vec()
3456 }
3457
3458 #[test]
3459 fn slack_x_lower_is_x0_minus_x_l() {
3460 // P_L^T x = [x[0]] = [2]; x_L = [0]; slack = 2 - 0 = 2.
3461 let cq = fixture();
3462 assert_eq!(dense_vals(&cq.curr_slack_x_l()), vec![2.0]);
3463 }
3464
3465 #[test]
3466 fn slack_x_upper_is_x_u_minus_x1() {
3467 // x_U = [5]; P_U^T x = [3]; slack = 5 - 3 = 2.
3468 let cq = fixture();
3469 assert_eq!(dense_vals(&cq.curr_slack_x_u()), vec![2.0]);
3470 }
3471
3472 #[test]
3473 fn slack_s_lower() {
3474 // d_L = [1]; P_L^T s = [4]; slack = 4 - 1 = 3.
3475 let cq = fixture();
3476 assert_eq!(dense_vals(&cq.curr_slack_s_l()), vec![3.0]);
3477 }
3478
3479 #[test]
3480 fn grad_f_is_twice_x() {
3481 let cq = fixture();
3482 assert_eq!(dense_vals(&cq.curr_grad_f()), vec![4.0, 6.0]);
3483 }
3484
3485 #[test]
3486 fn compl_x_l_is_slack_times_z() {
3487 // slack_x_L = [2]; z_L = [0.5]; compl = [1.0]
3488 let cq = fixture();
3489 assert_eq!(dense_vals(&cq.curr_compl_x_l()), vec![1.0]);
3490 }
3491
3492 #[test]
3493 fn relaxed_compl_x_l_subtracts_mu() {
3494 // compl = 1.0; mu = 0.1; relaxed = 0.9.
3495 let cq = fixture();
3496 assert!((dense_vals(&cq.curr_relaxed_compl_x_l())[0] - 0.9).abs() < 1e-15);
3497 }
3498
3499 #[test]
3500 fn sigma_x_routes_z_over_slack_through_p() {
3501 // P_L lifts (z_L/s_L) = (0.5/2 = 0.25) into x[0] slot.
3502 // P_U lifts (z_U/s_U) = (0.7/2 = 0.35) into x[1] slot.
3503 // sigma = (0.25, 0.35)
3504 let cq = fixture();
3505 let s = dense_vals(&cq.curr_sigma_x());
3506 assert!((s[0] - 0.25).abs() < 1e-15);
3507 assert!((s[1] - 0.35).abs() < 1e-15);
3508 }
3509
3510 /// gh#655 fixture. `x_L[0] = 0`, so the lower-bound block of `x` carries
3511 /// slack `x0` against multiplier `z_l`, at barrier parameter `mu`. The
3512 /// rest of the iterate is the default fixture's.
3513 fn fixture_at_mu(x0: Number, z_l: Number, mu: Number) -> IpoptCalculatedQuantities {
3514 let mut data = IpoptData::new();
3515 data.curr_mu = mu;
3516 let iv = IteratesVector::new(
3517 rcv(&[x0, 3.0]),
3518 rcv(&[4.0]),
3519 rcv(&[1.0]),
3520 rcv(&[1.0]),
3521 rcv(&[z_l]),
3522 rcv(&[0.7]),
3523 rcv(&[0.3]),
3524 rcv(&[]),
3525 );
3526 data.set_curr(iv);
3527 let data_handle = StdRc::new(RefCell::new(data));
3528 let nlp: StdRc<RefCell<dyn IpoptNlp>> = StdRc::new(RefCell::new(MockNlp::new()));
3529 let mut cq = IpoptCalculatedQuantities::new(data_handle, nlp);
3530 cq.kappa_d = 0.0;
3531 cq
3532 }
3533
3534 /// gh#655. The reported point, verbatim: `mu = 9.0909e-308`, a subnormal
3535 /// slack of `2.0202e-308` against `z = 4.5`, reached under a
3536 /// `SolveSucceeded`. The old floor never even fired here — `eps*mu` is
3537 /// `2.0e-323`, still a representable subnormal rather than the `0` that
3538 /// would have substituted `f64::MIN_POSITIVE`, so the slack cleared the
3539 /// threshold untouched and `4.5 / 2.0202e-308 = 2.2e308` overflowed.
3540 #[test]
3541 fn subnormal_slack_does_not_overflow_sigma() {
3542 let mu: Number = 9.0909e-308;
3543 let slack: Number = 2.0202e-308;
3544 let z: Number = 4.5;
3545 // The premise: the barrier-side threshold does not catch this point.
3546 assert!(f64::EPSILON * mu.min(1.0) > 0.0);
3547 assert!(slack > f64::EPSILON * mu.min(1.0));
3548 assert!(!(z / slack).is_finite());
3549
3550 let cq = fixture_at_mu(slack, z, mu);
3551 let s = dense_vals(&cq.curr_sigma_x());
3552 assert!(s[0].is_finite(), "Sigma_x[0] = {} is not finite", s[0]);
3553 // Floored at z/(MAX/4), so the ratio lands at MAX/4 at worst.
3554 assert!(s[0] <= f64::MAX / SIGMA_OVERFLOW_HEADROOM);
3555 // The slack itself was raised to the floor, not to f64::MIN_POSITIVE.
3556 assert!(dense_vals(&cq.curr_slack_x_l())[0] >= z / f64::MAX);
3557 // The untouched upper block still reads (5 - 3) against z_U = 0.7.
3558 assert!((s[1] - 0.35).abs() < 1e-15);
3559 }
3560
3561 /// gh#655, the half the trigger alone does not cover: a multiplier large
3562 /// enough that the bound-move cap (`slack_move*max(1,|bound|) + slack`)
3563 /// sits *below* the representability floor. Capping there would hand back
3564 /// a slack that still overflows, so the floor is re-applied after the cap.
3565 #[test]
3566 fn representability_floor_survives_the_bound_move_cap() {
3567 let cq = fixture_at_mu(1e-300, 1e300, 1e-8);
3568 // Premise: the cap really is the binding constraint here.
3569 assert!(cq.slack_move * 1.0 + 1e-300 < 1e300 / (f64::MAX / SIGMA_OVERFLOW_HEADROOM));
3570 let s = dense_vals(&cq.curr_sigma_x());
3571 assert!(s[0].is_finite(), "Sigma_x[0] = {} is not finite", s[0]);
3572 assert!(s[0] <= f64::MAX / SIGMA_OVERFLOW_HEADROOM);
3573 }
3574
3575 /// The floor is `z_max/4.5e307`; a slack twelve orders of magnitude above
3576 /// anything subnormal is nowhere near it, and must come back bit-identical
3577 /// — the correction is meant to be invisible off the overflow edge.
3578 #[test]
3579 fn ordinary_small_slack_is_left_exactly_alone() {
3580 let cq = fixture_at_mu(1e-20, 0.5, 1e-8);
3581 assert_eq!(dense_vals(&cq.curr_slack_x_l()), vec![1e-20]);
3582 assert_eq!(dense_vals(&cq.curr_sigma_x())[0], 0.5 / 1e-20);
3583 }
3584
3585 #[test]
3586 fn sigma_s_lower_only() {
3587 // P_L lifts (v_L/s_L) = (0.3/3 = 0.1).
3588 let cq = fixture();
3589 let s = dense_vals(&cq.curr_sigma_s());
3590 assert!((s[0] - 0.1).abs() < 1e-15);
3591 }
3592
3593 #[test]
3594 fn avrg_compl_averages_over_active_bounds() {
3595 // z_L·s_L + z_U·s_U + v_L·s_s_L + v_U·s_s_U
3596 // = 0.5*2 + 0.7*2 + 0.3*3 + 0
3597 // = 1 + 1.4 + 0.9 = 3.3
3598 // N = 1 + 1 + 1 + 0 = 3 → 1.1
3599 let cq = fixture();
3600 assert!((cq.curr_avrg_compl() - 1.1).abs() < 1e-15);
3601 }
3602
3603 #[test]
3604 fn complementarity_min_takes_min_over_active_pairs() {
3605 // compl entries: z_L·s_L=1.0, z_U·s_U=1.4, v_L·s_s_L=0.9.
3606 // v_U is empty (skipped). Min = 0.9.
3607 let cq = fixture();
3608 assert!((cq.curr_complementarity_min() - 0.9).abs() < 1e-15);
3609 }
3610
3611 #[test]
3612 fn centrality_measure_is_min_over_avrg() {
3613 // min/avrg = 0.9 / 1.1 ≈ 0.81818…
3614 let cq = fixture();
3615 let xi = cq.curr_centrality_measure();
3616 assert!((xi - 0.9 / 1.1).abs() < 1e-15);
3617 }
3618
3619 #[test]
3620 fn curr_f_evaluates_objective() {
3621 // f(x) = x[0]^2 + x[1]^2 at x = (2, 3) → 4 + 9 = 13.
3622 let cq = fixture();
3623 assert!((cq.curr_f() - 13.0).abs() < 1e-15);
3624 }
3625
3626 #[test]
3627 fn curr_barrier_obj_subtracts_mu_log_slacks() {
3628 // f = 13; slacks = (s_x_L=2, s_x_U=2, s_s_L=3, s_s_U=∅).
3629 // log_sum = ln 2 + ln 2 + ln 3 + 0 = 2 ln 2 + ln 3.
3630 // mu = 0.1 → phi = 13 - 0.1*(2 ln 2 + ln 3).
3631 let cq = fixture();
3632 let expected = 13.0 - 0.1 * (2.0 * 2.0_f64.ln() + 3.0_f64.ln());
3633 assert!((cq.curr_barrier_obj() - expected).abs() < 1e-13);
3634 }
3635
3636 /// pounce#476. `inf_pr_output = original` (upstream's default) must report
3637 /// the violation of the **original** rows, not of the internal slack
3638 /// reformulation. The fixture is exactly the case that made the two
3639 /// diverge on Mittelmann's `robot_a`: `d(x) = 2` against `d >= 1` — the
3640 /// original row is *satisfied*, so the original-NLP violation is 0 — while
3641 /// the slack has drifted to `s = 4`, so `|d − s| = 2` and the internal
3642 /// measure reads 2. Reporting the internal number made feasible iterates
3643 /// look badly infeasible (2.79e4 where Ipopt printed 0.00e+00).
3644 ///
3645 /// The equality row is genuinely violated (`c = 4`), and both measures
3646 /// must still see it — the fix must not swallow real infeasibility.
3647 #[test]
3648 fn original_nlp_violation_ignores_slack_drift_but_not_a_violated_row() {
3649 let cq = fixture();
3650 // Internal: max(|c|, |d − s|) = max(4, 2) = 4.
3651 assert_eq!(cq.curr_primal_infeasibility_max(), 4.0);
3652 // Original: max(|c|, dist(d, [d_l, d_u])) = max(4, 0) = 4 — the
3653 // equality violation survives, the slack drift does not contribute.
3654 assert_eq!(cq.curr_unscaled_nlp_constraint_violation_max(), 4.0);
3655 }
3656
3657 /// The other half of pounce#476: with the equality block satisfied, the
3658 /// two measures disagree outright — internal still sees the slack drift,
3659 /// original sees a feasible point.
3660 #[test]
3661 fn original_nlp_violation_is_zero_when_only_the_slack_has_drifted() {
3662 let cq = fixture_with(MockNlp::new().with_c(0.0));
3663 assert_eq!(cq.curr_primal_infeasibility_max(), 2.0);
3664 assert_eq!(cq.curr_unscaled_nlp_constraint_violation_max(), 0.0);
3665 }
3666
3667 /// …and the `inf_pr` column must actually be *wired* to the right one.
3668 /// The two tests above pass whichever accessor `OrigIterationOutput`
3669 /// picks, so without this the exact regression — a one-line match arm
3670 /// reaching for `curr_primal_infeasibility_max` — goes unnoticed.
3671 /// `InfPrTag::Original` is upstream's default, so this is what the column
3672 /// prints unless the user asks for `internal`.
3673 #[test]
3674 fn inf_pr_column_prints_the_original_violation_under_the_default_tag() {
3675 use crate::ipopt_data::IpoptData;
3676 use crate::output::orig::{InfPrTag, OrigIterationOutput};
3677 use crate::output::r#trait::IterationOutput;
3678
3679 // Slack drift only: internal reads 2, original reads 0.
3680 let cq: IpoptCqHandle = Rc::new(RefCell::new(fixture_with(MockNlp::new().with_c(0.0))));
3681 let data: IpoptDataHandle = Rc::new(RefCell::new(IpoptData::default()));
3682
3683 let field = |tag| {
3684 let mut out = OrigIterationOutput::new();
3685 out.inf_pr_output = tag;
3686 // Column 2 of the row is `inf_pr` (iter, objective, inf_pr, …).
3687 out.format_row(&data, &cq)
3688 .split_whitespace()
3689 .nth(2)
3690 .unwrap()
3691 .to_string()
3692 };
3693 assert_eq!(field(InfPrTag::Original), "0.00e+00");
3694 assert_eq!(field(InfPrTag::Internal), "2.00e+00");
3695 }
3696
3697 #[test]
3698 fn curr_constraint_violation_is_one_norm() {
3699 // c(x) = x[0]+x[1]-1 = 4 ⇒ |c| = 4.
3700 // d(x)=x[0]=2; s=4 ⇒ d-s = -2 ⇒ |d-s| = 2.
3701 // theta = 4 + 2 = 6.
3702 let cq = fixture();
3703 assert!((cq.curr_constraint_violation() - 6.0).abs() < 1e-13);
3704 }
3705
3706 /// gh#390. The fixture's equality row is `x0 + x1 == 1` at `x = (2, 3)`,
3707 /// so `c = 4`. Judged against a declared RHS of 2 that is a 200% violation
3708 /// — and it is 200% however the row is written, which is the point.
3709 #[test]
3710 fn relative_c_infeasibility_is_residual_over_declared_rhs() {
3711 let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![2.0])));
3712 assert_eq!(cq.relative_c_infeasibility_max(), 2.0);
3713 // The fixture's inequality row (`d = 2` against `d >= 1`) is satisfied,
3714 // so the combined measure is the equality block's verdict.
3715 assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
3716 assert_eq!(cq.curr_relative_primal_infeasibility_max(), 2.0);
3717 }
3718
3719 /// An NLP that does not track the pre-fold RHS (the trait default, e.g.
3720 /// the restoration NLP) must abstain rather than invent a magnitude.
3721 #[test]
3722 fn relative_c_infeasibility_abstains_without_declared_rhs() {
3723 let cq = fixture();
3724 assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3725 assert_eq!(cq.curr_relative_primal_infeasibility_max(), 0.0);
3726 }
3727
3728 /// A homogeneous row (`g(x) == 0`) has no declared magnitude and needs
3729 /// none — `s·g(x) == 0` is the same row at every `s`. Dividing by its zero
3730 /// RHS would report every float-noise residual as an infinite violation.
3731 #[test]
3732 fn relative_c_infeasibility_abstains_on_homogeneous_row() {
3733 let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![0.0])));
3734 assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3735 }
3736
3737 /// An unjudgeable row must not fabricate a relative verdict.
3738 #[test]
3739 fn relative_c_infeasibility_abstains_on_non_finite_rhs() {
3740 let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::INFINITY])));
3741 assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3742 let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::NAN])));
3743 assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3744 }
3745
3746 /// gh #446. "Homogeneous" has to be judged numerically. The fixture's row
3747 /// is `x0 + x1 == b` at `x = (2, 3)`, so its noise floor is
3748 /// `ROW_NOISE_KAPPA · eps · 1 · 3 ≈ 4.3e-14`: an RHS under that is
3749 /// rounding residue — a converter writing `2^-53` where the model says
3750 /// `0` — and the row must abstain exactly as a declared zero does. Above
3751 /// the floor the RHS is real data and is judged, however small.
3752 #[test]
3753 fn relative_c_infeasibility_abstains_on_rhs_below_the_row_noise_floor() {
3754 let floor = ROW_NOISE_KAPPA * Number::EPSILON * 3.0;
3755 // The QSCSD1 value: an RHS of exactly one machine epsilon.
3756 let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::EPSILON])));
3757 assert!(Number::EPSILON < floor);
3758 assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3759 // Just above the floor the row still carries a magnitude, and a
3760 // residual of 4 against it is judged on its merits.
3761 let rhs = 2.0 * floor;
3762 let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![rhs])));
3763 assert_eq!(cq.relative_c_infeasibility_max(), 4.0 / rhs);
3764 }
3765
3766 /// gh #446. Every variable of the row fixed and substituted out leaves
3767 /// `0 = b`, which no iterate can move — a statement about the model, for
3768 /// presolve to certify, not a residual to judge an iterate by. QPILOTNO's
3769 /// row 150 reduces to `0 = −2.22e-16` this way and pinned the relative
3770 /// measure at 100% for the entire run.
3771 #[test]
3772 fn relative_c_infeasibility_abstains_on_a_row_no_iterate_can_move() {
3773 let cq = fixture_with(
3774 MockNlp::new()
3775 .with_empty_jac_c()
3776 .with_c_rhs(Some(vec![Number::EPSILON])),
3777 );
3778 assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3779 // Not a licence to ignore a real one: the absolute `constr_viol_tol`
3780 // arm still sees the row, and it is what governs here.
3781 assert_eq!(cq.curr_primal_infeasibility_max(), 4.0);
3782 }
3783
3784 /// gh #446. The inequality block draws its magnitude from the declared
3785 /// bounds, and needs the same numeric reading of "zero" — QPILOTNO carries
3786 /// 43 bounds at `1e-17`–`1e-15`. `d(x) = x0 = 2` against an upper bound
3787 /// under the row's noise floor is 2e14 times its magnitude by the old
3788 /// arithmetic, and unjudgeable by the new.
3789 #[test]
3790 fn relative_d_infeasibility_abstains_on_bound_below_the_row_noise_floor() {
3791 let floor = ROW_NOISE_KAPPA * Number::EPSILON * 3.0;
3792 let cq = fixture_with(MockNlp::new().with_d_box(Number::EPSILON));
3793 assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
3794 // A bound above the floor is real, and `d = 2` violates it hugely.
3795 let bound = 2.0 * floor;
3796 let cq = fixture_with(MockNlp::new().with_d_box(bound));
3797 assert_eq!(cq.relative_d_infeasibility_max(), (2.0 - bound) / bound);
3798 }
3799
3800 /// The floor tracks `‖x‖_∞` **deliberately**, and this pins it. `x` is one
3801 /// vector produced by a linear solve with norm-wise backward error, so a
3802 /// large variable anywhere really does coarsen how finely every other
3803 /// component can be placed — and a declared magnitude finer than that is a
3804 /// target no iterate could hit. The per-row alternative, `Σ_j |a_ij x_j|`
3805 /// via `|J|·|x|`, looks more precise and measures the wrong thing (a row's
3806 /// *evaluation* error, not what limits its residual); it was implemented
3807 /// and it regressed QETAMACR, QSCORPIO and QPILOTNO of gh #446's 15. Re-run
3808 /// those three before changing this.
3809 #[test]
3810 fn row_noise_floor_tracks_the_iterate_norm() {
3811 // `d(x) = x0` against a declared box of ±1e-9.
3812 let bound = 1e-9;
3813 // At ‖x‖_∞ = 3 the floor is ~4.3e-14: the bound is real data, judged.
3814 let cq = fixture_with(MockNlp::new().with_d_box(bound));
3815 assert_eq!(cq.relative_d_infeasibility_max(), (2.0 - bound) / bound);
3816 // At ‖x‖_∞ = 1e8 the floor is ~1.4e-6 and the same bound is finer than
3817 // the iterate can be resolved, so the row abstains.
3818 let cq = fixture_with_x(MockNlp::new().with_d_box(bound), &[2.0, 1e8]);
3819 assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
3820 }
3821
3822 /// A row-count mismatch means the RHS does not describe this `c` block;
3823 /// pairing them up anyway would judge rows against other rows' magnitudes.
3824 #[test]
3825 fn relative_c_infeasibility_abstains_on_length_mismatch() {
3826 let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![2.0, 2.0])));
3827 assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
3828 }
3829
3830 #[test]
3831 fn grad_barrier_obj_x_subtracts_mu_inv_slack() {
3832 // grad_f = (4, 6).
3833 // P_L lifts -mu*(1/s_x_L) = -0.1*(1/2)=-0.05 into x[0].
3834 // P_U lifts +mu*(1/s_x_U) = +0.1*(1/2)=+0.05 into x[1].
3835 // result = (4 - 0.05, 6 + 0.05) = (3.95, 6.05).
3836 let cq = fixture();
3837 let g = dense_vals(&cq.curr_grad_barrier_obj_x());
3838 assert!((g[0] - 3.95).abs() < 1e-13);
3839 assert!((g[1] - 6.05).abs() < 1e-13);
3840 }
3841
3842 #[test]
3843 fn grad_lag_s_is_minus_y_d_minus_pl_v_l_plus_pu_v_u() {
3844 // tmp = P_U v_U = (zero-dim contrib) → 0
3845 // tmp -= P_L v_L → tmp = -[0.3]
3846 // tmp -= y_d = -[0.3] - [1.0] = [-1.3]
3847 let cq = fixture();
3848 assert!((dense_vals(&cq.curr_grad_lag_s())[0] + 1.3).abs() < 1e-15);
3849 }
3850
3851 fn zero_iv_like(iv: &IteratesVector) -> IteratesVector {
3852 // Materialize explicit zeros for every component so the
3853 // affine-step tests can compose direct-sum updates.
3854 IteratesVector::new(
3855 rcv(&vec![0.0; iv.x.dim() as usize]),
3856 rcv(&vec![0.0; iv.s.dim() as usize]),
3857 rcv(&vec![0.0; iv.y_c.dim() as usize]),
3858 rcv(&vec![0.0; iv.y_d.dim() as usize]),
3859 rcv(&vec![0.0; iv.z_l.dim() as usize]),
3860 rcv(&vec![0.0; iv.z_u.dim() as usize]),
3861 rcv(&vec![0.0; iv.v_l.dim() as usize]),
3862 rcv(&vec![0.0; iv.v_u.dim() as usize]),
3863 )
3864 }
3865
3866 #[test]
3867 fn aff_step_compl_avrg_with_zero_step_matches_curr_avrg_compl() {
3868 // Δ_aff = 0 ⇒ predicted compl ≡ current compl.
3869 // 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.
3870 // Total = 3.3; N = 3 (z_l + z_u + v_l, v_u empty); avrg = 1.1.
3871 let cq = fixture();
3872 let iv = cq.curr_iv();
3873 let zero = zero_iv_like(&iv);
3874 let m = cq.aff_step_compl_avrg(&zero, 1.0, 1.0);
3875 assert!((m - 1.1).abs() < 1e-13);
3876 assert!((cq.curr_avrg_compl() - 1.1).abs() < 1e-13);
3877 }
3878
3879 #[test]
3880 fn aff_step_compl_avrg_responds_to_primal_step() {
3881 // Δ_aff.x = (1, 0), α_pri = 1, others = 0.
3882 // s_X_L_aff = 2 + 1·1 = 3; s_X_U_aff = 2 (P_U^T·dx = 0); s_S_L_aff = 3.
3883 // (3·0.5 + 2·0.7 + 3·0.3) / 3 = (1.5 + 1.4 + 0.9) / 3 = 1.2667.
3884 let cq = fixture();
3885 let iv = cq.curr_iv();
3886 let mut z = zero_iv_like(&iv);
3887 z.x = rcv(&[1.0, 0.0]);
3888 let m = cq.aff_step_compl_avrg(&z, 1.0, 1.0);
3889 assert!((m - 1.2666666666666666).abs() < 1e-13);
3890 }
3891
3892 #[test]
3893 fn aff_step_alpha_primal_truncates_to_x_lower_bound() {
3894 // Δ_aff.x = (-3, 0); s_X_L = 2; tau = 1 ⇒ α_max = 2/3.
3895 let cq = fixture();
3896 let iv = cq.curr_iv();
3897 let mut z = zero_iv_like(&iv);
3898 z.x = rcv(&[-3.0, 0.0]);
3899 let a = cq.aff_step_alpha_primal_max(&z, 1.0);
3900 assert!((a - 2.0 / 3.0).abs() < 1e-13);
3901 }
3902
3903 #[test]
3904 fn aff_step_alpha_dual_truncates_to_z_lower_bound() {
3905 // Δ_aff.z_L = (-1); z_L = 0.5; tau = 1 ⇒ α_max = 0.5.
3906 let cq = fixture();
3907 let iv = cq.curr_iv();
3908 let mut z = zero_iv_like(&iv);
3909 z.z_l = rcv(&[-1.0]);
3910 let a = cq.aff_step_alpha_dual_max(&z, 1.0);
3911 assert!((a - 0.5).abs() < 1e-13);
3912 }
3913
3914 #[test]
3915 fn grad_barr_t_delta_dots_barrier_grads_with_step() {
3916 // ∇_x φ = (3.95, 6.05); ∇_s φ = (-mu/s_s_L) = -0.1/3 ≈ -0.03333…
3917 // δx = (1, 2); δs = (3): result = 3.95·1 + 6.05·2 + (-0.0333…)·3
3918 // = 3.95 + 12.10 − 0.1 = 15.95.
3919 let cq = fixture();
3920 let dx = dvec(&[1.0, 2.0]);
3921 let ds = dvec(&[3.0]);
3922 let r = cq.curr_grad_barr_t_delta(&dx, &ds);
3923 let expected = 3.95 + 12.10 - 0.1;
3924 assert!((r - expected).abs() < 1e-13, "r = {r}");
3925 }
3926
3927 #[test]
3928 fn dwd_with_no_w_collapses_to_sigma_quadratic() {
3929 // W is None in the fixture (no Hessian seeded), perts default to 0.
3930 // σ_x = (0.25, 0.35); σ_s = (0.1).
3931 // δx = (2, -1); δs = (3) ⇒ dWd = 0.25·4 + 0.35·1 + 0.1·9
3932 // = 1.00 + 0.35 + 0.90 = 2.25.
3933 let cq = fixture();
3934 let dx = dvec(&[2.0, -1.0]);
3935 let ds = dvec(&[3.0]);
3936 let r = cq.curr_dwd(&dx, &ds);
3937 assert!((r - 2.25).abs() < 1e-13, "r = {r}");
3938 }
3939
3940 #[test]
3941 fn dwd_includes_pd_perturbations() {
3942 // Without perts: dWd = 0.25·4 + 0.35·1 + 0.1·9 = 2.25.
3943 // δ_pert_x = 0.5, δ_pert_s = 0.25:
3944 // add δ_pert_x · ‖δx‖² + δ_pert_s · ‖δs‖²
3945 // = 0.5·(4+1) + 0.25·9 = 2.5 + 2.25 = 4.75.
3946 // Total = 7.00.
3947 let cq = fixture();
3948 {
3949 let mut d = cq.data.borrow_mut();
3950 d.perturbations.delta_x = 0.5;
3951 d.perturbations.delta_s = 0.25;
3952 }
3953 let dx = dvec(&[2.0, -1.0]);
3954 let ds = dvec(&[3.0]);
3955 let r = cq.curr_dwd(&dx, &ds);
3956 assert!((r - 7.00).abs() < 1e-13, "r = {r}");
3957 }
3958
3959 // ---- #292: NaN gradient / Jacobian must not launder to a finite KKT error
3960
3961 #[test]
3962 fn nlp_error_is_finite_for_a_finite_iterate() {
3963 // Baseline: the well-formed fixture produces a finite, positive KKT
3964 // error (this iterate is not a KKT point). The finiteness guard added
3965 // for #292 must not perturb this normal path.
3966 let cq = fixture();
3967 let err = cq.curr_nlp_error();
3968 assert!(err.is_finite() && err > 0.0, "err = {err}");
3969 }
3970
3971 #[test]
3972 fn nlp_error_is_non_finite_when_gradient_has_nan() {
3973 // A NaN gradient component reaches ∇_x L, whose max-norm (`amax`)
3974 // silently drops NaN and would launder the dual infeasibility to a
3975 // finite value → bogus `Solve_Succeeded` (#292). `curr_nlp_error` must
3976 // instead surface a non-finite error so the caller's
3977 // `!nlp_err.is_finite()` guard fires `Invalid_Number_Detected`.
3978 let cq = fixture_with(MockNlp::new().with_nan_grad());
3979 assert!(
3980 !cq.curr_nlp_error().is_finite(),
3981 "NaN gradient laundered to finite KKT error: {}",
3982 cq.curr_nlp_error()
3983 );
3984 }
3985
3986 #[test]
3987 fn nlp_error_is_non_finite_when_constraint_jacobian_has_nan() {
3988 // A NaN in the constraint Jacobian enters ∇_x L through the Jᵀy term
3989 // and is likewise laundered by `amax` on the fixture's nonzero
3990 // multipliers. Must read as a non-finite KKT error, not `Optimal`.
3991 let cq = fixture_with(MockNlp::new().with_nan_jac_c());
3992 assert!(
3993 !cq.curr_nlp_error().is_finite(),
3994 "NaN constraint Jacobian laundered to finite KKT error: {}",
3995 cq.curr_nlp_error()
3996 );
3997 }
3998
3999 // ---- Unscaled (user-space) KKT residuals — pounce#173 -------------
4000
4001 #[test]
4002 fn unscaled_dual_inf_is_scaled_over_df() {
4003 // df = 2: every Lagrangian-gradient term carries the objective
4004 // factor, so the unscaled dual infeasibility is the scaled one
4005 // divided by df.
4006 let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
4007 let scaled = cq.curr_dual_infeasibility_max();
4008 let unscaled = cq.curr_unscaled_dual_infeasibility_max();
4009 assert!(scaled > 0.0, "fixture should have nonzero dual inf");
4010 assert!(
4011 (unscaled - scaled / 2.0).abs() < 1e-12,
4012 "unscaled {unscaled} != scaled/df {}",
4013 scaled / 2.0
4014 );
4015 }
4016
4017 /// gh #532. The dual *scale* is the largest single term `∇L` is assembled
4018 /// from, so the strict gate can ask what fraction of those terms failed to
4019 /// cancel instead of comparing a residual against an absolute constant.
4020 #[test]
4021 fn dual_inf_scale_is_the_largest_lagrangian_term() {
4022 // Fixture at x = (2, 3): ∇f = (4, 6); J_cᵀ y_c = (1, 1); J_dᵀ y_d =
4023 // (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
4024 // empty. The largest is ‖∇f‖_∞ = 6.
4025 let cq = fixture();
4026 assert_eq!(cq.curr_dual_infeasibility_scale_max(), 6.0);
4027 // No scaling → the unscaled accessor is the identity, as for every
4028 // other residual on the common path.
4029 assert_eq!(
4030 cq.curr_unscaled_dual_infeasibility_scale_max(),
4031 cq.curr_dual_infeasibility_scale_max()
4032 );
4033 }
4034
4035 /// The scale unscales exactly as the residual it is the scale of: every
4036 /// term of the scaled Lagrangian gradient carries `df`, so both are the
4037 /// scaled value over `|df|`. If the two ever divided differently the ratio
4038 /// the strict gate tests would silently pick up a factor of `df`.
4039 #[test]
4040 fn unscaled_dual_inf_scale_is_scaled_over_df() {
4041 let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
4042 assert_eq!(cq.curr_unscaled_dual_infeasibility_scale_max(), 3.0);
4043 // A negative factor is the documented way to pose a maximization; a
4044 // max-norm has no business coming back negative (the sign trap that
4045 // defeated the unscaled dual residual gate).
4046 let neg = fixture_with(MockNlp::new().with_scaling(-2.0, None, None));
4047 assert_eq!(neg.curr_unscaled_dual_infeasibility_scale_max(), 3.0);
4048 }
4049
4050 #[test]
4051 fn unscaled_residuals_are_identity_without_scaling() {
4052 // df = 1, no row scaling → unscaled accessors return exactly the
4053 // scaled values (the common no-scaling path).
4054 let cq = fixture();
4055 assert_eq!(
4056 cq.curr_unscaled_dual_infeasibility_max(),
4057 cq.curr_dual_infeasibility_max()
4058 );
4059 assert_eq!(
4060 cq.curr_unscaled_complementarity_max(),
4061 cq.curr_complementarity_max()
4062 );
4063 assert_eq!(
4064 cq.curr_unscaled_primal_infeasibility_max(),
4065 cq.curr_primal_infeasibility_max()
4066 );
4067 }
4068
4069 #[test]
4070 fn unscaled_compl_is_scaled_over_df() {
4071 let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
4072 let scaled = cq.curr_complementarity_max();
4073 let unscaled = cq.curr_unscaled_complementarity_max();
4074 assert!(scaled > 0.0);
4075 assert!((unscaled - scaled / 2.0).abs() < 1e-12);
4076 }
4077
4078 #[test]
4079 fn unscaled_primal_divides_each_row_by_its_factor() {
4080 // Fixture residuals: c = x0+x1-1 = 4; d-s = x0 - s = 2 - 4 = -2.
4081 // Scaled max-norm primal = max(|4|, |-2|) = 4.
4082 // With dc = [4], dd = [2]: unscaled = max(|4/4|, |-2/2|) = 1.
4083 let cq = fixture_with(MockNlp::new().with_scaling(1.0, Some(vec![4.0]), Some(vec![2.0])));
4084 assert!((cq.curr_primal_infeasibility_max() - 4.0).abs() < 1e-12);
4085 assert!(
4086 (cq.curr_unscaled_primal_infeasibility_max() - 1.0).abs() < 1e-12,
4087 "got {}",
4088 cq.curr_unscaled_primal_infeasibility_max()
4089 );
4090 }
4091
4092 #[test]
4093 fn unscaled_nlp_error_is_max_of_unscaled_components() {
4094 let cq = fixture_with(MockNlp::new().with_scaling(2.0, Some(vec![4.0]), Some(vec![2.0])));
4095 let expected = cq
4096 .curr_unscaled_dual_infeasibility_max()
4097 .max(cq.curr_unscaled_primal_infeasibility_max())
4098 .max(cq.curr_unscaled_complementarity_max());
4099 assert_eq!(cq.curr_unscaled_nlp_error(), expected);
4100 }
4101
4102 /// gh #528. A component at or below its own floor drops out; everything
4103 /// above it is counted in full, not net of the floor — the question the
4104 /// floor answers is whether the row says anything at all.
4105 #[test]
4106 fn amax_above_floor_drops_only_sub_floor_components() {
4107 let v = dvec(&[1e-9, -3e-7, 5e-3]);
4108 assert_eq!(amax_above_floor(&v, &[1e-8, 1e-8, 1e-8]), 5e-3);
4109 // The largest component is the only one under its floor: the max comes
4110 // from what remains, not from the vector's own `amax`.
4111 assert_eq!(amax_above_floor(&v, &[1e-8, 1e-8, 1.0]), 3e-7);
4112 // Everything silenced.
4113 assert_eq!(amax_above_floor(&v, &[1.0, 1.0, 1.0]), 0.0);
4114 // Exactly at the floor is silenced (`>`, not `>=`).
4115 assert_eq!(amax_above_floor(&dvec(&[1e-8]), &[1e-8]), 0.0);
4116 }
4117
4118 /// A floor that cannot be attributed component-wise must not silence
4119 /// anything: over-reporting the residual is the safe direction.
4120 #[test]
4121 fn amax_above_floor_falls_back_on_a_length_mismatch() {
4122 let v = dvec(&[1e-9, -3e-7]);
4123 assert_eq!(amax_above_floor(&v, &[1.0]), 3e-7);
4124 assert_eq!(amax_above_floor(&v, &[]), 3e-7);
4125 }
4126
4127 /// The floored aggregate is never larger than the raw one, and on a
4128 /// fixture whose residuals (`c = 4`, `d − s = −2`) are nowhere near any
4129 /// resolution limit the two are identical — the common path is untouched.
4130 #[test]
4131 fn nlp_error_above_primal_noise_matches_on_ordinary_residuals() {
4132 let cq = fixture_with(MockNlp::new());
4133 assert_eq!(
4134 cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4135 cq.curr_primal_infeasibility_max()
4136 );
4137 assert_eq!(
4138 cq.curr_nlp_error_above_primal_noise(ROW_NOISE_KAPPA),
4139 cq.curr_nlp_error()
4140 );
4141 }
4142
4143 /// gh #528, **equality block**, through the real accessor rather than a
4144 /// hand-supplied floor. The integration LP is all-inequality (`g_u = 2e19`,
4145 /// so `c.dim() == 0`), so this is the only cover the `declared_c_rhs()`
4146 /// branch has.
4147 ///
4148 /// `x = (4, 3)` puts `d = x0 = 4` on top of `s = 4`, so the inequality
4149 /// block's residual is an exact `0` and what the accessor returns is the
4150 /// `c` block alone.
4151 #[test]
4152 fn a_sub_quantum_equality_residual_is_silenced_and_a_coarser_one_is_not() {
4153 let rhs = 1e8;
4154 let floor = ROW_NOISE_KAPPA * Number::EPSILON * rhs;
4155 let cq_for = |c: Number| {
4156 fixture_with_x(
4157 MockNlp::new().with_c_rhs(Some(vec![rhs])).with_c(c),
4158 &[4.0, 3.0],
4159 )
4160 };
4161
4162 // Under the quantum of `g(x) − b` at `|b| = 1e8`: no iterate could
4163 // have placed the residual here, so the row says nothing.
4164 let cq = cq_for(floor * 0.5);
4165 assert_eq!(cq.curr_primal_infeasibility_max(), floor * 0.5);
4166 assert_eq!(
4167 cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4168 0.0
4169 );
4170
4171 // Above it: counted in full, not net of the floor.
4172 let cq = cq_for(floor * 2.0);
4173 assert_eq!(
4174 cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4175 floor * 2.0
4176 );
4177
4178 // The placement floor alone would not have silenced anything here —
4179 // at ‖x‖_∞ = 4 through a row of `max_j |∂c/∂x_j| = 1` it is ~5.7e-14,
4180 // eight decades under the formation floor. The `c` branch's own
4181 // magnitude is what does the work.
4182 let cq = fixture_with_x(MockNlp::new().with_c(floor * 0.5), &[4.0, 3.0]);
4183 assert_eq!(
4184 cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4185 floor * 0.5
4186 );
4187 }
4188
4189 /// The `primal_noise_floor_kappa = 0` escape hatch: every floor collapses
4190 /// to `0`, so every residual is counted and the floored aggregate is the
4191 /// raw one — the strict gate is bit-for-bit upstream Ipopt's again. Pinned
4192 /// on a fixture where the floor otherwise *does* silence the row, so this
4193 /// cannot pass by the two agreeing anyway.
4194 #[test]
4195 fn a_zero_kappa_switches_the_floor_off_completely() {
4196 let rhs = 1e8;
4197 let residual = ROW_NOISE_KAPPA * Number::EPSILON * rhs * 0.5;
4198 let cq = fixture_with_x(
4199 MockNlp::new().with_c_rhs(Some(vec![rhs])).with_c(residual),
4200 &[4.0, 3.0],
4201 );
4202 // The floor is live at the default kappa …
4203 assert_eq!(
4204 cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4205 0.0
4206 );
4207 // … and gone at zero.
4208 assert_eq!(
4209 cq.curr_primal_infeasibility_above_noise(0.0),
4210 cq.curr_primal_infeasibility_max()
4211 );
4212 assert_eq!(
4213 cq.curr_nlp_error_above_primal_noise(0.0),
4214 cq.curr_nlp_error()
4215 );
4216 }
4217
4218 /// The equality floor rides the row scaling, because both sides of the
4219 /// comparison do: `declared_c_rhs()` reapplies `c_scale` (pinned by
4220 /// `declared_c_rhs_carries_the_row_scaling` in `orig_ipopt_nlp.rs`) and
4221 /// `curr_c()` is the scaled residual `dc · (g(x) − b)`. Scaling a row by
4222 /// `k` scales its residual and its floor together, so the verdict is
4223 /// invariant — which is what makes it legitimate to compare a floor built
4224 /// from the declared RHS against `curr_c()` at all.
4225 #[test]
4226 fn the_equality_floor_rides_the_row_scaling() {
4227 let rhs = 1e8;
4228 let quantum = ROW_NOISE_KAPPA * Number::EPSILON * rhs;
4229 for k in [1.0, 4.0, 0.25] {
4230 let cq_for = |c: Number| {
4231 fixture_with_x(
4232 MockNlp::new()
4233 .with_scaling(1.0, Some(vec![k]), None)
4234 .with_c_rhs(Some(vec![k * rhs]))
4235 .with_c(k * c),
4236 &[4.0, 3.0],
4237 )
4238 };
4239 assert_eq!(
4240 cq_for(quantum * 0.5).curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4241 0.0,
4242 "sub-quantum residual must stay silenced at row scaling {k}",
4243 );
4244 assert_eq!(
4245 cq_for(quantum * 2.0).curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
4246 k * quantum * 2.0,
4247 "above-quantum residual must survive at row scaling {k}",
4248 );
4249 }
4250 }
4251}