#![forbid(unsafe_code)]
mod active;
mod batch;
mod boxed;
mod certified_cuts;
mod choice_mass;
mod choice_route;
mod components;
mod cuts;
mod dense;
mod diagnostics;
mod dyadic;
mod ft;
mod grouped;
mod heuristic_budget;
mod incumbent;
mod integer_equality;
mod jump;
mod local_mip;
#[cfg(feature = "local-mip-bench")]
#[doc(hidden)]
pub mod local_mip_bench;
#[cfg(not(feature = "local-mip-bench"))]
mod local_mip_bench;
mod lp;
mod lu;
mod mip_presolve;
mod mixed;
mod ordered;
mod ordering;
mod packing;
pub mod parallel;
#[cfg(feature = "parallel-bench")]
#[doc(hidden)]
pub mod parallel_bench;
mod presolve;
mod primal;
pub mod profile;
mod proof_conflicts;
mod propagate;
mod rational;
#[cfg(feature = "basis-replay")]
pub mod replay;
mod root;
mod root_fix;
mod root_policy;
mod rootcuts;
mod tree;
mod witness;
use lp::{Basis, Lp};
use lp_ip_craft::{
BackendReport, Bounds, CancellationToken, Duals, Error, LpIpSolver, Model, Options, Result,
Sense, SolveResult, StartStatus, Status, WarmStart, check, safe_dual_bound_with_bounds,
};
use std::sync::Arc;
use std::time::Instant;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BasisUpdate {
#[default]
Auto,
Eta,
ForrestTomlin,
}
impl BasisUpdate {
pub fn as_str(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Eta => "eta",
Self::ForrestTomlin => "forrest_tomlin",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FactorOrdering {
#[default]
Auto,
Natural,
MinDegree,
}
impl FactorOrdering {
pub fn as_str(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Natural => "natural",
Self::MinDegree => "min_degree",
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct NativeOptions {
pub time_limit_seconds: Option<f64>,
pub node_limit: Option<u64>,
pub mip_relative_gap: Option<f64>,
pub mip_absolute_gap: Option<f64>,
pub iteration_limit: Option<u64>,
pub pivot_tolerance: f64,
pub dual_tolerance: f64,
pub max_factor_entries: usize,
pub refactor_interval: usize,
pub adaptive_refactor: bool,
pub basis_update: BasisUpdate,
pub factor_pivot_search: usize,
pub factor_ordering: FactorOrdering,
pub steepest_edge: bool,
pub presolve: bool,
pub redundant_rows: bool,
pub redundant_row_min_ratio: f64,
pub node_reoptimization: bool,
pub strong_branching: bool,
pub reliability_branching: bool,
pub reliability_threshold: u32,
pub reliability_max_probes: u64,
pub reduced_cost_fixing: bool,
pub mixed_fix_trials: usize,
pub proof_conflict_limit: usize,
pub choice_tree_cut_interval: u64,
pub choice_tree_cut_limit: usize,
pub branch_probe_score: bool,
pub branch_probe_proofs: bool,
pub root_probe_limit: usize,
pub dive_node_limit: usize,
pub estimated_diving: bool,
pub repair_integral_leaves: bool,
pub dual_cutoff_interval: u64,
pub root_cut_delay: usize,
pub root_cut_gap: f64,
pub root_cut_progress: f64,
pub cutoff_pseudocosts: bool,
pub branch_probe_pivot_share: u64,
pub branch_probe_actual_work: bool,
pub mixed_fix_depth: usize,
pub mixed_root_rounds: usize,
pub root_refit_sweeps: usize,
pub root_refit_fraction: f64,
pub choice_route_depth: usize,
pub choice_pair_depth: usize,
pub choice_local_depth: usize,
pub choice_local_rounds: usize,
pub safe_node_pruning: bool,
pub choice_order_presolve: bool,
pub incumbent_heuristic: bool,
pub rational_certification: bool,
pub feasibility_jump: bool,
pub feasibility_jump_steps: u64,
pub local_mip_effort: u64,
pub local_mip_seed: u64,
pub objective_lattice: bool,
pub decompose: bool,
pub decomposition_min_variables: usize,
pub component_threads: usize,
pub component_parallel_min_entries: usize,
pub root_cuts: bool,
pub root_separation: bool,
pub mip_presolve: bool,
pub integer_equality_presolve: bool,
pub objective_cutoff_bounds: bool,
pub adaptive_root: bool,
pub coefficient_tightening: bool,
pub dual_presolve: bool,
pub mip_presolve_rounds: usize,
pub gmi_cuts: bool,
pub mir_cuts: bool,
pub mip_cut_rounds: usize,
pub mip_cut_limit: usize,
pub cut_exact_work: u64,
pub root_heuristics: bool,
pub grouped_heuristics: bool,
pub ordered_group_cuts: bool,
pub choice_mass_rounds: usize,
pub choice_route_passes: usize,
pub choice_route_restarts: usize,
pub heuristic_lp_calls: usize,
pub branching_score: String,
pub pseudocost_min_step: f64,
pub branch_trace_limit: usize,
pub root_cut_rounds: usize,
pub cover_lifting: bool,
pub root_propagation: bool,
pub mixed_propagation: bool,
pub singleton_presolve: bool,
pub avoid_dominant_components: bool,
pub devex: bool,
pub adaptive_pricing: bool,
pub factor_replay: bool,
pub mip_diagnostics: bool,
pub mip_trace_limit: usize,
pub packing_root: bool,
pub packing_root_iterations: usize,
pub packing_root_work: u64,
pub packing_neighborhoods: usize,
pub packing_neighborhood_size: usize,
pub packing_workers: usize,
pub packing_neighborhood_nodes: u64,
pub packing_cuts: bool,
pub packing_cut_work: u64,
pub packing_combine_repairs: bool,
pub packing_rounds: usize,
pub packing_neighborhood_growth: usize,
pub packing_seed_strategy: String,
pub packing_residual_cliques: bool,
pub packing_clique_work: u64,
pub packing_price_diagnostics: bool,
pub packing_repair_seconds: Option<f64>,
pub packing_proof_seconds: Option<f64>,
pub partial_dual_bounds: bool,
pub scalable_branching: bool,
pub branch_probe_candidates: usize,
pub branch_probe_pivots: u64,
pub branch_probe_work: u64,
pub tree_threads: usize,
pub tree_split_depth: usize,
}
impl Default for NativeOptions {
fn default() -> Self {
Self {
time_limit_seconds: None,
node_limit: Some(100_000),
mip_relative_gap: None,
mip_absolute_gap: None,
iteration_limit: Some(1_000_000),
pivot_tolerance: 1e-9,
dual_tolerance: 1e-7,
max_factor_entries: 4_000_000,
refactor_interval: 256,
adaptive_refactor: true,
basis_update: BasisUpdate::Auto,
factor_pivot_search: 4,
factor_ordering: FactorOrdering::Auto,
steepest_edge: true,
presolve: true,
redundant_rows: true,
redundant_row_min_ratio: 1.0,
node_reoptimization: true,
strong_branching: false,
reliability_branching: false,
reliability_threshold: 2,
reliability_max_probes: 64,
reduced_cost_fixing: true,
mixed_fix_trials: 0,
proof_conflict_limit: 0,
choice_tree_cut_interval: 64,
choice_tree_cut_limit: 0,
branch_probe_score: false,
branch_probe_proofs: false,
root_probe_limit: 0,
dive_node_limit: 0,
estimated_diving: false,
repair_integral_leaves: true,
dual_cutoff_interval: 0,
root_cut_delay: 0,
root_cut_gap: 0.,
root_cut_progress: 0.001,
cutoff_pseudocosts: false,
branch_probe_pivot_share: 0,
branch_probe_actual_work: false,
mixed_fix_depth: 8,
mixed_root_rounds: 0,
root_refit_sweeps: 0,
root_refit_fraction: 0.05,
choice_route_depth: 0,
choice_pair_depth: 0,
choice_local_depth: 0,
choice_local_rounds: 1,
safe_node_pruning: false,
choice_order_presolve: false,
incumbent_heuristic: true,
rational_certification: true,
feasibility_jump: false,
feasibility_jump_steps: 2000,
local_mip_effort: 0,
local_mip_seed: 0,
objective_lattice: true,
decompose: true,
decomposition_min_variables: 32,
component_threads: 16,
component_parallel_min_entries: 2048,
root_cuts: false,
root_separation: false,
mip_presolve: true,
integer_equality_presolve: false,
objective_cutoff_bounds: false,
adaptive_root: false,
coefficient_tightening: true,
dual_presolve: false,
mip_presolve_rounds: 8,
gmi_cuts: false,
mir_cuts: false,
mip_cut_rounds: 8,
mip_cut_limit: 16,
cut_exact_work: 4_000_000,
root_heuristics: false,
grouped_heuristics: false,
ordered_group_cuts: false,
choice_mass_rounds: 0,
choice_route_passes: 0,
choice_route_restarts: 1,
heuristic_lp_calls: 16,
branching_score: "weighted_sum".into(),
pseudocost_min_step: 0.,
branch_trace_limit: 0,
root_cut_rounds: 2,
cover_lifting: true,
root_propagation: true,
mixed_propagation: false,
singleton_presolve: true,
avoid_dominant_components: true,
devex: false,
adaptive_pricing: true,
factor_replay: false,
mip_diagnostics: false,
mip_trace_limit: 256,
packing_root: false,
packing_root_iterations: 1000,
packing_root_work: 200_000_000,
packing_neighborhoods: 0,
packing_neighborhood_size: 192,
packing_workers: 1,
packing_neighborhood_nodes: 128,
packing_cuts: false,
packing_cut_work: 2_000_000,
packing_combine_repairs: false,
packing_rounds: 1,
packing_neighborhood_growth: 0,
packing_seed_strategy: "incumbent".into(),
packing_residual_cliques: false,
packing_clique_work: 50_000,
packing_price_diagnostics: false,
packing_repair_seconds: None,
packing_proof_seconds: None,
partial_dual_bounds: false,
scalable_branching: false,
branch_probe_candidates: 4,
branch_probe_pivots: 32,
branch_probe_work: 2_000_000,
tree_threads: 1,
tree_split_depth: 2,
}
}
}
impl NativeOptions {
pub fn has_gap_limit(&self) -> bool {
self.mip_relative_gap.is_some_and(|v| v > 0.0)
|| self.mip_absolute_gap.is_some_and(|v| v > 0.0)
}
pub fn validate(&self) -> Result<()> {
for (name, value) in [
("mip_relative_gap", self.mip_relative_gap),
("mip_absolute_gap", self.mip_absolute_gap),
] {
if value.is_some_and(|v| !v.is_finite() || v < 0.0) {
return Err(Error::InvalidInput(format!(
"{name} must be finite and nonnegative"
)));
}
}
for (valid, message) in [
(
self.mip_presolve_rounds <= 32,
"mip_presolve_rounds must be at most 32",
),
(
self.choice_route_depth <= 256 && self.choice_pair_depth <= 256,
"choice_route_depth and choice_pair_depth must be at most 256",
),
(
self.choice_local_depth <= 8 && (1..=3).contains(&self.choice_local_rounds),
"choice_local_depth must be at most 8 and choice_local_rounds in 1..=3",
),
(
self.root_refit_sweeps <= 32 && (0. ..=1.).contains(&self.root_refit_fraction),
"root_refit_sweeps must be at most 32 and root_refit_fraction must be in [0, 1]",
),
(
self.choice_tree_cut_limit <= 256
&& (8..=4096).contains(&self.choice_tree_cut_interval)
&& self.proof_conflict_limit <= 256,
"tree cut and conflict limits must be at most 256 and tree cut interval in 8..=4096",
),
(
self.root_probe_limit <= 4096 && self.dual_cutoff_interval <= 256,
"root_probe_limit must be at most 4096 and dual_cutoff_interval at most 256",
),
(
self.branch_probe_pivot_share <= 1024
&& (self.branch_probe_pivot_share == 0 || self.branch_probe_actual_work),
"branch_probe_pivot_share must be at most 1024 and requires branch_probe_actual_work",
),
(
(0. ..=1.).contains(&self.root_cut_progress)
&& self.root_cut_gap.is_finite()
&& self.root_cut_gap >= 0.
&& self.root_cut_delay <= 16,
"invalid root cut progress, gap, or starting round",
),
(
self.mixed_fix_trials <= 128 && self.mixed_root_rounds <= 6,
"mixed_fix_trials must be at most 128 and mixed_root_rounds at most 6",
),
(
self.choice_route_passes <= 12 && (1..=6).contains(&self.choice_route_restarts),
"choice_route_passes must be at most 12 and choice_route_restarts within 1..=6",
),
(
self.mip_cut_rounds <= 50 && self.choice_mass_rounds <= 16,
"mip_cut_rounds must be at most 50 and choice_mass_rounds at most 16",
),
(
(1..=64).contains(&self.mip_cut_limit),
"mip_cut_limit must lie in 1..=64",
),
(
self.cut_exact_work <= 100_000_000,
"cut_exact_work must be at most 100000000",
),
(
self.heuristic_lp_calls <= 128,
"heuristic_lp_calls must be at most 128",
),
(
self.branch_trace_limit <= 256,
"branch_trace_limit must be at most 256",
),
(
["weighted_sum", "product"].contains(&self.branching_score.as_str()),
"branching_score must be weighted_sum or product",
),
(
self.pseudocost_min_step.is_finite()
&& (0.0..=0.5).contains(&self.pseudocost_min_step),
"pseudocost_min_step must be finite in 0..=0.5",
),
] {
if !valid {
return Err(Error::InvalidInput(message.into()));
}
}
let phase = |t: Option<f64>| t.is_none_or(|t| t.is_finite() && t >= 0.);
for (ok, message) in [
(
(1..=32).contains(&self.packing_rounds),
"packing_rounds must lie in 1..=32",
),
(
self.packing_neighborhoods
.saturating_mul(self.packing_rounds)
<= 4096,
"packing_neighborhoods * packing_rounds must be at most 4096",
),
(
self.packing_neighborhood_growth <= 1024,
"packing_neighborhood_growth must be at most 1024",
),
(
self.packing_clique_work <= 1_000_000,
"packing_clique_work must be at most 1000000",
),
(
["incumbent", "rejected", "mixed"].contains(&self.packing_seed_strategy.as_str()),
"packing_seed_strategy must be incumbent, rejected or mixed",
),
(
phase(self.packing_repair_seconds),
"packing_repair_seconds must be finite and nonnegative",
),
(
phase(self.packing_proof_seconds),
"packing_proof_seconds must be finite and nonnegative",
),
(
self.packing_root_iterations <= 100_000,
"packing_root_iterations must be at most 100000",
),
(
self.packing_root_work <= 10_000_000_000,
"packing_root_work must be at most 10000000000",
),
(
self.packing_neighborhoods <= 4096,
"packing_neighborhoods must be at most 4096",
),
(
(4..=1024).contains(&self.packing_neighborhood_size),
"packing_neighborhood_size must lie in 4..=1024",
),
(
(1..=16).contains(&self.packing_workers),
"packing_workers must lie in 1..=16",
),
(
self.packing_neighborhood_nodes <= 100_000,
"packing_neighborhood_nodes must be at most 100000",
),
(
self.packing_cut_work <= 100_000_000,
"packing_cut_work must be at most 100000000",
),
(
(1..=16).contains(&self.branch_probe_candidates),
"branch_probe_candidates must lie in 1..=16",
),
(
self.branch_probe_pivots <= 1024,
"branch_probe_pivots must be at most 1024",
),
(
self.branch_probe_work <= 10_000_000_000,
"branch_probe_work must be at most 10000000000",
),
(
(1..=16).contains(&self.tree_threads),
"tree_threads must lie in 1..=16",
),
(
self.tree_split_depth <= 8,
"tree_split_depth must be at most 8",
),
] {
if !ok {
return Err(Error::InvalidInput(message.into()));
}
}
if !(1..=16).contains(&self.reliability_threshold) || self.reliability_max_probes > 1024 {
return Err(Error::InvalidInput(
"reliability threshold must be 1..=16 and max probes at most 1024".into(),
));
}
if self.feasibility_jump_steps > 100_000 {
return Err(Error::InvalidInput(
"feasibility_jump_steps must be at most 100000".into(),
));
}
if self.root_cut_rounds > 4 {
return Err(Error::InvalidInput(
"root_cut_rounds must be at most 4".into(),
));
}
if self.mip_trace_limit > 4096 {
return Err(Error::InvalidInput(
"mip_trace_limit must be at most 4096".into(),
));
}
if self
.time_limit_seconds
.is_some_and(|v| !v.is_finite() || v < 0.0)
{
return Err(Error::InvalidInput(
"time_limit_seconds must be finite and nonnegative".into(),
));
}
if !self.pivot_tolerance.is_finite()
|| self.pivot_tolerance <= 0.0
|| self.pivot_tolerance >= 0.01
{
return Err(Error::InvalidInput(
"pivot_tolerance must lie in (0, .01)".into(),
));
}
if !self.dual_tolerance.is_finite() || self.dual_tolerance <= 0.0 {
return Err(Error::InvalidInput(
"dual_tolerance must be positive and finite".into(),
));
}
if !self.redundant_row_min_ratio.is_finite() || self.redundant_row_min_ratio < 0. {
return Err(Error::InvalidInput(
"redundant_row_min_ratio must be finite and nonnegative".into(),
));
}
if !(1..=16).contains(&self.component_threads) {
return Err(Error::InvalidInput(
"component_threads must lie in 1..=16".into(),
));
}
if self.decomposition_min_variables == 0 {
return Err(Error::InvalidInput(
"decomposition_min_variables must be positive".into(),
));
}
if !(1..=64).contains(&self.factor_pivot_search) {
return Err(Error::InvalidInput(
"factor_pivot_search must be between 1 and 64".into(),
));
}
if self.max_factor_entries == 0 || self.refactor_interval == 0 {
return Err(Error::InvalidInput(
"max_factor_entries and refactor_interval must be positive".into(),
));
}
Ok(())
}
}
pub(crate) struct Budget<'a> {
pub start: Instant,
pub settings: &'a NativeOptions,
pub cancel: &'a CancellationToken,
pub pivots: u64,
}
impl Budget<'_> {
fn stop(&self) -> Option<Status> {
if self.cancel.is_cancelled() {
Some(Status::Cancelled)
} else if self
.settings
.time_limit_seconds
.is_some_and(|t| self.start.elapsed().as_secs_f64() >= t)
{
Some(Status::TimeLimit)
} else if self
.settings
.iteration_limit
.is_some_and(|p| self.pivots >= p)
{
Some(Status::IterationLimit)
} else {
None
}
}
}
#[derive(Clone, Debug, Default)]
pub struct NativeSolver {
pub settings: NativeOptions,
}
impl NativeSolver {
pub fn new(settings: NativeOptions) -> Self {
Self { settings }
}
}
fn oriented(model: &Model, v: f64) -> f64 {
if model.sense() == Sense::Minimize {
v
} else {
-v
}
}
fn objective_scale(model: &Model) -> f64 {
1.0 + model
.objective()
.iter()
.fold(0.0_f64, |a, &b| a.max(b.abs()))
}
fn accepted(
model: &Model,
bounds: &Bounds,
x: &[f64],
duals: &lp_ip_craft::Duals,
options: &Options,
settings: &NativeOptions,
) -> bool {
let Ok(r) = check::lp_residuals_with_bounds(model, bounds, x, duals) else {
return false;
};
let scale = objective_scale(model);
r.primal <= options.tolerances.feasibility
&& r.dual_sign <= settings.dual_tolerance * scale
&& r.stationarity <= settings.dual_tolerance * scale
&& r.duality_gap <= settings.dual_tolerance
}
struct Incumbents<'a, 't> {
best: f64,
upper: f64,
certified: Option<(Vec<f64>, lp_ip_craft::Evaluation)>,
trace: Option<diagnostics::SearchDiagnostics>,
original_model: &'a Model,
pivots: u64,
pilot: Option<&'a mut local_mip_bench::Trace<'t>>,
rounding_trials_left: u8,
}
fn consider(
model: &Model,
x: Vec<f64>,
options: &Options,
result: &mut SolveResult,
pool: &mut Incumbents<'_, '_>,
source: &'static str,
) -> Result<bool> {
let e = check::evaluate(model, &x, &options.tolerances)?;
if !e.feasible_candidate {
return Ok(false);
}
let previous_upper = pool.upper;
if let Some(upper) = incumbent::upper(model, &x) {
if upper < pool.upper {
pool.upper = upper;
pool.certified = Some((x.clone(), e.clone()));
}
}
if pool.trace.is_some() || pool.pilot.is_some() {
let original = check::evaluate(pool.original_model, &x, &options.tolerances)
.ok()
.filter(|e| e.feasible_candidate);
let proof = (pool.upper < previous_upper).then(|| oriented(model, pool.upper));
if let Some(trace) = &mut pool.trace {
if let Some(e) = &original {
trace.candidate(e.objective, proof, source, result.nodes, pool.pivots);
} else {
trace.original_check_rejections += 1;
}
}
if let Some(trace) = &mut pool.pilot {
let work = (result.nodes, pool.pivots);
if let Some(e) = &original {
trace.candidate(e.objective, source, work);
if proof.is_some() {
trace.event(
"certified_incumbent",
source,
work,
Some(e.objective),
proof,
);
}
} else {
trace.event("original_check_rejection", source, work, None, None);
}
}
}
let obj = oriented(model, e.objective);
if obj < pool.best {
pool.best = obj;
result.candidate = Some(x);
result.evaluation = Some(e);
}
Ok(true)
}
struct Certifier {
lp: Option<Lp>,
attempts: u64,
certified: u64,
last: Option<Vec<f64>>,
lp_attempts: u64,
witness_attempts: u64,
witness_successes: u64,
witness_work: u64,
witness_outcome: witness::Outcome,
witness_assignment: Option<u64>,
}
const MAX_CERTIFICATIONS: u64 = 64;
const WITNESS_WORK: u64 = 64_000_000;
#[allow(clippy::too_many_arguments)]
fn certify(
model: &Model,
options: &Options,
settings: &NativeOptions,
keep: &[bool],
certifier: &mut Certifier,
pool: &mut Incumbents<'_, '_>,
result: &mut SolveResult,
budget: &mut Budget<'_>,
) -> Result<()> {
let Some(x) = result.candidate.as_ref() else {
return Ok(());
};
if pool.best >= pool.upper
|| certifier.attempts >= MAX_CERTIFICATIONS
|| certifier.last.as_ref() == Some(x)
|| budget.stop().is_some()
{
return Ok(());
}
certifier.last = Some(x.clone());
certifier.attempts += 1;
let started = pool.pilot.as_ref().map(|_| Instant::now());
let work_before = (result.nodes, budget.pivots);
let remaining = WITNESS_WORK.saturating_sub(certifier.witness_work);
let witness_started = pool.trace.as_ref().map(|_| Instant::now());
let witness = if settings.rational_certification && remaining > 0 {
certifier.witness_attempts += 1;
let limit = remaining.min(witness::ATTEMPT_WORK);
let (witness, work, outcome) = witness::upper(pool.original_model, x, budget, limit);
certifier.witness_outcome = outcome;
if pool.trace.is_some() {
use std::hash::{Hash, Hasher};
let mut hash = std::collections::hash_map::DefaultHasher::new();
for (j, value) in pool
.original_model
.kinds()
.iter()
.zip(x)
.enumerate()
.filter_map(|(j, (kind, value))| kind.is_integral().then_some((j, value)))
{
(j, value.round() as i64).hash(&mut hash);
}
certifier.witness_assignment = Some(hash.finish());
}
certifier.witness_work += work;
witness
} else {
None
};
if let Some((trace, started)) = pool.trace.as_mut().zip(witness_started) {
trace.witness_seconds += started.elapsed().as_secs_f64();
}
if let Some(witness) = witness {
let point = witness.point;
let upper = witness.upper;
let evaluation = check::evaluate(model, &point, &options.tolerances)?;
if upper < pool.upper
&& evaluation.feasible_candidate
&& check::evaluate(pool.original_model, &point, &options.tolerances)?.feasible_candidate
{
pool.upper = upper;
pool.certified = Some((point.clone(), evaluation.clone()));
let objective = oriented(model, evaluation.objective);
if objective < pool.best {
pool.best = objective;
result.candidate = Some(point);
result.evaluation = Some(evaluation);
}
certifier.witness_successes += 1;
if let Some(trace) = &mut pool.trace {
trace.candidate(
oriented(model, objective),
Some(oriented(model, upper)),
"rational_witness",
result.nodes,
budget.pivots,
);
}
if let Some((trace, started)) = pool.pilot.as_deref_mut().zip(started) {
let work = (result.nodes, budget.pivots);
let value = oriented(model, objective);
trace.candidate(value, "rational_witness", work);
trace.event(
"certified_incumbent",
"rational_witness",
work,
Some(value),
Some(oriented(model, upper)),
);
trace.stage("certification", work, work_before, started);
}
return Ok(());
}
}
let integral: Vec<bool> = model.kinds().iter().map(|k| k.is_integral()).collect();
let rounded: Vec<f64> = x
.iter()
.zip(&integral)
.map(|(&v, &i)| if i { v.round() } else { v })
.collect();
certifier.lp_attempts += 1;
let lp = match &mut certifier.lp {
Some(lp) => lp,
none => {
let columns = presolve::kept_columns(model, model.variables(), settings);
let mut lp = Lp::new(model, keep, &columns, controls(model, options, settings))?;
lp.shrink_rows(model);
none.insert(lp)
}
};
lp.fix_for_certification(&rounded, &integral, model.variables())?;
let solved = lp.solve(budget, true)?;
if let Some((trace, started)) = pool.pilot.as_deref_mut().zip(started) {
trace.stage(
"certification",
(result.nodes, budget.pivots),
work_before,
started,
);
}
if solved != Status::Optimal {
return Ok(());
}
let mut point = lp.point();
for j in (0..model.n()).filter(|&j| integral[j]) {
point[j] = rounded[j];
}
let before = pool.upper;
pool.pivots = budget.pivots;
consider(model, point, options, result, pool, "certification")?;
if pool.upper < before {
certifier.certified += 1;
}
Ok(())
}
fn heuristic(
model: &Model,
node_bounds: &Bounds,
x: &[f64],
options: &Options,
result: &mut SolveResult,
pool: &mut Incumbents<'_, '_>,
budget: &Budget<'_>,
) -> Result<u64> {
let mut found = 0;
if let Some(trace) = &mut pool.trace {
trace.heuristic_calls += 1;
}
let mut order: Vec<_> = (0..model.n())
.filter(|&j| model.kinds()[j].is_integral())
.collect();
order.sort_by(|&a, &b| {
model.objective()[b]
.abs()
.total_cmp(&model.objective()[a].abs())
.then(a.cmp(&b))
});
for mode in 0..3 {
if budget.stop().is_some() {
break;
}
let mut point = x.to_vec();
if let Some(trace) = &mut pool.trace {
trace.rounding_attempts += 1;
}
for &j in &order {
point[j] = match mode {
0 => point[j].round(),
1 => point[j].floor(),
_ => point[j].ceil(),
};
point[j] = point[j]
.max(node_bounds.lower[j].ceil())
.min(node_bounds.upper[j].floor());
}
if !consider(model, point.clone(), options, result, pool, "rounding")? {
continue;
}
found += 1;
for &j in order.iter().take(64) {
if budget.stop().is_some() {
break;
}
let c = oriented(model, model.objective()[j]);
if c == 0.0 {
continue;
}
let old = point[j];
point[j] += if c < 0.0 { 1.0 } else { -1.0 };
if point[j] < node_bounds.lower[j]
|| point[j] > node_bounds.upper[j]
|| !consider(model, point.clone(), options, result, pool, "unit_move")?
{
point[j] = old;
} else {
found += 1;
}
}
}
Ok(found)
}
fn root_local_search(
model: &Model,
(bounds, point): (&Bounds, &[f64]),
options: &Options,
budget: &Budget<'_>,
result: &mut SolveResult,
pool: &mut Incumbents<'_, '_>,
) -> Result<jump::Stats> {
use heuristic_budget::{Meter, Stop};
let settings = budget.settings;
let controls = pool
.pilot
.as_ref()
.map_or_else(local_mip_bench::Controls::default, |t| t.controls);
let mut jump_stats = jump::Stats::default();
if settings.feasibility_jump
&& controls.matched_fj_effort == 0
&& !controls.replace_root_fj
&& budget.stop().is_none()
{
let started = pool.pilot.as_ref().map(|_| Instant::now());
let (proposal, stats) = jump::search(
model,
bounds,
point,
budget,
settings.feasibility_jump_steps,
);
jump_stats = stats;
if let Some(x) = proposal {
consider(model, x, options, result, pool, "feasibility_jump")?;
}
if let Some((trace, started)) = pool.pilot.as_deref_mut().zip(started) {
let work = (result.nodes, budget.pivots);
trace.stage("feasibility_jump", work, work, started);
}
}
let matched_fj = controls.matched_fj_effort != 0;
let effort = if matched_fj {
controls.matched_fj_effort
} else {
settings.local_mip_effort
};
let skip = if effort == 0 {
"disabled"
} else if options.threads != 1 || !settings.presolve {
"ineligible_path"
} else if budget.stop().is_some() || settings.node_limit.is_some_and(|n| result.nodes >= n) {
"global_stop_before_dispatch"
} else {
"dispatched"
};
if let Some(trace) = &mut pool.pilot {
trace.skip = skip;
}
if skip != "dispatched" {
if settings.local_mip_effort != 0 {
result
.backend
.effective_options
.push(("diagnostics.root_local_search.skip".into(), skip.into()));
}
return Ok(jump_stats);
}
let started = pool.pilot.as_ref().map(|_| Instant::now());
let mut meter = Meter::new(budget, effort, effort / 4);
let source = if matched_fj {
"feasibility_jump_metered"
} else {
"local_mip"
};
let mut local_stats = local_mip::Stats::default();
let proposal = if matched_fj {
let (proposal, stats) = jump::search_metered(
model,
bounds,
point,
budget,
settings.feasibility_jump_steps,
&mut meter,
);
jump_stats = stats;
proposal.and_then(|x| {
if meter.valid_point(model, pool.original_model, &x, &options.tolerances)? {
Ok(x)
} else {
Err(Stop::Numerical)
}
})
} else {
let (proposal, stats) = local_mip::search(
model,
pool.original_model,
bounds,
point,
&options.tolerances,
&mut meter,
settings.local_mip_seed,
);
local_stats = stats;
proposal
};
let previous_best = pool.best;
let stop = match proposal {
Ok(x) => {
let first = !pool.best.is_finite();
if consider(model, x, options, result, pool, source)? && first {
pool.rounding_trials_left = 8;
}
Stop::Feasible
}
Err(reason) => reason,
};
let improved = u64::from(pool.best < previous_best);
meter.report(
&mut result.backend.effective_options,
source,
stop,
&[
("improved_incumbent", improved),
(
"proposals",
if matched_fj {
jump_stats.proposals
} else {
local_stats.proposals
},
),
(
"moves",
if matched_fj {
jump_stats.steps
} else {
local_stats.moves
},
),
(
"weight_bumps",
if matched_fj {
jump_stats.bumps
} else {
local_stats.weight_bumps
},
),
],
);
if let Some((trace, started)) = pool.pilot.as_deref_mut().zip(started) {
let work = (result.nodes, budget.pivots);
trace.stage(source, work, work, started);
}
Ok(jump_stats)
}
struct Branch {
parent: Option<Arc<Branch>>,
j: usize,
lower: f64,
upper: f64,
}
struct Node {
branch: Option<Arc<Branch>>,
depth: usize,
bound: Option<f64>,
basis: Option<Arc<Basis>>,
origin: Option<Origin>,
}
#[derive(Clone, Copy)]
struct Origin {
j: usize,
up: bool,
distance: f64,
parent_objective: f64,
}
struct Pseudocosts {
sum: Vec<[f64; 2]>,
count: Vec<[u32; 2]>,
total: [f64; 2],
total_count: [u32; 2],
min_step: f64,
}
impl Pseudocosts {
fn new(n: usize) -> Self {
Self {
sum: vec![[0.0; 2]; n],
count: vec![[0; 2]; n],
total: [0.0; 2],
total_count: [0; 2],
min_step: 0.,
}
}
fn record(&mut self, origin: Origin, objective: f64) {
let gain =
(objective - origin.parent_objective).max(0.0) / origin.distance.max(self.min_step);
if gain.is_finite() && origin.distance > 0.0 {
let d = usize::from(origin.up);
self.sum[origin.j][d] += gain;
self.count[origin.j][d] += 1;
self.total[d] += gain;
self.total_count[d] += 1;
}
}
fn known(&self) -> bool {
self.total_count[0] + self.total_count[1] > 0
}
fn estimate(&self, j: usize, up: bool) -> f64 {
let d = usize::from(up);
let prior = if self.total_count[d] > 0 {
self.total[d] / f64::from(self.total_count[d])
} else {
1.
};
(self.sum[j][d] + 2. * prior) / (f64::from(self.count[j][d]) + 2.)
}
}
struct Open {
key: f64,
serial: u64,
node: Node,
}
fn diagnostic_frontier_bound(
closed: f64,
all_closed_known: bool,
open: &std::collections::BinaryHeap<Open>,
current: Option<Option<f64>>,
) -> Option<f64> {
if !all_closed_known {
return None;
}
let mut bound = closed;
if let Some(node) = open.peek() {
bound = bound.min(node.node.bound?);
}
if let Some(node_bound) = current {
bound = bound.min(node_bound?);
}
bound.is_finite().then_some(bound)
}
fn gap_reached(
settings: &NativeOptions,
model: &Model,
pool: &Incumbents<'_, '_>,
result: &SolveResult,
bound: Option<f64>,
) -> bool {
if !settings.has_gap_limit() || !pool.upper.is_finite() {
return false;
}
let (Some(bound), Some(e)) = (bound, result.evaluation.as_ref()) else {
return false;
};
let within = |gap: lp_ip_craft::Gap| {
gap.absolute.is_finite()
&& gap.absolute > 0.0
&& (settings
.mip_absolute_gap
.is_some_and(|limit| limit > 0.0 && gap.absolute <= limit)
|| settings
.mip_relative_gap
.is_some_and(|limit| limit > 0.0 && gap.relative <= limit))
};
within(lp_ip_craft::Gap::new(Sense::Minimize, pool.upper, bound))
&& within(lp_ip_craft::Gap::new(
Sense::Minimize,
oriented(model, e.objective),
bound,
))
}
impl PartialEq for Open {
fn eq(&self, other: &Self) -> bool {
self.cmp(other).is_eq()
}
}
impl Eq for Open {}
impl PartialOrd for Open {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Open {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other
.key
.total_cmp(&self.key)
.then(self.node.depth.cmp(&other.node.depth))
.then(self.serial.cmp(&other.serial))
}
}
const SNAPSHOT_BUDGET_BYTES: usize = 256 << 20;
struct NodeBox {
bounds: Bounds,
changed: Vec<usize>,
path: Vec<(usize, f64, f64)>,
previous: Vec<usize>,
}
impl NodeBox {
fn enter(&mut self, root: &Bounds, branch: &Option<Arc<Branch>>, lp: &mut Lp) -> Result<bool> {
for &j in &self.changed {
self.bounds.lower[j] = root.lower[j];
self.bounds.upper[j] = root.upper[j];
}
self.path.clear();
let mut at = branch.as_deref();
while let Some(b) = at {
self.path.push((b.j, b.lower, b.upper));
at = b.parent.as_deref();
}
std::mem::swap(&mut self.previous, &mut self.changed);
self.changed.clear();
for &(j, l, u) in self.path.iter().rev() {
self.bounds.lower[j] = self.bounds.lower[j].max(l);
self.bounds.upper[j] = self.bounds.upper[j].min(u);
self.changed.push(j);
}
for &j in self.previous.iter().chain(&self.changed) {
if self.bounds.lower[j] <= self.bounds.upper[j] {
lp.set_bound(j, self.bounds.lower[j], self.bounds.upper[j])?;
}
}
Ok(self
.changed
.iter()
.all(|&j| self.bounds.lower[j] <= self.bounds.upper[j]))
}
}
struct RootRefit {
duals: Duals,
last_upper: f64,
min_gain: f64,
}
#[derive(Default)]
struct Counters {
warm_nodes: u64,
cold_solves: u64,
fallbacks: u64,
unweighted_retries: u64,
unverified_infeasible: u64,
heuristic_candidates: u64,
pruned_nodes: u64,
propagated_infeasible: u64,
implied_bounds: u64,
strong_probes: u64,
strong_pivots: u64,
strong_work: u64,
strong_work_exits: u64,
reduced_cost_fixings: u64,
mixed_fix_tests: u64,
root_refit: root_fix::Stats,
root_refit_sweeps: usize,
root_refit_conflicts: u64,
choice_route_bounds: u64,
choice_pair_bounds: u64,
choice_local_rounds: u64,
choice_local_cuts: u64,
choice_local_prunes: u64,
safe_node_prunes: u64,
dual_cutoff_prunes: u64,
probe_proof_prunes: u64,
probe_proof_fixings: u64,
choice_tree_cuts: usize,
leaf_repair_attempts: u64,
leaf_repaired: u64,
leaf_resplits: u64,
leaf_open: u64,
branch_events: Vec<String>,
}
impl NativeSolver {
fn solve_internal(
&mut self,
model: &Model,
options: &Options,
start: Option<&WarmStart>,
cancel: &CancellationToken,
diagnostic_original: &Model,
pilot: Option<&mut local_mip_bench::Trace<'_>>,
) -> Result<SolveResult> {
options.validate()?;
self.settings.validate()?;
if let Some(s) = start {
if s.primal.len() != model.n() || s.primal.iter().any(|v| !v.is_finite()) {
return Err(Error::InvalidInput(
"start must contain n finite values".into(),
));
}
}
if model.is_mip()
&& model
.variables()
.lower
.iter()
.chain(&model.variables().upper)
.any(|v| !v.is_finite() || v.abs() > 9_007_199_254_740_991.0)
{
return Err(Error::Unsupported(
"native MIP requires finite variable bounds of magnitude <= 2^53-1".into(),
));
}
let call_started = Instant::now();
if self.settings.presolve && model.m() == 0 && !model.is_mip() {
return boxed::solve(model, options, &self.settings, start, cancel, call_started);
}
let original_model = model;
let strengthened = if self.settings.presolve
&& !cancel.is_cancelled()
&& self.settings.time_limit_seconds != Some(0.)
{
presolve::strengthen_integer_rows(model, options.tolerances.feasibility)?
} else {
None
};
let model = strengthened.as_ref().unwrap_or(model);
let preserve_start = match (strengthened.as_ref(), start) {
(Some(_), Some(s)) => {
check::evaluate(original_model, &s.primal, &options.tolerances)?.feasible_candidate
&& !check::evaluate(model, &s.primal, &options.tolerances)?.feasible_candidate
}
_ => false,
};
if self.settings.decompose
&& !(model.is_mip() && self.settings.has_gap_limit())
&& !preserve_start
&& model.nnz() > 0
&& model.n() >= self.settings.decomposition_min_variables
&& !cancel.is_cancelled()
&& self.settings.time_limit_seconds != Some(0.)
{
if let Some(mut out) = components::solve_if_separable(
&self.settings,
model,
options,
start,
cancel,
call_started,
)? {
if strengthened.is_some() {
if let Some(x) = &out.candidate {
out.evaluation =
Some(check::evaluate(original_model, x, &options.tolerances)?);
}
}
return Ok(out);
}
}
let settings = &self.settings;
let mut budget = Budget {
start: call_started,
settings,
cancel,
pivots: 0,
};
let mut report = BackendReport::new("native");
report.version = Some(env!("CARGO_PKG_VERSION").into());
report.effective_options = effective_options(settings);
if model.is_mip() && settings.has_gap_limit() {
report.effective_options.retain(|(k, _)| k != "decompose");
report
.effective_options
.push(("decompose".into(), "false".into()));
report
.effective_options
.push(("gap_limit_scope".into(), "whole_model".into()));
}
report.start_status = match start {
None => StartStatus::NotProvided,
Some(_) if model.is_mip() => StartStatus::Evaluated,
Some(_) => StartStatus::Rejected,
};
let mut result = SolveResult::empty(Status::Unknown, "", report);
let mut pool = Incumbents {
best: f64::INFINITY,
upper: f64::INFINITY,
certified: None,
trace: (settings.mip_diagnostics && model.is_mip()).then(|| {
diagnostics::SearchDiagnostics::new(model, call_started, settings.mip_trace_limit)
}),
original_model: diagnostic_original,
pivots: 0,
pilot,
rounding_trials_left: 0,
};
let lattice = settings.objective_lattice && incumbent::integer_lattice(model);
let tree_lattice = lattice && model.kinds().iter().all(|k| k.is_integral());
let mut counters = Counters::default();
let mut jump_stats = jump::Stats::default();
if model.is_mip() {
if let Some(s) = start {
consider(
original_model,
s.primal.clone(),
options,
&mut result,
&mut pool,
"start",
)?;
}
}
let mut domain = propagate::Domain::with_equalities(
model,
settings.presolve,
options.tolerances.feasibility,
(settings.integer_equality_presolve && presolve::supported_arithmetic())
.then_some(&options.tolerances),
);
let mut mixed = mixed::Domain::new(
model,
settings.presolve && settings.mixed_propagation,
options.tolerances.feasibility,
);
if pool.trace.is_some() && settings.presolve {
domain.enable_statistics();
}
let supported_choice_arithmetic = model.is_mip()
&& (settings.choice_route_depth > 0 || settings.choice_pair_depth > 0)
&& presolve::supported_arithmetic();
let mut choice_domain = (supported_choice_arithmetic && settings.choice_route_depth > 0)
.then(|| choice_route::Domain::read(model, &budget));
let mut pair_domain = (model.is_mip()
&& ((supported_choice_arithmetic && settings.choice_pair_depth > 0)
|| settings.choice_local_depth > 0))
.then(|| choice_mass::Separator::new(model, &budget));
let mut tree_model = None::<Model>;
let mut tree_separator = (model.is_mip() && settings.choice_tree_cut_limit > 0)
.then(|| choice_mass::Separator::new(model, &budget));
let mut conflicts = proof_conflicts::Pool::default();
let mut root = std::borrow::Cow::Borrowed(model.variables());
let mut root_refit = None::<RootRefit>;
let mut node_box = NodeBox {
bounds: root.as_ref().clone(),
changed: Vec::new(),
path: Vec::new(),
previous: Vec::new(),
};
let mut open = std::collections::BinaryHeap::new();
let (mut serial, mut snapshot_bytes) = (0u64, 0usize);
let mut dive = Some(Node {
branch: None,
depth: 0,
bound: None,
basis: None,
origin: None,
});
let probe_structure = settings
.scalable_branching
.then(|| branching_structure(model));
let mut pseudocosts = Pseudocosts::new(model.n());
pseudocosts.min_step = settings.pseudocost_min_step;
let mut certifier = Certifier {
lp: None,
attempts: 0,
certified: 0,
last: None,
lp_attempts: 0,
witness_attempts: 0,
witness_successes: 0,
witness_work: 0,
witness_outcome: witness::Outcome::NotAttempted,
witness_assignment: None,
};
let mut keep = presolve::kept_rows(model, &root, settings);
let mut closed_bound = f64::INFINITY;
let mut all_bounds = true;
let mut unresolved_leaf = f64::INFINITY;
let mut consecutive_dive = 0usize;
let mut status = Status::Optimal;
let mut lp: Option<Lp> = None;
let (mut removed_rows, mut removed_columns) = (0usize, 0usize);
loop {
let model = tree_model.as_ref().unwrap_or(model);
if let Some(trace) = &mut pool.trace {
trace.checkpoint(
result.nodes,
budget.pivots,
diagnostic_frontier_bound(
closed_bound,
all_bounds,
&open,
dive.as_ref().map(|n| n.bound),
)
.map(|b| oriented(model, b)),
open.len() + usize::from(dive.is_some()),
);
}
let mut node = match dive.take() {
Some(node) => {
consecutive_dive += 1;
node
}
None => match open.pop() {
Some(Open { node, .. }) => {
consecutive_dive = 0;
if let Some(basis) = &node.basis {
snapshot_bytes -= basis.bytes();
}
node
}
None => break,
},
};
let stop = budget
.stop()
.or_else(|| {
(model.is_mip() && settings.node_limit.is_some_and(|n| result.nodes >= n))
.then_some(Status::NodeLimit)
})
.or_else(|| {
(model.is_mip()
&& gap_reached(
settings,
model,
&pool,
&result,
diagnostic_frontier_bound(
closed_bound,
all_bounds,
&open,
Some(node.bound),
),
))
.then_some(Status::GapLimit)
});
if let Some(s) = stop {
status = s;
serial += 1;
open.push(Open {
key: node.bound.unwrap_or(f64::NEG_INFINITY),
serial,
node,
});
break;
}
if node.bound.is_some_and(|b| b >= pool.upper) {
if let Some(trace) = &mut pool.trace {
trace.enter_node(node.depth, open.len() + 1);
trace.bound_prune(true, result.nodes, budget.pivots);
}
closed_bound = closed_bound.min(node.bound.unwrap());
counters.pruned_nodes += 1;
continue;
}
if let Some(trace) = &mut pool.trace {
trace.enter_node(node.depth, open.len() + 1);
}
let conversion = Instant::now();
let fresh = lp.is_none();
let lp = match &mut lp {
Some(lp) => lp,
None => {
let columns = presolve::kept_columns(model, &root, settings);
let built = lp.insert(Lp::new(
model,
&keep,
&columns,
controls(model, options, settings),
)?);
removed_rows = built.removed_rows(model);
removed_columns = built.removed_columns();
built
}
};
let sweep = match (&mut root_refit, &pool.certified) {
(Some(refit), Some((seed, _)))
if counters.root_refit_sweeps < settings.root_refit_sweeps
&& pool.upper < refit.last_upper
&& refit.last_upper - pool.upper >= refit.min_gain =>
{
Some((refit, seed))
}
_ => None,
};
if let Some((refit, seed)) = sweep {
refit.last_upper = pool.upper;
counters.root_refit_sweeps += 1;
let tight = root_fix::narrow_box(
model,
&root,
seed,
pool.upper,
&refit.duals,
&budget,
&mut counters.root_refit,
)?
.filter(|tight| {
seed.iter()
.enumerate()
.all(|(j, &v)| tight.lower[j] <= v && v <= tight.upper[j])
});
if let Some(tight) = tight {
closed_bound = closed_bound.min(pool.upper);
lp.set_bounds(&tight.lower, &tight.upper)?;
root = std::borrow::Cow::Owned(tight);
node_box.bounds = root.as_ref().clone();
node_box.changed.clear();
let mut data = model.data().clone();
data.variables = root.as_ref().clone();
let narrowed = Model::new(data)?;
domain = propagate::Domain::with_equalities(
&narrowed,
settings.presolve,
options.tolerances.feasibility,
(settings.integer_equality_presolve && presolve::supported_arithmetic())
.then_some(&options.tolerances),
);
mixed = mixed::Domain::new(
&narrowed,
settings.presolve && settings.mixed_propagation,
options.tolerances.feasibility,
);
if pool.trace.is_some() && settings.presolve {
domain.enable_statistics();
}
counters.root_refit.applied += 1;
}
}
if !node_box.enter(&root, &node.branch, lp)? {
counters.root_refit_conflicts += 1;
continue;
}
let before = node_box.changed.len();
let mut feasible = domain.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
if feasible && settings.mixed_propagation {
for _ in 0..2 {
let previous = node_box.changed.len();
feasible =
mixed.apply(model, &mut node_box.bounds, &mut node_box.changed, &budget)
&& domain.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
if !feasible || previous == node_box.changed.len() {
break;
}
}
}
if let Some(routes) = choice_domain
.as_mut()
.filter(|_| feasible && node.depth < settings.choice_route_depth)
{
let previous = node_box.changed.len();
feasible = routes.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
counters.choice_route_bounds += (node_box.changed.len() - previous) as u64;
}
if let Some(pairs) = pair_domain.as_ref().filter(|_| {
feasible && supported_choice_arithmetic && node.depth < settings.choice_pair_depth
}) {
let previous = node_box.changed.len();
feasible =
pairs.propagate(model, &mut node_box.bounds, &mut node_box.changed, &budget);
counters.choice_pair_bounds += (node_box.changed.len() - previous) as u64;
}
if feasible
&& (node.depth < settings.choice_pair_depth
|| node.depth < settings.choice_route_depth)
{
feasible = domain.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
}
if feasible && settings.proof_conflict_limit > 0 {
let prior = node_box.changed.len();
feasible = conflicts.apply(
&mut node_box.bounds,
&mut node_box.changed,
&mut closed_bound,
);
if feasible && node_box.changed.len() != prior {
feasible = domain.apply(&mut node_box.bounds, &mut node_box.changed, &budget);
}
}
if !feasible {
counters.propagated_infeasible += 1;
if node.depth == 0 {
status = if result.candidate.is_some() {
Status::NumericalFailure
} else {
Status::Infeasible
};
break;
}
continue;
}
for &j in &node_box.changed[before..] {
lp.set_bound(j, node_box.bounds.lower[j], node_box.bounds.upper[j])?;
}
counters.implied_bounds += (node_box.changed.len() - before) as u64;
let warm = if !settings.node_reoptimization {
if !fresh {
lp.reset_to_slack();
}
false
} else {
if let Some(basis) = &node.basis {
lp.restore(basis);
}
!fresh
};
result.backend.conversion_seconds += conversion.elapsed().as_secs_f64();
let solve = Instant::now();
let before_pivots = budget.pivots;
if warm {
counters.warm_nodes += 1;
} else {
counters.cold_solves += 1;
}
let node_bounds = &node_box.bounds;
let (mut s, mut cutoff) = if warm
&& settings.dual_cutoff_interval > 0
&& pool.upper.is_finite()
{
lp.solve_verified_cutoff(&mut budget, model, node_bounds, pool.upper, tree_lattice)?
} else {
(lp.solve(&mut budget, !warm)?, None)
};
let simplex_cutoff = cutoff.is_some();
let mut checked_solution = None;
let mut checked_bound = None;
if warm && budget.stop().is_none() {
let retry = match s {
Status::Optimal => {
let point = lp.point();
let duals = lp.duals(model);
if settings.safe_node_pruning && pool.upper.is_finite() {
let objective = oriented(
model,
model.objective_offset()
+ model
.objective()
.iter()
.zip(&point)
.map(|(c, v)| c * v)
.sum::<f64>(),
);
let margin = 1e-8 * (1. + pool.upper.abs());
if objective >= pool.upper - margin {
let bound =
node_dual_bound(model, node_bounds, &duals, tree_lattice)?;
checked_bound = Some(bound);
cutoff = bound.filter(|&b| b >= pool.upper);
}
}
if cutoff.is_some() {
false
} else if accepted(model, node_bounds, &point, &duals, options, settings) {
checked_solution = Some((point, duals));
false
} else {
checked_bound = None;
true
}
}
Status::Infeasible => !lp.infeasibility_verified(),
Status::NumericalFailure => true,
_ => false,
};
if retry {
counters.fallbacks += 1;
counters.cold_solves += 1;
lp.reset_to_slack();
s = lp.solve(&mut budget, true)?;
if let Some(trace) = &mut pool.trace {
trace.node_lp_solves += 1;
}
}
}
if s == Status::NumericalFailure
&& model.is_mip()
&& settings.steepest_edge
&& budget.stop().is_none()
{
counters.cold_solves += 1;
counters.unweighted_retries += 1;
if let Some(trace) = &mut pool.trace {
trace.node_lp_solves += 1;
}
s = lp.retry_unweighted(&mut budget)?;
if s == Status::Infeasible && !lp.infeasibility_verified() {
s = Status::NumericalFailure;
}
}
if s == Status::Infeasible && !lp.infeasibility_verified() {
counters.unverified_infeasible += 1;
}
let node_seconds = solve.elapsed().as_secs_f64();
result.backend.solve_seconds += node_seconds;
if let Some(trace) = &mut pool.trace {
trace.node_lp_solves += 1;
trace.node_lp_pivots += budget.pivots - before_pivots;
trace.node_lp_seconds += node_seconds;
if node.depth == 0 {
trace.root_lp(s, budget.pivots - before_pivots, node_seconds);
}
if s == Status::Infeasible {
trace.infeasible_lps += 1;
}
}
if model.is_mip() {
result.nodes += 1;
if node.depth == 0 {
if let Some(trace) = &mut pool.pilot {
trace.stage(
"search_root_lp",
(result.nodes, budget.pivots),
(result.nodes - 1, before_pivots),
solve,
);
}
}
}
let checks = Instant::now();
if let Some(bound) = cutoff {
if settings.proof_conflict_limit > 0 && result.nodes % 16 == 0 {
conflicts.learn(
model,
&root,
node_bounds,
&lp.duals(model),
pool.upper,
&budget,
)?;
}
if let Some(origin) = node.origin.filter(|_| settings.cutoff_pseudocosts) {
pseudocosts.record(
origin,
bound.min(pool.upper) - oriented(model, model.objective_offset()),
);
}
if let Some(trace) = &mut pool.trace {
trace.bound_prune(false, result.nodes, budget.pivots);
}
closed_bound = closed_bound.min(bound);
counters.pruned_nodes += 1;
if simplex_cutoff {
counters.dual_cutoff_prunes += 1;
} else {
counters.safe_node_prunes += 1;
}
result.backend.check_seconds += checks.elapsed().as_secs_f64();
continue;
}
if s == Status::Infeasible {
if model.is_mip() && result.nodes == 1 {
status = if result.candidate.is_some() {
Status::NumericalFailure
} else {
Status::Infeasible
};
break;
}
if !model.is_mip() {
status = s;
break;
}
continue;
}
if s != Status::Optimal {
if settings.partial_dual_bounds {
let duals = lp.duals(model);
if duals.row_duals.iter().all(|v| v.is_finite()) {
if let Some(value) =
safe_dual_bound_with_bounds(model, node_bounds, &duals.row_duals)?.bound
{
let b = oriented(model, value);
let b = if tree_lattice {
incumbent::lattice_ceil(b)
} else {
b
};
node.bound = Some(node.bound.map_or(b, |old| old.max(b)));
if !model.is_mip() {
result.best_bound = Some(oriented(model, b));
}
}
}
}
status = if model.is_mip() && s == Status::Unbounded {
Status::Unknown
} else {
s
};
serial += 1;
open.push(Open {
key: node.bound.unwrap_or(f64::NEG_INFINITY),
serial,
node: Node {
basis: None,
..node
},
});
break;
}
let checked = checked_solution.is_some();
let (x, duals) = checked_solution.unwrap_or_else(|| (lp.point(), lp.duals(model)));
if !checked && !accepted(model, node_bounds, &x, &duals, options, settings) {
#[cfg(feature = "kernel-profile")]
if std::env::var_os("LPIP_TRACE_SIMPLEX").is_some() {
eprintln!(
"acceptance failure {:?}",
check::lp_residuals_with_bounds(model, node_bounds, &x, &duals)
);
}
status = Status::NumericalFailure;
all_bounds = false;
break;
}
let mut bound = match checked_bound {
Some(bound) => bound,
None => node_dual_bound(model, node_bounds, &duals, tree_lattice)?,
};
if !model.is_mip() {
result.evaluation = Some(check::evaluate(model, &x, &options.tolerances)?);
if let Some(trace) = &mut pool.pilot {
trace.checked_point(&x, options, "lp_solution", (result.nodes, budget.pivots));
}
result.candidate = Some(x);
result.duals = Some(duals);
result.best_bound = bound.map(|b| oriented(model, b));
result.backend.check_seconds += checks.elapsed().as_secs_f64();
break;
}
let objective = oriented(
model,
model.objective().iter().zip(&x).map(|(c, v)| c * v).sum(),
);
pool.pivots = budget.pivots;
if let Some(trace) = &mut pool.trace {
trace.checkpoint(
result.nodes,
budget.pivots,
diagnostic_frontier_bound(closed_bound, all_bounds, &open, Some(bound))
.map(|b| oriented(model, b)),
open.len() + 1,
);
if node.depth == 0 {
let fractional = (0..model.n())
.filter(|&j| {
model.kinds()[j].is_integral()
&& (x[j] - x[j].round()).abs() > options.tolerances.integrality
})
.count();
trace.root_solution(
result.nodes,
budget.pivots,
model.objective_offset() + oriented(model, objective),
bound.map(|b| oriented(model, b)),
fractional,
);
}
}
if let Some(origin) = node.origin {
pseudocosts.record(origin, objective);
}
let branch =
branching_variable(model, node_bounds, &x, options, &pseudocosts, settings);
if branch.is_some()
&& settings.incumbent_heuristic
&& (result.nodes == 1 || !pool.upper.is_finite() || pool.rounding_trials_left > 0)
{
let found = heuristic(
model,
node_bounds,
&x,
options,
&mut result,
&mut pool,
&budget,
)?;
counters.heuristic_candidates += found;
pool.rounding_trials_left = if found > 0 {
0
} else {
pool.rounding_trials_left.saturating_sub(1)
};
}
if node.depth == 0 {
if let Some(trace) = &mut pool.pilot {
trace.skip = if branch.is_some() {
"disabled"
} else {
"integral_root"
};
trace.event(
"root_relaxation",
"search_root_lp",
(result.nodes, budget.pivots),
Some(model.objective_offset() + oriented(model, objective)),
bound.map(|b| oriented(model, b)),
);
}
if branch.is_some()
&& (settings.feasibility_jump
|| settings.local_mip_effort != 0
|| pool.pilot.is_some())
{
jump_stats = root_local_search(
model,
(node_bounds, &x),
options,
&budget,
&mut result,
&mut pool,
)?;
}
}
certify(
model,
options,
settings,
&keep,
&mut certifier,
&mut pool,
&mut result,
&mut budget,
)?;
if let Some(separator) = pair_domain.as_mut().filter(|_| {
branch.is_some()
&& node.depth < settings.choice_local_depth
&& !bound.is_some_and(|b| b >= pool.upper)
&& budget.stop().is_none()
}) {
let local = separator.shallow_bound(model, node_bounds, (lp, &x), &mut budget)?;
counters.choice_local_rounds += local.rounds;
counters.choice_local_cuts += local.cuts;
if let Some(local_bound) = local.bound {
bound = Some(bound.map_or(local_bound, |b| b.max(local_bound)));
if local_bound >= pool.upper {
counters.choice_local_prunes += 1;
}
}
}
if let Some(b) = bound.filter(|_| settings.root_refit_sweeps > 0 && node.depth == 0) {
root_refit = Some(RootRefit {
duals: duals.clone(),
last_upper: pool.upper,
min_gain: if pool.upper.is_finite() {
settings.root_refit_fraction * (pool.upper - b).max(0.)
} else {
0.
},
});
}
let mut stop_after_root = false;
if node.depth == 0 && branch.is_some() {
if let Some(trace) = &mut pool.pilot {
trace.root_end((result.nodes, budget.pivots));
stop_after_root = trace.controls.stop_at_root;
}
}
if stop_after_root
|| gap_reached(
settings,
model,
&pool,
&result,
diagnostic_frontier_bound(closed_bound, all_bounds, &open, Some(bound)),
)
{
node.bound = bound;
serial += 1;
open.push(Open {
key: bound.unwrap_or(f64::NEG_INFINITY),
serial,
node,
});
status = if stop_after_root {
Status::Unknown
} else {
Status::GapLimit
};
break;
}
if bound.is_some_and(|b| b >= pool.upper) {
if settings.proof_conflict_limit > 0 && result.nodes % 16 == 0 {
conflicts.learn(model, &root, node_bounds, &duals, pool.upper, &budget)?;
}
if let Some(trace) = &mut pool.trace {
trace.bound_prune(false, result.nodes, budget.pivots);
}
closed_bound = closed_bound.min(bound.unwrap());
counters.pruned_nodes += 1;
result.backend.check_seconds += checks.elapsed().as_secs_f64();
continue;
}
if let Some(separator) = tree_separator.as_mut().filter(|_| {
branch.is_some()
&& node.depth >= 4
&& counters.choice_tree_cuts < settings.choice_tree_cut_limit
&& result.nodes % settings.choice_tree_cut_interval == 0
&& budget.stop().is_none()
}) {
let mut cuts = separator.separate(&x, &budget);
cuts.truncate((settings.choice_tree_cut_limit - counters.choice_tree_cuts).min(8));
if !cuts.is_empty() {
let mut extended = model.clone();
certified_cuts::append(&mut extended, &cuts)?;
if let Ok(mut added) = lp.extend_rows(&extended, model.m()) {
added.set_bounds(&node_bounds.lower, &node_bounds.upper)?;
*lp = added;
keep.resize(extended.m(), true);
if let Some(refit) = &mut root_refit {
refit.duals.row_duals.resize(extended.m(), 0.);
}
counters.choice_tree_cuts += cuts.len();
certifier.lp = None;
node.basis = None;
node.bound = bound;
dive = Some(node);
tree_model = Some(extended);
continue;
}
}
}
let mut probe_seconds = 0.;
let mut probe_bounds = Vec::new();
let branch = if branch.is_some()
&& (((settings.reliability_branching || settings.scalable_branching)
&& node.depth <= 8
&& probe_count_available(settings, &counters))
|| (node.depth == 0 && settings.strong_branching))
&& settings.node_reoptimization
&& (if settings.scalable_branching {
true
} else if settings.reliability_branching {
model.n() <= 1024 && model.m() <= 1024 && model.nnz() <= 20000
} else {
eligible_strong_branching(model)
}) {
let probe_started = Instant::now();
let chosen = strong_branch(
model,
node_bounds,
&x,
objective,
options,
lp,
&mut pseudocosts,
&mut budget,
&mut result.nodes,
&mut counters,
probe_structure.as_deref(),
&mut probe_bounds,
)?;
probe_seconds = probe_started.elapsed().as_secs_f64();
result.backend.solve_seconds += probe_seconds;
probe_bounds
.iter()
.max_by_key(|(_, sides)| {
sides
.iter()
.filter(|b| b.is_some_and(|v| v >= pool.upper))
.count()
})
.filter(|(_, sides)| sides.iter().any(|b| b.is_some_and(|v| v >= pool.upper)))
.map(|(j, _)| *j)
.or(chosen)
.or(branch)
} else {
branch
};
if let Some(j) = branch {
if counters.branch_events.len() < settings.branch_trace_limit {
let mut columns = vec![j];
columns.extend(
(0..model.n())
.filter(|&k| {
k != j
&& model.kinds()[k].is_integral()
&& (x[k] - x[k].round()).abs() > options.tolerances.integrality
})
.take(15),
);
let number = |v: f64| {
if v.is_finite() {
v.to_string()
} else {
"null".into()
}
};
let candidates = columns
.iter()
.map(|&k| {
format!(
"{{\"column\":{k},\"value\":{},\"down_sum\":{},\"up_sum\":{},\"down_count\":{},\"up_count\":{},\"down_estimate\":{},\"up_estimate\":{}}}",
number(x[k]),
number(pseudocosts.sum[k][0]),
number(pseudocosts.sum[k][1]),
pseudocosts.count[k][0],
pseudocosts.count[k][1],
number(pseudocosts.estimate(k, false)),
number(pseudocosts.estimate(k, true))
)
})
.collect::<Vec<_>>()
.join(",");
counters.branch_events.push(format!(
"{{\"node\":{},\"chosen\":{j},\"candidates\":[{candidates}]}}",
result.nodes
));
}
let limit = if tree_lattice {
16
} else {
settings.mixed_fix_trials.min(128)
};
let fix_depth = if tree_lattice {
8
} else {
settings.mixed_fix_depth
};
let fixes = if settings.reduced_cost_fixing
&& limit > 0
&& (fix_depth == 0 || node.depth <= fix_depth)
{
let (fixes, tests) = reduced_cost_fixes(
model,
node_bounds,
&x,
&duals,
(pool.upper, bound),
limit,
&budget,
)?;
if !tree_lattice {
counters.mixed_fix_tests += tests;
}
fixes
} else {
Vec::new()
};
let mut child_parent = node.branch.clone();
if !fixes.is_empty() {
closed_bound = closed_bound.min(pool.upper);
counters.reduced_cost_fixings += fixes.len() as u64;
for (column, value) in fixes {
child_parent = Some(Arc::new(Branch {
parent: child_parent,
j: column,
lower: value,
upper: value,
}));
}
}
for &(k, sides) in probe_bounds.iter().filter(|(k, _)| *k != j) {
let [down, up] = sides;
if let Some(b) = down.filter(|&b| b >= pool.upper) {
closed_bound = closed_bound.min(b);
counters.probe_proof_fixings += 1;
child_parent = Some(Arc::new(Branch {
parent: child_parent,
j: k,
lower: x[k].ceil(),
upper: node_bounds.upper[k],
}));
} else if let Some(b) = up.filter(|&b| b >= pool.upper) {
closed_bound = closed_bound.min(b);
counters.probe_proof_fixings += 1;
child_parent = Some(Arc::new(Branch {
parent: child_parent,
j: k,
lower: node_bounds.lower[k],
upper: x[k].floor(),
}));
}
}
let sides = probe_bounds
.iter()
.find(|(k, _)| *k == j)
.map_or([None; 2], |(_, v)| *v);
let (l, u) = (node_bounds.lower[j], node_bounds.upper[j]);
let (floor, ceil) = (x[j].floor(), x[j].ceil());
let mut child = |lower: f64, upper: f64, up: bool| {
let child_bound = match (bound, sides[usize::from(up)]) {
(Some(a), Some(b)) => Some(a.max(b)),
(a, b) => a.or(b),
};
if let Some(b) = child_bound.filter(|&b| b >= pool.upper) {
closed_bound = closed_bound.min(b);
counters.probe_proof_prunes += 1;
return None;
}
(lower <= upper).then(|| Node {
branch: Some(Arc::new(Branch {
parent: child_parent.clone(),
j,
lower,
upper,
})),
depth: node.depth + 1,
bound: child_bound,
basis: None,
origin: Some(Origin {
j,
up,
distance: if up { ceil - x[j] } else { x[j] - floor },
parent_objective: objective,
}),
})
};
let (down, up) = (child(l, u.min(floor), false), child(l.max(ceil), u, true));
let prefer_up = if settings.estimated_diving {
let up_gain = pseudocosts.estimate(j, true) * (ceil - x[j]);
let down_gain = pseudocosts.estimate(j, false) * (x[j] - floor);
up_gain < down_gain || (up_gain == down_gain && x[j] - floor >= 0.5)
} else {
x[j] - floor >= 0.5
};
let (next, other) = if prefer_up { (up, down) } else { (down, up) };
if let Some(mut other) = other {
let size = lp.snapshot_bytes();
if settings.node_reoptimization
&& snapshot_bytes + size <= SNAPSHOT_BUDGET_BYTES
{
other.basis = Some(Arc::new(lp.snapshot()));
snapshot_bytes += size;
}
serial += 1;
open.push(Open {
key: other.bound.unwrap_or(f64::NEG_INFINITY),
serial,
node: other,
});
}
match next {
Some(next)
if settings.dive_node_limit > 0
&& consecutive_dive >= settings.dive_node_limit =>
{
serial += 1;
open.push(Open {
key: next.bound.unwrap_or(f64::NEG_INFINITY),
serial,
node: next,
});
}
next => dive = next,
}
} else {
pool.pivots = budget.pivots;
if let Some(trace) = &mut pool.trace {
trace.integral_leaves += 1;
}
let mut point = x;
for (j, v) in point.iter_mut().enumerate() {
if model.kinds()[j].is_integral() {
*v = v.round();
}
}
if !consider(
model,
point,
options,
&mut result,
&mut pool,
"integral_leaf",
)? {
if !settings.repair_integral_leaves {
status = Status::NumericalFailure;
all_bounds = false;
break;
}
let mut assignment = lp.point();
for (j, value) in assignment.iter_mut().enumerate() {
if model.kinds()[j].is_integral() {
*value = value.round();
}
}
counters.leaf_repair_attempts += 1;
let repaired = if budget.stop().is_none() {
repair_leaf(
model,
pool.original_model,
node_bounds,
&assignment,
&keep,
options,
&mut budget,
)?
} else {
None
};
let mut closed_by_repair = false;
if let Some(point) = repaired {
let objective = oriented(
model,
model.objective_offset()
+ model
.objective()
.iter()
.zip(&point)
.map(|(c, v)| c * v)
.sum::<f64>(),
);
let closes = bound.is_some_and(|b| {
objective - b <= settings.dual_tolerance * (1. + objective.abs())
});
if consider(
model,
point,
options,
&mut result,
&mut pool,
"repaired_leaf",
)? && closes
{
counters.leaf_repaired += 1;
closed_by_repair = true;
}
}
if closed_by_repair {
} else if let Some((j, split)) =
integral_resplit(model, node_bounds, &assignment)
{
let child = |lower: f64, upper: f64| Node {
bound,
branch: Some(Arc::new(Branch {
parent: node.branch.clone(),
j,
lower,
upper,
})),
depth: node.depth + 1,
basis: None,
origin: None,
};
let down = child(node_bounds.lower[j], split);
let up = child(split + 1., node_bounds.upper[j]);
serial += 1;
open.push(Open {
key: bound.unwrap_or(f64::NEG_INFINITY),
serial,
node: down,
});
dive = Some(up);
counters.leaf_resplits += 1;
continue;
} else {
let residual = bound.unwrap_or(f64::NEG_INFINITY);
unresolved_leaf = unresolved_leaf.min(residual);
if let Some(b) = bound {
closed_bound = closed_bound.min(b);
} else {
all_bounds = false;
}
counters.leaf_open += 1;
continue;
}
}
pool.rounding_trials_left = 0;
certify(
model,
options,
settings,
&keep,
&mut certifier,
&mut pool,
&mut result,
&mut budget,
)?;
if let Some(b) = bound {
closed_bound = closed_bound.min(b);
} else {
all_bounds = false;
}
}
result.backend.check_seconds +=
(checks.elapsed().as_secs_f64() - probe_seconds).max(0.);
}
if model.is_mip() {
if status == Status::Optimal && unresolved_leaf < pool.upper {
status = Status::NumericalFailure;
}
for o in open.iter().map(|o| &o.node).chain(dive.as_ref()) {
if let Some(b) = o.bound {
closed_bound = closed_bound.min(b);
} else {
all_bounds = false;
}
}
if all_bounds && closed_bound.is_finite() {
let bound = if lattice {
incumbent::lattice_ceil(closed_bound)
} else {
closed_bound
};
result.best_bound = Some(oriented(model, bound));
}
if status == Status::Optimal && result.candidate.is_none() {
status = Status::Infeasible;
}
}
if status == Status::Optimal {
if let (Some(e), Some(b)) = (&result.evaluation, result.best_bound) {
let gap = oriented(model, e.objective) - oriented(model, b);
if gap < -settings.dual_tolerance * (1.0 + e.objective.abs()) {
if let Some((x, e)) = pool.certified {
let gap = oriented(model, e.objective) - oriented(model, b);
if gap >= -settings.dual_tolerance * (1.0 + e.objective.abs()) {
result.candidate = Some(x);
result.evaluation = Some(e);
} else {
status = Status::NumericalFailure;
}
} else {
status = Status::NumericalFailure;
}
}
}
}
let model = tree_model.as_ref().unwrap_or(model);
let stats = lp.as_ref().map(|lp| lp.stats).unwrap_or_default();
result.backend.effective_options.extend(
[
("factor_peak_entries", stats.peak_entries as u64),
("refactorizations", stats.refactors),
("phase_one_pivots", stats.phase_one_pivots),
("degenerate_pivots", stats.degenerate_pivots),
("weight_resets", stats.weight_resets),
("row_pricings", stats.row_pricings),
("column_pricings", stats.column_pricings),
("replayed_pivots", stats.replayed_pivots),
("basis_updates", stats.updates),
("forrest_tomlin_updates", stats.ft_updates),
("bound_flips", stats.bound_flips),
("basis_repairs", stats.repairs),
("basis_restores", stats.restores),
("cost_perturbations", stats.perturbations),
("component_count", 1),
("component_workers", 1),
("reoptimized_nodes", counters.warm_nodes),
("presolve_removed_rows", removed_rows as u64),
("presolve_removed_columns", removed_columns as u64),
("cold_lp_solves", counters.cold_solves),
("cold_fallbacks", counters.fallbacks),
("unweighted_node_retries", counters.unweighted_retries),
(
"unverified_infeasible_nodes",
counters.unverified_infeasible,
),
("heuristic_candidates", counters.heuristic_candidates),
("mixed_propagation_rows", mixed.stats.rows),
("mixed_propagation_visits", mixed.stats.visits),
("mixed_propagation_terms", mixed.stats.terms),
("mixed_propagation_changes", mixed.stats.changes),
("mixed_propagation_infeasibilities", mixed.stats.infeasible),
("mixed_propagation_work_limits", mixed.stats.limits),
("feasibility_jump_steps", jump_stats.steps),
("feasibility_jump_work", jump_stats.work),
("feasibility_jump_candidates", jump_stats.feasible),
("feasibility_jump_weight_bumps", jump_stats.bumps),
("pruned_nodes", counters.pruned_nodes),
(
"propagated_infeasible_nodes",
counters.propagated_infeasible,
),
("implied_bounds", counters.implied_bounds),
("strong_branch_probes", counters.strong_probes),
("strong_branch_pivots", counters.strong_pivots),
("strong_branch_work", counters.strong_work),
("strong_branch_work_exits", counters.strong_work_exits),
("reduced_cost_fixings", counters.reduced_cost_fixings),
("mixed_fix_tests", counters.mixed_fix_tests),
("root_refit_sweeps", counters.root_refit_sweeps as u64),
("root_refit_tests", counters.root_refit.tests),
("root_refit_certified", counters.root_refit.certified),
("root_refit_implied", counters.root_refit.implied),
("root_refit_applied", counters.root_refit.applied),
("root_refit_conflicts", counters.root_refit_conflicts),
("choice_route_bounds", counters.choice_route_bounds),
("choice_pair_bounds", counters.choice_pair_bounds),
("choice_local_rounds", counters.choice_local_rounds),
("choice_local_cuts", counters.choice_local_cuts),
("choice_local_prunes", counters.choice_local_prunes),
("safe_node_prunes", counters.safe_node_prunes),
("dual_cutoff_prunes", counters.dual_cutoff_prunes),
("probe_proof_prunes", counters.probe_proof_prunes),
("probe_proof_fixings", counters.probe_proof_fixings),
("choice_tree_cuts", counters.choice_tree_cuts as u64),
("conflict_learned", conflicts.learned),
("conflict_prunes", conflicts.prunes),
("conflict_implications", conflicts.implications),
("leaf_repair_attempts", counters.leaf_repair_attempts),
("leaf_repaired", counters.leaf_repaired),
("leaf_resplits", counters.leaf_resplits),
("leaf_open", counters.leaf_open),
("certification_solves", certifier.lp_attempts),
("rational_witness_attempts", certifier.witness_attempts),
("rational_witness_successes", certifier.witness_successes),
("rational_witness_work", certifier.witness_work),
("certified_incumbents", certifier.certified),
]
.map(|(k, v)| (format!("diagnostics.{k}"), v.to_string())),
);
result
.backend
.effective_options
.push(("diagnostics.objective_lattice".into(), lattice.to_string()));
if let Some(x) = result.candidate.as_ref().filter(|_| strengthened.is_some()) {
result.evaluation = Some(check::evaluate(original_model, x, &options.tolerances)?);
}
result.status = status;
result.iterations = budget.pivots;
if pool.trace.is_some() {
result.backend.effective_options.push((
"diagnostics.rational_witness_outcome".into(),
certifier.witness_outcome.as_str().into(),
));
if let Some(hash) = certifier.witness_assignment {
result.backend.effective_options.push((
"diagnostics.rational_witness_assignment".into(),
format!("{hash:016x}"),
));
}
}
if let Some(trace) = pool.trace.take() {
trace.finish(&mut result, domain.statistics(), diagnostic_original, model);
}
if settings.branch_trace_limit > 0 {
result.backend.effective_options.push((
"diagnostics.branch_trace".into(),
format!("[{}]", counters.branch_events.join(",")),
));
}
result.message = format!(
"Native dual simplex numerical solve: {} (not an exact certificate)",
status.as_str()
);
result.backend.raw_status = Some(status.as_str().into());
result.backend.total_seconds = budget.start.elapsed().as_secs_f64();
result.backend.time_budget_exceeded = settings
.time_limit_seconds
.is_some_and(|t| result.backend.total_seconds > t);
Ok(result)
}
}
fn repair_leaf(
model: &Model,
original: &Model,
bounds: &Bounds,
assignment: &[f64],
kept_rows: &[bool],
options: &Options,
budget: &mut Budget<'_>,
) -> Result<Option<Vec<f64>>> {
let valid = |x: &[f64]| -> Result<bool> {
let tolerance = options.tolerances.feasibility;
Ok(x.iter()
.enumerate()
.all(|(j, &v)| bounds.lower[j] - tolerance <= v && v <= bounds.upper[j] + tolerance)
&& check::evaluate(model, x, &options.tolerances)?.feasible_candidate
&& check::evaluate(original, x, &options.tolerances)?.feasible_candidate)
};
if budget.settings.rational_certification {
if let (Some(witness), _, _) =
witness::upper(model, assignment, budget, witness::ATTEMPT_WORK)
{
if valid(&witness.point)? {
return Ok(Some(witness.point));
}
}
}
if budget.stop().is_some() {
return Ok(None);
}
let mut fixed = bounds.clone();
for (j, &value) in assignment
.iter()
.enumerate()
.filter(|(j, _)| model.kinds()[*j].is_integral())
{
if value < fixed.lower[j] || value > fixed.upper[j] {
return Ok(None);
}
fixed.lower[j] = value;
fixed.upper[j] = value;
}
let settings = NativeOptions {
iteration_limit: Some(
budget
.settings
.iteration_limit
.unwrap_or(u64::MAX)
.min(budget.pivots.saturating_add(384)),
),
..budget.settings.clone()
};
let mut attempt = Budget {
settings: &settings,
..*budget
};
let columns = presolve::kept_columns(model, model.variables(), &settings);
let mut lp = Lp::new(
model,
kept_rows,
&columns,
controls(model, options, &settings),
)?;
lp.set_bounds(&fixed.lower, &fixed.upper)?;
let solved = lp.solve(&mut attempt, true)?;
budget.pivots = attempt.pivots;
if solved == Status::Optimal {
let point = lp.point();
if valid(&point)? {
return Ok(Some(point));
}
}
Ok(None)
}
fn integral_resplit(model: &Model, bounds: &Bounds, point: &[f64]) -> Option<(usize, f64)> {
point.iter().enumerate().find_map(|(j, &v)| {
if !model.kinds()[j].is_integral() || bounds.lower[j] == bounds.upper[j] {
None
} else {
let split = if v < bounds.upper[j] { v } else { v - 1. };
(bounds.lower[j] <= split && split + 1. <= bounds.upper[j]).then_some((j, split))
}
})
}
fn node_dual_bound(
model: &Model,
bounds: &Bounds,
duals: &Duals,
lattice: bool,
) -> Result<Option<f64>> {
Ok(
safe_dual_bound_with_bounds(model, bounds, &duals.row_duals)?
.bound
.map(|b| {
let b = oriented(model, b);
if lattice {
incumbent::lattice_ceil(b)
} else {
b
}
}),
)
}
fn reduced_cost_fixes(
model: &Model,
bounds: &Bounds,
x: &[f64],
duals: &Duals,
(upper, parent_bound): (f64, Option<f64>),
limit: usize,
budget: &Budget<'_>,
) -> Result<(Vec<(usize, f64)>, u64)> {
let Some(parent_bound) = parent_bound.filter(|_| upper.is_finite()) else {
return Ok((Vec::new(), 0));
};
let _fixing = crate::profile::enter("reduced_cost_fixing");
let gap = (upper - parent_bound).max(0.);
let mut trials = Vec::new();
for (j, &value) in x.iter().enumerate() {
if !model.kinds()[j].is_integral()
|| value.fract() != 0.
|| bounds.upper[j] - bounds.lower[j] < 1.
{
continue;
}
let rc = oriented(model, duals.reduced_costs[j]);
let gain = if value == bounds.lower[j] {
rc
} else if value == bounds.upper[j] {
-rc
} else {
continue;
};
if gain.is_finite() && gain > 0. && gain >= 0.9 * gap {
trials.push((j, value, gain));
}
}
trials.sort_by(|a, b| b.2.total_cmp(&a.2).then(a.0.cmp(&b.0)));
trials.truncate(limit);
if trials.is_empty() {
return Ok((Vec::new(), 0));
}
let mut prepared = if trials.len() >= 2 {
let _prepare = crate::profile::enter("fixing_prepare");
Some(lp_ip_craft::PreparedDualBound::new(
model,
bounds,
&duals.row_duals,
)?)
} else {
None
};
let mut opposite = bounds.clone();
let mut fixes = Vec::new();
let mut tests = 0;
for (j, value, _) in trials {
if budget.stop().is_some() {
break;
}
let (lo, hi) = (opposite.lower[j], opposite.upper[j]);
if value == lo {
opposite.lower[j] = lo + 1.;
} else {
opposite.upper[j] = hi - 1.;
}
tests += 1;
let proof = {
let _bound = crate::profile::enter("fixing_bound");
let report = if let Some(cache) = &mut prepared {
cache.set_bound(j, opposite.lower[j], opposite.upper[j])?;
cache.bound()
} else {
safe_dual_bound_with_bounds(model, &opposite, &duals.row_duals)?
};
report.bound.map(|v| oriented(model, v))
};
if proof.is_some_and(|b| b >= upper) {
opposite.lower[j] = value;
opposite.upper[j] = value;
fixes.push((j, value));
} else {
opposite.lower[j] = lo;
opposite.upper[j] = hi;
}
if let Some(cache) = &mut prepared {
cache.set_bound(j, opposite.lower[j], opposite.upper[j])?;
}
}
Ok((fixes, tests))
}
fn eligible_strong_branching(model: &Model) -> bool {
(12..=256).contains(&model.n())
&& model.m() <= 512
&& model.nnz() <= 10000
&& model
.matrix()
.pattern
.indptr
.windows(2)
.filter(|w| w[1] - w[0] > 8)
.take(2)
.count()
== 2
}
fn branching_structure(model: &Model) -> Vec<f64> {
let mut structure = vec![0.; model.n()];
let a = model.matrix();
for range in a.pattern.indptr.windows(2) {
let degree = (range[1] - range[0]).max(1) as f64;
for &j in &a.pattern.indices[range[0]..range[1]] {
structure[j] += 1. / degree;
}
}
structure
}
fn probe_count_available(settings: &NativeOptions, counters: &Counters) -> bool {
(settings.scalable_branching && settings.branch_probe_pivot_share > 0)
|| counters.strong_probes < settings.reliability_max_probes
}
fn probe_work_available(model: &Model, budget: &Budget<'_>, counters: &Counters) -> (u64, u64) {
let unit = (model.nnz() + model.n() + model.m()).max(1) as u64;
let settings = budget.settings;
let extra = budget
.pivots
.saturating_sub(counters.strong_pivots)
.checked_div(settings.branch_probe_pivot_share)
.unwrap_or(0);
let left = settings
.branch_probe_work
.saturating_add(extra.saturating_mul(unit))
.saturating_sub(counters.strong_work);
(settings.branch_probe_pivots.min(left / unit), unit)
}
#[allow(clippy::too_many_arguments)]
fn strong_branch(
model: &Model,
bounds: &Bounds,
x: &[f64],
objective: f64,
options: &Options,
lp: &mut Lp,
pseudocosts: &mut Pseudocosts,
budget: &mut Budget<'_>,
nodes: &mut u64,
counters: &mut Counters,
structure: Option<&[f64]>,
proofs: &mut Vec<(usize, [Option<f64>; 2])>,
) -> Result<Option<usize>> {
let reliable = budget.settings.reliability_branching || budget.settings.scalable_branching;
let eligible = |j: usize| {
model.kinds()[j].is_integral()
&& (x[j] - x[j].round()).abs() > options.tolerances.integrality
&& (!reliable
|| pseudocosts.count[j]
.iter()
.any(|&n| n < budget.settings.reliability_threshold))
};
let mut candidates = Vec::new();
if let Some(structure) = structure {
let score = |j: usize| {
let fraction = (x[j] - x[j].round()).abs();
if budget.settings.branch_probe_score && pseudocosts.known() {
let down = x[j] - x[j].floor();
let a = pseudocosts.estimate(j, false) * down;
let b = pseudocosts.estimate(j, true) * (1. - down);
if budget.settings.branching_score == "product" {
(a * b).sqrt()
} else {
0.8 * a.min(b) + 0.2 * a.max(b)
}
} else {
fraction * (1. + structure[j])
}
};
for j in (0..model.n()).filter(|&j| eligible(j)) {
let at = candidates
.iter()
.position(|&k| score(j) > score(k))
.unwrap_or(candidates.len());
if at < budget.settings.branch_probe_candidates {
candidates.insert(at, j);
candidates.truncate(budget.settings.branch_probe_candidates);
}
}
} else {
candidates = (0..model.n()).filter(|&j| eligible(j)).collect();
candidates.sort_by(|&a, &b| {
(x[b] - x[b].round())
.abs()
.total_cmp(&(x[a] - x[a].round()).abs())
.then(a.cmp(&b))
});
candidates.truncate(2);
}
if candidates.is_empty() || (!reliable && candidates.len() < 2) {
return Ok(None);
}
let basis = lp.snapshot();
let mut best = None;
let mut best_score = -1.;
let mut box_for_proof = budget.settings.branch_probe_proofs.then(|| bounds.clone());
for j in candidates {
let mut sides = [None; 2];
let mut gains = [0.; 2];
let mut complete = true;
for (d, gain) in gains.iter_mut().enumerate() {
if budget.stop().is_some()
|| (reliable && !probe_count_available(budget.settings, counters))
|| budget.settings.node_limit.is_some_and(|cap| *nodes >= cap)
{
complete = false;
break;
}
let up = d == 1;
let (lo, hi) = if up {
(bounds.lower[j].max(x[j].ceil()), bounds.upper[j])
} else {
(bounds.lower[j], bounds.upper[j].min(x[j].floor()))
};
if lo > hi {
complete = false;
break;
}
let (probe_cap, unit) = if budget.settings.scalable_branching {
let (cap, unit) = probe_work_available(model, budget, counters);
if cap == 0 {
counters.strong_work_exits += 1;
complete = false;
break;
}
if !budget.settings.branch_probe_actual_work {
counters.strong_work += cap * unit;
}
(cap, unit)
} else {
(32, 0)
};
lp.set_bound(j, lo, hi)?;
let mut settings = budget.settings.clone();
settings.iteration_limit = Some(
settings
.iteration_limit
.unwrap_or(u64::MAX)
.min(budget.pivots.saturating_add(probe_cap)),
);
let mut probe = Budget {
start: budget.start,
settings: &settings,
cancel: budget.cancel,
pivots: budget.pivots,
};
let status = lp.solve(&mut probe, false);
let spent = probe.pivots - budget.pivots;
counters.strong_pivots += spent;
if budget.settings.branch_probe_actual_work {
counters.strong_work = counters.strong_work.saturating_add(spent.max(1) * unit);
}
budget.pivots = probe.pivots;
*nodes += 1;
counters.strong_probes += 1;
if let Some(probe_box) = &mut box_for_proof {
sides[d] = match status.as_ref() {
Ok(Status::Optimal) => {
probe_box.lower[j] = lo;
probe_box.upper[j] = hi;
let value = node_dual_bound(model, probe_box, &lp.duals(model), false)?;
probe_box.lower[j] = bounds.lower[j];
probe_box.upper[j] = bounds.upper[j];
value
}
Ok(Status::Infeasible) if lp.infeasibility_verified() => Some(f64::INFINITY),
_ => None,
};
}
if status.as_ref().is_ok_and(|s| *s == Status::Optimal) {
let point = lp.point();
let value = oriented(
model,
model
.objective()
.iter()
.zip(&point)
.map(|(c, v)| c * v)
.sum(),
);
*gain = (value - objective).max(0.);
pseudocosts.record(
Origin {
j,
up,
distance: if up {
x[j].ceil() - x[j]
} else {
x[j] - x[j].floor()
},
parent_objective: objective,
},
value,
);
} else {
complete = false;
}
lp.set_bound(j, bounds.lower[j], bounds.upper[j])?;
lp.restore(&basis);
let _ = status;
}
if sides.iter().any(Option::is_some) {
proofs.push((j, sides));
}
if complete {
let score = gains[0].max(1e-6) * gains[1].max(1e-6);
if score > best_score {
best_score = score;
best = Some(j);
}
}
}
if reliable {
Ok(branching_variable(model, bounds, x, options, pseudocosts, budget.settings).or(best))
} else {
Ok(best)
}
}
fn branching_variable(
model: &Model,
bounds: &Bounds,
x: &[f64],
options: &Options,
pseudocosts: &Pseudocosts,
settings: &NativeOptions,
) -> Option<usize> {
let fraction = |j: usize| (j, (x[j] - x[j].round()).abs());
let most = |a: &(usize, f64), b: &(usize, f64)| a.1.total_cmp(&b.1);
let integral = (0..model.n()).filter(|&j| model.kinds()[j].is_integral());
let fractional = integral
.clone()
.map(fraction)
.filter(|&(_, f)| f > options.tolerances.integrality);
let chosen = if pseudocosts.known() {
fractional
.map(|(j, f)| {
let down = x[j] - x[j].floor();
let a = (pseudocosts.estimate(j, false) * down).max(1e-6);
let b = (pseudocosts.estimate(j, true) * (1.0 - down)).max(1e-6);
let score = if settings.branching_score == "product" {
a.sqrt() * b.sqrt()
} else {
0.8 * a.min(b) + 0.2 * a.max(b)
};
(j, score + 1e-12 * f)
})
.max_by(most)
} else {
fractional.max_by(most)
};
if let Some((j, _)) = chosen {
return Some(j);
}
let mut rounded = x.to_vec();
for j in integral.clone() {
rounded[j] = rounded[j].round();
}
if incumbent::upper_with_bounds(model, bounds, &rounded).is_some() {
return None;
}
integral
.filter(|&j| x[j].floor() >= bounds.lower[j] && x[j].ceil() <= bounds.upper[j])
.map(fraction)
.filter(|&(_, f)| f > 0.0)
.max_by(most)
.map(|(j, _)| j)
}
fn controls(model: &Model, options: &Options, settings: &NativeOptions) -> lp::Controls {
lp::Controls {
threads: options.threads,
pivot_tolerance: settings.pivot_tolerance,
refactor_interval: settings.refactor_interval,
adaptive_refactor: settings.adaptive_refactor,
basis_update: settings.basis_update,
factor_pivot_search: settings.factor_pivot_search,
factor_ordering: settings.factor_ordering,
max_factor_entries: settings.max_factor_entries,
factor_replay: settings.factor_replay,
adaptive_pricing: settings.adaptive_pricing,
devex: settings.devex,
steepest_edge: settings.steepest_edge,
feasibility: options.tolerances.feasibility,
dual: settings.dual_tolerance * objective_scale(model),
}
}
fn effective_options(s: &NativeOptions) -> Vec<(String, String)> {
let mut options: Vec<(String, String)> = [
(
"algorithm",
"dual_simplex+best_bound_diving_branch_and_bound".to_string(),
),
(
"linear_kernel",
"bounded_dual_revised_simplex+markowitz_lu".into(),
),
("max_factor_entries", s.max_factor_entries.to_string()),
("packing_root", s.packing_root.to_string()),
(
"packing_root_iterations",
s.packing_root_iterations.to_string(),
),
("packing_root_work", s.packing_root_work.to_string()),
("packing_neighborhoods", s.packing_neighborhoods.to_string()),
(
"packing_neighborhood_size",
s.packing_neighborhood_size.to_string(),
),
("packing_workers", s.packing_workers.to_string()),
(
"packing_neighborhood_nodes",
s.packing_neighborhood_nodes.to_string(),
),
("packing_cuts", s.packing_cuts.to_string()),
("packing_cut_work", s.packing_cut_work.to_string()),
(
"packing_combine_repairs",
s.packing_combine_repairs.to_string(),
),
("packing_rounds", s.packing_rounds.to_string()),
(
"packing_neighborhood_growth",
s.packing_neighborhood_growth.to_string(),
),
("packing_seed_strategy", s.packing_seed_strategy.to_string()),
(
"packing_residual_cliques",
s.packing_residual_cliques.to_string(),
),
("packing_clique_work", s.packing_clique_work.to_string()),
(
"packing_price_diagnostics",
s.packing_price_diagnostics.to_string(),
),
(
"packing_repair_seconds",
format!("{:?}", s.packing_repair_seconds),
),
(
"packing_proof_seconds",
format!("{:?}", s.packing_proof_seconds),
),
("partial_dual_bounds", s.partial_dual_bounds.to_string()),
("scalable_branching", s.scalable_branching.to_string()),
(
"branch_probe_candidates",
s.branch_probe_candidates.to_string(),
),
("branch_probe_pivots", s.branch_probe_pivots.to_string()),
("branch_probe_work", s.branch_probe_work.to_string()),
("tree_threads", s.tree_threads.to_string()),
("tree_split_depth", s.tree_split_depth.to_string()),
("refactor_interval", s.refactor_interval.to_string()),
("adaptive_refactor", s.adaptive_refactor.to_string()),
("basis_update", s.basis_update.as_str().to_string()),
("factor_pivot_search", s.factor_pivot_search.to_string()),
("factor_ordering", s.factor_ordering.as_str().to_string()),
("steepest_edge", s.steepest_edge.to_string()),
("root_cuts", s.root_cuts.to_string()),
("root_separation", s.root_separation.to_string()),
("mip_presolve", s.mip_presolve.to_string()),
("adaptive_root", s.adaptive_root.to_string()),
(
"integer_equality_presolve",
s.integer_equality_presolve.to_string(),
),
(
"coefficient_tightening",
s.coefficient_tightening.to_string(),
),
("dual_presolve", s.dual_presolve.to_string()),
("mip_presolve_rounds", s.mip_presolve_rounds.to_string()),
("gmi_cuts", s.gmi_cuts.to_string()),
("mir_cuts", s.mir_cuts.to_string()),
("mip_cut_rounds", s.mip_cut_rounds.to_string()),
("mip_cut_limit", s.mip_cut_limit.to_string()),
("cut_exact_work", s.cut_exact_work.to_string()),
("root_heuristics", s.root_heuristics.to_string()),
("grouped_heuristics", s.grouped_heuristics.to_string()),
("ordered_group_cuts", s.ordered_group_cuts.to_string()),
("choice_mass_rounds", s.choice_mass_rounds.to_string()),
("choice_route_passes", s.choice_route_passes.to_string()),
("choice_route_restarts", s.choice_route_restarts.to_string()),
("heuristic_lp_calls", s.heuristic_lp_calls.to_string()),
("branching_score", s.branching_score.to_string()),
("pseudocost_min_step", s.pseudocost_min_step.to_string()),
("branch_trace_limit", s.branch_trace_limit.to_string()),
("root_cut_rounds", s.root_cut_rounds.to_string()),
("cover_lifting", s.cover_lifting.to_string()),
("root_propagation", s.root_propagation.to_string()),
("mixed_propagation", s.mixed_propagation.to_string()),
("singleton_presolve", s.singleton_presolve.to_string()),
(
"avoid_dominant_components",
s.avoid_dominant_components.to_string(),
),
("devex", s.devex.to_string()),
("adaptive_pricing", s.adaptive_pricing.to_string()),
("factor_replay", s.factor_replay.to_string()),
("mip_diagnostics", s.mip_diagnostics.to_string()),
("mip_trace_limit", s.mip_trace_limit.to_string()),
("component_threads", s.component_threads.to_string()),
(
"component_parallel_min_entries",
s.component_parallel_min_entries.to_string(),
),
("decompose", s.decompose.to_string()),
(
"decomposition_min_variables",
s.decomposition_min_variables.to_string(),
),
("time_limit_seconds", format!("{:?}", s.time_limit_seconds)),
("node_limit", format!("{:?}", s.node_limit)),
("iteration_limit", format!("{:?}", s.iteration_limit)),
("pivot_tolerance", s.pivot_tolerance.to_string()),
("dual_tolerance", s.dual_tolerance.to_string()),
("presolve", s.presolve.to_string()),
("redundant_rows", s.redundant_rows.to_string()),
(
"redundant_row_min_ratio",
s.redundant_row_min_ratio.to_string(),
),
("node_reoptimization", s.node_reoptimization.to_string()),
("strong_branching", s.strong_branching.to_string()),
("reliability_branching", s.reliability_branching.to_string()),
("reliability_threshold", s.reliability_threshold.to_string()),
(
"reliability_max_probes",
s.reliability_max_probes.to_string(),
),
("reduced_cost_fixing", s.reduced_cost_fixing.to_string()),
("mixed_fix_trials", s.mixed_fix_trials.to_string()),
("proof_conflict_limit", s.proof_conflict_limit.to_string()),
(
"choice_tree_cut_interval",
s.choice_tree_cut_interval.to_string(),
),
("choice_tree_cut_limit", s.choice_tree_cut_limit.to_string()),
("branch_probe_score", s.branch_probe_score.to_string()),
("branch_probe_proofs", s.branch_probe_proofs.to_string()),
("root_probe_limit", s.root_probe_limit.to_string()),
("dive_node_limit", s.dive_node_limit.to_string()),
("estimated_diving", s.estimated_diving.to_string()),
(
"repair_integral_leaves",
s.repair_integral_leaves.to_string(),
),
("dual_cutoff_interval", s.dual_cutoff_interval.to_string()),
("root_cut_delay", s.root_cut_delay.to_string()),
("root_cut_gap", s.root_cut_gap.to_string()),
("root_cut_progress", s.root_cut_progress.to_string()),
("cutoff_pseudocosts", s.cutoff_pseudocosts.to_string()),
(
"branch_probe_pivot_share",
s.branch_probe_pivot_share.to_string(),
),
(
"branch_probe_actual_work",
s.branch_probe_actual_work.to_string(),
),
("mixed_fix_depth", s.mixed_fix_depth.to_string()),
("mixed_root_rounds", s.mixed_root_rounds.to_string()),
("root_refit_sweeps", s.root_refit_sweeps.to_string()),
("root_refit_fraction", s.root_refit_fraction.to_string()),
("choice_route_depth", s.choice_route_depth.to_string()),
("choice_pair_depth", s.choice_pair_depth.to_string()),
("choice_local_depth", s.choice_local_depth.to_string()),
("choice_local_rounds", s.choice_local_rounds.to_string()),
("safe_node_pruning", s.safe_node_pruning.to_string()),
("choice_order_presolve", s.choice_order_presolve.to_string()),
("incumbent_heuristic", s.incumbent_heuristic.to_string()),
(
"rational_certification",
s.rational_certification.to_string(),
),
("feasibility_jump", s.feasibility_jump.to_string()),
(
"feasibility_jump_steps",
s.feasibility_jump_steps.to_string(),
),
("objective_lattice", s.objective_lattice.to_string()),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
if s.objective_cutoff_bounds {
options.push(("objective_cutoff_bounds".into(), "true".into()));
}
if let Some(value) = s.mip_relative_gap {
options.push(("mip_relative_gap".into(), value.to_string()));
}
if let Some(value) = s.mip_absolute_gap {
options.push(("mip_absolute_gap".into(), value.to_string()));
}
if s.local_mip_effort != 0 {
options.push(("local_mip_effort".into(), s.local_mip_effort.to_string()));
options.push(("local_mip_seed".into(), s.local_mip_seed.to_string()));
}
options
}
impl LpIpSolver for NativeSolver {
fn solve(
&mut self,
model: &Model,
options: &Options,
start: Option<&WarmStart>,
cancel: &CancellationToken,
) -> Result<SolveResult> {
let began = Instant::now();
options.validate()?;
self.settings.validate()?;
if model.is_mip()
&& self.settings.has_gap_limit()
&& (self.settings.tree_threads > 1
|| self.settings.packing_root
|| self.settings.packing_neighborhoods > 0
|| self.settings.packing_cuts)
{
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()));
}
if let Some(s) = start {
if s.primal.len() != model.n() || s.primal.iter().any(|v| !v.is_finite()) {
return Err(Error::InvalidInput(
"start must contain n finite values".into(),
));
}
}
if options.threads == 1 {
let mut result = (|| {
if self.settings.packing_root
|| self.settings.packing_neighborhoods > 0
|| self.settings.packing_cuts
{
if let Some(r) = packing::solve(self, model, options, start, cancel)? {
return Ok(r);
}
}
if self.settings.tree_threads > 1 {
if let Some(r) = tree::solve(self, model, options, start, cancel, None, None)? {
return Ok(r);
}
}
root::solve(self, model, options, start, cancel)
})()?;
result
.backend
.effective_options
.retain(|(k, _)| k != "numeric_threads");
result
.backend
.effective_options
.push(("numeric_threads".into(), "1".into()));
return Ok(result);
}
let eligible = options.threads > 1
&& model.nnz() >= 65_536
&& !(self.settings.packing_root
&& self.settings.packing_proof_seconds == Some(0.)
&& model.nnz() < 131_072)
&& !cancel.is_cancelled()
&& !self
.settings
.time_limit_seconds
.is_some_and(|t| began.elapsed().as_secs_f64() >= t)
&& self.settings.node_limit != Some(0)
&& self.settings.iteration_limit != Some(0);
let _execution = if eligible {
parallel::Execution::new(options.threads).map_err(Error::Backend)?
} else {
parallel::Execution::default()
};
let mut settings = self.settings.clone();
if options.threads > 1 {
settings.component_threads = 1;
settings.packing_workers = 1;
settings.tree_threads = 1;
}
settings.time_limit_seconds = settings
.time_limit_seconds
.map(|t| (t - began.elapsed().as_secs_f64()).max(0.));
let mut solver = NativeSolver::new(settings);
let mut result = (|| {
if solver.settings.packing_root
|| solver.settings.packing_neighborhoods > 0
|| solver.settings.packing_cuts
{
if let Some(result) = packing::solve(&mut solver, model, options, start, cancel)? {
return Ok(result);
}
}
if solver.settings.tree_threads > 1 {
if let Some(result) =
tree::solve(&mut solver, model, options, start, cancel, None, None)?
{
return Ok(result);
}
}
root::solve(&mut solver, model, options, start, cancel)
})()?;
result
.backend
.effective_options
.retain(|(k, _)| k != "numeric_threads");
result
.backend
.effective_options
.push(("numeric_threads".into(), options.threads.to_string()));
Ok(result)
}
}
#[cfg(test)]
mod option_validation_tests {
use super::*;
#[test]
fn invalid_packing_controls_name_the_field() {
let cases: Vec<(NativeOptions, &str)> = vec![
(
NativeOptions {
packing_rounds: 0,
..Default::default()
},
"packing_rounds",
),
(
NativeOptions {
packing_neighborhoods: 4096,
packing_rounds: 2,
..Default::default()
},
"packing_neighborhoods * packing_rounds",
),
(
NativeOptions {
packing_neighborhood_growth: 1025,
..Default::default()
},
"packing_neighborhood_growth",
),
(
NativeOptions {
packing_clique_work: 1_000_001,
..Default::default()
},
"packing_clique_work",
),
(
NativeOptions {
packing_seed_strategy: "best".into(),
..Default::default()
},
"packing_seed_strategy",
),
(
NativeOptions {
packing_repair_seconds: Some(f64::NAN),
..Default::default()
},
"packing_repair_seconds",
),
(
NativeOptions {
packing_proof_seconds: Some(-1.),
..Default::default()
},
"packing_proof_seconds",
),
(
NativeOptions {
packing_root_iterations: 100_001,
..Default::default()
},
"packing_root_iterations",
),
(
NativeOptions {
packing_neighborhood_size: 3,
..Default::default()
},
"packing_neighborhood_size",
),
(
NativeOptions {
packing_workers: 17,
..Default::default()
},
"packing_workers",
),
(
NativeOptions {
branch_probe_candidates: 0,
..Default::default()
},
"branch_probe_candidates",
),
(
NativeOptions {
tree_threads: 0,
..Default::default()
},
"tree_threads",
),
(
NativeOptions {
tree_split_depth: 9,
..Default::default()
},
"tree_split_depth",
),
];
for (settings, field) in cases {
match settings.validate() {
Err(Error::InvalidInput(message)) => {
assert!(message.starts_with(field), "{message} should name {field}")
}
other => panic!("{field}: expected InvalidInput, got {other:?}"),
}
}
assert!(
NativeOptions {
packing_neighborhoods: 4096,
packing_rounds: 1,
packing_repair_seconds: Some(0.),
packing_proof_seconds: Some(0.),
..Default::default()
}
.validate()
.is_ok()
);
}
}
#[cfg(test)]
mod branching_policy_tests {
use super::*;
use lp_ip_craft::{CsrMatrix, ModelData, VariableKind};
#[test]
fn product_and_weighted_sum_choose_distinct_planted_candidates() {
let m = Model::new(ModelData {
objective: vec![1.; 2],
objective_offset: 0.,
sense: Sense::Minimize,
variables: Bounds::new(vec![0.; 2], vec![2.; 2]),
kinds: vec![VariableKind::Integer; 2],
matrix: CsrMatrix::from_dense(0, 2, &[]).unwrap(),
rows: Bounds::free(0),
})
.unwrap();
let mut p = Pseudocosts::new(2);
p.sum = vec![[200., 20000.], [3000., 3000.]];
p.count = vec![[1000, 1000]; 2];
p.total = [3200., 23000.];
p.total_count = [2000, 2000];
for (score, expected) in [("weighted_sum", 0), ("product", 1)] {
let s = NativeOptions {
branching_score: score.into(),
..Default::default()
};
assert_eq!(
branching_variable(&m, m.variables(), &[0.5, 0.5], &Options::default(), &p, &s),
Some(expected)
);
}
}
#[test]
fn pseudocost_step_floor_is_opt_in_and_does_not_inflate_tiny_steps() {
let origin = Origin {
j: 0,
up: false,
distance: 1e-8,
parent_objective: 0.,
};
let mut raw = Pseudocosts::new(1);
raw.record(origin, 1.);
let mut clamped = Pseudocosts::new(1);
clamped.min_step = 0.01;
clamped.record(origin, 1.);
assert_eq!(raw.sum[0][0], 1e8);
assert_eq!(clamped.sum[0][0], 100.);
}
}
#[cfg(test)]
mod leaf_repair_tests {
use super::*;
use lp_ip_craft::{CsrMatrix, ModelData, VariableKind};
fn model() -> Model {
Model::new(ModelData {
objective: vec![1., -1.],
objective_offset: 0.,
sense: Sense::Minimize,
variables: Bounds::new(vec![0.; 2], vec![3., 1.]),
kinds: vec![VariableKind::Integer, VariableKind::Continuous],
matrix: CsrMatrix::from_dense(1, 2, &[1., 1.]).unwrap(),
rows: Bounds::new(vec![2.5], vec![2.5]),
})
.unwrap()
}
#[test]
fn a_rejected_leaf_is_repaired_only_with_a_checked_point() {
let m = model();
let cancel = CancellationToken::default();
for exact in [true, false] {
let settings = NativeOptions {
rational_certification: exact,
..Default::default()
};
let mut budget = Budget {
start: Instant::now(),
settings: &settings,
cancel: &cancel,
pivots: 0,
};
let repaired = repair_leaf(
&m,
&m,
m.variables(),
&[2., 0.49],
&[true],
&Options::default(),
&mut budget,
)
.unwrap()
.expect("z = 2 admits y = 0.5");
assert_eq!(repaired[0], 2.);
assert!((repaired[1] - 0.5).abs() <= 1e-9, "{repaired:?}");
assert!(
repair_leaf(
&m,
&m,
m.variables(),
&[0., 1.],
&[true],
&Options::default(),
&mut budget,
)
.unwrap()
.is_none()
);
}
}
#[test]
fn leaf_resplits_partition_the_integer_domain() {
let m = model();
let b = m.variables();
assert_eq!(integral_resplit(&m, b, &[3., 0.]), Some((0, 2.)));
assert_eq!(integral_resplit(&m, b, &[1., 0.]), Some((0, 1.)));
assert_eq!(integral_resplit(&m, b, &[0., 0.]), Some((0, 0.)));
let fixed = Bounds::new(vec![2., 0.], vec![2., 1.]);
assert_eq!(integral_resplit(&m, &fixed, &[2., 0.5]), None);
}
}