1use oximo_core::ModelKind;
2use oximo_solver::{HasUniversal, UniversalOptions};
3
4#[derive(Clone, Debug, Default, PartialEq)]
19pub struct PounceOptions {
20 pub universal: UniversalOptions,
21 pub tol: Option<f64>,
23 pub max_iter: Option<u32>,
25 pub print_level: Option<u32>,
27 pub mu_strategy: Option<MuStrategy>,
29 pub algorithm: Option<PounceAlgorithm>,
32 pub solver_selection: Option<PounceSolverSelection>,
36 num_opts: Vec<(&'static str, f64)>,
38 int_opts: Vec<(&'static str, i32)>,
39 str_opts: Vec<(&'static str, String)>,
40 bool_opts: Vec<(&'static str, bool)>,
41 pub extra: Vec<(String, PounceOptionValue)>,
43}
44
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
47pub enum MuStrategy {
48 Monotone,
49 Adaptive,
50}
51
52#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
60pub enum PounceAlgorithm {
61 #[default]
63 InteriorPoint,
64 ActiveSetSqp,
66}
67
68#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
70pub enum PounceSolverSelection {
71 #[default]
74 Auto,
75 Nlp,
77 LpIpm,
79 QpIpm,
81 QpActiveSet,
83 Socp,
85}
86
87impl PounceSolverSelection {
88 pub(crate) const fn as_str(self) -> &'static str {
89 match self {
90 Self::Auto => "auto",
91 Self::Nlp => "nlp",
92 Self::LpIpm => "lp-ipm",
93 Self::QpIpm => "qp-ipm",
94 Self::QpActiveSet => "qp-active-set",
95 Self::Socp => "socp",
96 }
97 }
98
99 pub(crate) fn parse(value: &str) -> Option<Self> {
100 match value {
101 "auto" => Some(Self::Auto),
102 "nlp" => Some(Self::Nlp),
103 "lp-ipm" => Some(Self::LpIpm),
104 "qp-ipm" => Some(Self::QpIpm),
105 "qp-active-set" => Some(Self::QpActiveSet),
106 "socp" => Some(Self::Socp),
107 _ => None,
108 }
109 }
110}
111
112impl PounceAlgorithm {
113 pub(crate) const fn as_str(self) -> &'static str {
114 match self {
115 Self::InteriorPoint => "interior-point",
116 Self::ActiveSetSqp => "active-set-sqp",
117 }
118 }
119
120 pub(crate) const fn supports(self, kind: ModelKind) -> bool {
121 match self {
122 Self::InteriorPoint | Self::ActiveSetSqp => {
123 matches!(
124 kind,
125 ModelKind::LP
126 | ModelKind::QP
127 | ModelKind::QCP
128 | ModelKind::SOCP
129 | ModelKind::NLP
130 )
131 }
132 }
133 }
134}
135
136#[derive(Clone, Debug, PartialEq)]
138pub enum PounceOptionValue {
139 Num(f64),
140 Int(i32),
141 Str(String),
142 Bool(bool),
143}
144
145impl From<f64> for PounceOptionValue {
146 fn from(v: f64) -> Self {
147 Self::Num(v)
148 }
149}
150
151impl From<i32> for PounceOptionValue {
152 fn from(v: i32) -> Self {
153 Self::Int(v)
154 }
155}
156
157impl From<&str> for PounceOptionValue {
158 fn from(v: &str) -> Self {
159 Self::Str(v.to_owned())
160 }
161}
162
163impl From<bool> for PounceOptionValue {
164 fn from(v: bool) -> Self {
165 Self::Bool(v)
166 }
167}
168
169macro_rules! pounce_options {
172 ($( ($kind:ident, $method:ident, $tag:literal) ),* $(,)?) => {
173 $(pounce_options!(@impl $kind, $method, $tag);)*
174 };
175 (@impl num, $method:ident, $tag:literal) => {
176 #[doc = concat!("Set the POUNCE `", $tag, "` option.")]
177 #[must_use]
178 pub fn $method(mut self, v: f64) -> Self {
179 self.num_opts.push(($tag, v));
180 self
181 }
182 };
183 (@impl int, $method:ident, $tag:literal) => {
184 #[doc = concat!("Set the POUNCE `", $tag, "` option.")]
185 #[must_use]
186 pub fn $method(mut self, v: i32) -> Self {
187 self.int_opts.push(($tag, v));
188 self
189 }
190 };
191 (@impl str, $method:ident, $tag:literal) => {
192 #[doc = concat!("Set the POUNCE `", $tag, "` option.")]
193 #[must_use]
194 pub fn $method(mut self, v: impl Into<String>) -> Self {
195 self.str_opts.push(($tag, v.into()));
196 self
197 }
198 };
199 (@impl bool, $method:ident, $tag:literal) => {
200 #[doc = concat!("Set the POUNCE `", $tag, "` option.")]
201 #[must_use]
202 pub fn $method(mut self, v: bool) -> Self {
203 self.bool_opts.push(($tag, v));
204 self
205 }
206 };
207}
208
209impl PounceOptions {
210 pounce_options!(
211 (str, mu_oracle, "mu_oracle"),
213 (num, mu_init, "mu_init"),
214 (num, mu_min, "mu_min"),
215 (num, mu_max, "mu_max"),
216 (num, mu_max_fact, "mu_max_fact"),
217 (num, mu_target, "mu_target"),
218 (num, mu_linear_decrease_factor, "mu_linear_decrease_factor"),
219 (num, mu_superlinear_decrease_power, "mu_superlinear_decrease_power"),
220 (num, barrier_tol_factor, "barrier_tol_factor"),
221 (num, sigma_max, "sigma_max"),
222 (num, sigma_min, "sigma_min"),
223 (str, adaptive_mu_globalization, "adaptive_mu_globalization"),
224 (str, quality_function_norm_type, "quality_function_norm_type"),
226 (str, quality_function_centrality, "quality_function_centrality"),
227 (str, quality_function_balancing_term, "quality_function_balancing_term"),
228 (int, quality_function_max_section_steps, "quality_function_max_section_steps"),
229 (num, quality_function_section_sigma_tol, "quality_function_section_sigma_tol"),
230 (num, quality_function_section_qf_tol, "quality_function_section_qf_tol"),
231 (num, adaptive_mu_safeguard_factor, "adaptive_mu_safeguard_factor"),
233 (num, adaptive_mu_monotone_init_factor, "adaptive_mu_monotone_init_factor"),
234 (bool, adaptive_mu_restore_previous_iterate, "adaptive_mu_restore_previous_iterate"),
235 (int, adaptive_mu_kkterror_red_iters, "adaptive_mu_kkterror_red_iters"),
236 (num, adaptive_mu_kkterror_red_fact, "adaptive_mu_kkterror_red_fact"),
237 (str, adaptive_mu_kkt_norm_type, "adaptive_mu_kkt_norm_type"),
238 (bool, l1_exact_penalty_barrier, "l1_exact_penalty_barrier"),
240 (bool, l1_fallback_on_restoration_failure, "l1_fallback_on_restoration_failure"),
241 (num, l1_penalty_init, "l1_penalty_init"),
242 (num, l1_penalty_max, "l1_penalty_max"),
243 (num, l1_penalty_increase_factor, "l1_penalty_increase_factor"),
244 (int, l1_penalty_max_outer_iter, "l1_penalty_max_outer_iter"),
245 (num, l1_slack_tol, "l1_slack_tol"),
246 (num, l1_steering_factor, "l1_steering_factor"),
247 (bool, presolve, "presolve"),
249 (bool, presolve_bound_tightening, "presolve_bound_tightening"),
250 (bool, presolve_redundant_constraint_removal, "presolve_redundant_constraint_removal"),
251 (bool, presolve_linear_eq_reduction, "presolve_linear_eq_reduction"),
252 (bool, presolve_licq_check, "presolve_licq_check"),
253 (str, presolve_licq_action, "presolve_licq_action"),
254 (bool, presolve_warm_z_bounds, "presolve_warm_z_bounds"),
255 (num, presolve_bound_mult_init_val, "presolve_bound_mult_init_val"),
256 (int, presolve_max_passes, "presolve_max_passes"),
257 (int, presolve_print_level, "presolve_print_level"),
258 (bool, presolve_fbbt, "presolve_fbbt"),
260 (num, fbbt_tol, "fbbt_tol"),
261 (int, fbbt_max_iter, "fbbt_max_iter"),
262 (int, fbbt_max_constraints, "fbbt_max_constraints"),
263 (bool, presolve_auxiliary, "presolve_auxiliary"),
265 (str, presolve_auxiliary_coupling, "presolve_auxiliary_coupling"),
266 (num, presolve_auxiliary_tol, "presolve_auxiliary_tol"),
267 (int, presolve_auxiliary_max_block_dim, "presolve_auxiliary_max_block_dim"),
268 (num, presolve_auxiliary_wall_time_fraction, "presolve_auxiliary_wall_time_fraction"),
269 (bool, presolve_auxiliary_diagnostics, "presolve_auxiliary_diagnostics"),
270 (str, linear_solver, "linear_solver"),
272 (str, feral_ordering, "feral_ordering"),
273 (str, feral_scaling, "feral_scaling"),
274 (num, feral_pivtol, "feral_pivtol"),
275 (bool, feral_refine, "feral_refine"),
276 (bool, feral_cascade_break, "feral_cascade_break"),
277 (bool, feral_fma, "feral_fma"),
278 (num, feral_singular_pivot_floor, "feral_singular_pivot_floor"),
279 (num, acceptable_progress_kappa, "acceptable_progress_kappa"),
281 (num, dual_inf_scale_kappa, "dual_inf_scale_kappa"),
282 (num, feral_inertia_pivot_floor, "feral_inertia_pivot_floor"),
283 (bool, infeasibility_mu_strategy_retry, "infeasibility_mu_strategy_retry"),
284 (num, primal_noise_floor_kappa, "primal_noise_floor_kappa"),
285 (num, qp_tau_max, "qp_tau_max"),
286 (int, resto_decline_deferrals, "resto_decline_deferrals"),
287 (num, resto_decline_progress_ratio, "resto_decline_progress_ratio"),
288 (int, sqp_qp_max_schur_updates_before_refactor, "sqp_qp_max_schur_updates_before_refactor"),
289 (bool, sqp_qp_use_homotopy, "sqp_qp_use_homotopy"),
290 (bool, sqp_qp_use_schur_updates, "sqp_qp_use_schur_updates"),
291 (num, theta_max_adaptive_factor, "theta_max_adaptive_factor"),
292 (int, theta_max_adaptive_max_raises, "theta_max_adaptive_max_raises"),
293 (int, theta_max_adaptive_trigger, "theta_max_adaptive_trigger"),
294 (num, theta_max_row_scale_kappa, "theta_max_row_scale_kappa"),
295 (bool, qp_presolve, "qp_presolve"),
297 (num, qp_tau, "qp_tau"),
298 (num, qp_reg, "qp_reg"),
299 (num, qp_infeas_tol, "qp_infeas_tol"),
300 (bool, qp_hsde, "qp_hsde"),
301 (bool, qp_equilibrate, "qp_equilibrate"),
302 (bool, qp_crossover, "qp_crossover"),
303 (bool, feral_infeasibility_scaling_retry, "feral_infeasibility_scaling_retry"),
304 (int, sqp_qp_max_iter, "sqp_qp_max_iter"),
306 (num, sqp_qp_feas_tol, "sqp_qp_feas_tol"),
307 (num, sqp_qp_opt_tol, "sqp_qp_opt_tol"),
308 (num, sqp_qp_elastic_gamma, "sqp_qp_elastic_gamma"),
309 (str, sqp_qp_anti_cycling, "sqp_qp_anti_cycling"),
310 );
311
312 #[must_use]
313 pub fn tol(mut self, tol: f64) -> Self {
314 self.tol = Some(tol);
315 self
316 }
317
318 #[must_use]
319 pub fn max_iter(mut self, n: u32) -> Self {
320 self.max_iter = Some(n);
321 self
322 }
323
324 #[must_use]
325 pub fn print_level(mut self, level: u32) -> Self {
326 self.print_level = Some(level);
327 self
328 }
329
330 #[must_use]
331 pub fn mu_strategy(mut self, s: MuStrategy) -> Self {
332 self.mu_strategy = Some(s);
333 self
334 }
335
336 #[must_use]
338 pub fn algorithm(mut self, algorithm: PounceAlgorithm) -> Self {
339 self.algorithm = Some(algorithm);
340 self
341 }
342
343 #[must_use]
345 pub fn solver_selection(mut self, selection: PounceSolverSelection) -> Self {
346 self.solver_selection = Some(selection);
347 self
348 }
349
350 #[must_use]
354 pub fn set(mut self, name: impl Into<String>, value: impl Into<PounceOptionValue>) -> Self {
355 self.extra.push((name.into(), value.into()));
356 self
357 }
358
359 pub(crate) fn num_opts(&self) -> &[(&'static str, f64)] {
360 &self.num_opts
361 }
362
363 pub(crate) fn int_opts(&self) -> &[(&'static str, i32)] {
364 &self.int_opts
365 }
366
367 pub(crate) fn str_opts(&self) -> &[(&'static str, String)] {
368 &self.str_opts
369 }
370
371 pub(crate) fn bool_opts(&self) -> &[(&'static str, bool)] {
372 &self.bool_opts
373 }
374
375 fn effective_value<T>(
376 &self,
377 name: &str,
378 typed: impl Iterator<Item = (&'static str, T)>,
379 from_raw: impl Fn(&PounceOptionValue) -> Option<T>,
380 ) -> Option<T> {
381 let mut value = typed.filter(|(key, _)| *key == name).map(|(_, value)| value).last();
382 for (key, raw) in &self.extra {
383 if key == name {
384 value = from_raw(raw);
385 }
386 }
387 value
388 }
389
390 pub(crate) fn effective_num(&self, name: &str) -> Option<f64> {
391 self.effective_value(name, self.num_opts.iter().map(|&(key, value)| (key, value)), |raw| {
392 match raw {
393 PounceOptionValue::Num(value) => Some(*value),
394 _ => None,
395 }
396 })
397 }
398
399 pub(crate) fn effective_int(&self, name: &str) -> Option<i32> {
400 self.effective_value(name, self.int_opts.iter().map(|&(key, value)| (key, value)), |raw| {
401 match raw {
402 PounceOptionValue::Int(value) => Some(*value),
403 _ => None,
404 }
405 })
406 }
407
408 pub(crate) fn effective_bool(&self, name: &str) -> Option<bool> {
409 self.effective_value(name, self.bool_opts.iter().map(|&(key, value)| (key, value)), |raw| {
410 match raw {
411 PounceOptionValue::Bool(value) => Some(*value),
412 PounceOptionValue::Str(value)
413 if matches!(value.as_str(), "yes" | "true" | "on") =>
414 {
415 Some(true)
416 }
417 PounceOptionValue::Str(value)
418 if matches!(value.as_str(), "no" | "false" | "off") =>
419 {
420 Some(false)
421 }
422 _ => None,
423 }
424 })
425 }
426
427 pub(crate) fn effective_string(&self, name: &str) -> Option<String> {
428 self.effective_value(
429 name,
430 self.str_opts.iter().map(|(key, value)| (*key, value.clone())),
431 |raw| match raw {
432 PounceOptionValue::Str(value) => Some(value.clone()),
433 _ => None,
434 },
435 )
436 }
437}
438
439impl HasUniversal for PounceOptions {
440 fn universal(&self) -> &UniversalOptions {
441 &self.universal
442 }
443
444 fn universal_mut(&mut self) -> &mut UniversalOptions {
445 &mut self.universal
446 }
447}
448
449#[cfg(test)]
450mod tests {
451 use super::*;
452
453 #[test]
454 fn typed_setters_push_onto_the_right_vecs() {
455 let o = PounceOptions::default()
456 .mu_oracle("probing")
457 .mu_init(0.05)
458 .presolve(true)
459 .presolve_max_passes(5)
460 .feral_refine(false);
461 assert_eq!(o.str_opts, vec![("mu_oracle", "probing".to_owned())]);
462 assert_eq!(o.num_opts, vec![("mu_init", 0.05)]);
463 assert_eq!(o.int_opts, vec![("presolve_max_passes", 5)]);
464 assert_eq!(o.bool_opts, vec![("presolve", true), ("feral_refine", false)]);
465 }
466
467 #[test]
468 fn default_vecs_are_empty() {
469 let o = PounceOptions::default();
470 assert!(o.num_opts.is_empty());
471 assert!(o.int_opts.is_empty());
472 assert!(o.str_opts.is_empty());
473 assert!(o.bool_opts.is_empty());
474 assert!(o.extra.is_empty());
475 }
476
477 #[test]
478 fn same_option_twice_keeps_both_entries() {
479 let o = PounceOptions::default().mu_init(0.1).mu_init(0.5);
480 assert_eq!(o.num_opts, vec![("mu_init", 0.1), ("mu_init", 0.5)]);
481 }
482
483 #[test]
484 fn clone_preserves_all_vecs() {
485 let o = PounceOptions::default().mu_init(0.1).presolve_max_passes(2).presolve(true);
486 let c = o.clone();
487 assert_eq!(o.num_opts, c.num_opts);
488 assert_eq!(o.int_opts, c.int_opts);
489 assert_eq!(o.bool_opts, c.bool_opts);
490 }
491
492 #[test]
493 fn set_pushes_onto_extra_with_bool() {
494 let o = PounceOptions::default().set("presolve", true).set("acceptable_tol", 1e-5);
495 assert_eq!(
496 o.extra,
497 vec![
498 ("presolve".to_owned(), PounceOptionValue::Bool(true)),
499 ("acceptable_tol".to_owned(), PounceOptionValue::Num(1e-5)),
500 ]
501 );
502 }
503
504 #[test]
505 fn pounce_setters_use_the_declared_storage_kinds() {
506 let o = PounceOptions::default()
507 .solver_selection(PounceSolverSelection::Socp)
508 .acceptable_progress_kappa(0.2)
509 .resto_decline_deferrals(2)
510 .infeasibility_mu_strategy_retry(false)
511 .qp_tau(0.9)
512 .qp_presolve(true)
513 .sqp_qp_anti_cycling("bland");
514 assert_eq!(o.solver_selection, Some(PounceSolverSelection::Socp));
515 assert!(o.num_opts.contains(&("acceptable_progress_kappa", 0.2)));
516 assert!(o.num_opts.contains(&("qp_tau", 0.9)));
517 assert!(o.int_opts.contains(&("resto_decline_deferrals", 2)));
518 assert!(o.bool_opts.contains(&("infeasibility_mu_strategy_retry", false)));
519 assert!(o.bool_opts.contains(&("qp_presolve", true)));
520 assert!(o.str_opts.contains(&("sqp_qp_anti_cycling", "bland".to_owned())));
521 }
522
523 #[test]
524 fn solver_selection_parses_every_public_value() {
525 for (text, expected) in [
526 ("auto", PounceSolverSelection::Auto),
527 ("nlp", PounceSolverSelection::Nlp),
528 ("lp-ipm", PounceSolverSelection::LpIpm),
529 ("qp-ipm", PounceSolverSelection::QpIpm),
530 ("qp-active-set", PounceSolverSelection::QpActiveSet),
531 ("socp", PounceSolverSelection::Socp),
532 ] {
533 assert_eq!(PounceSolverSelection::parse(text), Some(expected));
534 assert_eq!(expected.as_str(), text);
535 }
536 assert_eq!(PounceSolverSelection::parse("unknown"), None);
537 }
538
539 #[test]
540 fn algorithms_report_their_names_and_supported_model_kinds() {
541 for (algorithm, name) in [
542 (PounceAlgorithm::InteriorPoint, "interior-point"),
543 (PounceAlgorithm::ActiveSetSqp, "active-set-sqp"),
544 ] {
545 assert_eq!(algorithm.as_str(), name);
546 for kind in
547 [ModelKind::LP, ModelKind::QP, ModelKind::QCP, ModelKind::SOCP, ModelKind::NLP]
548 {
549 assert!(algorithm.supports(kind), "{algorithm:?} should support {kind:?}");
550 }
551 assert!(!algorithm.supports(ModelKind::MILP));
552 }
553 }
554
555 #[test]
556 fn wrong_kind_raw_overrides_clear_typed_values() {
557 let options = PounceOptions::default()
558 .qp_tau(0.9)
559 .set("qp_tau", true)
560 .sqp_qp_max_iter(20)
561 .set("sqp_qp_max_iter", "wrong")
562 .qp_presolve(true)
563 .set("qp_presolve", 1.0)
564 .sqp_qp_anti_cycling("bland")
565 .set("sqp_qp_anti_cycling", false);
566 assert_eq!(options.effective_num("qp_tau"), None);
567 assert_eq!(options.effective_int("sqp_qp_max_iter"), None);
568 assert_eq!(options.effective_bool("qp_presolve"), None);
569 assert_eq!(options.effective_string("sqp_qp_anti_cycling"), None);
570 }
571}