1use crate::ipopt_cq::IpoptCqHandle;
24use crate::ipopt_data::IpoptDataHandle;
25use crate::ipopt_nlp::IpoptNlp;
26use crate::iterates_vector::IteratesVector;
27use crate::kkt::pd_search_dir_calc::PdSearchDirCalc;
28use crate::mu::oracle::r#trait::MuOracle;
29use pounce_common::types::Number;
30use pounce_linalg::Vector;
31use std::cell::RefCell;
32use std::rc::Rc;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum NormType {
36 OneNorm,
37 TwoNormSquared,
40 TwoNorm,
41 MaxNorm,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum CentralityType {
46 None,
47 LogCenter,
48 ReciprocalCenter,
49 CubedReciprocalCenter,
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum BalancingTermType {
54 None,
55 CubicTerm,
56}
57
58pub struct QualityFunctionMuOracle {
59 pub norm_type: NormType,
60 pub centrality_type: CentralityType,
61 pub balancing_term: BalancingTermType,
62 pub max_section_steps: i32,
63 pub section_sigma_tol: Number,
64 pub section_qf_tol: Number,
65 pub sigma_max: Number,
66 pub sigma_min: Number,
67 pub mu_min: Number,
68 pub mu_max: Number,
69}
70
71impl Default for QualityFunctionMuOracle {
72 fn default() -> Self {
73 Self {
75 norm_type: NormType::TwoNormSquared,
76 centrality_type: CentralityType::None,
77 balancing_term: BalancingTermType::None,
78 max_section_steps: 8,
79 section_sigma_tol: 1e-2,
80 section_qf_tol: 0.0,
81 sigma_max: 100.0,
82 sigma_min: 1e-6,
91 mu_min: 1e-11,
92 mu_max: 1e5,
93 }
94 }
95}
96
97impl QualityFunctionMuOracle {
98 pub fn new() -> Self {
99 Self::default()
100 }
101
102 #[allow(clippy::too_many_lines)]
113 pub fn calculate_mu_with_predictor_centering(
114 &mut self,
115 data: &IpoptDataHandle,
116 cq: &IpoptCqHandle,
117 nlp: &Rc<RefCell<dyn IpoptNlp>>,
118 pd_search_dir: &mut PdSearchDirCalc,
119 ) -> Option<Number> {
120 if !pd_search_dir.compute_affine_step(data, cq, nlp) {
121 return None;
122 }
123 if !pd_search_dir.compute_centering_step(data, cq, nlp) {
124 return None;
125 }
126
127 let delta_aff: IteratesVector = data.borrow().delta_aff.clone()?;
128 let delta_cen: IteratesVector = data.borrow().delta_cen.clone()?;
129
130 let nlp_ref = nlp.borrow();
134 let cq_ref = cq.borrow();
135 let curr_iv = cq_ref.curr_iv();
136 let curr_slack_x_l = cq_ref.curr_slack_x_l();
137 let curr_slack_x_u = cq_ref.curr_slack_x_u();
138 let curr_slack_s_l = cq_ref.curr_slack_s_l();
139 let curr_slack_s_u = cq_ref.curr_slack_s_u();
140 let avrg_compl = cq_ref.curr_avrg_compl();
141
142 let project = |sign_l_x: Number,
143 sign_u_x: Number,
144 step_x: &dyn Vector,
145 step_s: &dyn Vector|
146 -> [Rc<dyn Vector>; 4] {
147 let mut x_l = curr_slack_x_l.make_new();
148 nlp_ref
149 .px_l()
150 .trans_mult_vector(sign_l_x, step_x, 0.0, &mut *x_l);
151 let mut x_u = curr_slack_x_u.make_new();
152 nlp_ref
153 .px_u()
154 .trans_mult_vector(sign_u_x, step_x, 0.0, &mut *x_u);
155 let mut s_l = curr_slack_s_l.make_new();
156 nlp_ref
157 .pd_l()
158 .trans_mult_vector(sign_l_x, step_s, 0.0, &mut *s_l);
159 let mut s_u = curr_slack_s_u.make_new();
160 nlp_ref
161 .pd_u()
162 .trans_mult_vector(sign_u_x, step_s, 0.0, &mut *s_u);
163 [Rc::from(x_l), Rc::from(x_u), Rc::from(s_l), Rc::from(s_u)]
164 };
165
166 let [step_aff_x_l, step_aff_x_u, step_aff_s_l, step_aff_s_u] =
167 project(1.0, -1.0, &*delta_aff.x, &*delta_aff.s);
168 let [step_cen_x_l, step_cen_x_u, step_cen_s_l, step_cen_s_u] =
169 project(1.0, -1.0, &*delta_cen.x, &*delta_cen.s);
170
171 let step_aff_z_l = delta_aff.z_l.clone();
174 let step_aff_z_u = delta_aff.z_u.clone();
175 let step_aff_v_l = delta_aff.v_l.clone();
176 let step_aff_v_u = delta_aff.v_u.clone();
177 let step_cen_z_l = delta_cen.z_l.clone();
178 let step_cen_z_u = delta_cen.z_u.clone();
179 let step_cen_v_l = delta_cen.v_l.clone();
180 let step_cen_v_u = delta_cen.v_u.clone();
181
182 drop(nlp_ref);
186
187 let grad_lag_x = cq_ref.curr_grad_lag_x();
191 let grad_lag_s = cq_ref.curr_grad_lag_s();
192 let c = cq_ref.curr_c();
193 let d_minus_s = cq_ref.curr_d_minus_s();
194 let dual_aggr = match self.norm_type {
195 NormType::OneNorm => grad_lag_x.asum() + grad_lag_s.asum(),
196 NormType::TwoNormSquared => {
197 let nx = grad_lag_x.nrm2();
198 let ns = grad_lag_s.nrm2();
199 nx * nx + ns * ns
200 }
201 NormType::TwoNorm => {
202 let nx = grad_lag_x.nrm2();
203 let ns = grad_lag_s.nrm2();
204 (nx * nx + ns * ns).sqrt()
205 }
206 NormType::MaxNorm => grad_lag_x.amax().max(grad_lag_s.amax()),
207 };
208 let primal_aggr = match self.norm_type {
209 NormType::OneNorm => c.asum() + d_minus_s.asum(),
210 NormType::TwoNormSquared => {
211 let nc = c.nrm2();
212 let nd = d_minus_s.nrm2();
213 nc * nc + nd * nd
214 }
215 NormType::TwoNorm => {
216 let nc = c.nrm2();
217 let nd = d_minus_s.nrm2();
218 (nc * nc + nd * nd).sqrt()
219 }
220 NormType::MaxNorm => c.amax().max(d_minus_s.amax()),
221 };
222
223 let n_dual = curr_iv.x.dim() + curr_iv.s.dim();
224 let n_pri = curr_iv.y_c.dim() + curr_iv.y_d.dim();
225 let n_comp = curr_iv.z_l.dim() + curr_iv.z_u.dim() + curr_iv.v_l.dim() + curr_iv.v_u.dim();
226 let tau = data.borrow().curr_tau;
227
228 let curr_z_l = curr_iv.z_l.clone();
229 let curr_z_u = curr_iv.z_u.clone();
230 let curr_v_l = curr_iv.v_l.clone();
231 let curr_v_u = curr_iv.v_u.clone();
232
233 drop(cq_ref);
234
235 let norm_type = self.norm_type;
236 let centrality = self.centrality_type;
237 let balancing = self.balancing_term;
238
239 let mut eval_q = |sigma: Number| -> Number {
243 let combine = |aff: &Rc<dyn Vector>, cen: &Rc<dyn Vector>| -> Box<dyn Vector> {
245 let mut out = aff.make_new();
246 out.set(0.0);
247 out.add_two_vectors(1.0, &**aff, sigma, &**cen, 0.0);
248 out
249 };
250 let stp_x_l = combine(&step_aff_x_l, &step_cen_x_l);
251 let stp_x_u = combine(&step_aff_x_u, &step_cen_x_u);
252 let stp_s_l = combine(&step_aff_s_l, &step_cen_s_l);
253 let stp_s_u = combine(&step_aff_s_u, &step_cen_s_u);
254 let stp_z_l = combine(&step_aff_z_l, &step_cen_z_l);
255 let stp_z_u = combine(&step_aff_z_u, &step_cen_z_u);
256 let stp_v_l = combine(&step_aff_v_l, &step_cen_v_l);
257 let stp_v_u = combine(&step_aff_v_u, &step_cen_v_u);
258
259 let alpha_pri = curr_slack_x_l
261 .frac_to_bound(&*stp_x_l, tau)
262 .min(curr_slack_x_u.frac_to_bound(&*stp_x_u, tau))
263 .min(curr_slack_s_l.frac_to_bound(&*stp_s_l, tau))
264 .min(curr_slack_s_u.frac_to_bound(&*stp_s_u, tau));
265 let alpha_du = curr_z_l
266 .frac_to_bound(&*stp_z_l, tau)
267 .min(curr_z_u.frac_to_bound(&*stp_z_u, tau))
268 .min(curr_v_l.frac_to_bound(&*stp_v_l, tau))
269 .min(curr_v_u.frac_to_bound(&*stp_v_u, tau));
270
271 let mut trial_s_x_l = curr_slack_x_l.make_new();
273 trial_s_x_l.set(0.0);
274 trial_s_x_l.add_two_vectors(1.0, &*curr_slack_x_l, alpha_pri, &*stp_x_l, 0.0);
275 let mut trial_s_x_u = curr_slack_x_u.make_new();
276 trial_s_x_u.set(0.0);
277 trial_s_x_u.add_two_vectors(1.0, &*curr_slack_x_u, alpha_pri, &*stp_x_u, 0.0);
278 let mut trial_s_s_l = curr_slack_s_l.make_new();
279 trial_s_s_l.set(0.0);
280 trial_s_s_l.add_two_vectors(1.0, &*curr_slack_s_l, alpha_pri, &*stp_s_l, 0.0);
281 let mut trial_s_s_u = curr_slack_s_u.make_new();
282 trial_s_s_u.set(0.0);
283 trial_s_s_u.add_two_vectors(1.0, &*curr_slack_s_u, alpha_pri, &*stp_s_u, 0.0);
284
285 let mut trial_z_l = curr_z_l.make_new();
286 trial_z_l.set(0.0);
287 trial_z_l.add_two_vectors(1.0, &*curr_z_l, alpha_du, &*stp_z_l, 0.0);
288 let mut trial_z_u = curr_z_u.make_new();
289 trial_z_u.set(0.0);
290 trial_z_u.add_two_vectors(1.0, &*curr_z_u, alpha_du, &*stp_z_u, 0.0);
291 let mut trial_v_l = curr_v_l.make_new();
292 trial_v_l.set(0.0);
293 trial_v_l.add_two_vectors(1.0, &*curr_v_l, alpha_du, &*stp_v_l, 0.0);
294 let mut trial_v_u = curr_v_u.make_new();
295 trial_v_u.set(0.0);
296 trial_v_u.add_two_vectors(1.0, &*curr_v_u, alpha_du, &*stp_v_u, 0.0);
297
298 trial_s_x_l.element_wise_multiply(&*trial_z_l);
300 trial_s_x_u.element_wise_multiply(&*trial_z_u);
301 trial_s_s_l.element_wise_multiply(&*trial_v_l);
302 trial_s_s_u.element_wise_multiply(&*trial_v_u);
303
304 let compl_aggr = match norm_type {
305 NormType::OneNorm => {
306 trial_s_x_l.asum()
307 + trial_s_x_u.asum()
308 + trial_s_s_l.asum()
309 + trial_s_s_u.asum()
310 }
311 NormType::TwoNormSquared => {
312 let a = trial_s_x_l.nrm2();
313 let b = trial_s_x_u.nrm2();
314 let c = trial_s_s_l.nrm2();
315 let d = trial_s_s_u.nrm2();
316 a * a + b * b + c * c + d * d
317 }
318 NormType::TwoNorm => {
319 let a = trial_s_x_l.nrm2();
320 let b = trial_s_x_u.nrm2();
321 let c = trial_s_s_l.nrm2();
322 let d = trial_s_s_u.nrm2();
323 (a * a + b * b + c * c + d * d).sqrt()
324 }
325 NormType::MaxNorm => trial_s_x_l
326 .amax()
327 .max(trial_s_x_u.amax())
328 .max(trial_s_s_l.amax())
329 .max(trial_s_s_u.amax()),
330 };
331
332 let xi = if matches!(centrality, CentralityType::None) {
333 1.0
334 } else {
335 let total = trial_s_x_l.asum()
339 + trial_s_x_u.asum()
340 + trial_s_s_l.asum()
341 + trial_s_s_u.asum();
342 let avg = if n_comp > 0 {
343 total / n_comp as Number
344 } else {
345 1.0
346 };
347 let mn = trial_s_x_l
348 .min()
349 .min(trial_s_x_u.min())
350 .min(trial_s_s_l.min())
351 .min(trial_s_s_u.min());
352 if avg > 0.0 { mn / avg } else { 1.0 }
353 };
354
355 let aggr = QualityFunctionAggregates {
356 dual_aggr,
357 primal_aggr,
358 compl_aggr,
359 n_dual,
360 n_pri,
361 n_comp,
362 };
363
364 if std::env::var("POUNCE_DBG_QF_AGGR").is_ok() {
365 tracing::debug!(target: "pounce::mu",
366 "[QF_AGGR] σ={:.6e} α_pri={:.6e} α_du={:.6e} xi={:.6e} dual_aggr={:.6e} primal_aggr={:.6e} compl_aggr={:.6e} n_dual={} n_pri={} n_comp={}",
367 sigma, alpha_pri, alpha_du, xi,
368 dual_aggr, primal_aggr, compl_aggr,
369 n_dual, n_pri, n_comp
370 );
371 }
372
373 evaluate_quality_function(
374 norm_type, centrality, balancing, alpha_pri, alpha_du, xi, aggr,
375 )
376 };
377
378 if let Ok(s) = std::env::var("POUNCE_DBG_QF_SWEEP") {
382 if let Ok(target_iter) = s.parse::<i32>() {
383 if data.borrow().iter_count == target_iter {
384 let lo = self.sigma_min.max(self.mu_min / avrg_compl);
385 let hi = self.sigma_max.min(self.mu_max / avrg_compl).max(lo * 10.0);
386 let log_lo = lo.ln();
387 let log_hi = hi.ln();
388 tracing::debug!(target: "pounce::mu", "[QF_SWEEP] iter={} avrg_compl={:.6e} σ_range=[{:.3e},{:.3e}] sigma_min={:.3e} sigma_max={:.3e} mu_min={:.3e} mu_max={:.3e}",
389 target_iter, avrg_compl, lo, hi,
390 self.sigma_min, self.sigma_max, self.mu_min, self.mu_max);
391 let n = 21;
392 for i in 0..n {
393 let frac = i as f64 / (n - 1) as f64;
394 let sig = (log_lo + frac * (log_hi - log_lo)).exp();
395 let q = eval_q(sig);
396 tracing::debug!(target: "pounce::mu", "[QF_SWEEP] σ={:.6e} q={:.10e}", sig, q);
397 }
398 let q1 = eval_q(1.0);
399 let s1m = 1.0 - self.section_sigma_tol.max(1e-4);
400 let q1m = eval_q(s1m);
401 tracing::debug!(target: "pounce::mu",
402 "[QF_SWEEP] σ=1.0 q={:.10e} σ={:.6e} q={:.10e} (q_1minus>q_1: {})",
403 q1,
404 s1m,
405 q1m,
406 q1m > q1
407 );
408 }
409 }
410 }
411
412 let sigma = pick_sigma(
413 self.sigma_min,
414 self.sigma_max,
415 self.mu_min,
416 self.mu_max,
417 avrg_compl,
418 self.section_sigma_tol,
419 self.section_qf_tol,
420 self.max_section_steps,
421 &mut eval_q,
422 );
423
424 let mu_new = sigma * avrg_compl;
425 let mu_clamped = mu_new.clamp(self.mu_min, self.mu_max);
426 if std::env::var("POUNCE_DBG_QF").is_ok() {
427 let iter_count = data.borrow().iter_count;
428 let curr_mu = data.borrow().curr_mu;
429 let sigma_floor = self.sigma_min.max(self.mu_min / avrg_compl);
430 let sigma_up_dn = sigma_floor
431 .max(1.0 - self.section_sigma_tol.max(1e-4))
432 .min(self.mu_max / avrg_compl);
433 tracing::debug!(target: "pounce::mu",
434 "[QF] iter={} curr_mu={:.3e} avrg_compl={:.3e} sigma={:.3e} mu_new={:.3e} mu_clamped={:.3e} | sigma_min={:.3e} mu_min={:.3e} sigma_lo_dn={:.3e} sigma_up_dn={:.3e} mu_min/avrg={:.3e}",
435 iter_count, curr_mu, avrg_compl, sigma, mu_new, mu_clamped,
436 self.sigma_min, self.mu_min, sigma_floor, sigma_up_dn,
437 self.mu_min / avrg_compl,
438 );
439 }
440 Some(mu_clamped)
441 }
442}
443
444impl MuOracle for QualityFunctionMuOracle {
445 fn calculate_mu(&mut self) -> Option<Number> {
446 None
451 }
452}
453
454pub fn golden_section(
468 sigma_lo_in: Number,
469 sigma_up_in: Number,
470 q_lo_in: Number,
471 q_up_in: Number,
472 sigma_tol: Number,
473 qf_tol: Number,
474 max_steps: i32,
475 mut q: impl FnMut(Number) -> Number,
476) -> Number {
477 let mut sigma_lo = sigma_lo_in;
478 let mut sigma_up = sigma_up_in;
479 let mut q_lo = q_lo_in;
480 let mut q_up = q_up_in;
481
482 let gfac = (3.0 - 5.0_f64.sqrt()) / 2.0;
483 let mut sigma_mid1 = sigma_lo + gfac * (sigma_up - sigma_lo);
484 let mut sigma_mid2 = sigma_lo + (1.0 - gfac) * (sigma_up - sigma_lo);
485 let mut qmid1 = q(sigma_mid1);
486 let mut qmid2 = q(sigma_mid2);
487
488 let mut nsections = 0;
489 let mut width_ok;
490 let mut qf_ok;
491 loop {
492 width_ok = (sigma_up - sigma_lo) >= sigma_tol * sigma_up;
493 let qmin = q_lo.min(q_up).min(qmid1).min(qmid2);
494 let qmax = q_lo.max(q_up).max(qmid1).max(qmid2);
495 qf_ok = qmax > 0.0 && (1.0 - qmin / qmax) >= qf_tol;
496 if !(width_ok && qf_ok && nsections < max_steps) {
497 break;
498 }
499 nsections += 1;
500 if qmid1 > qmid2 {
501 sigma_lo = sigma_mid1;
502 q_lo = qmid1;
503 sigma_mid1 = sigma_mid2;
504 qmid1 = qmid2;
505 sigma_mid2 = sigma_lo + (1.0 - gfac) * (sigma_up - sigma_lo);
506 qmid2 = q(sigma_mid2);
507 } else {
508 sigma_up = sigma_mid2;
509 q_up = qmid2;
510 sigma_mid2 = sigma_mid1;
511 qmid2 = qmid1;
512 sigma_mid1 = sigma_lo + gfac * (sigma_up - sigma_lo);
513 qmid1 = q(sigma_mid1);
514 }
515 }
516
517 if width_ok && !qf_ok {
541 if sigma_lo == sigma_lo_in && q_lo < 0.0 {
549 q_lo = q(sigma_lo);
550 }
551 if sigma_up == sigma_up_in && q_up < 0.0 {
552 q_up = q(sigma_up);
553 }
554 let mut best_s = sigma_lo;
555 let mut best_q = q_lo;
556 if q_up < best_q {
557 best_s = sigma_up;
558 best_q = q_up;
559 }
560 if qmid1 < best_q {
561 best_s = sigma_mid1;
562 best_q = qmid1;
563 }
564 if qmid2 < best_q {
565 best_s = sigma_mid2;
566 }
567 return best_s;
568 }
569 let (mut sigma, mut qval) = if qmid1 < qmid2 {
570 (sigma_mid1, qmid1)
571 } else {
572 (sigma_mid2, qmid2)
573 };
574 if sigma_up == sigma_up_in {
575 let qtmp = if q_up < 0.0 { q(sigma_up) } else { q_up };
576 if qtmp < qval {
577 sigma = sigma_up;
578 qval = qtmp;
579 }
580 } else if sigma_lo == sigma_lo_in {
581 let qtmp = if q_lo < 0.0 { q(sigma_lo) } else { q_lo };
582 if qtmp < qval {
583 sigma = sigma_lo;
584 }
585 }
586 let _ = qval;
587 sigma
588}
589
590#[derive(Debug, Clone, Copy)]
605pub struct QualityFunctionAggregates {
606 pub dual_aggr: Number,
607 pub primal_aggr: Number,
608 pub compl_aggr: Number,
609 pub n_dual: i32,
610 pub n_pri: i32,
611 pub n_comp: i32,
612}
613
614pub fn evaluate_quality_function(
623 norm: NormType,
624 centrality: CentralityType,
625 balancing: BalancingTermType,
626 alpha_primal: Number,
627 alpha_dual: Number,
628 xi: Number,
629 aggr: QualityFunctionAggregates,
630) -> Number {
631 let (mut dual_inf, mut primal_inf, mut compl_inf) = match norm {
632 NormType::OneNorm => {
633 let mut d = (1.0 - alpha_dual) * aggr.dual_aggr;
634 let mut p = (1.0 - alpha_primal) * aggr.primal_aggr;
635 let mut c = aggr.compl_aggr;
636 d /= aggr.n_dual as Number;
637 if aggr.n_pri > 0 {
638 p /= aggr.n_pri as Number;
639 }
640 debug_assert!(aggr.n_comp > 0);
641 c /= aggr.n_comp as Number;
642 (d, p, c)
643 }
644 NormType::TwoNormSquared => {
645 let mut d = (1.0 - alpha_dual).powi(2) * aggr.dual_aggr;
649 let mut p = (1.0 - alpha_primal).powi(2) * aggr.primal_aggr;
650 let mut c = aggr.compl_aggr;
651 d /= aggr.n_dual as Number;
652 if aggr.n_pri > 0 {
653 p /= aggr.n_pri as Number;
654 }
655 debug_assert!(aggr.n_comp > 0);
656 c /= aggr.n_comp as Number;
657 (d, p, c)
658 }
659 NormType::MaxNorm => (
660 (1.0 - alpha_dual) * aggr.dual_aggr,
661 (1.0 - alpha_primal) * aggr.primal_aggr,
662 aggr.compl_aggr,
663 ),
664 NormType::TwoNorm => {
665 let mut d = (1.0 - alpha_dual) * aggr.dual_aggr;
666 let mut p = (1.0 - alpha_primal) * aggr.primal_aggr;
667 let mut c = aggr.compl_aggr;
668 d /= (aggr.n_dual as Number).sqrt();
669 if aggr.n_pri > 0 {
670 p /= (aggr.n_pri as Number).sqrt();
671 }
672 debug_assert!(aggr.n_comp > 0);
673 c /= (aggr.n_comp as Number).sqrt();
674 (d, p, c)
675 }
676 };
677
678 if dual_inf.is_nan() {
680 dual_inf = 0.0;
681 }
682 if primal_inf.is_nan() {
683 primal_inf = 0.0;
684 }
685 if compl_inf.is_nan() {
686 compl_inf = 0.0;
687 }
688
689 let mut q = dual_inf + primal_inf + compl_inf;
690
691 match centrality {
692 CentralityType::None => {}
693 CentralityType::LogCenter => q -= compl_inf * xi.ln(),
694 CentralityType::ReciprocalCenter => q += compl_inf / xi,
695 CentralityType::CubedReciprocalCenter => q += compl_inf / xi.powi(3),
696 }
697
698 match balancing {
699 BalancingTermType::None => {}
700 BalancingTermType::CubicTerm => {
701 let dom = dual_inf.max(primal_inf) - compl_inf;
702 q += dom.max(0.0).powi(3);
703 }
704 }
705
706 q
707}
708
709#[allow(clippy::too_many_arguments)]
720pub fn pick_sigma(
721 sigma_min: Number,
722 sigma_max: Number,
723 mu_min: Number,
724 mu_max: Number,
725 avrg_compl: Number,
726 sigma_tol: Number,
727 qf_tol: Number,
728 max_steps: i32,
729 mut q: impl FnMut(Number) -> Number,
730) -> Number {
731 let qf_1 = q(1.0);
732 let sigma_1minus = 1.0 - sigma_tol.max(1e-4);
733 let qf_1minus = q(sigma_1minus);
734
735 if qf_1minus > qf_1 {
736 let sigma_up = sigma_max.min(mu_max / avrg_compl);
738 let sigma_lo = 1.0;
739 if sigma_lo >= sigma_up {
740 sigma_up
741 } else {
742 golden_section(
743 sigma_lo, sigma_up, qf_1, -100.0, sigma_tol, qf_tol, max_steps, q,
744 )
745 }
746 } else {
747 let sigma_lo = sigma_min.max(mu_min / avrg_compl);
749 let sigma_up = sigma_lo.max(sigma_1minus).min(mu_max / avrg_compl);
750 if sigma_lo >= sigma_up {
751 sigma_lo
752 } else {
753 golden_section(
754 sigma_lo, sigma_up, -100.0, qf_1minus, sigma_tol, qf_tol, max_steps, q,
755 )
756 }
757 }
758}
759
760#[cfg(test)]
761mod tests {
762 use super::*;
763
764 #[test]
765 fn golden_section_minimizes_parabola() {
766 let f = |s: f64| (s - 0.3).powi(2);
768 let s = golden_section(0.0, 1.0, f(0.0), f(1.0), 1e-6, 0.0, 50, f);
769 assert!((s - 0.3).abs() < 1e-3);
770 }
771
772 #[test]
773 fn golden_section_respects_max_steps() {
774 let f = |s: f64| (s - 0.5).powi(2);
776 let s = golden_section(0.0, 1.0, f(0.0), f(1.0), 1e-12, 0.0, 5, f);
777 assert!((s - 0.5).abs() < 0.2);
778 }
779
780 #[test]
781 fn golden_section_handles_monotone() {
782 let f = |s: f64| s;
784 let s = golden_section(0.1, 2.0, 0.1, 2.0, 1e-6, 0.0, 50, f);
785 assert!(s < 0.2, "got s = {}", s);
786 }
787
788 #[test]
789 fn golden_section_never_returns_unevaluated_sentinel() {
790 let sigma_lo = 1.0_f64;
801 let sigma_up = 3.0_f64;
802 let q = move |s: f64| if s == sigma_up { 50.0 } else { -s };
805 let s = golden_section(sigma_lo, sigma_up, q(sigma_lo), -100.0, 1e-3, 0.0, 50, q);
807 assert!(
808 s < sigma_up,
809 "golden_section returned the unevaluated sentinel endpoint σ = {} \
810 (true q there = {}, the bracket maximum); it must re-evaluate the \
811 sentinel before selecting a minimum",
812 s,
813 q(s)
814 );
815 }
816
817 #[test]
818 fn calculate_mu_returns_none_until_plumbed() {
819 let mut o = QualityFunctionMuOracle::new();
820 assert!(o.calculate_mu().is_none());
821 }
822
823 fn aggr(
824 d: Number,
825 p: Number,
826 c: Number,
827 nd: i32,
828 np: i32,
829 nc: i32,
830 ) -> QualityFunctionAggregates {
831 QualityFunctionAggregates {
832 dual_aggr: d,
833 primal_aggr: p,
834 compl_aggr: c,
835 n_dual: nd,
836 n_pri: np,
837 n_comp: nc,
838 }
839 }
840
841 #[test]
842 fn evaluate_one_norm_averages_by_n() {
843 let q = evaluate_quality_function(
845 NormType::OneNorm,
846 CentralityType::None,
847 BalancingTermType::None,
848 0.5, 0.25, 1.0,
851 aggr(8.0, 4.0, 6.0, 4, 2, 3),
852 );
853 assert!((q - 4.5).abs() < 1e-12, "got {}", q);
855 }
856
857 #[test]
858 fn evaluate_max_norm_does_not_divide() {
859 let q = evaluate_quality_function(
860 NormType::MaxNorm,
861 CentralityType::None,
862 BalancingTermType::None,
863 0.0,
864 0.0,
865 1.0,
866 aggr(2.0, 3.0, 5.0, 10, 10, 10),
867 );
868 assert!((q - 10.0).abs() < 1e-12);
869 }
870
871 #[test]
872 fn evaluate_two_norm_divides_by_sqrt_n() {
873 let q = evaluate_quality_function(
874 NormType::TwoNorm,
875 CentralityType::None,
876 BalancingTermType::None,
877 0.0,
878 0.0,
879 1.0,
880 aggr(2.0, 0.0, 4.0, 4, 0, 16),
881 );
882 assert!((q - 2.0).abs() < 1e-12, "got {}", q);
884 }
885
886 #[test]
887 fn evaluate_one_norm_handles_zero_pri_dim() {
888 let q = evaluate_quality_function(
890 NormType::OneNorm,
891 CentralityType::None,
892 BalancingTermType::None,
893 0.0,
894 0.0,
895 1.0,
896 aggr(0.0, 0.0, 1.0, 1, 0, 1),
897 );
898 assert!(q.is_finite() && (q - 1.0).abs() < 1e-12);
899 }
900
901 #[test]
902 fn evaluate_log_centrality_subtracts_compl_log_xi() {
903 let base = evaluate_quality_function(
904 NormType::MaxNorm,
905 CentralityType::None,
906 BalancingTermType::None,
907 0.0,
908 0.0,
909 std::f64::consts::E,
910 aggr(0.0, 0.0, 4.0, 1, 1, 1),
911 );
912 let logc = evaluate_quality_function(
913 NormType::MaxNorm,
914 CentralityType::LogCenter,
915 BalancingTermType::None,
916 0.0,
917 0.0,
918 std::f64::consts::E,
919 aggr(0.0, 0.0, 4.0, 1, 1, 1),
920 );
921 assert!((base - logc - 4.0).abs() < 1e-12, "base={base} logc={logc}");
923 }
924
925 #[test]
926 fn evaluate_reciprocal_centrality_adds_c_over_xi() {
927 let q = evaluate_quality_function(
928 NormType::MaxNorm,
929 CentralityType::ReciprocalCenter,
930 BalancingTermType::None,
931 0.0,
932 0.0,
933 0.5,
934 aggr(0.0, 0.0, 1.0, 1, 1, 1),
935 );
936 assert!((q - 3.0).abs() < 1e-12);
938 }
939
940 #[test]
941 fn evaluate_cubed_reciprocal_centrality_adds_c_over_xi3() {
942 let q = evaluate_quality_function(
943 NormType::MaxNorm,
944 CentralityType::CubedReciprocalCenter,
945 BalancingTermType::None,
946 0.0,
947 0.0,
948 0.5,
949 aggr(0.0, 0.0, 1.0, 1, 1, 1),
950 );
951 assert!((q - 9.0).abs() < 1e-12);
953 }
954
955 #[test]
956 fn evaluate_cubic_balancing_adds_when_dual_dominates() {
957 let q = evaluate_quality_function(
958 NormType::MaxNorm,
959 CentralityType::None,
960 BalancingTermType::CubicTerm,
961 0.0,
962 0.0,
963 1.0,
964 aggr(5.0, 1.0, 2.0, 1, 1, 1),
965 );
966 assert!((q - 35.0).abs() < 1e-12, "got {}", q);
968 }
969
970 #[test]
971 fn evaluate_cubic_balancing_zero_when_compl_dominates() {
972 let q = evaluate_quality_function(
973 NormType::MaxNorm,
974 CentralityType::None,
975 BalancingTermType::CubicTerm,
976 0.0,
977 0.0,
978 1.0,
979 aggr(1.0, 1.0, 5.0, 1, 1, 1),
980 );
981 assert!((q - 7.0).abs() < 1e-12);
983 }
984
985 #[test]
986 fn pick_sigma_searches_below_one_for_decreasing_q() {
987 let f = |s: f64| (s - 0.4).powi(2);
989 let s = pick_sigma(1e-9, 100.0, 1e-11, 1e5, 1.0, 1e-6, 0.0, 50, f);
990 assert!((s - 0.4).abs() < 1e-2, "got s = {}", s);
991 }
992
993 #[test]
994 fn pick_sigma_searches_above_one_for_q_decreasing_in_sigma() {
995 let f = |s: f64| -s;
997 let s = pick_sigma(1e-9, 10.0, 1e-11, 1e5, 1.0, 1e-6, 0.0, 50, f);
998 assert!(s > 5.0, "got s = {}", s);
1000 }
1001
1002 #[test]
1003 fn pick_sigma_clamps_to_mu_max_over_avrg_in_up_search() {
1004 let f = |s: f64| -s;
1006 let s = pick_sigma(1e-9, 100.0, 1e-11, 2.0, 1.0, 1e-6, 0.0, 50, f);
1007 assert!(s <= 2.0 + 1e-9 && s >= 1.0, "got s = {}", s);
1008 }
1009
1010 #[test]
1011 fn pick_sigma_clamps_to_mu_min_over_avrg_in_down_search() {
1012 let f = |s: f64| s;
1015 let s = pick_sigma(1e-9, 100.0, 0.5, 1e5, 1.0, 1e-6, 0.0, 50, f);
1016 assert!(s >= 0.5 - 1e-9 && s <= 1.0, "got s = {}", s);
1017 }
1018}