1#![forbid(unsafe_code)]
6mod active;
7mod batch;
8mod boxed;
9mod certified_cuts;
10mod choice_mass;
11mod choice_route;
12mod components;
13mod cuts;
14mod dense;
15mod diagnostics;
16mod dyadic;
17mod ft;
18mod grouped;
19mod heuristic_budget;
20mod incumbent;
21mod integer_equality;
22mod jump;
23mod local_mip;
24#[cfg(feature = "local-mip-bench")]
25#[doc(hidden)]
26pub mod local_mip_bench;
27#[cfg(not(feature = "local-mip-bench"))]
28mod local_mip_bench;
29mod lp;
30mod lu;
31mod mip_presolve;
32mod mixed;
33mod ordered;
34mod ordering;
35mod packing;
36pub mod parallel;
37#[cfg(feature = "parallel-bench")]
38#[doc(hidden)]
39pub mod parallel_bench;
40mod presolve;
41mod primal;
42pub mod profile;
43mod proof_conflicts;
44mod propagate;
45mod rational;
46#[cfg(feature = "basis-replay")]
47pub mod replay;
48mod root;
49mod root_fix;
50mod root_policy;
51mod rootcuts;
52mod tree;
53mod witness;
54
55use lp::{Basis, Lp};
56use lp_ip_craft::{
57 BackendReport, Bounds, CancellationToken, Duals, Error, LpIpSolver, Model, Options, Result,
58 Sense, SolveResult, StartStatus, Status, WarmStart, check, safe_dual_bound_with_bounds,
59};
60use std::sync::Arc;
61use std::time::Instant;
62
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
65pub enum BasisUpdate {
66 #[default]
67 Auto,
68 Eta,
70 ForrestTomlin,
72}
73impl BasisUpdate {
74 pub fn as_str(self) -> &'static str {
75 match self {
76 Self::Auto => "auto",
77 Self::Eta => "eta",
78 Self::ForrestTomlin => "forrest_tomlin",
79 }
80 }
81}
82
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub enum FactorOrdering {
86 #[default]
87 Auto,
88 Natural,
89 MinDegree,
90}
91impl FactorOrdering {
92 pub fn as_str(self) -> &'static str {
93 match self {
94 Self::Auto => "auto",
95 Self::Natural => "natural",
96 Self::MinDegree => "min_degree",
97 }
98 }
99}
100
101#[derive(Clone, Debug, PartialEq)]
103pub struct NativeOptions {
104 pub time_limit_seconds: Option<f64>,
106 pub node_limit: Option<u64>,
108 pub mip_relative_gap: Option<f64>,
111 pub mip_absolute_gap: Option<f64>,
113 pub iteration_limit: Option<u64>,
115 pub pivot_tolerance: f64,
117 pub dual_tolerance: f64,
119 pub max_factor_entries: usize,
121 pub refactor_interval: usize,
123 pub adaptive_refactor: bool,
125 pub basis_update: BasisUpdate,
127 pub factor_pivot_search: usize,
129 pub factor_ordering: FactorOrdering,
131 pub steepest_edge: bool,
133 pub presolve: bool,
135 pub redundant_rows: bool,
137 pub redundant_row_min_ratio: f64,
139 pub node_reoptimization: bool,
141 pub strong_branching: bool,
143 pub reliability_branching: bool,
145 pub reliability_threshold: u32,
146 pub reliability_max_probes: u64,
147 pub reduced_cost_fixing: bool,
149 pub mixed_fix_trials: usize,
152 pub proof_conflict_limit: usize,
154 pub choice_tree_cut_interval: u64,
156 pub choice_tree_cut_limit: usize,
158 pub branch_probe_score: bool,
160 pub branch_probe_proofs: bool,
162 pub root_probe_limit: usize,
164 pub dive_node_limit: usize,
166 pub estimated_diving: bool,
168 pub repair_integral_leaves: bool,
170 pub dual_cutoff_interval: u64,
172 pub root_cut_delay: usize,
174 pub root_cut_gap: f64,
176 pub root_cut_progress: f64,
178 pub cutoff_pseudocosts: bool,
180 pub branch_probe_pivot_share: u64,
182 pub branch_probe_actual_work: bool,
184 pub mixed_fix_depth: usize,
186 pub mixed_root_rounds: usize,
188 pub root_refit_sweeps: usize,
190 pub root_refit_fraction: f64,
192 pub choice_route_depth: usize,
194 pub choice_pair_depth: usize,
196 pub choice_local_depth: usize,
198 pub choice_local_rounds: usize,
200 pub safe_node_pruning: bool,
202 pub choice_order_presolve: bool,
204 pub incumbent_heuristic: bool,
206 pub rational_certification: bool,
208 pub feasibility_jump: bool,
210 pub feasibility_jump_steps: u64,
211 pub local_mip_effort: u64,
214 pub local_mip_seed: u64,
216 pub objective_lattice: bool,
218 pub decompose: bool,
220 pub decomposition_min_variables: usize,
222 pub component_threads: usize,
224 pub component_parallel_min_entries: usize,
227 pub root_cuts: bool,
229 pub root_separation: bool,
231 pub mip_presolve: bool,
235 pub integer_equality_presolve: bool,
237 pub objective_cutoff_bounds: bool,
240 pub adaptive_root: bool,
242 pub coefficient_tightening: bool,
245 pub dual_presolve: bool,
248 pub mip_presolve_rounds: usize,
250 pub gmi_cuts: bool,
253 pub mir_cuts: bool,
256 pub mip_cut_rounds: usize,
259 pub mip_cut_limit: usize,
261 pub cut_exact_work: u64,
264 pub root_heuristics: bool,
267 pub grouped_heuristics: bool,
269 pub ordered_group_cuts: bool,
271 pub choice_mass_rounds: usize,
273 pub choice_route_passes: usize,
275 pub choice_route_restarts: usize,
277 pub heuristic_lp_calls: usize,
279 pub branching_score: String,
282 pub pseudocost_min_step: f64,
285 pub branch_trace_limit: usize,
288 pub root_cut_rounds: usize,
290 pub cover_lifting: bool,
292 pub root_propagation: bool,
294 pub mixed_propagation: bool,
296 pub singleton_presolve: bool,
298 pub avoid_dominant_components: bool,
300 pub devex: bool,
302 pub adaptive_pricing: bool,
304 pub factor_replay: bool,
306 pub mip_diagnostics: bool,
308 pub mip_trace_limit: usize,
310 pub packing_root: bool,
316 pub packing_root_iterations: usize,
318 pub packing_root_work: u64,
320 pub packing_neighborhoods: usize,
323 pub packing_neighborhood_size: usize,
325 pub packing_workers: usize,
327 pub packing_neighborhood_nodes: u64,
329 pub packing_cuts: bool,
331 pub packing_cut_work: u64,
333 pub packing_combine_repairs: bool,
335 pub packing_rounds: usize,
337 pub packing_neighborhood_growth: usize,
339 pub packing_seed_strategy: String,
341 pub packing_residual_cliques: bool,
343 pub packing_clique_work: u64,
345 pub packing_price_diagnostics: bool,
347 pub packing_repair_seconds: Option<f64>,
349 pub packing_proof_seconds: Option<f64>,
352 pub partial_dual_bounds: bool,
354 pub scalable_branching: bool,
356 pub branch_probe_candidates: usize,
358 pub branch_probe_pivots: u64,
360 pub branch_probe_work: u64,
362 pub tree_threads: usize,
364 pub tree_split_depth: usize,
366}
367impl Default for NativeOptions {
368 fn default() -> Self {
369 Self {
370 time_limit_seconds: None,
371 node_limit: Some(100_000),
372 mip_relative_gap: None,
373 mip_absolute_gap: None,
374 iteration_limit: Some(1_000_000),
375 pivot_tolerance: 1e-9,
376 dual_tolerance: 1e-7,
377 max_factor_entries: 4_000_000,
378 refactor_interval: 256,
379 adaptive_refactor: true,
380 basis_update: BasisUpdate::Auto,
381 factor_pivot_search: 4,
382 factor_ordering: FactorOrdering::Auto,
383 steepest_edge: true,
384 presolve: true,
385 redundant_rows: true,
386 redundant_row_min_ratio: 1.0,
387 node_reoptimization: true,
388 strong_branching: false,
389 reliability_branching: false,
390 reliability_threshold: 2,
391 reliability_max_probes: 64,
392 reduced_cost_fixing: true,
393 mixed_fix_trials: 0,
394 proof_conflict_limit: 0,
395 choice_tree_cut_interval: 64,
396 choice_tree_cut_limit: 0,
397 branch_probe_score: false,
398 branch_probe_proofs: false,
399 root_probe_limit: 0,
400 dive_node_limit: 0,
401 estimated_diving: false,
402 repair_integral_leaves: true,
403 dual_cutoff_interval: 0,
404 root_cut_delay: 0,
405 root_cut_gap: 0.,
406 root_cut_progress: 0.001,
407 cutoff_pseudocosts: false,
408 branch_probe_pivot_share: 0,
409 branch_probe_actual_work: false,
410 mixed_fix_depth: 8,
411 mixed_root_rounds: 0,
412 root_refit_sweeps: 0,
413 root_refit_fraction: 0.05,
414 choice_route_depth: 0,
415 choice_pair_depth: 0,
416 choice_local_depth: 0,
417 choice_local_rounds: 1,
418 safe_node_pruning: false,
419 choice_order_presolve: false,
420 incumbent_heuristic: true,
421 rational_certification: true,
422 feasibility_jump: false,
423 feasibility_jump_steps: 2000,
424 local_mip_effort: 0,
425 local_mip_seed: 0,
426 objective_lattice: true,
427 decompose: true,
428 decomposition_min_variables: 32,
429 component_threads: 16,
430 component_parallel_min_entries: 2048,
431 root_cuts: false,
432 root_separation: false,
433 mip_presolve: true,
434 integer_equality_presolve: false,
435 objective_cutoff_bounds: false,
436 adaptive_root: false,
437 coefficient_tightening: true,
438 dual_presolve: false,
439 mip_presolve_rounds: 8,
440 gmi_cuts: false,
441 mir_cuts: false,
442 mip_cut_rounds: 8,
443 mip_cut_limit: 16,
444 cut_exact_work: 4_000_000,
445 root_heuristics: false,
446 grouped_heuristics: false,
447 ordered_group_cuts: false,
448 choice_mass_rounds: 0,
449 choice_route_passes: 0,
450 choice_route_restarts: 1,
451 heuristic_lp_calls: 16,
452 branching_score: "weighted_sum".into(),
453 pseudocost_min_step: 0.,
454 branch_trace_limit: 0,
455 root_cut_rounds: 2,
456 cover_lifting: true,
457 root_propagation: true,
458 mixed_propagation: false,
459 singleton_presolve: true,
460 avoid_dominant_components: true,
461 devex: false,
462 adaptive_pricing: true,
463 factor_replay: false,
464 mip_diagnostics: false,
465 mip_trace_limit: 256,
466 packing_root: false,
467 packing_root_iterations: 1000,
468 packing_root_work: 200_000_000,
469 packing_neighborhoods: 0,
470 packing_neighborhood_size: 192,
471 packing_workers: 1,
472 packing_neighborhood_nodes: 128,
473 packing_cuts: false,
474 packing_cut_work: 2_000_000,
475 packing_combine_repairs: false,
476 packing_rounds: 1,
477 packing_neighborhood_growth: 0,
478 packing_seed_strategy: "incumbent".into(),
479 packing_residual_cliques: false,
480 packing_clique_work: 50_000,
481 packing_price_diagnostics: false,
482 packing_repair_seconds: None,
483 packing_proof_seconds: None,
484 partial_dual_bounds: false,
485 scalable_branching: false,
486 branch_probe_candidates: 4,
487 branch_probe_pivots: 32,
488 branch_probe_work: 2_000_000,
489 tree_threads: 1,
490 tree_split_depth: 2,
491 }
492 }
493}
494impl NativeOptions {
495 pub fn has_gap_limit(&self) -> bool {
498 self.mip_relative_gap.is_some_and(|v| v > 0.0)
499 || self.mip_absolute_gap.is_some_and(|v| v > 0.0)
500 }
501
502 pub fn validate(&self) -> Result<()> {
503 for (name, value) in [
504 ("mip_relative_gap", self.mip_relative_gap),
505 ("mip_absolute_gap", self.mip_absolute_gap),
506 ] {
507 if value.is_some_and(|v| !v.is_finite() || v < 0.0) {
508 return Err(Error::InvalidInput(format!(
509 "{name} must be finite and nonnegative"
510 )));
511 }
512 }
513 for (valid, message) in [
514 (
515 self.mip_presolve_rounds <= 32,
516 "mip_presolve_rounds must be at most 32",
517 ),
518 (
519 self.choice_route_depth <= 256 && self.choice_pair_depth <= 256,
520 "choice_route_depth and choice_pair_depth must be at most 256",
521 ),
522 (
523 self.choice_local_depth <= 8 && (1..=3).contains(&self.choice_local_rounds),
524 "choice_local_depth must be at most 8 and choice_local_rounds in 1..=3",
525 ),
526 (
527 self.root_refit_sweeps <= 32 && (0. ..=1.).contains(&self.root_refit_fraction),
528 "root_refit_sweeps must be at most 32 and root_refit_fraction must be in [0, 1]",
529 ),
530 (
531 self.choice_tree_cut_limit <= 256
532 && (8..=4096).contains(&self.choice_tree_cut_interval)
533 && self.proof_conflict_limit <= 256,
534 "tree cut and conflict limits must be at most 256 and tree cut interval in 8..=4096",
535 ),
536 (
537 self.root_probe_limit <= 4096 && self.dual_cutoff_interval <= 256,
538 "root_probe_limit must be at most 4096 and dual_cutoff_interval at most 256",
539 ),
540 (
541 self.branch_probe_pivot_share <= 1024
542 && (self.branch_probe_pivot_share == 0 || self.branch_probe_actual_work),
543 "branch_probe_pivot_share must be at most 1024 and requires branch_probe_actual_work",
544 ),
545 (
546 (0. ..=1.).contains(&self.root_cut_progress)
547 && self.root_cut_gap.is_finite()
548 && self.root_cut_gap >= 0.
549 && self.root_cut_delay <= 16,
550 "invalid root cut progress, gap, or starting round",
551 ),
552 (
553 self.mixed_fix_trials <= 128 && self.mixed_root_rounds <= 6,
554 "mixed_fix_trials must be at most 128 and mixed_root_rounds at most 6",
555 ),
556 (
557 self.choice_route_passes <= 12 && (1..=6).contains(&self.choice_route_restarts),
558 "choice_route_passes must be at most 12 and choice_route_restarts within 1..=6",
559 ),
560 (
561 self.mip_cut_rounds <= 50 && self.choice_mass_rounds <= 16,
562 "mip_cut_rounds must be at most 50 and choice_mass_rounds at most 16",
563 ),
564 (
565 (1..=64).contains(&self.mip_cut_limit),
566 "mip_cut_limit must lie in 1..=64",
567 ),
568 (
569 self.cut_exact_work <= 100_000_000,
570 "cut_exact_work must be at most 100000000",
571 ),
572 (
573 self.heuristic_lp_calls <= 128,
574 "heuristic_lp_calls must be at most 128",
575 ),
576 (
577 self.branch_trace_limit <= 256,
578 "branch_trace_limit must be at most 256",
579 ),
580 (
581 ["weighted_sum", "product"].contains(&self.branching_score.as_str()),
582 "branching_score must be weighted_sum or product",
583 ),
584 (
585 self.pseudocost_min_step.is_finite()
586 && (0.0..=0.5).contains(&self.pseudocost_min_step),
587 "pseudocost_min_step must be finite in 0..=0.5",
588 ),
589 ] {
590 if !valid {
591 return Err(Error::InvalidInput(message.into()));
592 }
593 }
594 let phase = |t: Option<f64>| t.is_none_or(|t| t.is_finite() && t >= 0.);
595 for (ok, message) in [
596 (
597 (1..=32).contains(&self.packing_rounds),
598 "packing_rounds must lie in 1..=32",
599 ),
600 (
601 self.packing_neighborhoods
602 .saturating_mul(self.packing_rounds)
603 <= 4096,
604 "packing_neighborhoods * packing_rounds must be at most 4096",
605 ),
606 (
607 self.packing_neighborhood_growth <= 1024,
608 "packing_neighborhood_growth must be at most 1024",
609 ),
610 (
611 self.packing_clique_work <= 1_000_000,
612 "packing_clique_work must be at most 1000000",
613 ),
614 (
615 ["incumbent", "rejected", "mixed"].contains(&self.packing_seed_strategy.as_str()),
616 "packing_seed_strategy must be incumbent, rejected or mixed",
617 ),
618 (
619 phase(self.packing_repair_seconds),
620 "packing_repair_seconds must be finite and nonnegative",
621 ),
622 (
623 phase(self.packing_proof_seconds),
624 "packing_proof_seconds must be finite and nonnegative",
625 ),
626 (
627 self.packing_root_iterations <= 100_000,
628 "packing_root_iterations must be at most 100000",
629 ),
630 (
631 self.packing_root_work <= 10_000_000_000,
632 "packing_root_work must be at most 10000000000",
633 ),
634 (
635 self.packing_neighborhoods <= 4096,
636 "packing_neighborhoods must be at most 4096",
637 ),
638 (
639 (4..=1024).contains(&self.packing_neighborhood_size),
640 "packing_neighborhood_size must lie in 4..=1024",
641 ),
642 (
643 (1..=16).contains(&self.packing_workers),
644 "packing_workers must lie in 1..=16",
645 ),
646 (
647 self.packing_neighborhood_nodes <= 100_000,
648 "packing_neighborhood_nodes must be at most 100000",
649 ),
650 (
651 self.packing_cut_work <= 100_000_000,
652 "packing_cut_work must be at most 100000000",
653 ),
654 (
655 (1..=16).contains(&self.branch_probe_candidates),
656 "branch_probe_candidates must lie in 1..=16",
657 ),
658 (
659 self.branch_probe_pivots <= 1024,
660 "branch_probe_pivots must be at most 1024",
661 ),
662 (
663 self.branch_probe_work <= 10_000_000_000,
664 "branch_probe_work must be at most 10000000000",
665 ),
666 (
667 (1..=16).contains(&self.tree_threads),
668 "tree_threads must lie in 1..=16",
669 ),
670 (
671 self.tree_split_depth <= 8,
672 "tree_split_depth must be at most 8",
673 ),
674 ] {
675 if !ok {
676 return Err(Error::InvalidInput(message.into()));
677 }
678 }
679 if !(1..=16).contains(&self.reliability_threshold) || self.reliability_max_probes > 1024 {
680 return Err(Error::InvalidInput(
681 "reliability threshold must be 1..=16 and max probes at most 1024".into(),
682 ));
683 }
684 if self.feasibility_jump_steps > 100_000 {
685 return Err(Error::InvalidInput(
686 "feasibility_jump_steps must be at most 100000".into(),
687 ));
688 }
689 if self.root_cut_rounds > 4 {
690 return Err(Error::InvalidInput(
691 "root_cut_rounds must be at most 4".into(),
692 ));
693 }
694 if self.mip_trace_limit > 4096 {
695 return Err(Error::InvalidInput(
696 "mip_trace_limit must be at most 4096".into(),
697 ));
698 }
699 if self
700 .time_limit_seconds
701 .is_some_and(|v| !v.is_finite() || v < 0.0)
702 {
703 return Err(Error::InvalidInput(
704 "time_limit_seconds must be finite and nonnegative".into(),
705 ));
706 }
707 if !self.pivot_tolerance.is_finite()
708 || self.pivot_tolerance <= 0.0
709 || self.pivot_tolerance >= 0.01
710 {
711 return Err(Error::InvalidInput(
712 "pivot_tolerance must lie in (0, .01)".into(),
713 ));
714 }
715 if !self.dual_tolerance.is_finite() || self.dual_tolerance <= 0.0 {
716 return Err(Error::InvalidInput(
717 "dual_tolerance must be positive and finite".into(),
718 ));
719 }
720 if !self.redundant_row_min_ratio.is_finite() || self.redundant_row_min_ratio < 0. {
721 return Err(Error::InvalidInput(
722 "redundant_row_min_ratio must be finite and nonnegative".into(),
723 ));
724 }
725 if !(1..=16).contains(&self.component_threads) {
726 return Err(Error::InvalidInput(
727 "component_threads must lie in 1..=16".into(),
728 ));
729 }
730 if self.decomposition_min_variables == 0 {
731 return Err(Error::InvalidInput(
732 "decomposition_min_variables must be positive".into(),
733 ));
734 }
735 if !(1..=64).contains(&self.factor_pivot_search) {
736 return Err(Error::InvalidInput(
737 "factor_pivot_search must be between 1 and 64".into(),
738 ));
739 }
740 if self.max_factor_entries == 0 || self.refactor_interval == 0 {
741 return Err(Error::InvalidInput(
742 "max_factor_entries and refactor_interval must be positive".into(),
743 ));
744 }
745 Ok(())
746 }
747}
748pub(crate) struct Budget<'a> {
749 pub start: Instant,
750 pub settings: &'a NativeOptions,
751 pub cancel: &'a CancellationToken,
752 pub pivots: u64,
753}
754impl Budget<'_> {
755 fn stop(&self) -> Option<Status> {
756 if self.cancel.is_cancelled() {
757 Some(Status::Cancelled)
758 } else if self
759 .settings
760 .time_limit_seconds
761 .is_some_and(|t| self.start.elapsed().as_secs_f64() >= t)
762 {
763 Some(Status::TimeLimit)
764 } else if self
765 .settings
766 .iteration_limit
767 .is_some_and(|p| self.pivots >= p)
768 {
769 Some(Status::IterationLimit)
770 } else {
771 None
772 }
773 }
774}
775
776#[derive(Clone, Debug, Default)]
779pub struct NativeSolver {
780 pub settings: NativeOptions,
782}
783impl NativeSolver {
784 pub fn new(settings: NativeOptions) -> Self {
786 Self { settings }
787 }
788}
789
790fn oriented(model: &Model, v: f64) -> f64 {
791 if model.sense() == Sense::Minimize {
792 v
793 } else {
794 -v
795 }
796}
797fn objective_scale(model: &Model) -> f64 {
798 1.0 + model
799 .objective()
800 .iter()
801 .fold(0.0_f64, |a, &b| a.max(b.abs()))
802}
803fn accepted(
804 model: &Model,
805 bounds: &Bounds,
806 x: &[f64],
807 duals: &lp_ip_craft::Duals,
808 options: &Options,
809 settings: &NativeOptions,
810) -> bool {
811 let Ok(r) = check::lp_residuals_with_bounds(model, bounds, x, duals) else {
812 return false;
813 };
814 let scale = objective_scale(model);
815 r.primal <= options.tolerances.feasibility
816 && r.dual_sign <= settings.dual_tolerance * scale
817 && r.stationarity <= settings.dual_tolerance * scale
818 && r.duality_gap <= settings.dual_tolerance
819}
820
821struct Incumbents<'a, 't> {
822 best: f64,
823 upper: f64,
824 certified: Option<(Vec<f64>, lp_ip_craft::Evaluation)>,
825 trace: Option<diagnostics::SearchDiagnostics>,
826 original_model: &'a Model,
827 pivots: u64,
828 pilot: Option<&'a mut local_mip_bench::Trace<'t>>,
829 rounding_trials_left: u8,
831}
832fn consider(
833 model: &Model,
834 x: Vec<f64>,
835 options: &Options,
836 result: &mut SolveResult,
837 pool: &mut Incumbents<'_, '_>,
838 source: &'static str,
839) -> Result<bool> {
840 let e = check::evaluate(model, &x, &options.tolerances)?;
841 if !e.feasible_candidate {
842 return Ok(false);
843 }
844 let previous_upper = pool.upper;
845 if let Some(upper) = incumbent::upper(model, &x) {
846 if upper < pool.upper {
847 pool.upper = upper;
848 pool.certified = Some((x.clone(), e.clone()));
849 }
850 }
851 if pool.trace.is_some() || pool.pilot.is_some() {
852 let original = check::evaluate(pool.original_model, &x, &options.tolerances)
855 .ok()
856 .filter(|e| e.feasible_candidate);
857 let proof = (pool.upper < previous_upper).then(|| oriented(model, pool.upper));
858 if let Some(trace) = &mut pool.trace {
859 if let Some(e) = &original {
860 trace.candidate(e.objective, proof, source, result.nodes, pool.pivots);
861 } else {
862 trace.original_check_rejections += 1;
863 }
864 }
865 if let Some(trace) = &mut pool.pilot {
866 let work = (result.nodes, pool.pivots);
867 if let Some(e) = &original {
868 trace.candidate(e.objective, source, work);
869 if proof.is_some() {
870 trace.event(
871 "certified_incumbent",
872 source,
873 work,
874 Some(e.objective),
875 proof,
876 );
877 }
878 } else {
879 trace.event("original_check_rejection", source, work, None, None);
880 }
881 }
882 }
883 let obj = oriented(model, e.objective);
884 if obj < pool.best {
885 pool.best = obj;
886 result.candidate = Some(x);
887 result.evaluation = Some(e);
888 }
889 Ok(true)
890}
891struct Certifier {
897 lp: Option<Lp>,
898 attempts: u64,
899 certified: u64,
900 last: Option<Vec<f64>>,
901 lp_attempts: u64,
902 witness_attempts: u64,
903 witness_successes: u64,
904 witness_work: u64,
905 witness_outcome: witness::Outcome,
906 witness_assignment: Option<u64>,
907}
908const MAX_CERTIFICATIONS: u64 = 64;
909const WITNESS_WORK: u64 = 64_000_000;
912
913#[allow(clippy::too_many_arguments)]
914fn certify(
915 model: &Model,
916 options: &Options,
917 settings: &NativeOptions,
918 keep: &[bool],
919 certifier: &mut Certifier,
920 pool: &mut Incumbents<'_, '_>,
921 result: &mut SolveResult,
922 budget: &mut Budget<'_>,
923) -> Result<()> {
924 let Some(x) = result.candidate.as_ref() else {
925 return Ok(());
926 };
927 if pool.best >= pool.upper
928 || certifier.attempts >= MAX_CERTIFICATIONS
929 || certifier.last.as_ref() == Some(x)
930 || budget.stop().is_some()
931 {
932 return Ok(());
933 }
934 certifier.last = Some(x.clone());
935 certifier.attempts += 1;
936 let started = pool.pilot.as_ref().map(|_| Instant::now());
937 let work_before = (result.nodes, budget.pivots);
938 let remaining = WITNESS_WORK.saturating_sub(certifier.witness_work);
939 let witness_started = pool.trace.as_ref().map(|_| Instant::now());
940 let witness = if settings.rational_certification && remaining > 0 {
941 certifier.witness_attempts += 1;
942 let limit = remaining.min(witness::ATTEMPT_WORK);
943 let (witness, work, outcome) = witness::upper(pool.original_model, x, budget, limit);
944 certifier.witness_outcome = outcome;
945 if pool.trace.is_some() {
946 use std::hash::{Hash, Hasher};
947 let mut hash = std::collections::hash_map::DefaultHasher::new();
948 for (j, value) in pool
949 .original_model
950 .kinds()
951 .iter()
952 .zip(x)
953 .enumerate()
954 .filter_map(|(j, (kind, value))| kind.is_integral().then_some((j, value)))
955 {
956 (j, value.round() as i64).hash(&mut hash);
957 }
958 certifier.witness_assignment = Some(hash.finish());
959 }
960 certifier.witness_work += work;
961 witness
962 } else {
963 None
964 };
965 if let Some((trace, started)) = pool.trace.as_mut().zip(witness_started) {
966 trace.witness_seconds += started.elapsed().as_secs_f64();
967 }
968 if let Some(witness) = witness {
969 let point = witness.point;
970 let upper = witness.upper;
971 let evaluation = check::evaluate(model, &point, &options.tolerances)?;
972 if upper < pool.upper
973 && evaluation.feasible_candidate
974 && check::evaluate(pool.original_model, &point, &options.tolerances)?.feasible_candidate
975 {
976 pool.upper = upper;
977 pool.certified = Some((point.clone(), evaluation.clone()));
978 let objective = oriented(model, evaluation.objective);
979 if objective < pool.best {
980 pool.best = objective;
981 result.candidate = Some(point);
982 result.evaluation = Some(evaluation);
983 }
984 certifier.witness_successes += 1;
985 if let Some(trace) = &mut pool.trace {
986 trace.candidate(
987 oriented(model, objective),
988 Some(oriented(model, upper)),
989 "rational_witness",
990 result.nodes,
991 budget.pivots,
992 );
993 }
994 if let Some((trace, started)) = pool.pilot.as_deref_mut().zip(started) {
995 let work = (result.nodes, budget.pivots);
996 let value = oriented(model, objective);
997 trace.candidate(value, "rational_witness", work);
998 trace.event(
999 "certified_incumbent",
1000 "rational_witness",
1001 work,
1002 Some(value),
1003 Some(oriented(model, upper)),
1004 );
1005 trace.stage("certification", work, work_before, started);
1006 }
1007 return Ok(());
1008 }
1009 }
1010 let integral: Vec<bool> = model.kinds().iter().map(|k| k.is_integral()).collect();
1011 let rounded: Vec<f64> = x
1012 .iter()
1013 .zip(&integral)
1014 .map(|(&v, &i)| if i { v.round() } else { v })
1015 .collect();
1016 certifier.lp_attempts += 1;
1017 let lp = match &mut certifier.lp {
1018 Some(lp) => lp,
1019 none => {
1020 let columns = presolve::kept_columns(model, model.variables(), settings);
1021 let mut lp = Lp::new(model, keep, &columns, controls(model, options, settings))?;
1022 lp.shrink_rows(model);
1023 none.insert(lp)
1024 }
1025 };
1026 lp.fix_for_certification(&rounded, &integral, model.variables())?;
1027 let solved = lp.solve(budget, true)?;
1028 if let Some((trace, started)) = pool.pilot.as_deref_mut().zip(started) {
1029 trace.stage(
1030 "certification",
1031 (result.nodes, budget.pivots),
1032 work_before,
1033 started,
1034 );
1035 }
1036 if solved != Status::Optimal {
1037 return Ok(());
1038 }
1039 let mut point = lp.point();
1040 for j in (0..model.n()).filter(|&j| integral[j]) {
1041 point[j] = rounded[j];
1042 }
1043 let before = pool.upper;
1044 pool.pivots = budget.pivots;
1045 consider(model, point, options, result, pool, "certification")?;
1046 if pool.upper < before {
1047 certifier.certified += 1;
1048 }
1049 Ok(())
1050}
1051
1052fn heuristic(
1053 model: &Model,
1054 node_bounds: &Bounds,
1055 x: &[f64],
1056 options: &Options,
1057 result: &mut SolveResult,
1058 pool: &mut Incumbents<'_, '_>,
1059 budget: &Budget<'_>,
1060) -> Result<u64> {
1061 let mut found = 0;
1062 if let Some(trace) = &mut pool.trace {
1063 trace.heuristic_calls += 1;
1064 }
1065 let mut order: Vec<_> = (0..model.n())
1066 .filter(|&j| model.kinds()[j].is_integral())
1067 .collect();
1068 order.sort_by(|&a, &b| {
1069 model.objective()[b]
1070 .abs()
1071 .total_cmp(&model.objective()[a].abs())
1072 .then(a.cmp(&b))
1073 });
1074 for mode in 0..3 {
1075 if budget.stop().is_some() {
1076 break;
1077 }
1078 let mut point = x.to_vec();
1079 if let Some(trace) = &mut pool.trace {
1080 trace.rounding_attempts += 1;
1081 }
1082 for &j in &order {
1083 point[j] = match mode {
1084 0 => point[j].round(),
1085 1 => point[j].floor(),
1086 _ => point[j].ceil(),
1087 };
1088 point[j] = point[j]
1089 .max(node_bounds.lower[j].ceil())
1090 .min(node_bounds.upper[j].floor());
1091 }
1092 if !consider(model, point.clone(), options, result, pool, "rounding")? {
1093 continue;
1094 }
1095 found += 1;
1096 for &j in order.iter().take(64) {
1097 if budget.stop().is_some() {
1098 break;
1099 }
1100 let c = oriented(model, model.objective()[j]);
1101 if c == 0.0 {
1102 continue;
1103 }
1104 let old = point[j];
1105 point[j] += if c < 0.0 { 1.0 } else { -1.0 };
1106 if point[j] < node_bounds.lower[j]
1107 || point[j] > node_bounds.upper[j]
1108 || !consider(model, point.clone(), options, result, pool, "unit_move")?
1109 {
1110 point[j] = old;
1111 } else {
1112 found += 1;
1113 }
1114 }
1115 }
1116 Ok(found)
1117}
1118
1119fn root_local_search(
1120 model: &Model,
1121 (bounds, point): (&Bounds, &[f64]),
1122 options: &Options,
1123 budget: &Budget<'_>,
1124 result: &mut SolveResult,
1125 pool: &mut Incumbents<'_, '_>,
1126) -> Result<jump::Stats> {
1127 use heuristic_budget::{Meter, Stop};
1128
1129 let settings = budget.settings;
1130 let controls = pool
1131 .pilot
1132 .as_ref()
1133 .map_or_else(local_mip_bench::Controls::default, |t| t.controls);
1134 let mut jump_stats = jump::Stats::default();
1135 if settings.feasibility_jump
1136 && controls.matched_fj_effort == 0
1137 && !controls.replace_root_fj
1138 && budget.stop().is_none()
1139 {
1140 let started = pool.pilot.as_ref().map(|_| Instant::now());
1141 let (proposal, stats) = jump::search(
1142 model,
1143 bounds,
1144 point,
1145 budget,
1146 settings.feasibility_jump_steps,
1147 );
1148 jump_stats = stats;
1149 if let Some(x) = proposal {
1150 consider(model, x, options, result, pool, "feasibility_jump")?;
1151 }
1152 if let Some((trace, started)) = pool.pilot.as_deref_mut().zip(started) {
1153 let work = (result.nodes, budget.pivots);
1154 trace.stage("feasibility_jump", work, work, started);
1155 }
1156 }
1157
1158 let matched_fj = controls.matched_fj_effort != 0;
1159 let effort = if matched_fj {
1160 controls.matched_fj_effort
1161 } else {
1162 settings.local_mip_effort
1163 };
1164 let skip = if effort == 0 {
1165 "disabled"
1166 } else if options.threads != 1 || !settings.presolve {
1167 "ineligible_path"
1168 } else if budget.stop().is_some() || settings.node_limit.is_some_and(|n| result.nodes >= n) {
1169 "global_stop_before_dispatch"
1170 } else {
1171 "dispatched"
1172 };
1173 if let Some(trace) = &mut pool.pilot {
1174 trace.skip = skip;
1175 }
1176 if skip != "dispatched" {
1177 if settings.local_mip_effort != 0 {
1179 result
1180 .backend
1181 .effective_options
1182 .push(("diagnostics.root_local_search.skip".into(), skip.into()));
1183 }
1184 return Ok(jump_stats);
1185 }
1186
1187 let started = pool.pilot.as_ref().map(|_| Instant::now());
1188 let mut meter = Meter::new(budget, effort, effort / 4);
1189 let source = if matched_fj {
1190 "feasibility_jump_metered"
1191 } else {
1192 "local_mip"
1193 };
1194 let mut local_stats = local_mip::Stats::default();
1195 let proposal = if matched_fj {
1196 let (proposal, stats) = jump::search_metered(
1197 model,
1198 bounds,
1199 point,
1200 budget,
1201 settings.feasibility_jump_steps,
1202 &mut meter,
1203 );
1204 jump_stats = stats;
1205 proposal.and_then(|x| {
1206 if meter.valid_point(model, pool.original_model, &x, &options.tolerances)? {
1207 Ok(x)
1208 } else {
1209 Err(Stop::Numerical)
1210 }
1211 })
1212 } else {
1213 let (proposal, stats) = local_mip::search(
1214 model,
1215 pool.original_model,
1216 bounds,
1217 point,
1218 &options.tolerances,
1219 &mut meter,
1220 settings.local_mip_seed,
1221 );
1222 local_stats = stats;
1223 proposal
1224 };
1225 let previous_best = pool.best;
1226 let stop = match proposal {
1227 Ok(x) => {
1228 let first = !pool.best.is_finite();
1229 if consider(model, x, options, result, pool, source)? && first {
1230 pool.rounding_trials_left = 8;
1231 }
1232 Stop::Feasible
1233 }
1234 Err(reason) => reason,
1235 };
1236 let improved = u64::from(pool.best < previous_best);
1238 meter.report(
1239 &mut result.backend.effective_options,
1240 source,
1241 stop,
1242 &[
1243 ("improved_incumbent", improved),
1244 (
1245 "proposals",
1246 if matched_fj {
1247 jump_stats.proposals
1248 } else {
1249 local_stats.proposals
1250 },
1251 ),
1252 (
1253 "moves",
1254 if matched_fj {
1255 jump_stats.steps
1256 } else {
1257 local_stats.moves
1258 },
1259 ),
1260 (
1261 "weight_bumps",
1262 if matched_fj {
1263 jump_stats.bumps
1264 } else {
1265 local_stats.weight_bumps
1266 },
1267 ),
1268 ],
1269 );
1270 if let Some((trace, started)) = pool.pilot.as_deref_mut().zip(started) {
1271 let work = (result.nodes, budget.pivots);
1272 trace.stage(source, work, work, started);
1273 }
1274 Ok(jump_stats)
1275}
1276
1277struct Branch {
1280 parent: Option<Arc<Branch>>,
1281 j: usize,
1282 lower: f64,
1283 upper: f64,
1284}
1285
1286struct Node {
1289 branch: Option<Arc<Branch>>,
1290 depth: usize,
1291 bound: Option<f64>,
1292 basis: Option<Arc<Basis>>,
1293 origin: Option<Origin>,
1294}
1295
1296#[derive(Clone, Copy)]
1298struct Origin {
1299 j: usize,
1300 up: bool,
1301 distance: f64,
1302 parent_objective: f64,
1303}
1304
1305struct Pseudocosts {
1308 sum: Vec<[f64; 2]>,
1309 count: Vec<[u32; 2]>,
1310 total: [f64; 2],
1311 total_count: [u32; 2],
1312 min_step: f64,
1313}
1314impl Pseudocosts {
1315 fn new(n: usize) -> Self {
1316 Self {
1317 sum: vec![[0.0; 2]; n],
1318 count: vec![[0; 2]; n],
1319 total: [0.0; 2],
1320 total_count: [0; 2],
1321 min_step: 0.,
1322 }
1323 }
1324 fn record(&mut self, origin: Origin, objective: f64) {
1325 let gain =
1326 (objective - origin.parent_objective).max(0.0) / origin.distance.max(self.min_step);
1327 if gain.is_finite() && origin.distance > 0.0 {
1328 let d = usize::from(origin.up);
1329 self.sum[origin.j][d] += gain;
1330 self.count[origin.j][d] += 1;
1331 self.total[d] += gain;
1332 self.total_count[d] += 1;
1333 }
1334 }
1335 fn known(&self) -> bool {
1336 self.total_count[0] + self.total_count[1] > 0
1337 }
1338 fn estimate(&self, j: usize, up: bool) -> f64 {
1340 let d = usize::from(up);
1341 let prior = if self.total_count[d] > 0 {
1342 self.total[d] / f64::from(self.total_count[d])
1343 } else {
1344 1.
1345 };
1346 (self.sum[j][d] + 2. * prior) / (f64::from(self.count[j][d]) + 2.)
1349 }
1350}
1351
1352struct Open {
1355 key: f64,
1356 serial: u64,
1357 node: Node,
1358}
1359
1360fn diagnostic_frontier_bound(
1363 closed: f64,
1364 all_closed_known: bool,
1365 open: &std::collections::BinaryHeap<Open>,
1366 current: Option<Option<f64>>,
1367) -> Option<f64> {
1368 if !all_closed_known {
1369 return None;
1370 }
1371 let mut bound = closed;
1372 if let Some(node) = open.peek() {
1373 bound = bound.min(node.node.bound?);
1374 }
1375 if let Some(node_bound) = current {
1376 bound = bound.min(node_bound?);
1377 }
1378 bound.is_finite().then_some(bound)
1379}
1380fn gap_reached(
1383 settings: &NativeOptions,
1384 model: &Model,
1385 pool: &Incumbents<'_, '_>,
1386 result: &SolveResult,
1387 bound: Option<f64>,
1388) -> bool {
1389 if !settings.has_gap_limit() || !pool.upper.is_finite() {
1390 return false;
1391 }
1392 let (Some(bound), Some(e)) = (bound, result.evaluation.as_ref()) else {
1393 return false;
1394 };
1395 let within = |gap: lp_ip_craft::Gap| {
1396 gap.absolute.is_finite()
1397 && gap.absolute > 0.0
1398 && (settings
1399 .mip_absolute_gap
1400 .is_some_and(|limit| limit > 0.0 && gap.absolute <= limit)
1401 || settings
1402 .mip_relative_gap
1403 .is_some_and(|limit| limit > 0.0 && gap.relative <= limit))
1404 };
1405 within(lp_ip_craft::Gap::new(Sense::Minimize, pool.upper, bound))
1406 && within(lp_ip_craft::Gap::new(
1407 Sense::Minimize,
1408 oriented(model, e.objective),
1409 bound,
1410 ))
1411}
1412
1413impl PartialEq for Open {
1414 fn eq(&self, other: &Self) -> bool {
1415 self.cmp(other).is_eq()
1416 }
1417}
1418impl Eq for Open {}
1419impl PartialOrd for Open {
1420 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1421 Some(self.cmp(other))
1422 }
1423}
1424impl Ord for Open {
1425 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1426 other
1427 .key
1428 .total_cmp(&self.key)
1429 .then(self.node.depth.cmp(&other.node.depth))
1430 .then(self.serial.cmp(&other.serial))
1431 }
1432}
1433
1434const SNAPSHOT_BUDGET_BYTES: usize = 256 << 20;
1437
1438struct NodeBox {
1440 bounds: Bounds,
1441 changed: Vec<usize>,
1442 path: Vec<(usize, f64, f64)>,
1443 previous: Vec<usize>,
1444}
1445impl NodeBox {
1446 fn enter(&mut self, root: &Bounds, branch: &Option<Arc<Branch>>, lp: &mut Lp) -> Result<bool> {
1448 for &j in &self.changed {
1449 self.bounds.lower[j] = root.lower[j];
1450 self.bounds.upper[j] = root.upper[j];
1451 }
1452 self.path.clear();
1453 let mut at = branch.as_deref();
1454 while let Some(b) = at {
1455 self.path.push((b.j, b.lower, b.upper));
1456 at = b.parent.as_deref();
1457 }
1458 std::mem::swap(&mut self.previous, &mut self.changed);
1459 self.changed.clear();
1460 for &(j, l, u) in self.path.iter().rev() {
1461 self.bounds.lower[j] = self.bounds.lower[j].max(l);
1462 self.bounds.upper[j] = self.bounds.upper[j].min(u);
1463 self.changed.push(j);
1464 }
1465 for &j in self.previous.iter().chain(&self.changed) {
1466 if self.bounds.lower[j] <= self.bounds.upper[j] {
1469 lp.set_bound(j, self.bounds.lower[j], self.bounds.upper[j])?;
1470 }
1471 }
1472 Ok(self
1473 .changed
1474 .iter()
1475 .all(|&j| self.bounds.lower[j] <= self.bounds.upper[j]))
1476 }
1477}
1478
1479struct RootRefit {
1480 duals: Duals,
1481 last_upper: f64,
1482 min_gain: f64,
1483}
1484
1485#[derive(Default)]
1486struct Counters {
1487 warm_nodes: u64,
1488 cold_solves: u64,
1489 fallbacks: u64,
1490 unweighted_retries: u64,
1491 unverified_infeasible: u64,
1492 heuristic_candidates: u64,
1493 pruned_nodes: u64,
1494 propagated_infeasible: u64,
1495 implied_bounds: u64,
1496 strong_probes: u64,
1497 strong_pivots: u64,
1498 strong_work: u64,
1499 strong_work_exits: u64,
1500 reduced_cost_fixings: u64,
1501 mixed_fix_tests: u64,
1502 root_refit: root_fix::Stats,
1503 root_refit_sweeps: usize,
1504 root_refit_conflicts: u64,
1505 choice_route_bounds: u64,
1506 choice_pair_bounds: u64,
1507 choice_local_rounds: u64,
1508 choice_local_cuts: u64,
1509 choice_local_prunes: u64,
1510 safe_node_prunes: u64,
1511 dual_cutoff_prunes: u64,
1512 probe_proof_prunes: u64,
1513 probe_proof_fixings: u64,
1514 choice_tree_cuts: usize,
1515 leaf_repair_attempts: u64,
1516 leaf_repaired: u64,
1517 leaf_resplits: u64,
1518 leaf_open: u64,
1519 branch_events: Vec<String>,
1520}
1521
1522impl NativeSolver {
1523 fn solve_internal(
1524 &mut self,
1525 model: &Model,
1526 options: &Options,
1527 start: Option<&WarmStart>,
1528 cancel: &CancellationToken,
1529 diagnostic_original: &Model,
1530 pilot: Option<&mut local_mip_bench::Trace<'_>>,
1531 ) -> Result<SolveResult> {
1532 options.validate()?;
1533 self.settings.validate()?;
1534 if let Some(s) = start {
1535 if s.primal.len() != model.n() || s.primal.iter().any(|v| !v.is_finite()) {
1536 return Err(Error::InvalidInput(
1537 "start must contain n finite values".into(),
1538 ));
1539 }
1540 }
1541 if model.is_mip()
1542 && model
1543 .variables()
1544 .lower
1545 .iter()
1546 .chain(&model.variables().upper)
1547 .any(|v| !v.is_finite() || v.abs() > 9_007_199_254_740_991.0)
1548 {
1549 return Err(Error::Unsupported(
1550 "native MIP requires finite variable bounds of magnitude <= 2^53-1".into(),
1551 ));
1552 }
1553 let call_started = Instant::now();
1554 if self.settings.presolve && model.m() == 0 && !model.is_mip() {
1555 return boxed::solve(model, options, &self.settings, start, cancel, call_started);
1556 }
1557 let original_model = model;
1558 let strengthened = if self.settings.presolve
1559 && !cancel.is_cancelled()
1560 && self.settings.time_limit_seconds != Some(0.)
1561 {
1562 presolve::strengthen_integer_rows(model, options.tolerances.feasibility)?
1563 } else {
1564 None
1565 };
1566 let model = strengthened.as_ref().unwrap_or(model);
1567 let preserve_start = match (strengthened.as_ref(), start) {
1571 (Some(_), Some(s)) => {
1572 check::evaluate(original_model, &s.primal, &options.tolerances)?.feasible_candidate
1573 && !check::evaluate(model, &s.primal, &options.tolerances)?.feasible_candidate
1574 }
1575 _ => false,
1576 };
1577 if self.settings.decompose
1578 && !(model.is_mip() && self.settings.has_gap_limit())
1579 && !preserve_start
1580 && model.nnz() > 0
1581 && model.n() >= self.settings.decomposition_min_variables
1582 && !cancel.is_cancelled()
1583 && self.settings.time_limit_seconds != Some(0.)
1584 {
1585 if let Some(mut out) = components::solve_if_separable(
1586 &self.settings,
1587 model,
1588 options,
1589 start,
1590 cancel,
1591 call_started,
1592 )? {
1593 if strengthened.is_some() {
1594 if let Some(x) = &out.candidate {
1595 out.evaluation =
1596 Some(check::evaluate(original_model, x, &options.tolerances)?);
1597 }
1598 }
1599 return Ok(out);
1600 }
1601 }
1602 let settings = &self.settings;
1603 let mut budget = Budget {
1604 start: call_started,
1605 settings,
1606 cancel,
1607 pivots: 0,
1608 };
1609 let mut report = BackendReport::new("native");
1610 report.version = Some(env!("CARGO_PKG_VERSION").into());
1611 report.effective_options = effective_options(settings);
1612 if model.is_mip() && settings.has_gap_limit() {
1613 report.effective_options.retain(|(k, _)| k != "decompose");
1614 report
1615 .effective_options
1616 .push(("decompose".into(), "false".into()));
1617 report
1618 .effective_options
1619 .push(("gap_limit_scope".into(), "whole_model".into()));
1620 }
1621 report.start_status = match start {
1622 None => StartStatus::NotProvided,
1623 Some(_) if model.is_mip() => StartStatus::Evaluated,
1624 Some(_) => StartStatus::Rejected,
1625 };
1626 let mut result = SolveResult::empty(Status::Unknown, "", report);
1627 let mut pool = Incumbents {
1628 best: f64::INFINITY,
1629 upper: f64::INFINITY,
1630 certified: None,
1631 trace: (settings.mip_diagnostics && model.is_mip()).then(|| {
1632 diagnostics::SearchDiagnostics::new(model, call_started, settings.mip_trace_limit)
1633 }),
1634 original_model: diagnostic_original,
1635 pivots: 0,
1636 pilot,
1637 rounding_trials_left: 0,
1638 };
1639 let lattice = settings.objective_lattice && incumbent::integer_lattice(model);
1640 let tree_lattice = lattice && model.kinds().iter().all(|k| k.is_integral());
1644 let mut counters = Counters::default();
1645 let mut jump_stats = jump::Stats::default();
1646 if model.is_mip() {
1647 if let Some(s) = start {
1648 consider(
1649 original_model,
1650 s.primal.clone(),
1651 options,
1652 &mut result,
1653 &mut pool,
1654 "start",
1655 )?;
1656 }
1657 }
1658 let mut domain = propagate::Domain::with_equalities(
1659 model,
1660 settings.presolve,
1661 options.tolerances.feasibility,
1662 (settings.integer_equality_presolve && presolve::supported_arithmetic())
1663 .then_some(&options.tolerances),
1664 );
1665 let mut mixed = mixed::Domain::new(
1666 model,
1667 settings.presolve && settings.mixed_propagation,
1668 options.tolerances.feasibility,
1669 );
1670 if pool.trace.is_some() && settings.presolve {
1671 domain.enable_statistics();
1672 }
1673 let supported_choice_arithmetic = model.is_mip()
1674 && (settings.choice_route_depth > 0 || settings.choice_pair_depth > 0)
1675 && presolve::supported_arithmetic();
1676 let mut choice_domain = (supported_choice_arithmetic && settings.choice_route_depth > 0)
1677 .then(|| choice_route::Domain::read(model, &budget));
1678 let mut pair_domain = (model.is_mip()
1679 && ((supported_choice_arithmetic && settings.choice_pair_depth > 0)
1680 || settings.choice_local_depth > 0))
1681 .then(|| choice_mass::Separator::new(model, &budget));
1682 let mut tree_model = None::<Model>;
1683 let mut tree_separator = (model.is_mip() && settings.choice_tree_cut_limit > 0)
1684 .then(|| choice_mass::Separator::new(model, &budget));
1685 let mut conflicts = proof_conflicts::Pool::default();
1686 let mut root = std::borrow::Cow::Borrowed(model.variables());
1687 let mut root_refit = None::<RootRefit>;
1688 let mut node_box = NodeBox {
1689 bounds: root.as_ref().clone(),
1690 changed: Vec::new(),
1691 path: Vec::new(),
1692 previous: Vec::new(),
1693 };
1694 let mut open = std::collections::BinaryHeap::new();
1695 let (mut serial, mut snapshot_bytes) = (0u64, 0usize);
1696 let mut dive = Some(Node {
1697 branch: None,
1698 depth: 0,
1699 bound: None,
1700 basis: None,
1701 origin: None,
1702 });
1703 let probe_structure = settings
1704 .scalable_branching
1705 .then(|| branching_structure(model));
1706 let mut pseudocosts = Pseudocosts::new(model.n());
1707 pseudocosts.min_step = settings.pseudocost_min_step;
1708 let mut certifier = Certifier {
1709 lp: None,
1710 attempts: 0,
1711 certified: 0,
1712 last: None,
1713 lp_attempts: 0,
1714 witness_attempts: 0,
1715 witness_successes: 0,
1716 witness_work: 0,
1717 witness_outcome: witness::Outcome::NotAttempted,
1718 witness_assignment: None,
1719 };
1720 let mut keep = presolve::kept_rows(model, &root, settings);
1721 let mut closed_bound = f64::INFINITY;
1722 let mut all_bounds = true;
1723 let mut unresolved_leaf = f64::INFINITY;
1724 let mut consecutive_dive = 0usize;
1725 let mut status = Status::Optimal;
1726 let mut lp: Option<Lp> = None;
1727 let (mut removed_rows, mut removed_columns) = (0usize, 0usize);
1728 loop {
1729 let model = tree_model.as_ref().unwrap_or(model);
1730 if let Some(trace) = &mut pool.trace {
1731 trace.checkpoint(
1732 result.nodes,
1733 budget.pivots,
1734 diagnostic_frontier_bound(
1735 closed_bound,
1736 all_bounds,
1737 &open,
1738 dive.as_ref().map(|n| n.bound),
1739 )
1740 .map(|b| oriented(model, b)),
1741 open.len() + usize::from(dive.is_some()),
1742 );
1743 }
1744 let mut node = match dive.take() {
1745 Some(node) => {
1746 consecutive_dive += 1;
1747 node
1748 }
1749 None => match open.pop() {
1750 Some(Open { node, .. }) => {
1751 consecutive_dive = 0;
1752 if let Some(basis) = &node.basis {
1753 snapshot_bytes -= basis.bytes();
1754 }
1755 node
1756 }
1757 None => break,
1758 },
1759 };
1760 let stop = budget
1761 .stop()
1762 .or_else(|| {
1763 (model.is_mip() && settings.node_limit.is_some_and(|n| result.nodes >= n))
1764 .then_some(Status::NodeLimit)
1765 })
1766 .or_else(|| {
1767 (model.is_mip()
1768 && gap_reached(
1769 settings,
1770 model,
1771 &pool,
1772 &result,
1773 diagnostic_frontier_bound(
1774 closed_bound,
1775 all_bounds,
1776 &open,
1777 Some(node.bound),
1778 ),
1779 ))
1780 .then_some(Status::GapLimit)
1781 });
1782 if let Some(s) = stop {
1783 status = s;
1784 serial += 1;
1785 open.push(Open {
1786 key: node.bound.unwrap_or(f64::NEG_INFINITY),
1787 serial,
1788 node,
1789 });
1790 break;
1791 }
1792 if node.bound.is_some_and(|b| b >= pool.upper) {
1793 if let Some(trace) = &mut pool.trace {
1794 trace.enter_node(node.depth, open.len() + 1);
1795 trace.bound_prune(true, result.nodes, budget.pivots);
1796 }
1797 closed_bound = closed_bound.min(node.bound.unwrap());
1798 counters.pruned_nodes += 1;
1799 continue;
1800 }
1801 if let Some(trace) = &mut pool.trace {
1802 trace.enter_node(node.depth, open.len() + 1);
1803 }
1804 let conversion = Instant::now();
1805 let fresh = lp.is_none();
1806 let lp = match &mut lp {
1807 Some(lp) => lp,
1808 None => {
1809 let columns = presolve::kept_columns(model, &root, settings);
1810 let built = lp.insert(Lp::new(
1811 model,
1812 &keep,
1813 &columns,
1814 controls(model, options, settings),
1815 )?);
1816 removed_rows = built.removed_rows(model);
1817 removed_columns = built.removed_columns();
1818 built
1819 }
1820 };
1821 let sweep = match (&mut root_refit, &pool.certified) {
1823 (Some(refit), Some((seed, _)))
1824 if counters.root_refit_sweeps < settings.root_refit_sweeps
1825 && pool.upper < refit.last_upper
1826 && refit.last_upper - pool.upper >= refit.min_gain =>
1827 {
1828 Some((refit, seed))
1829 }
1830 _ => None,
1831 };
1832 if let Some((refit, seed)) = sweep {
1833 refit.last_upper = pool.upper;
1834 counters.root_refit_sweeps += 1;
1835 let tight = root_fix::narrow_box(
1836 model,
1837 &root,
1838 seed,
1839 pool.upper,
1840 &refit.duals,
1841 &budget,
1842 &mut counters.root_refit,
1843 )?
1844 .filter(|tight| {
1845 seed.iter()
1846 .enumerate()
1847 .all(|(j, &v)| tight.lower[j] <= v && v <= tight.upper[j])
1848 });
1849 if let Some(tight) = tight {
1850 closed_bound = closed_bound.min(pool.upper);
1853 lp.set_bounds(&tight.lower, &tight.upper)?;
1854 root = std::borrow::Cow::Owned(tight);
1855 node_box.bounds = root.as_ref().clone();
1856 node_box.changed.clear();
1857 let mut data = model.data().clone();
1860 data.variables = root.as_ref().clone();
1861 let narrowed = Model::new(data)?;
1862 domain = propagate::Domain::with_equalities(
1863 &narrowed,
1864 settings.presolve,
1865 options.tolerances.feasibility,
1866 (settings.integer_equality_presolve && presolve::supported_arithmetic())
1867 .then_some(&options.tolerances),
1868 );
1869 mixed = mixed::Domain::new(
1870 &narrowed,
1871 settings.presolve && settings.mixed_propagation,
1872 options.tolerances.feasibility,
1873 );
1874 if pool.trace.is_some() && settings.presolve {
1875 domain.enable_statistics();
1876 }
1877 counters.root_refit.applied += 1;
1878 }
1879 }
1880 if !node_box.enter(&root, &node.branch, lp)? {
1881 counters.root_refit_conflicts += 1;
1882 continue;
1883 }
1884 let before = node_box.changed.len();
1885 let mut feasible = domain.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
1886 if feasible && settings.mixed_propagation {
1887 for _ in 0..2 {
1888 let previous = node_box.changed.len();
1889 feasible =
1890 mixed.apply(model, &mut node_box.bounds, &mut node_box.changed, &budget)
1891 && domain.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
1892 if !feasible || previous == node_box.changed.len() {
1893 break;
1894 }
1895 }
1896 }
1897 if let Some(routes) = choice_domain
1898 .as_mut()
1899 .filter(|_| feasible && node.depth < settings.choice_route_depth)
1900 {
1901 let previous = node_box.changed.len();
1902 feasible = routes.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
1903 counters.choice_route_bounds += (node_box.changed.len() - previous) as u64;
1904 }
1905 if let Some(pairs) = pair_domain.as_ref().filter(|_| {
1906 feasible && supported_choice_arithmetic && node.depth < settings.choice_pair_depth
1907 }) {
1908 let previous = node_box.changed.len();
1909 feasible =
1910 pairs.propagate(model, &mut node_box.bounds, &mut node_box.changed, &budget);
1911 counters.choice_pair_bounds += (node_box.changed.len() - previous) as u64;
1912 }
1913 if feasible
1914 && (node.depth < settings.choice_pair_depth
1915 || node.depth < settings.choice_route_depth)
1916 {
1917 feasible = domain.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
1918 }
1919 if feasible && settings.proof_conflict_limit > 0 {
1920 let prior = node_box.changed.len();
1921 feasible = conflicts.apply(
1922 &mut node_box.bounds,
1923 &mut node_box.changed,
1924 &mut closed_bound,
1925 );
1926 if feasible && node_box.changed.len() != prior {
1927 feasible = domain.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
1928 }
1929 }
1930 if !feasible {
1931 counters.propagated_infeasible += 1;
1932 if node.depth == 0 {
1933 status = if result.candidate.is_some() {
1934 Status::NumericalFailure
1935 } else {
1936 Status::Infeasible
1937 };
1938 break;
1939 }
1940 continue;
1941 }
1942 for &j in &node_box.changed[before..] {
1943 lp.set_bound(j, node_box.bounds.lower[j], node_box.bounds.upper[j])?;
1944 }
1945 counters.implied_bounds += (node_box.changed.len() - before) as u64;
1946 let warm = if !settings.node_reoptimization {
1947 if !fresh {
1948 lp.reset_to_slack();
1949 }
1950 false
1951 } else {
1952 if let Some(basis) = &node.basis {
1953 lp.restore(basis);
1954 }
1955 !fresh
1956 };
1957 result.backend.conversion_seconds += conversion.elapsed().as_secs_f64();
1958 let solve = Instant::now();
1959 let before_pivots = budget.pivots;
1960 if warm {
1961 counters.warm_nodes += 1;
1962 } else {
1963 counters.cold_solves += 1;
1964 }
1965 let node_bounds = &node_box.bounds;
1966 let (mut s, mut cutoff) = if warm
1967 && settings.dual_cutoff_interval > 0
1968 && pool.upper.is_finite()
1969 {
1970 lp.solve_verified_cutoff(&mut budget, model, node_bounds, pool.upper, tree_lattice)?
1971 } else {
1972 (lp.solve(&mut budget, !warm)?, None)
1973 };
1974 let simplex_cutoff = cutoff.is_some();
1975 let mut checked_solution = None;
1976 let mut checked_bound = None;
1977 if warm && budget.stop().is_none() {
1978 let retry = match s {
1979 Status::Optimal => {
1980 let point = lp.point();
1981 let duals = lp.duals(model);
1982 if settings.safe_node_pruning && pool.upper.is_finite() {
1983 let objective = oriented(
1984 model,
1985 model.objective_offset()
1986 + model
1987 .objective()
1988 .iter()
1989 .zip(&point)
1990 .map(|(c, v)| c * v)
1991 .sum::<f64>(),
1992 );
1993 let margin = 1e-8 * (1. + pool.upper.abs());
1994 if objective >= pool.upper - margin {
1995 let bound =
1996 node_dual_bound(model, node_bounds, &duals, tree_lattice)?;
1997 checked_bound = Some(bound);
1998 cutoff = bound.filter(|&b| b >= pool.upper);
1999 }
2000 }
2001 if cutoff.is_some() {
2002 false
2003 } else if accepted(model, node_bounds, &point, &duals, options, settings) {
2004 checked_solution = Some((point, duals));
2005 false
2006 } else {
2007 checked_bound = None;
2008 true
2009 }
2010 }
2011 Status::Infeasible => !lp.infeasibility_verified(),
2012 Status::NumericalFailure => true,
2013 _ => false,
2014 };
2015 if retry {
2016 counters.fallbacks += 1;
2017 counters.cold_solves += 1;
2018 lp.reset_to_slack();
2019 s = lp.solve(&mut budget, true)?;
2020 if let Some(trace) = &mut pool.trace {
2021 trace.node_lp_solves += 1;
2022 }
2023 }
2024 }
2025 if s == Status::NumericalFailure
2026 && model.is_mip()
2027 && settings.steepest_edge
2028 && budget.stop().is_none()
2029 {
2030 counters.cold_solves += 1;
2031 counters.unweighted_retries += 1;
2032 if let Some(trace) = &mut pool.trace {
2033 trace.node_lp_solves += 1;
2034 }
2035 s = lp.retry_unweighted(&mut budget)?;
2036 if s == Status::Infeasible && !lp.infeasibility_verified() {
2037 s = Status::NumericalFailure;
2038 }
2039 }
2040 if s == Status::Infeasible && !lp.infeasibility_verified() {
2041 counters.unverified_infeasible += 1;
2042 }
2043 let node_seconds = solve.elapsed().as_secs_f64();
2044 result.backend.solve_seconds += node_seconds;
2045 if let Some(trace) = &mut pool.trace {
2046 trace.node_lp_solves += 1;
2047 trace.node_lp_pivots += budget.pivots - before_pivots;
2048 trace.node_lp_seconds += node_seconds;
2049 if node.depth == 0 {
2050 trace.root_lp(s, budget.pivots - before_pivots, node_seconds);
2051 }
2052 if s == Status::Infeasible {
2053 trace.infeasible_lps += 1;
2054 }
2055 }
2056 if model.is_mip() {
2057 result.nodes += 1;
2058 if node.depth == 0 {
2059 if let Some(trace) = &mut pool.pilot {
2060 trace.stage(
2061 "search_root_lp",
2062 (result.nodes, budget.pivots),
2063 (result.nodes - 1, before_pivots),
2064 solve,
2065 );
2066 }
2067 }
2068 }
2069 let checks = Instant::now();
2070 if let Some(bound) = cutoff {
2071 if settings.proof_conflict_limit > 0 && result.nodes % 16 == 0 {
2072 conflicts.learn(
2073 model,
2074 &root,
2075 node_bounds,
2076 &lp.duals(model),
2077 pool.upper,
2078 &budget,
2079 )?;
2080 }
2081 if let Some(origin) = node.origin.filter(|_| settings.cutoff_pseudocosts) {
2082 pseudocosts.record(
2083 origin,
2084 bound.min(pool.upper) - oriented(model, model.objective_offset()),
2085 );
2086 }
2087 if let Some(trace) = &mut pool.trace {
2088 trace.bound_prune(false, result.nodes, budget.pivots);
2089 }
2090 closed_bound = closed_bound.min(bound);
2091 counters.pruned_nodes += 1;
2092 if simplex_cutoff {
2093 counters.dual_cutoff_prunes += 1;
2094 } else {
2095 counters.safe_node_prunes += 1;
2096 }
2097 result.backend.check_seconds += checks.elapsed().as_secs_f64();
2098 continue;
2099 }
2100 if s == Status::Infeasible {
2101 if model.is_mip() && result.nodes == 1 {
2102 status = if result.candidate.is_some() {
2103 Status::NumericalFailure
2104 } else {
2105 Status::Infeasible
2106 };
2107 break;
2108 }
2109 if !model.is_mip() {
2110 status = s;
2111 break;
2112 }
2113 continue;
2114 }
2115 if s != Status::Optimal {
2116 if settings.partial_dual_bounds {
2117 let duals = lp.duals(model);
2118 if duals.row_duals.iter().all(|v| v.is_finite()) {
2119 if let Some(value) =
2120 safe_dual_bound_with_bounds(model, node_bounds, &duals.row_duals)?.bound
2121 {
2122 let b = oriented(model, value);
2123 let b = if tree_lattice {
2124 incumbent::lattice_ceil(b)
2125 } else {
2126 b
2127 };
2128 node.bound = Some(node.bound.map_or(b, |old| old.max(b)));
2129 if !model.is_mip() {
2130 result.best_bound = Some(oriented(model, b));
2131 }
2132 }
2133 }
2134 }
2135 status = if model.is_mip() && s == Status::Unbounded {
2136 Status::Unknown
2137 } else {
2138 s
2139 };
2140 serial += 1;
2141 open.push(Open {
2142 key: node.bound.unwrap_or(f64::NEG_INFINITY),
2143 serial,
2144 node: Node {
2145 basis: None,
2146 ..node
2147 },
2148 });
2149 break;
2150 }
2151 let checked = checked_solution.is_some();
2152 let (x, duals) = checked_solution.unwrap_or_else(|| (lp.point(), lp.duals(model)));
2153 if !checked && !accepted(model, node_bounds, &x, &duals, options, settings) {
2154 #[cfg(feature = "kernel-profile")]
2155 if std::env::var_os("LPIP_TRACE_SIMPLEX").is_some() {
2156 eprintln!(
2157 "acceptance failure {:?}",
2158 check::lp_residuals_with_bounds(model, node_bounds, &x, &duals)
2159 );
2160 }
2161 status = Status::NumericalFailure;
2162 all_bounds = false;
2163 break;
2164 }
2165 let mut bound = match checked_bound {
2166 Some(bound) => bound,
2167 None => node_dual_bound(model, node_bounds, &duals, tree_lattice)?,
2168 };
2169 if !model.is_mip() {
2170 result.evaluation = Some(check::evaluate(model, &x, &options.tolerances)?);
2171 if let Some(trace) = &mut pool.pilot {
2172 trace.checked_point(&x, options, "lp_solution", (result.nodes, budget.pivots));
2173 }
2174 result.candidate = Some(x);
2175 result.duals = Some(duals);
2176 result.best_bound = bound.map(|b| oriented(model, b));
2177 result.backend.check_seconds += checks.elapsed().as_secs_f64();
2178 break;
2179 }
2180 let objective = oriented(
2181 model,
2182 model.objective().iter().zip(&x).map(|(c, v)| c * v).sum(),
2183 );
2184 pool.pivots = budget.pivots;
2185 if let Some(trace) = &mut pool.trace {
2186 trace.checkpoint(
2187 result.nodes,
2188 budget.pivots,
2189 diagnostic_frontier_bound(closed_bound, all_bounds, &open, Some(bound))
2190 .map(|b| oriented(model, b)),
2191 open.len() + 1,
2192 );
2193 if node.depth == 0 {
2194 let fractional = (0..model.n())
2195 .filter(|&j| {
2196 model.kinds()[j].is_integral()
2197 && (x[j] - x[j].round()).abs() > options.tolerances.integrality
2198 })
2199 .count();
2200 trace.root_solution(
2201 result.nodes,
2202 budget.pivots,
2203 model.objective_offset() + oriented(model, objective),
2204 bound.map(|b| oriented(model, b)),
2205 fractional,
2206 );
2207 }
2208 }
2209 if let Some(origin) = node.origin {
2210 pseudocosts.record(origin, objective);
2211 }
2212 let branch =
2213 branching_variable(model, node_bounds, &x, options, &pseudocosts, settings);
2214 if branch.is_some()
2215 && settings.incumbent_heuristic
2216 && (result.nodes == 1 || !pool.upper.is_finite() || pool.rounding_trials_left > 0)
2217 {
2218 let found = heuristic(
2219 model,
2220 node_bounds,
2221 &x,
2222 options,
2223 &mut result,
2224 &mut pool,
2225 &budget,
2226 )?;
2227 counters.heuristic_candidates += found;
2228 pool.rounding_trials_left = if found > 0 {
2229 0
2230 } else {
2231 pool.rounding_trials_left.saturating_sub(1)
2232 };
2233 }
2234 if node.depth == 0 {
2235 if let Some(trace) = &mut pool.pilot {
2236 trace.skip = if branch.is_some() {
2237 "disabled"
2238 } else {
2239 "integral_root"
2240 };
2241 trace.event(
2242 "root_relaxation",
2243 "search_root_lp",
2244 (result.nodes, budget.pivots),
2245 Some(model.objective_offset() + oriented(model, objective)),
2246 bound.map(|b| oriented(model, b)),
2247 );
2248 }
2249 if branch.is_some()
2250 && (settings.feasibility_jump
2251 || settings.local_mip_effort != 0
2252 || pool.pilot.is_some())
2253 {
2254 jump_stats = root_local_search(
2255 model,
2256 (node_bounds, &x),
2257 options,
2258 &budget,
2259 &mut result,
2260 &mut pool,
2261 )?;
2262 }
2263 }
2264 certify(
2265 model,
2266 options,
2267 settings,
2268 &keep,
2269 &mut certifier,
2270 &mut pool,
2271 &mut result,
2272 &mut budget,
2273 )?;
2274 if let Some(separator) = pair_domain.as_mut().filter(|_| {
2275 branch.is_some()
2276 && node.depth < settings.choice_local_depth
2277 && !bound.is_some_and(|b| b >= pool.upper)
2278 && budget.stop().is_none()
2279 }) {
2280 let local = separator.shallow_bound(model, node_bounds, (lp, &x), &mut budget)?;
2281 counters.choice_local_rounds += local.rounds;
2282 counters.choice_local_cuts += local.cuts;
2283 if let Some(local_bound) = local.bound {
2284 bound = Some(bound.map_or(local_bound, |b| b.max(local_bound)));
2285 if local_bound >= pool.upper {
2286 counters.choice_local_prunes += 1;
2287 }
2288 }
2289 }
2290 if let Some(b) = bound.filter(|_| settings.root_refit_sweeps > 0 && node.depth == 0) {
2291 root_refit = Some(RootRefit {
2292 duals: duals.clone(),
2293 last_upper: pool.upper,
2294 min_gain: if pool.upper.is_finite() {
2295 settings.root_refit_fraction * (pool.upper - b).max(0.)
2296 } else {
2297 0.
2298 },
2299 });
2300 }
2301 let mut stop_after_root = false;
2302 if node.depth == 0 && branch.is_some() {
2303 if let Some(trace) = &mut pool.pilot {
2304 trace.root_end((result.nodes, budget.pivots));
2305 stop_after_root = trace.controls.stop_at_root;
2306 }
2307 }
2308 if stop_after_root
2309 || gap_reached(
2310 settings,
2311 model,
2312 &pool,
2313 &result,
2314 diagnostic_frontier_bound(closed_bound, all_bounds, &open, Some(bound)),
2315 )
2316 {
2317 node.bound = bound;
2318 serial += 1;
2319 open.push(Open {
2320 key: bound.unwrap_or(f64::NEG_INFINITY),
2321 serial,
2322 node,
2323 });
2324 status = if stop_after_root {
2325 Status::Unknown
2326 } else {
2327 Status::GapLimit
2328 };
2329 break;
2330 }
2331 if bound.is_some_and(|b| b >= pool.upper) {
2332 if settings.proof_conflict_limit > 0 && result.nodes % 16 == 0 {
2333 conflicts.learn(model, &root, node_bounds, &duals, pool.upper, &budget)?;
2334 }
2335 if let Some(trace) = &mut pool.trace {
2336 trace.bound_prune(false, result.nodes, budget.pivots);
2337 }
2338 closed_bound = closed_bound.min(bound.unwrap());
2339 counters.pruned_nodes += 1;
2340 result.backend.check_seconds += checks.elapsed().as_secs_f64();
2341 continue;
2342 }
2343 if let Some(separator) = tree_separator.as_mut().filter(|_| {
2344 branch.is_some()
2345 && node.depth >= 4
2346 && counters.choice_tree_cuts < settings.choice_tree_cut_limit
2347 && result.nodes % settings.choice_tree_cut_interval == 0
2348 && budget.stop().is_none()
2349 }) {
2350 let mut cuts = separator.separate(&x, &budget);
2351 cuts.truncate((settings.choice_tree_cut_limit - counters.choice_tree_cuts).min(8));
2352 if !cuts.is_empty() {
2353 let mut extended = model.clone();
2354 certified_cuts::append(&mut extended, &cuts)?;
2355 if let Ok(mut added) = lp.extend_rows(&extended, model.m()) {
2356 added.set_bounds(&node_bounds.lower, &node_bounds.upper)?;
2357 *lp = added;
2358 keep.resize(extended.m(), true);
2359 if let Some(refit) = &mut root_refit {
2360 refit.duals.row_duals.resize(extended.m(), 0.);
2361 }
2362 counters.choice_tree_cuts += cuts.len();
2363 certifier.lp = None;
2364 node.basis = None;
2365 node.bound = bound;
2366 dive = Some(node);
2367 tree_model = Some(extended);
2368 continue;
2369 }
2370 }
2371 }
2372 let mut probe_seconds = 0.;
2373 let mut probe_bounds = Vec::new();
2374 let branch = if branch.is_some()
2375 && (((settings.reliability_branching || settings.scalable_branching)
2376 && node.depth <= 8
2377 && probe_count_available(settings, &counters))
2378 || (node.depth == 0 && settings.strong_branching))
2379 && settings.node_reoptimization
2380 && (if settings.scalable_branching {
2381 true
2382 } else if settings.reliability_branching {
2383 model.n() <= 1024 && model.m() <= 1024 && model.nnz() <= 20000
2384 } else {
2385 eligible_strong_branching(model)
2386 }) {
2387 let probe_started = Instant::now();
2388 let chosen = strong_branch(
2389 model,
2390 node_bounds,
2391 &x,
2392 objective,
2393 options,
2394 lp,
2395 &mut pseudocosts,
2396 &mut budget,
2397 &mut result.nodes,
2398 &mut counters,
2399 probe_structure.as_deref(),
2400 &mut probe_bounds,
2401 )?;
2402 probe_seconds = probe_started.elapsed().as_secs_f64();
2403 result.backend.solve_seconds += probe_seconds;
2404 probe_bounds
2405 .iter()
2406 .max_by_key(|(_, sides)| {
2407 sides
2408 .iter()
2409 .filter(|b| b.is_some_and(|v| v >= pool.upper))
2410 .count()
2411 })
2412 .filter(|(_, sides)| sides.iter().any(|b| b.is_some_and(|v| v >= pool.upper)))
2413 .map(|(j, _)| *j)
2414 .or(chosen)
2415 .or(branch)
2416 } else {
2417 branch
2418 };
2419 if let Some(j) = branch {
2420 if counters.branch_events.len() < settings.branch_trace_limit {
2421 let mut columns = vec![j];
2422 columns.extend(
2423 (0..model.n())
2424 .filter(|&k| {
2425 k != j
2426 && model.kinds()[k].is_integral()
2427 && (x[k] - x[k].round()).abs() > options.tolerances.integrality
2428 })
2429 .take(15),
2430 );
2431 let number = |v: f64| {
2433 if v.is_finite() {
2434 v.to_string()
2435 } else {
2436 "null".into()
2437 }
2438 };
2439 let candidates = columns
2440 .iter()
2441 .map(|&k| {
2442 format!(
2443 "{{\"column\":{k},\"value\":{},\"down_sum\":{},\"up_sum\":{},\"down_count\":{},\"up_count\":{},\"down_estimate\":{},\"up_estimate\":{}}}",
2444 number(x[k]),
2445 number(pseudocosts.sum[k][0]),
2446 number(pseudocosts.sum[k][1]),
2447 pseudocosts.count[k][0],
2448 pseudocosts.count[k][1],
2449 number(pseudocosts.estimate(k, false)),
2450 number(pseudocosts.estimate(k, true))
2451 )
2452 })
2453 .collect::<Vec<_>>()
2454 .join(",");
2455 counters.branch_events.push(format!(
2456 "{{\"node\":{},\"chosen\":{j},\"candidates\":[{candidates}]}}",
2457 result.nodes
2458 ));
2459 }
2460 let limit = if tree_lattice {
2461 16
2462 } else {
2463 settings.mixed_fix_trials.min(128)
2464 };
2465 let fix_depth = if tree_lattice {
2466 8
2467 } else {
2468 settings.mixed_fix_depth
2469 };
2470 let fixes = if settings.reduced_cost_fixing
2471 && limit > 0
2472 && (fix_depth == 0 || node.depth <= fix_depth)
2473 {
2474 let (fixes, tests) = reduced_cost_fixes(
2475 model,
2476 node_bounds,
2477 &x,
2478 &duals,
2479 (pool.upper, bound),
2480 limit,
2481 &budget,
2482 )?;
2483 if !tree_lattice {
2484 counters.mixed_fix_tests += tests;
2485 }
2486 fixes
2487 } else {
2488 Vec::new()
2489 };
2490 let mut child_parent = node.branch.clone();
2491 if !fixes.is_empty() {
2492 closed_bound = closed_bound.min(pool.upper);
2493 counters.reduced_cost_fixings += fixes.len() as u64;
2494 for (column, value) in fixes {
2495 child_parent = Some(Arc::new(Branch {
2496 parent: child_parent,
2497 j: column,
2498 lower: value,
2499 upper: value,
2500 }));
2501 }
2502 }
2503 for &(k, sides) in probe_bounds.iter().filter(|(k, _)| *k != j) {
2504 let [down, up] = sides;
2505 if let Some(b) = down.filter(|&b| b >= pool.upper) {
2506 closed_bound = closed_bound.min(b);
2507 counters.probe_proof_fixings += 1;
2508 child_parent = Some(Arc::new(Branch {
2509 parent: child_parent,
2510 j: k,
2511 lower: x[k].ceil(),
2512 upper: node_bounds.upper[k],
2513 }));
2514 } else if let Some(b) = up.filter(|&b| b >= pool.upper) {
2515 closed_bound = closed_bound.min(b);
2516 counters.probe_proof_fixings += 1;
2517 child_parent = Some(Arc::new(Branch {
2518 parent: child_parent,
2519 j: k,
2520 lower: node_bounds.lower[k],
2521 upper: x[k].floor(),
2522 }));
2523 }
2524 }
2525 let sides = probe_bounds
2526 .iter()
2527 .find(|(k, _)| *k == j)
2528 .map_or([None; 2], |(_, v)| *v);
2529 let (l, u) = (node_bounds.lower[j], node_bounds.upper[j]);
2530 let (floor, ceil) = (x[j].floor(), x[j].ceil());
2531 let mut child = |lower: f64, upper: f64, up: bool| {
2532 let child_bound = match (bound, sides[usize::from(up)]) {
2533 (Some(a), Some(b)) => Some(a.max(b)),
2534 (a, b) => a.or(b),
2535 };
2536 if let Some(b) = child_bound.filter(|&b| b >= pool.upper) {
2537 closed_bound = closed_bound.min(b);
2538 counters.probe_proof_prunes += 1;
2539 return None;
2540 }
2541 (lower <= upper).then(|| Node {
2542 branch: Some(Arc::new(Branch {
2543 parent: child_parent.clone(),
2544 j,
2545 lower,
2546 upper,
2547 })),
2548 depth: node.depth + 1,
2549 bound: child_bound,
2550 basis: None,
2551 origin: Some(Origin {
2552 j,
2553 up,
2554 distance: if up { ceil - x[j] } else { x[j] - floor },
2555 parent_objective: objective,
2556 }),
2557 })
2558 };
2559 let (down, up) = (child(l, u.min(floor), false), child(l.max(ceil), u, true));
2560 let prefer_up = if settings.estimated_diving {
2561 let up_gain = pseudocosts.estimate(j, true) * (ceil - x[j]);
2562 let down_gain = pseudocosts.estimate(j, false) * (x[j] - floor);
2563 up_gain < down_gain || (up_gain == down_gain && x[j] - floor >= 0.5)
2564 } else {
2565 x[j] - floor >= 0.5
2566 };
2567 let (next, other) = if prefer_up { (up, down) } else { (down, up) };
2570 if let Some(mut other) = other {
2571 let size = lp.snapshot_bytes();
2572 if settings.node_reoptimization
2573 && snapshot_bytes + size <= SNAPSHOT_BUDGET_BYTES
2574 {
2575 other.basis = Some(Arc::new(lp.snapshot()));
2576 snapshot_bytes += size;
2577 }
2578 serial += 1;
2579 open.push(Open {
2580 key: other.bound.unwrap_or(f64::NEG_INFINITY),
2581 serial,
2582 node: other,
2583 });
2584 }
2585 match next {
2586 Some(next)
2588 if settings.dive_node_limit > 0
2589 && consecutive_dive >= settings.dive_node_limit =>
2590 {
2591 serial += 1;
2592 open.push(Open {
2593 key: next.bound.unwrap_or(f64::NEG_INFINITY),
2594 serial,
2595 node: next,
2596 });
2597 }
2598 next => dive = next,
2599 }
2600 } else {
2601 pool.pivots = budget.pivots;
2602 if let Some(trace) = &mut pool.trace {
2603 trace.integral_leaves += 1;
2604 }
2605 let mut point = x;
2606 for (j, v) in point.iter_mut().enumerate() {
2607 if model.kinds()[j].is_integral() {
2608 *v = v.round();
2609 }
2610 }
2611 if !consider(
2612 model,
2613 point,
2614 options,
2615 &mut result,
2616 &mut pool,
2617 "integral_leaf",
2618 )? {
2619 if !settings.repair_integral_leaves {
2620 status = Status::NumericalFailure;
2621 all_bounds = false;
2622 break;
2623 }
2624 let mut assignment = lp.point();
2625 for (j, value) in assignment.iter_mut().enumerate() {
2626 if model.kinds()[j].is_integral() {
2627 *value = value.round();
2628 }
2629 }
2630 counters.leaf_repair_attempts += 1;
2631 let repaired = if budget.stop().is_none() {
2632 repair_leaf(
2633 model,
2634 pool.original_model,
2635 node_bounds,
2636 &assignment,
2637 &keep,
2638 options,
2639 &mut budget,
2640 )?
2641 } else {
2642 None
2643 };
2644 let mut closed_by_repair = false;
2647 if let Some(point) = repaired {
2648 let objective = oriented(
2649 model,
2650 model.objective_offset()
2651 + model
2652 .objective()
2653 .iter()
2654 .zip(&point)
2655 .map(|(c, v)| c * v)
2656 .sum::<f64>(),
2657 );
2658 let closes = bound.is_some_and(|b| {
2659 objective - b <= settings.dual_tolerance * (1. + objective.abs())
2660 });
2661 if consider(
2662 model,
2663 point,
2664 options,
2665 &mut result,
2666 &mut pool,
2667 "repaired_leaf",
2668 )? && closes
2669 {
2670 counters.leaf_repaired += 1;
2671 closed_by_repair = true;
2672 }
2673 }
2674 if closed_by_repair {
2675 } else if let Some((j, split)) =
2677 integral_resplit(model, node_bounds, &assignment)
2678 {
2679 let child = |lower: f64, upper: f64| Node {
2680 bound,
2681 branch: Some(Arc::new(Branch {
2682 parent: node.branch.clone(),
2683 j,
2684 lower,
2685 upper,
2686 })),
2687 depth: node.depth + 1,
2688 basis: None,
2689 origin: None,
2690 };
2691 let down = child(node_bounds.lower[j], split);
2692 let up = child(split + 1., node_bounds.upper[j]);
2693 serial += 1;
2694 open.push(Open {
2695 key: bound.unwrap_or(f64::NEG_INFINITY),
2696 serial,
2697 node: down,
2698 });
2699 dive = Some(up);
2700 counters.leaf_resplits += 1;
2701 continue;
2702 } else {
2703 let residual = bound.unwrap_or(f64::NEG_INFINITY);
2704 unresolved_leaf = unresolved_leaf.min(residual);
2705 if let Some(b) = bound {
2706 closed_bound = closed_bound.min(b);
2707 } else {
2708 all_bounds = false;
2709 }
2710 counters.leaf_open += 1;
2711 continue;
2712 }
2713 }
2714 pool.rounding_trials_left = 0;
2715 certify(
2716 model,
2717 options,
2718 settings,
2719 &keep,
2720 &mut certifier,
2721 &mut pool,
2722 &mut result,
2723 &mut budget,
2724 )?;
2725 if let Some(b) = bound {
2726 closed_bound = closed_bound.min(b);
2727 } else {
2728 all_bounds = false;
2729 }
2730 }
2731 result.backend.check_seconds +=
2732 (checks.elapsed().as_secs_f64() - probe_seconds).max(0.);
2733 }
2734 if model.is_mip() {
2735 if status == Status::Optimal && unresolved_leaf < pool.upper {
2736 status = Status::NumericalFailure;
2737 }
2738 for o in open.iter().map(|o| &o.node).chain(dive.as_ref()) {
2739 if let Some(b) = o.bound {
2740 closed_bound = closed_bound.min(b);
2741 } else {
2742 all_bounds = false;
2743 }
2744 }
2745 if all_bounds && closed_bound.is_finite() {
2746 let bound = if lattice {
2747 incumbent::lattice_ceil(closed_bound)
2748 } else {
2749 closed_bound
2750 };
2751 result.best_bound = Some(oriented(model, bound));
2752 }
2753 if status == Status::Optimal && result.candidate.is_none() {
2754 status = Status::Infeasible;
2755 }
2756 }
2757 if status == Status::Optimal {
2758 if let (Some(e), Some(b)) = (&result.evaluation, result.best_bound) {
2759 let gap = oriented(model, e.objective) - oriented(model, b);
2760 if gap < -settings.dual_tolerance * (1.0 + e.objective.abs()) {
2761 if let Some((x, e)) = pool.certified {
2762 let gap = oriented(model, e.objective) - oriented(model, b);
2763 if gap >= -settings.dual_tolerance * (1.0 + e.objective.abs()) {
2764 result.candidate = Some(x);
2765 result.evaluation = Some(e);
2766 } else {
2767 status = Status::NumericalFailure;
2768 }
2769 } else {
2770 status = Status::NumericalFailure;
2771 }
2772 }
2773 }
2774 }
2775 let model = tree_model.as_ref().unwrap_or(model);
2776 let stats = lp.as_ref().map(|lp| lp.stats).unwrap_or_default();
2777 result.backend.effective_options.extend(
2778 [
2779 ("factor_peak_entries", stats.peak_entries as u64),
2780 ("refactorizations", stats.refactors),
2781 ("phase_one_pivots", stats.phase_one_pivots),
2782 ("degenerate_pivots", stats.degenerate_pivots),
2783 ("weight_resets", stats.weight_resets),
2784 ("row_pricings", stats.row_pricings),
2785 ("column_pricings", stats.column_pricings),
2786 ("replayed_pivots", stats.replayed_pivots),
2787 ("basis_updates", stats.updates),
2788 ("forrest_tomlin_updates", stats.ft_updates),
2789 ("bound_flips", stats.bound_flips),
2790 ("basis_repairs", stats.repairs),
2791 ("basis_restores", stats.restores),
2792 ("cost_perturbations", stats.perturbations),
2793 ("component_count", 1),
2794 ("component_workers", 1),
2795 ("reoptimized_nodes", counters.warm_nodes),
2796 ("presolve_removed_rows", removed_rows as u64),
2797 ("presolve_removed_columns", removed_columns as u64),
2798 ("cold_lp_solves", counters.cold_solves),
2799 ("cold_fallbacks", counters.fallbacks),
2800 ("unweighted_node_retries", counters.unweighted_retries),
2801 (
2802 "unverified_infeasible_nodes",
2803 counters.unverified_infeasible,
2804 ),
2805 ("heuristic_candidates", counters.heuristic_candidates),
2806 ("mixed_propagation_rows", mixed.stats.rows),
2807 ("mixed_propagation_visits", mixed.stats.visits),
2808 ("mixed_propagation_terms", mixed.stats.terms),
2809 ("mixed_propagation_changes", mixed.stats.changes),
2810 ("mixed_propagation_infeasibilities", mixed.stats.infeasible),
2811 ("mixed_propagation_work_limits", mixed.stats.limits),
2812 ("feasibility_jump_steps", jump_stats.steps),
2813 ("feasibility_jump_work", jump_stats.work),
2814 ("feasibility_jump_candidates", jump_stats.feasible),
2815 ("feasibility_jump_weight_bumps", jump_stats.bumps),
2816 ("pruned_nodes", counters.pruned_nodes),
2817 (
2818 "propagated_infeasible_nodes",
2819 counters.propagated_infeasible,
2820 ),
2821 ("implied_bounds", counters.implied_bounds),
2822 ("strong_branch_probes", counters.strong_probes),
2823 ("strong_branch_pivots", counters.strong_pivots),
2824 ("strong_branch_work", counters.strong_work),
2825 ("strong_branch_work_exits", counters.strong_work_exits),
2826 ("reduced_cost_fixings", counters.reduced_cost_fixings),
2827 ("mixed_fix_tests", counters.mixed_fix_tests),
2828 ("root_refit_sweeps", counters.root_refit_sweeps as u64),
2829 ("root_refit_tests", counters.root_refit.tests),
2830 ("root_refit_certified", counters.root_refit.certified),
2831 ("root_refit_implied", counters.root_refit.implied),
2832 ("root_refit_applied", counters.root_refit.applied),
2833 ("root_refit_conflicts", counters.root_refit_conflicts),
2834 ("choice_route_bounds", counters.choice_route_bounds),
2835 ("choice_pair_bounds", counters.choice_pair_bounds),
2836 ("choice_local_rounds", counters.choice_local_rounds),
2837 ("choice_local_cuts", counters.choice_local_cuts),
2838 ("choice_local_prunes", counters.choice_local_prunes),
2839 ("safe_node_prunes", counters.safe_node_prunes),
2840 ("dual_cutoff_prunes", counters.dual_cutoff_prunes),
2841 ("probe_proof_prunes", counters.probe_proof_prunes),
2842 ("probe_proof_fixings", counters.probe_proof_fixings),
2843 ("choice_tree_cuts", counters.choice_tree_cuts as u64),
2844 ("conflict_learned", conflicts.learned),
2845 ("conflict_prunes", conflicts.prunes),
2846 ("conflict_implications", conflicts.implications),
2847 ("leaf_repair_attempts", counters.leaf_repair_attempts),
2848 ("leaf_repaired", counters.leaf_repaired),
2849 ("leaf_resplits", counters.leaf_resplits),
2850 ("leaf_open", counters.leaf_open),
2851 ("certification_solves", certifier.lp_attempts),
2852 ("rational_witness_attempts", certifier.witness_attempts),
2853 ("rational_witness_successes", certifier.witness_successes),
2854 ("rational_witness_work", certifier.witness_work),
2855 ("certified_incumbents", certifier.certified),
2856 ]
2857 .map(|(k, v)| (format!("diagnostics.{k}"), v.to_string())),
2858 );
2859 result
2860 .backend
2861 .effective_options
2862 .push(("diagnostics.objective_lattice".into(), lattice.to_string()));
2863 if let Some(x) = result.candidate.as_ref().filter(|_| strengthened.is_some()) {
2864 result.evaluation = Some(check::evaluate(original_model, x, &options.tolerances)?);
2865 }
2866 result.status = status;
2867 result.iterations = budget.pivots;
2868 if pool.trace.is_some() {
2869 result.backend.effective_options.push((
2870 "diagnostics.rational_witness_outcome".into(),
2871 certifier.witness_outcome.as_str().into(),
2872 ));
2873 if let Some(hash) = certifier.witness_assignment {
2874 result.backend.effective_options.push((
2875 "diagnostics.rational_witness_assignment".into(),
2876 format!("{hash:016x}"),
2877 ));
2878 }
2879 }
2880 if let Some(trace) = pool.trace.take() {
2881 trace.finish(&mut result, domain.statistics(), diagnostic_original, model);
2882 }
2883 if settings.branch_trace_limit > 0 {
2884 result.backend.effective_options.push((
2885 "diagnostics.branch_trace".into(),
2886 format!("[{}]", counters.branch_events.join(",")),
2887 ));
2888 }
2889 result.message = format!(
2890 "Native dual simplex numerical solve: {} (not an exact certificate)",
2891 status.as_str()
2892 );
2893 result.backend.raw_status = Some(status.as_str().into());
2894 result.backend.total_seconds = budget.start.elapsed().as_secs_f64();
2895 result.backend.time_budget_exceeded = settings
2896 .time_limit_seconds
2897 .is_some_and(|t| result.backend.total_seconds > t);
2898 Ok(result)
2899 }
2900}
2901
2902fn repair_leaf(
2903 model: &Model,
2904 original: &Model,
2905 bounds: &Bounds,
2906 assignment: &[f64],
2907 kept_rows: &[bool],
2908 options: &Options,
2909 budget: &mut Budget<'_>,
2910) -> Result<Option<Vec<f64>>> {
2911 let valid = |x: &[f64]| -> Result<bool> {
2912 let tolerance = options.tolerances.feasibility;
2913 Ok(x.iter()
2914 .enumerate()
2915 .all(|(j, &v)| bounds.lower[j] - tolerance <= v && v <= bounds.upper[j] + tolerance)
2916 && check::evaluate(model, x, &options.tolerances)?.feasible_candidate
2917 && check::evaluate(original, x, &options.tolerances)?.feasible_candidate)
2918 };
2919 if budget.settings.rational_certification {
2920 if let (Some(witness), _, _) =
2921 witness::upper(model, assignment, budget, witness::ATTEMPT_WORK)
2922 {
2923 if valid(&witness.point)? {
2924 return Ok(Some(witness.point));
2925 }
2926 }
2927 }
2928 if budget.stop().is_some() {
2929 return Ok(None);
2930 }
2931 let mut fixed = bounds.clone();
2932 for (j, &value) in assignment
2933 .iter()
2934 .enumerate()
2935 .filter(|(j, _)| model.kinds()[*j].is_integral())
2936 {
2937 if value < fixed.lower[j] || value > fixed.upper[j] {
2938 return Ok(None);
2939 }
2940 fixed.lower[j] = value;
2941 fixed.upper[j] = value;
2942 }
2943 let settings = NativeOptions {
2944 iteration_limit: Some(
2945 budget
2946 .settings
2947 .iteration_limit
2948 .unwrap_or(u64::MAX)
2949 .min(budget.pivots.saturating_add(384)),
2950 ),
2951 ..budget.settings.clone()
2952 };
2953 let mut attempt = Budget {
2954 settings: &settings,
2955 ..*budget
2956 };
2957 let columns = presolve::kept_columns(model, model.variables(), &settings);
2958 let mut lp = Lp::new(
2959 model,
2960 kept_rows,
2961 &columns,
2962 controls(model, options, &settings),
2963 )?;
2964 lp.set_bounds(&fixed.lower, &fixed.upper)?;
2965 let solved = lp.solve(&mut attempt, true)?;
2966 budget.pivots = attempt.pivots;
2967 if solved == Status::Optimal {
2968 let point = lp.point();
2969 if valid(&point)? {
2970 return Ok(Some(point));
2971 }
2972 }
2973 Ok(None)
2974}
2975
2976fn integral_resplit(model: &Model, bounds: &Bounds, point: &[f64]) -> Option<(usize, f64)> {
2977 point.iter().enumerate().find_map(|(j, &v)| {
2978 if !model.kinds()[j].is_integral() || bounds.lower[j] == bounds.upper[j] {
2979 None
2980 } else {
2981 let split = if v < bounds.upper[j] { v } else { v - 1. };
2982 (bounds.lower[j] <= split && split + 1. <= bounds.upper[j]).then_some((j, split))
2983 }
2984 })
2985}
2986
2987fn node_dual_bound(
2988 model: &Model,
2989 bounds: &Bounds,
2990 duals: &Duals,
2991 lattice: bool,
2992) -> Result<Option<f64>> {
2993 Ok(
2994 safe_dual_bound_with_bounds(model, bounds, &duals.row_duals)?
2995 .bound
2996 .map(|b| {
2997 let b = oriented(model, b);
2998 if lattice {
2999 incumbent::lattice_ceil(b)
3000 } else {
3001 b
3002 }
3003 }),
3004 )
3005}
3006
3007fn reduced_cost_fixes(
3011 model: &Model,
3012 bounds: &Bounds,
3013 x: &[f64],
3014 duals: &Duals,
3015 (upper, parent_bound): (f64, Option<f64>),
3016 limit: usize,
3017 budget: &Budget<'_>,
3018) -> Result<(Vec<(usize, f64)>, u64)> {
3019 let Some(parent_bound) = parent_bound.filter(|_| upper.is_finite()) else {
3020 return Ok((Vec::new(), 0));
3021 };
3022 let _fixing = crate::profile::enter("reduced_cost_fixing");
3023 let gap = (upper - parent_bound).max(0.);
3024 let mut trials = Vec::new();
3025 for (j, &value) in x.iter().enumerate() {
3026 if !model.kinds()[j].is_integral()
3027 || value.fract() != 0.
3028 || bounds.upper[j] - bounds.lower[j] < 1.
3029 {
3030 continue;
3031 }
3032 let rc = oriented(model, duals.reduced_costs[j]);
3033 let gain = if value == bounds.lower[j] {
3034 rc
3035 } else if value == bounds.upper[j] {
3036 -rc
3037 } else {
3038 continue;
3039 };
3040 if gain.is_finite() && gain > 0. && gain >= 0.9 * gap {
3041 trials.push((j, value, gain));
3042 }
3043 }
3044 trials.sort_by(|a, b| b.2.total_cmp(&a.2).then(a.0.cmp(&b.0)));
3045 trials.truncate(limit);
3046 if trials.is_empty() {
3047 return Ok((Vec::new(), 0));
3048 }
3049 let mut prepared = if trials.len() >= 2 {
3050 let _prepare = crate::profile::enter("fixing_prepare");
3051 Some(lp_ip_craft::PreparedDualBound::new(
3052 model,
3053 bounds,
3054 &duals.row_duals,
3055 )?)
3056 } else {
3057 None
3058 };
3059 let mut opposite = bounds.clone();
3060 let mut fixes = Vec::new();
3061 let mut tests = 0;
3062 for (j, value, _) in trials {
3063 if budget.stop().is_some() {
3064 break;
3065 }
3066 let (lo, hi) = (opposite.lower[j], opposite.upper[j]);
3067 if value == lo {
3068 opposite.lower[j] = lo + 1.;
3069 } else {
3070 opposite.upper[j] = hi - 1.;
3071 }
3072 tests += 1;
3073 let proof = {
3074 let _bound = crate::profile::enter("fixing_bound");
3075 let report = if let Some(cache) = &mut prepared {
3076 cache.set_bound(j, opposite.lower[j], opposite.upper[j])?;
3077 cache.bound()
3078 } else {
3079 safe_dual_bound_with_bounds(model, &opposite, &duals.row_duals)?
3080 };
3081 report.bound.map(|v| oriented(model, v))
3082 };
3083 if proof.is_some_and(|b| b >= upper) {
3084 opposite.lower[j] = value;
3085 opposite.upper[j] = value;
3086 fixes.push((j, value));
3087 } else {
3088 opposite.lower[j] = lo;
3089 opposite.upper[j] = hi;
3090 }
3091 if let Some(cache) = &mut prepared {
3092 cache.set_bound(j, opposite.lower[j], opposite.upper[j])?;
3093 }
3094 }
3095 Ok((fixes, tests))
3096}
3097
3098fn eligible_strong_branching(model: &Model) -> bool {
3100 (12..=256).contains(&model.n())
3101 && model.m() <= 512
3102 && model.nnz() <= 10000
3103 && model
3104 .matrix()
3105 .pattern
3106 .indptr
3107 .windows(2)
3108 .filter(|w| w[1] - w[0] > 8)
3109 .take(2)
3110 .count()
3111 == 2
3112}
3113
3114fn branching_structure(model: &Model) -> Vec<f64> {
3115 let mut structure = vec![0.; model.n()];
3116 let a = model.matrix();
3117 for range in a.pattern.indptr.windows(2) {
3118 let degree = (range[1] - range[0]).max(1) as f64;
3119 for &j in &a.pattern.indices[range[0]..range[1]] {
3120 structure[j] += 1. / degree;
3121 }
3122 }
3123 structure
3124}
3125
3126fn probe_count_available(settings: &NativeOptions, counters: &Counters) -> bool {
3127 (settings.scalable_branching && settings.branch_probe_pivot_share > 0)
3128 || counters.strong_probes < settings.reliability_max_probes
3129}
3130
3131fn probe_work_available(model: &Model, budget: &Budget<'_>, counters: &Counters) -> (u64, u64) {
3132 let unit = (model.nnz() + model.n() + model.m()).max(1) as u64;
3133 let settings = budget.settings;
3134 let extra = budget
3135 .pivots
3136 .saturating_sub(counters.strong_pivots)
3137 .checked_div(settings.branch_probe_pivot_share)
3138 .unwrap_or(0);
3139 let left = settings
3140 .branch_probe_work
3141 .saturating_add(extra.saturating_mul(unit))
3142 .saturating_sub(counters.strong_work);
3143 (settings.branch_probe_pivots.min(left / unit), unit)
3144}
3145
3146#[allow(clippy::too_many_arguments)]
3147fn strong_branch(
3148 model: &Model,
3149 bounds: &Bounds,
3150 x: &[f64],
3151 objective: f64,
3152 options: &Options,
3153 lp: &mut Lp,
3154 pseudocosts: &mut Pseudocosts,
3155 budget: &mut Budget<'_>,
3156 nodes: &mut u64,
3157 counters: &mut Counters,
3158 structure: Option<&[f64]>,
3159 proofs: &mut Vec<(usize, [Option<f64>; 2])>,
3160) -> Result<Option<usize>> {
3161 let reliable = budget.settings.reliability_branching || budget.settings.scalable_branching;
3162 let eligible = |j: usize| {
3163 model.kinds()[j].is_integral()
3164 && (x[j] - x[j].round()).abs() > options.tolerances.integrality
3165 && (!reliable
3166 || pseudocosts.count[j]
3167 .iter()
3168 .any(|&n| n < budget.settings.reliability_threshold))
3169 };
3170 let mut candidates = Vec::new();
3171 if let Some(structure) = structure {
3172 let score = |j: usize| {
3173 let fraction = (x[j] - x[j].round()).abs();
3174 if budget.settings.branch_probe_score && pseudocosts.known() {
3175 let down = x[j] - x[j].floor();
3176 let a = pseudocosts.estimate(j, false) * down;
3177 let b = pseudocosts.estimate(j, true) * (1. - down);
3178 if budget.settings.branching_score == "product" {
3179 (a * b).sqrt()
3180 } else {
3181 0.8 * a.min(b) + 0.2 * a.max(b)
3182 }
3183 } else {
3184 fraction * (1. + structure[j])
3185 }
3186 };
3187 for j in (0..model.n()).filter(|&j| eligible(j)) {
3188 let at = candidates
3189 .iter()
3190 .position(|&k| score(j) > score(k))
3191 .unwrap_or(candidates.len());
3192 if at < budget.settings.branch_probe_candidates {
3193 candidates.insert(at, j);
3194 candidates.truncate(budget.settings.branch_probe_candidates);
3195 }
3196 }
3197 } else {
3198 candidates = (0..model.n()).filter(|&j| eligible(j)).collect();
3199 candidates.sort_by(|&a, &b| {
3200 (x[b] - x[b].round())
3201 .abs()
3202 .total_cmp(&(x[a] - x[a].round()).abs())
3203 .then(a.cmp(&b))
3204 });
3205 candidates.truncate(2);
3206 }
3207 if candidates.is_empty() || (!reliable && candidates.len() < 2) {
3210 return Ok(None);
3211 }
3212 let basis = lp.snapshot();
3213 let mut best = None;
3214 let mut best_score = -1.;
3215 let mut box_for_proof = budget.settings.branch_probe_proofs.then(|| bounds.clone());
3216 for j in candidates {
3217 let mut sides = [None; 2];
3218 let mut gains = [0.; 2];
3219 let mut complete = true;
3220 for (d, gain) in gains.iter_mut().enumerate() {
3221 if budget.stop().is_some()
3222 || (reliable && !probe_count_available(budget.settings, counters))
3223 || budget.settings.node_limit.is_some_and(|cap| *nodes >= cap)
3224 {
3225 complete = false;
3226 break;
3227 }
3228 let up = d == 1;
3229 let (lo, hi) = if up {
3230 (bounds.lower[j].max(x[j].ceil()), bounds.upper[j])
3231 } else {
3232 (bounds.lower[j], bounds.upper[j].min(x[j].floor()))
3233 };
3234 if lo > hi {
3235 complete = false;
3236 break;
3237 }
3238 let (probe_cap, unit) = if budget.settings.scalable_branching {
3239 let (cap, unit) = probe_work_available(model, budget, counters);
3240 if cap == 0 {
3241 counters.strong_work_exits += 1;
3242 complete = false;
3243 break;
3244 }
3245 if !budget.settings.branch_probe_actual_work {
3246 counters.strong_work += cap * unit;
3247 }
3248 (cap, unit)
3249 } else {
3250 (32, 0)
3251 };
3252 lp.set_bound(j, lo, hi)?;
3253 let mut settings = budget.settings.clone();
3254 settings.iteration_limit = Some(
3255 settings
3256 .iteration_limit
3257 .unwrap_or(u64::MAX)
3258 .min(budget.pivots.saturating_add(probe_cap)),
3259 );
3260 let mut probe = Budget {
3261 start: budget.start,
3262 settings: &settings,
3263 cancel: budget.cancel,
3264 pivots: budget.pivots,
3265 };
3266 let status = lp.solve(&mut probe, false);
3267 let spent = probe.pivots - budget.pivots;
3268 counters.strong_pivots += spent;
3269 if budget.settings.branch_probe_actual_work {
3270 counters.strong_work = counters.strong_work.saturating_add(spent.max(1) * unit);
3272 }
3273 budget.pivots = probe.pivots;
3274 *nodes += 1;
3275 counters.strong_probes += 1;
3276 if let Some(probe_box) = &mut box_for_proof {
3277 sides[d] = match status.as_ref() {
3278 Ok(Status::Optimal) => {
3279 probe_box.lower[j] = lo;
3280 probe_box.upper[j] = hi;
3281 let value = node_dual_bound(model, probe_box, &lp.duals(model), false)?;
3282 probe_box.lower[j] = bounds.lower[j];
3283 probe_box.upper[j] = bounds.upper[j];
3284 value
3285 }
3286 Ok(Status::Infeasible) if lp.infeasibility_verified() => Some(f64::INFINITY),
3287 _ => None,
3288 };
3289 }
3290 if status.as_ref().is_ok_and(|s| *s == Status::Optimal) {
3291 let point = lp.point();
3292 let value = oriented(
3293 model,
3294 model
3295 .objective()
3296 .iter()
3297 .zip(&point)
3298 .map(|(c, v)| c * v)
3299 .sum(),
3300 );
3301 *gain = (value - objective).max(0.);
3302 pseudocosts.record(
3303 Origin {
3304 j,
3305 up,
3306 distance: if up {
3307 x[j].ceil() - x[j]
3308 } else {
3309 x[j] - x[j].floor()
3310 },
3311 parent_objective: objective,
3312 },
3313 value,
3314 );
3315 } else {
3316 complete = false;
3317 }
3318 lp.set_bound(j, bounds.lower[j], bounds.upper[j])?;
3321 lp.restore(&basis);
3322 let _ = status;
3324 }
3325 if sides.iter().any(Option::is_some) {
3326 proofs.push((j, sides));
3327 }
3328 if complete {
3329 let score = gains[0].max(1e-6) * gains[1].max(1e-6);
3330 if score > best_score {
3331 best_score = score;
3332 best = Some(j);
3333 }
3334 }
3335 }
3336 if reliable {
3337 Ok(branching_variable(model, bounds, x, options, pseudocosts, budget.settings).or(best))
3338 } else {
3339 Ok(best)
3340 }
3341}
3342
3343fn branching_variable(
3348 model: &Model,
3349 bounds: &Bounds,
3350 x: &[f64],
3351 options: &Options,
3352 pseudocosts: &Pseudocosts,
3353 settings: &NativeOptions,
3354) -> Option<usize> {
3355 let fraction = |j: usize| (j, (x[j] - x[j].round()).abs());
3356 let most = |a: &(usize, f64), b: &(usize, f64)| a.1.total_cmp(&b.1);
3357 let integral = (0..model.n()).filter(|&j| model.kinds()[j].is_integral());
3358 let fractional = integral
3359 .clone()
3360 .map(fraction)
3361 .filter(|&(_, f)| f > options.tolerances.integrality);
3362 let chosen = if pseudocosts.known() {
3363 fractional
3364 .map(|(j, f)| {
3365 let down = x[j] - x[j].floor();
3366 let a = (pseudocosts.estimate(j, false) * down).max(1e-6);
3367 let b = (pseudocosts.estimate(j, true) * (1.0 - down)).max(1e-6);
3368 let score = if settings.branching_score == "product" {
3369 a.sqrt() * b.sqrt()
3370 } else {
3371 0.8 * a.min(b) + 0.2 * a.max(b)
3372 };
3373 (j, score + 1e-12 * f)
3374 })
3375 .max_by(most)
3376 } else {
3377 fractional.max_by(most)
3378 };
3379 if let Some((j, _)) = chosen {
3380 return Some(j);
3381 }
3382 let mut rounded = x.to_vec();
3383 for j in integral.clone() {
3384 rounded[j] = rounded[j].round();
3385 }
3386 if incumbent::upper_with_bounds(model, bounds, &rounded).is_some() {
3387 return None;
3388 }
3389 integral
3390 .filter(|&j| x[j].floor() >= bounds.lower[j] && x[j].ceil() <= bounds.upper[j])
3391 .map(fraction)
3392 .filter(|&(_, f)| f > 0.0)
3393 .max_by(most)
3394 .map(|(j, _)| j)
3395}
3396
3397fn controls(model: &Model, options: &Options, settings: &NativeOptions) -> lp::Controls {
3398 lp::Controls {
3399 threads: options.threads,
3400 pivot_tolerance: settings.pivot_tolerance,
3401 refactor_interval: settings.refactor_interval,
3402 adaptive_refactor: settings.adaptive_refactor,
3403 basis_update: settings.basis_update,
3404 factor_pivot_search: settings.factor_pivot_search,
3405 factor_ordering: settings.factor_ordering,
3406 max_factor_entries: settings.max_factor_entries,
3407 factor_replay: settings.factor_replay,
3408 adaptive_pricing: settings.adaptive_pricing,
3409 devex: settings.devex,
3410 steepest_edge: settings.steepest_edge,
3411 feasibility: options.tolerances.feasibility,
3412 dual: settings.dual_tolerance * objective_scale(model),
3413 }
3414}
3415
3416fn effective_options(s: &NativeOptions) -> Vec<(String, String)> {
3417 let mut options: Vec<(String, String)> = [
3418 (
3419 "algorithm",
3420 "dual_simplex+best_bound_diving_branch_and_bound".to_string(),
3421 ),
3422 (
3423 "linear_kernel",
3424 "bounded_dual_revised_simplex+markowitz_lu".into(),
3425 ),
3426 ("max_factor_entries", s.max_factor_entries.to_string()),
3427 ("packing_root", s.packing_root.to_string()),
3428 (
3429 "packing_root_iterations",
3430 s.packing_root_iterations.to_string(),
3431 ),
3432 ("packing_root_work", s.packing_root_work.to_string()),
3433 ("packing_neighborhoods", s.packing_neighborhoods.to_string()),
3434 (
3435 "packing_neighborhood_size",
3436 s.packing_neighborhood_size.to_string(),
3437 ),
3438 ("packing_workers", s.packing_workers.to_string()),
3439 (
3440 "packing_neighborhood_nodes",
3441 s.packing_neighborhood_nodes.to_string(),
3442 ),
3443 ("packing_cuts", s.packing_cuts.to_string()),
3444 ("packing_cut_work", s.packing_cut_work.to_string()),
3445 (
3446 "packing_combine_repairs",
3447 s.packing_combine_repairs.to_string(),
3448 ),
3449 ("packing_rounds", s.packing_rounds.to_string()),
3450 (
3451 "packing_neighborhood_growth",
3452 s.packing_neighborhood_growth.to_string(),
3453 ),
3454 ("packing_seed_strategy", s.packing_seed_strategy.to_string()),
3455 (
3456 "packing_residual_cliques",
3457 s.packing_residual_cliques.to_string(),
3458 ),
3459 ("packing_clique_work", s.packing_clique_work.to_string()),
3460 (
3461 "packing_price_diagnostics",
3462 s.packing_price_diagnostics.to_string(),
3463 ),
3464 (
3465 "packing_repair_seconds",
3466 format!("{:?}", s.packing_repair_seconds),
3467 ),
3468 (
3469 "packing_proof_seconds",
3470 format!("{:?}", s.packing_proof_seconds),
3471 ),
3472 ("partial_dual_bounds", s.partial_dual_bounds.to_string()),
3473 ("scalable_branching", s.scalable_branching.to_string()),
3474 (
3475 "branch_probe_candidates",
3476 s.branch_probe_candidates.to_string(),
3477 ),
3478 ("branch_probe_pivots", s.branch_probe_pivots.to_string()),
3479 ("branch_probe_work", s.branch_probe_work.to_string()),
3480 ("tree_threads", s.tree_threads.to_string()),
3481 ("tree_split_depth", s.tree_split_depth.to_string()),
3482 ("refactor_interval", s.refactor_interval.to_string()),
3483 ("adaptive_refactor", s.adaptive_refactor.to_string()),
3484 ("basis_update", s.basis_update.as_str().to_string()),
3485 ("factor_pivot_search", s.factor_pivot_search.to_string()),
3486 ("factor_ordering", s.factor_ordering.as_str().to_string()),
3487 ("steepest_edge", s.steepest_edge.to_string()),
3488 ("root_cuts", s.root_cuts.to_string()),
3489 ("root_separation", s.root_separation.to_string()),
3490 ("mip_presolve", s.mip_presolve.to_string()),
3491 ("adaptive_root", s.adaptive_root.to_string()),
3492 (
3493 "integer_equality_presolve",
3494 s.integer_equality_presolve.to_string(),
3495 ),
3496 (
3497 "coefficient_tightening",
3498 s.coefficient_tightening.to_string(),
3499 ),
3500 ("dual_presolve", s.dual_presolve.to_string()),
3501 ("mip_presolve_rounds", s.mip_presolve_rounds.to_string()),
3502 ("gmi_cuts", s.gmi_cuts.to_string()),
3503 ("mir_cuts", s.mir_cuts.to_string()),
3504 ("mip_cut_rounds", s.mip_cut_rounds.to_string()),
3505 ("mip_cut_limit", s.mip_cut_limit.to_string()),
3506 ("cut_exact_work", s.cut_exact_work.to_string()),
3507 ("root_heuristics", s.root_heuristics.to_string()),
3508 ("grouped_heuristics", s.grouped_heuristics.to_string()),
3509 ("ordered_group_cuts", s.ordered_group_cuts.to_string()),
3510 ("choice_mass_rounds", s.choice_mass_rounds.to_string()),
3511 ("choice_route_passes", s.choice_route_passes.to_string()),
3512 ("choice_route_restarts", s.choice_route_restarts.to_string()),
3513 ("heuristic_lp_calls", s.heuristic_lp_calls.to_string()),
3514 ("branching_score", s.branching_score.to_string()),
3515 ("pseudocost_min_step", s.pseudocost_min_step.to_string()),
3516 ("branch_trace_limit", s.branch_trace_limit.to_string()),
3517 ("root_cut_rounds", s.root_cut_rounds.to_string()),
3518 ("cover_lifting", s.cover_lifting.to_string()),
3519 ("root_propagation", s.root_propagation.to_string()),
3520 ("mixed_propagation", s.mixed_propagation.to_string()),
3521 ("singleton_presolve", s.singleton_presolve.to_string()),
3522 (
3523 "avoid_dominant_components",
3524 s.avoid_dominant_components.to_string(),
3525 ),
3526 ("devex", s.devex.to_string()),
3527 ("adaptive_pricing", s.adaptive_pricing.to_string()),
3528 ("factor_replay", s.factor_replay.to_string()),
3529 ("mip_diagnostics", s.mip_diagnostics.to_string()),
3530 ("mip_trace_limit", s.mip_trace_limit.to_string()),
3531 ("component_threads", s.component_threads.to_string()),
3532 (
3533 "component_parallel_min_entries",
3534 s.component_parallel_min_entries.to_string(),
3535 ),
3536 ("decompose", s.decompose.to_string()),
3537 (
3538 "decomposition_min_variables",
3539 s.decomposition_min_variables.to_string(),
3540 ),
3541 ("time_limit_seconds", format!("{:?}", s.time_limit_seconds)),
3542 ("node_limit", format!("{:?}", s.node_limit)),
3543 ("iteration_limit", format!("{:?}", s.iteration_limit)),
3544 ("pivot_tolerance", s.pivot_tolerance.to_string()),
3545 ("dual_tolerance", s.dual_tolerance.to_string()),
3546 ("presolve", s.presolve.to_string()),
3547 ("redundant_rows", s.redundant_rows.to_string()),
3548 (
3549 "redundant_row_min_ratio",
3550 s.redundant_row_min_ratio.to_string(),
3551 ),
3552 ("node_reoptimization", s.node_reoptimization.to_string()),
3553 ("strong_branching", s.strong_branching.to_string()),
3554 ("reliability_branching", s.reliability_branching.to_string()),
3555 ("reliability_threshold", s.reliability_threshold.to_string()),
3556 (
3557 "reliability_max_probes",
3558 s.reliability_max_probes.to_string(),
3559 ),
3560 ("reduced_cost_fixing", s.reduced_cost_fixing.to_string()),
3561 ("mixed_fix_trials", s.mixed_fix_trials.to_string()),
3562 ("proof_conflict_limit", s.proof_conflict_limit.to_string()),
3563 (
3564 "choice_tree_cut_interval",
3565 s.choice_tree_cut_interval.to_string(),
3566 ),
3567 ("choice_tree_cut_limit", s.choice_tree_cut_limit.to_string()),
3568 ("branch_probe_score", s.branch_probe_score.to_string()),
3569 ("branch_probe_proofs", s.branch_probe_proofs.to_string()),
3570 ("root_probe_limit", s.root_probe_limit.to_string()),
3571 ("dive_node_limit", s.dive_node_limit.to_string()),
3572 ("estimated_diving", s.estimated_diving.to_string()),
3573 (
3574 "repair_integral_leaves",
3575 s.repair_integral_leaves.to_string(),
3576 ),
3577 ("dual_cutoff_interval", s.dual_cutoff_interval.to_string()),
3578 ("root_cut_delay", s.root_cut_delay.to_string()),
3579 ("root_cut_gap", s.root_cut_gap.to_string()),
3580 ("root_cut_progress", s.root_cut_progress.to_string()),
3581 ("cutoff_pseudocosts", s.cutoff_pseudocosts.to_string()),
3582 (
3583 "branch_probe_pivot_share",
3584 s.branch_probe_pivot_share.to_string(),
3585 ),
3586 (
3587 "branch_probe_actual_work",
3588 s.branch_probe_actual_work.to_string(),
3589 ),
3590 ("mixed_fix_depth", s.mixed_fix_depth.to_string()),
3591 ("mixed_root_rounds", s.mixed_root_rounds.to_string()),
3592 ("root_refit_sweeps", s.root_refit_sweeps.to_string()),
3593 ("root_refit_fraction", s.root_refit_fraction.to_string()),
3594 ("choice_route_depth", s.choice_route_depth.to_string()),
3595 ("choice_pair_depth", s.choice_pair_depth.to_string()),
3596 ("choice_local_depth", s.choice_local_depth.to_string()),
3597 ("choice_local_rounds", s.choice_local_rounds.to_string()),
3598 ("safe_node_pruning", s.safe_node_pruning.to_string()),
3599 ("choice_order_presolve", s.choice_order_presolve.to_string()),
3600 ("incumbent_heuristic", s.incumbent_heuristic.to_string()),
3601 (
3602 "rational_certification",
3603 s.rational_certification.to_string(),
3604 ),
3605 ("feasibility_jump", s.feasibility_jump.to_string()),
3606 (
3607 "feasibility_jump_steps",
3608 s.feasibility_jump_steps.to_string(),
3609 ),
3610 ("objective_lattice", s.objective_lattice.to_string()),
3611 ]
3612 .into_iter()
3613 .map(|(k, v)| (k.to_string(), v))
3614 .collect();
3615 if s.objective_cutoff_bounds {
3616 options.push(("objective_cutoff_bounds".into(), "true".into()));
3617 }
3618 if let Some(value) = s.mip_relative_gap {
3619 options.push(("mip_relative_gap".into(), value.to_string()));
3620 }
3621 if let Some(value) = s.mip_absolute_gap {
3622 options.push(("mip_absolute_gap".into(), value.to_string()));
3623 }
3624 if s.local_mip_effort != 0 {
3625 options.push(("local_mip_effort".into(), s.local_mip_effort.to_string()));
3626 options.push(("local_mip_seed".into(), s.local_mip_seed.to_string()));
3627 }
3628 options
3629}
3630
3631impl LpIpSolver for NativeSolver {
3632 fn solve(
3633 &mut self,
3634 model: &Model,
3635 options: &Options,
3636 start: Option<&WarmStart>,
3637 cancel: &CancellationToken,
3638 ) -> Result<SolveResult> {
3639 let began = Instant::now();
3640 options.validate()?;
3641 self.settings.validate()?;
3642 if model.is_mip()
3643 && self.settings.has_gap_limit()
3644 && (self.settings.tree_threads > 1
3645 || self.settings.packing_root
3646 || self.settings.packing_neighborhoods > 0
3647 || self.settings.packing_cuts)
3648 {
3649 return Err(Error::Unsupported("MIP gap limits require the general serial search; tree splitting and specialized packing do not implement a global gap stop".into()));
3650 }
3651
3652 if let Some(s) = start {
3653 if s.primal.len() != model.n() || s.primal.iter().any(|v| !v.is_finite()) {
3654 return Err(Error::InvalidInput(
3655 "start must contain n finite values".into(),
3656 ));
3657 }
3658 }
3659 if options.threads == 1 {
3660 let mut result = (|| {
3661 if self.settings.packing_root
3662 || self.settings.packing_neighborhoods > 0
3663 || self.settings.packing_cuts
3664 {
3665 if let Some(r) = packing::solve(self, model, options, start, cancel)? {
3666 return Ok(r);
3667 }
3668 }
3669 if self.settings.tree_threads > 1 {
3670 if let Some(r) = tree::solve(self, model, options, start, cancel, None, None)? {
3671 return Ok(r);
3672 }
3673 }
3674 root::solve(self, model, options, start, cancel)
3675 })()?;
3676 result
3677 .backend
3678 .effective_options
3679 .retain(|(k, _)| k != "numeric_threads");
3680 result
3681 .backend
3682 .effective_options
3683 .push(("numeric_threads".into(), "1".into()));
3684 return Ok(result);
3685 }
3686 let eligible = options.threads > 1
3687 && model.nnz() >= 65_536
3688 && !(self.settings.packing_root
3689 && self.settings.packing_proof_seconds == Some(0.)
3690 && model.nnz() < 131_072)
3691 && !cancel.is_cancelled()
3692 && !self
3693 .settings
3694 .time_limit_seconds
3695 .is_some_and(|t| began.elapsed().as_secs_f64() >= t)
3696 && self.settings.node_limit != Some(0)
3697 && self.settings.iteration_limit != Some(0);
3698 let _execution = if eligible {
3699 parallel::Execution::new(options.threads).map_err(Error::Backend)?
3700 } else {
3701 parallel::Execution::default()
3702 };
3703 let mut settings = self.settings.clone();
3704 if options.threads > 1 {
3705 settings.component_threads = 1;
3706 settings.packing_workers = 1;
3707 settings.tree_threads = 1;
3708 }
3709 settings.time_limit_seconds = settings
3710 .time_limit_seconds
3711 .map(|t| (t - began.elapsed().as_secs_f64()).max(0.));
3712 let mut solver = NativeSolver::new(settings);
3713 let mut result = (|| {
3714 if solver.settings.packing_root
3715 || solver.settings.packing_neighborhoods > 0
3716 || solver.settings.packing_cuts
3717 {
3718 if let Some(result) = packing::solve(&mut solver, model, options, start, cancel)? {
3719 return Ok(result);
3720 }
3721 }
3722 if solver.settings.tree_threads > 1 {
3723 if let Some(result) =
3724 tree::solve(&mut solver, model, options, start, cancel, None, None)?
3725 {
3726 return Ok(result);
3727 }
3728 }
3729 root::solve(&mut solver, model, options, start, cancel)
3730 })()?;
3731 result
3732 .backend
3733 .effective_options
3734 .retain(|(k, _)| k != "numeric_threads");
3735 result
3736 .backend
3737 .effective_options
3738 .push(("numeric_threads".into(), options.threads.to_string()));
3739 Ok(result)
3740 }
3741}
3742
3743#[cfg(test)]
3744mod option_validation_tests {
3745 use super::*;
3746 #[test]
3747 fn invalid_packing_controls_name_the_field() {
3748 let cases: Vec<(NativeOptions, &str)> = vec![
3749 (
3750 NativeOptions {
3751 packing_rounds: 0,
3752 ..Default::default()
3753 },
3754 "packing_rounds",
3755 ),
3756 (
3757 NativeOptions {
3758 packing_neighborhoods: 4096,
3759 packing_rounds: 2,
3760 ..Default::default()
3761 },
3762 "packing_neighborhoods * packing_rounds",
3763 ),
3764 (
3765 NativeOptions {
3766 packing_neighborhood_growth: 1025,
3767 ..Default::default()
3768 },
3769 "packing_neighborhood_growth",
3770 ),
3771 (
3772 NativeOptions {
3773 packing_clique_work: 1_000_001,
3774 ..Default::default()
3775 },
3776 "packing_clique_work",
3777 ),
3778 (
3779 NativeOptions {
3780 packing_seed_strategy: "best".into(),
3781 ..Default::default()
3782 },
3783 "packing_seed_strategy",
3784 ),
3785 (
3786 NativeOptions {
3787 packing_repair_seconds: Some(f64::NAN),
3788 ..Default::default()
3789 },
3790 "packing_repair_seconds",
3791 ),
3792 (
3793 NativeOptions {
3794 packing_proof_seconds: Some(-1.),
3795 ..Default::default()
3796 },
3797 "packing_proof_seconds",
3798 ),
3799 (
3800 NativeOptions {
3801 packing_root_iterations: 100_001,
3802 ..Default::default()
3803 },
3804 "packing_root_iterations",
3805 ),
3806 (
3807 NativeOptions {
3808 packing_neighborhood_size: 3,
3809 ..Default::default()
3810 },
3811 "packing_neighborhood_size",
3812 ),
3813 (
3814 NativeOptions {
3815 packing_workers: 17,
3816 ..Default::default()
3817 },
3818 "packing_workers",
3819 ),
3820 (
3821 NativeOptions {
3822 branch_probe_candidates: 0,
3823 ..Default::default()
3824 },
3825 "branch_probe_candidates",
3826 ),
3827 (
3828 NativeOptions {
3829 tree_threads: 0,
3830 ..Default::default()
3831 },
3832 "tree_threads",
3833 ),
3834 (
3835 NativeOptions {
3836 tree_split_depth: 9,
3837 ..Default::default()
3838 },
3839 "tree_split_depth",
3840 ),
3841 ];
3842 for (settings, field) in cases {
3843 match settings.validate() {
3844 Err(Error::InvalidInput(message)) => {
3845 assert!(message.starts_with(field), "{message} should name {field}")
3846 }
3847 other => panic!("{field}: expected InvalidInput, got {other:?}"),
3848 }
3849 }
3850 assert!(
3851 NativeOptions {
3852 packing_neighborhoods: 4096,
3853 packing_rounds: 1,
3854 packing_repair_seconds: Some(0.),
3855 packing_proof_seconds: Some(0.),
3856 ..Default::default()
3857 }
3858 .validate()
3859 .is_ok()
3860 );
3861 }
3862}
3863
3864#[cfg(test)]
3865mod branching_policy_tests {
3866 use super::*;
3867 use lp_ip_craft::{CsrMatrix, ModelData, VariableKind};
3868 #[test]
3869 fn product_and_weighted_sum_choose_distinct_planted_candidates() {
3870 let m = Model::new(ModelData {
3871 objective: vec![1.; 2],
3872 objective_offset: 0.,
3873 sense: Sense::Minimize,
3874 variables: Bounds::new(vec![0.; 2], vec![2.; 2]),
3875 kinds: vec![VariableKind::Integer; 2],
3876 matrix: CsrMatrix::from_dense(0, 2, &[]).unwrap(),
3877 rows: Bounds::free(0),
3878 })
3879 .unwrap();
3880 let mut p = Pseudocosts::new(2);
3881 p.sum = vec![[200., 20000.], [3000., 3000.]];
3882 p.count = vec![[1000, 1000]; 2];
3883 p.total = [3200., 23000.];
3884 p.total_count = [2000, 2000];
3885 for (score, expected) in [("weighted_sum", 0), ("product", 1)] {
3886 let s = NativeOptions {
3887 branching_score: score.into(),
3888 ..Default::default()
3889 };
3890 assert_eq!(
3891 branching_variable(&m, m.variables(), &[0.5, 0.5], &Options::default(), &p, &s),
3892 Some(expected)
3893 );
3894 }
3895 }
3896 #[test]
3897 fn pseudocost_step_floor_is_opt_in_and_does_not_inflate_tiny_steps() {
3898 let origin = Origin {
3899 j: 0,
3900 up: false,
3901 distance: 1e-8,
3902 parent_objective: 0.,
3903 };
3904 let mut raw = Pseudocosts::new(1);
3905 raw.record(origin, 1.);
3906 let mut clamped = Pseudocosts::new(1);
3907 clamped.min_step = 0.01;
3908 clamped.record(origin, 1.);
3909 assert_eq!(raw.sum[0][0], 1e8);
3910 assert_eq!(clamped.sum[0][0], 100.);
3911 }
3912}
3913
3914#[cfg(test)]
3915mod leaf_repair_tests {
3916 use super::*;
3917 use lp_ip_craft::{CsrMatrix, ModelData, VariableKind};
3918
3919 fn model() -> Model {
3921 Model::new(ModelData {
3922 objective: vec![1., -1.],
3923 objective_offset: 0.,
3924 sense: Sense::Minimize,
3925 variables: Bounds::new(vec![0.; 2], vec![3., 1.]),
3926 kinds: vec![VariableKind::Integer, VariableKind::Continuous],
3927 matrix: CsrMatrix::from_dense(1, 2, &[1., 1.]).unwrap(),
3928 rows: Bounds::new(vec![2.5], vec![2.5]),
3929 })
3930 .unwrap()
3931 }
3932
3933 #[test]
3934 fn a_rejected_leaf_is_repaired_only_with_a_checked_point() {
3935 let m = model();
3936 let cancel = CancellationToken::default();
3937 for exact in [true, false] {
3938 let settings = NativeOptions {
3939 rational_certification: exact,
3940 ..Default::default()
3941 };
3942 let mut budget = Budget {
3943 start: Instant::now(),
3944 settings: &settings,
3945 cancel: &cancel,
3946 pivots: 0,
3947 };
3948 let repaired = repair_leaf(
3950 &m,
3951 &m,
3952 m.variables(),
3953 &[2., 0.49],
3954 &[true],
3955 &Options::default(),
3956 &mut budget,
3957 )
3958 .unwrap()
3959 .expect("z = 2 admits y = 0.5");
3960 assert_eq!(repaired[0], 2.);
3961 assert!((repaired[1] - 0.5).abs() <= 1e-9, "{repaired:?}");
3962 assert!(
3964 repair_leaf(
3965 &m,
3966 &m,
3967 m.variables(),
3968 &[0., 1.],
3969 &[true],
3970 &Options::default(),
3971 &mut budget,
3972 )
3973 .unwrap()
3974 .is_none()
3975 );
3976 }
3977 }
3978
3979 #[test]
3980 fn leaf_resplits_partition_the_integer_domain() {
3981 let m = model();
3982 let b = m.variables();
3983 assert_eq!(integral_resplit(&m, b, &[3., 0.]), Some((0, 2.)));
3985 assert_eq!(integral_resplit(&m, b, &[1., 0.]), Some((0, 1.)));
3986 assert_eq!(integral_resplit(&m, b, &[0., 0.]), Some((0, 0.)));
3987 let fixed = Bounds::new(vec![2., 0.], vec![2., 1.]);
3989 assert_eq!(integral_resplit(&m, &fixed, &[2., 0.5]), None);
3990 }
3991}