use crate::*;
#[derive(Default)]
pub(crate) struct Stats {
pub pivots: u64,
pub nodes: u64,
pub gmi: u64,
pub small_gap_skips: u64,
pub mir: u64,
pub choice_mass: u64,
pub choice_precedence_rows: u64,
pub choice_precedence_signs: u64,
pub route_improvements: u64,
pub route_work: usize,
pub mixed_root: root_fix::Stats,
pub root_probe: root_fix::ProbeStats,
pub covers: u64,
pub lifted: u64,
pub exact_work: u64,
pub gmi_work: u64,
pub candidates: u64,
pub rejected: u64,
pub vubs: u64,
pub basis_reuses: u64,
pub pruned: u64,
pub rens_nodes: u64,
pub rens_found: u64,
pub grouped: grouped::Stats,
pub bound: Option<f64>,
pub initial_objective: Option<f64>,
pub stages: Vec<String>,
pub seed: Option<Vec<f64>>,
pub primal: primal::Stats,
pub stop: &'static str,
}
fn number(v: Option<f64>) -> String {
v.filter(|v| v.is_finite())
.map_or_else(|| "null".into(), |v| v.to_string())
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run(
model: &mut Model,
original: &Model,
options: &Options,
settings: &NativeOptions,
start: Option<&WarmStart>,
cancel: &CancellationToken,
began: Instant,
policy: Option<&root_policy::Policy>,
mut pilot: Option<&mut local_mip_bench::Trace<'_>>,
) -> Result<Stats> {
let mut stats = Stats {
seed: start.map(|s| s.primal.clone()),
..Default::default()
};
let root_budget = policy.map(|_| root_policy::Policy::budget(settings));
let mut budget = Budget {
start: began,
settings: root_budget.as_ref().unwrap_or(settings),
cancel,
pivots: 0,
};
if policy.is_some() && budget.stop().is_some() {
stats.stop = "root_budget";
return Ok(stats);
}
let mut choice_mass = (settings.choice_mass_rounds > 0
|| settings.choice_route_passes > 0
|| settings.choice_order_presolve)
.then(|| choice_mass::Separator::new(model, &budget))
.filter(|s| !s.is_empty());
if let Some(separator) = choice_mass
.as_ref()
.filter(|_| settings.choice_order_presolve)
{
let (cuts, signs) = separator.precedence(model, &budget)?;
stats.choice_precedence_rows = cuts as u64;
stats.choice_precedence_signs = signs as u64;
}
if let Some(s) = choice_mass
.as_ref()
.filter(|_| settings.choice_route_passes > 0)
{
(stats.route_improvements, stats.route_work) =
choice_route::improve(model, &s.pairs, options, &budget, &mut stats.seed)?;
}
let mut lp = match Lp::new(
model,
&vec![true; model.m()],
&presolve::kept_columns(model, model.variables(), settings),
controls(model, options, settings),
) {
Ok(lp) => lp,
Err(_) if policy.is_some() => {
stats.stop = "lp_setup";
return Ok(stats);
}
Err(e) => return Err(e),
};
let generic_rounds = policy.map_or_else(
|| {
if settings.gmi_cuts || settings.mir_cuts {
settings.mip_cut_rounds
} else {
0
}
},
|p| p.rounds,
);
let delay = if choice_mass.is_some() && generic_rounds > 0 {
settings.root_cut_delay.min(settings.choice_mass_rounds)
} else {
0
};
let cut_upper = (settings.root_cut_gap > 0.)
.then(|| {
stats
.seed
.as_deref()
.and_then(|seed| certified_start(original, seed, &budget))
})
.flatten();
let rounds = (generic_rounds + delay).max(if choice_mass.is_some() {
settings.choice_mass_rounds
} else {
0
});
let mut stagnant = 0;
let mut previous: Option<f64> = None;
let mut families = policy.map_or([settings.gmi_cuts, settings.mir_cuts], |p| p.families);
let initial_nnz = model.nnz();
const POLICY_EXACT_WORK: u64 = 4_000_000;
stats.stop = "round_limit";
let cuts_from = model.m();
let mut last: Option<(usize, Vec<f64>)> = None;
for round in 0..=rounds {
if budget.stop().is_some() || budget.settings.node_limit.is_some_and(|n| stats.nodes >= n) {
stats.stop = "root_budget";
break;
}
let before = (stats.nodes, budget.pivots);
stats.nodes += 1;
let t = Instant::now();
let status = lp
.solve(&mut budget, round == 0)
.unwrap_or(Status::NumericalFailure);
if let Some(trace) = &mut pilot {
trace.stage("presolve_root_lp", (stats.nodes, budget.pivots), before, t);
}
if status != Status::Optimal {
stats.stop = "lp_status";
stats.stages.push(format!("{{\"round\":{round},\"status\":\"{}\",\"bound\":null,\"objective\":null,\"seconds\":{}}}",status.as_str(),t.elapsed().as_secs_f64()));
break;
}
let x = lp.point();
let duals = lp.duals(model);
if !accepted(model, model.variables(), &x, &duals, options, settings) {
stats.stop = "lp_check";
break;
}
let objective = check::evaluate(model, &x, &options.tolerances)?.objective;
last = Some((model.m(), x.clone()));
let bound = safe_dual_bound_with_bounds(model, model.variables(), &duals.row_duals)?.bound;
if let Some(b) = bound {
stats.bound = Some(stats.bound.map_or(b, |old| {
if model.sense() == Sense::Minimize {
old.max(b)
} else {
old.min(b)
}
}));
}
if round == 0 {
stats.initial_objective = Some(objective);
}
stats.stages.push(format!("{{\"round\":{round},\"status\":\"optimal\",\"bound\":{},\"objective\":{objective},\"seconds\":{},\"elapsed_seconds\":{},\"rows\":{},\"pivots\":{}}}",number(bound),t.elapsed().as_secs_f64(),began.elapsed().as_secs_f64(),model.m(),budget.pivots));
if let Some(old) = previous {
let improvement = (objective - old).abs();
if improvement < settings.root_cut_progress * (1.0f64 + f64::abs(old)) {
stagnant += 1;
} else {
stagnant = 0;
}
}
previous = Some(objective);
if round == 0 && settings.root_heuristics && budget.stop().is_none() {
stats.primal = primal::run(
model,
&mut lp,
options,
&mut budget,
&mut stats.nodes,
&mut stats.seed,
pilot.as_deref_mut(),
)?;
if budget.stop().is_some() || settings.node_limit.is_some_and(|n| stats.nodes >= n) {
break;
}
let before = (stats.nodes, budget.pivots);
let started = pilot.as_ref().map(|_| Instant::now());
stats.nodes += 1;
let status = lp
.solve(&mut budget, false)
.unwrap_or(Status::NumericalFailure);
if let Some((trace, started)) = pilot.as_deref_mut().zip(started) {
trace.stage(
"root_lp_restore",
(stats.nodes, budget.pivots),
before,
started,
);
}
if status != Status::Optimal
|| !accepted(
model,
model.variables(),
&lp.point(),
&lp.duals(model),
options,
settings,
)
{
break;
}
}
if policy.is_some() {
if !root_policy::Policy::can_improve(model, &x, bound, start, options) {
stats.stop = "integral_or_closed";
break;
}
if stats.exact_work >= POLICY_EXACT_WORK
|| model.nnz() > initial_nnz.saturating_mul(12).saturating_add(128)
{
stats.stop = "separation_work";
break;
}
}
if stagnant >= 3 {
stats.stop = "low_progress";
break;
}
if round == rounds {
break;
}
let max_terms = if round >= 1 && families == [true, true] {
50.max(model.n() / 4)
} else {
usize::MAX
};
let work = if policy.is_some() {
settings
.cut_exact_work
.min(POLICY_EXACT_WORK.saturating_sub(stats.exact_work))
} else {
settings.cut_exact_work
};
let generic = round >= delay && round - delay < generic_rounds;
if generic
&& cut_upper.zip(bound).is_some_and(|(upper, bound)| {
(upper - oriented(model, bound)).max(0.) <= settings.root_cut_gap
})
&& families.iter().any(|&x| x)
{
families.fill(false);
stats.small_gap_skips += 1;
}
let (mut selected, cuts) = if generic {
certified_cuts::separate(model, &mut lp, &x, &budget, families, max_terms, work)
} else {
(Vec::new(), certified_cuts::Stats::default())
};
if let Some(separator) = choice_mass
.as_mut()
.filter(|_| round < settings.choice_mass_rounds)
{
let additional = separator.separate(&x, &budget);
stats.choice_mass += additional.len() as u64;
selected.extend(additional);
}
if generic {
for (active, family) in families.iter_mut().zip(["gmi", "mir"]) {
*active &= selected.iter().any(|c| c.family == family);
}
}
stats.exact_work += cuts.work;
stats.gmi_work += cuts.gmi_work;
stats.candidates += cuts.candidates;
stats.rejected += cuts.rejected;
stats.vubs = stats.vubs.max(cuts.vubs);
let old_rows = model.m();
stats.gmi += selected.iter().filter(|c| c.family == "gmi").count() as u64;
stats.mir += selected.iter().filter(|c| c.family == "mir").count() as u64;
certified_cuts::append(model, &selected)?;
if settings.root_separation && (round < generic_rounds || choice_mass.is_none()) {
let c = cuts::separate(model, &x, settings.cover_lifting, cancel)?;
stats.covers += c.added as u64;
stats.lifted += c.lifted as u64;
}
if model.m() == old_rows {
if round < delay {
continue;
}
stats.stop = "no_selected_cut";
break;
}
match lp.extend_rows(model, old_rows) {
Ok(extended) => lp = extended,
Err(_) if policy.is_some() => {
stats.stop = "basis_extension";
break;
}
Err(e) => return Err(e),
}
stats.basis_reuses += 1;
}
if let Some((rows, x)) = last {
if rows == model.m() && settings.mixed_root_rounds > 0 && budget.stop().is_none() {
if let Some(seed) = stats.seed.as_ref() {
if let Some(upper) = certified_start(original, seed, &budget) {
for _ in 0..settings.mixed_root_rounds.min(6) {
if budget.stop().is_some()
|| settings.node_limit.is_some_and(|n| stats.nodes >= n)
{
break;
}
let duals = lp.duals(model);
let Some(bounds) = root_fix::narrow(
model,
seed,
upper,
&duals,
&budget,
&mut stats.mixed_root,
)?
else {
break;
};
if seed
.iter()
.enumerate()
.any(|(j, &v)| v < bounds.lower[j] || v > bounds.upper[j])
{
break;
}
let mut data = model.data().clone();
data.variables = bounds;
let next = Model::new(data)?;
lp.set_bounds(&next.variables().lower, &next.variables().upper)?;
*model = next;
stats.mixed_root.applied += 1;
stats.nodes += 1;
let started = Instant::now();
if lp.solve(&mut budget, false)? != Status::Optimal {
break;
}
let duals = lp.duals(model);
let bound = safe_dual_bound_with_bounds(
model,
model.variables(),
&duals.row_duals,
)?
.bound;
if let Some(b) = bound {
let clipped = oriented(model, oriented(model, b).min(upper));
stats.bound = Some(stats.bound.map_or(clipped, |old| {
oriented(model, oriented(model, old).max(oriented(model, clipped)))
}));
}
stats.stages.push(format!(
"{{\"stage\":\"mixed_root_fix\",\"bound\":{},\"elapsed_seconds\":{},\"seconds\":{},\"pivots\":{}}}",
number(bound), began.elapsed().as_secs_f64(),
started.elapsed().as_secs_f64(), budget.pivots
));
}
}
}
}
let probe_seed = stats.seed.as_ref().filter(|_| {
rows == model.m() && settings.root_probe_limit > 0 && budget.stop().is_none()
});
if let Some(seed) = probe_seed {
if let Some(upper) = certified_start(original, seed, &budget) {
if let Some(bounds) = root_fix::probe(
model,
&mut lp,
seed,
upper,
&mut stats.nodes,
&mut budget,
&mut stats.root_probe,
)? {
let mut data = model.data().clone();
data.variables = bounds;
*model = Model::new(data)?;
stats.mixed_root.applied += 1;
}
}
}
if rows == model.m() && rows > cuts_from && choice_mass.is_none() {
stats.pruned = prune_slack(model, cuts_from, &x)?;
}
if settings.root_heuristics && budget.stop().is_none() {
rens(model, &x, options, &mut budget, began, &mut stats, pilot)?;
}
if settings.grouped_heuristics {
stats.grouped = grouped::improve(
model,
&x,
options,
&mut budget,
began,
&mut stats.nodes,
&mut stats.seed,
)?;
}
}
stats.pivots = budget.pivots;
Ok(stats)
}
fn certified_start(model: &Model, seed: &[f64], budget: &Budget<'_>) -> Option<f64> {
incumbent::upper(model, seed).or_else(|| {
budget
.settings
.rational_certification
.then(|| {
witness::upper(model, seed, budget, witness::ATTEMPT_WORK)
.0
.map(|w| w.upper)
})
.flatten()
})
}
fn rens(
model: &Model,
x: &[f64],
options: &Options,
budget: &mut Budget<'_>,
began: Instant,
stats: &mut Stats,
mut pilot: Option<&mut local_mip_bench::Trace<'_>>,
) -> Result<()> {
let settings = budget.settings;
let started = pilot.as_ref().map(|_| Instant::now());
let before = (stats.nodes, budget.pivots);
let mut data = model.data().clone();
let (mut open, mut fixed) = (0, 0);
for (j, &v) in x.iter().enumerate() {
if !model.kinds()[j].is_integral() {
continue;
}
let (lo, hi) = (
data.variables.lower[j].ceil(),
data.variables.upper[j].floor(),
);
if (v - v.round()).abs() <= 1e-6 {
fixed += 1;
let r = v.round().clamp(lo, hi);
data.variables.lower[j] = r;
data.variables.upper[j] = r;
} else {
data.variables.lower[j] = lo.max(v.floor());
data.variables.upper[j] = hi.min(v.ceil());
open += 1;
}
}
let nodes = 50 * settings.heuristic_lp_calls as u64;
let nodes = settings
.node_limit
.map_or(nodes, |n| n.saturating_sub(stats.nodes).min(nodes));
if open == 0 || nodes == 0 || fixed < open {
return Ok(());
}
let mut s = packing::child_settings(settings, began);
s.node_limit = Some(nodes);
s.iteration_limit = settings
.iteration_limit
.map(|p| p.saturating_sub(budget.pivots));
s.mip_trace_limit = 0;
s.branch_trace_limit = 0;
let Ok(sub) = Model::new(data) else {
return Ok(());
};
let Ok(r) = NativeSolver::new(s).solve(&sub, options, None, budget.cancel) else {
return Ok(());
};
stats.nodes += r.nodes;
stats.rens_nodes += r.nodes;
budget.pivots += r.iterations;
if let Some(c) = r.candidate {
if primal::candidate(
model,
c,
options,
&mut stats.seed,
pilot
.as_deref_mut()
.map(|p| (p, "rens", (stats.nodes, budget.pivots))),
)? {
stats.rens_found += 1;
}
}
if let Some((trace, started)) = pilot.zip(started) {
trace.stage("rens", (stats.nodes, budget.pivots), before, started);
}
Ok(())
}
fn prune_slack(model: &mut Model, from: usize, x: &[f64]) -> Result<u64> {
let a = model.matrix();
let rows = model.rows();
let slack = |i: usize| {
let activity: f64 = (a.pattern.indptr[i]..a.pattern.indptr[i + 1])
.map(|k| a.values[k] * x[a.pattern.indices[k]])
.sum();
let margin = |b: f64| 1e-6 * (1. + b.abs());
(!rows.lower[i].is_finite() || activity > rows.lower[i] + margin(rows.lower[i]))
&& (!rows.upper[i].is_finite() || activity < rows.upper[i] - margin(rows.upper[i]))
};
let keep: Vec<bool> = (0..model.m()).map(|i| i < from || !slack(i)).collect();
let removed = keep.iter().filter(|k| !**k).count() as u64;
if removed == 0 {
return Ok(0);
}
let mut data = model.data().clone();
let (mut indptr, mut indices, mut values) = (vec![0], Vec::new(), Vec::new());
let (mut lower, mut upper) = (Vec::new(), Vec::new());
for i in (0..model.m()).filter(|&i| keep[i]) {
let range = a.pattern.indptr[i]..a.pattern.indptr[i + 1];
indices.extend_from_slice(&a.pattern.indices[range.clone()]);
values.extend_from_slice(&a.values[range]);
indptr.push(values.len());
lower.push(rows.lower[i]);
upper.push(rows.upper[i]);
}
data.matrix.pattern.rows = lower.len();
data.matrix.pattern.indptr = indptr;
data.matrix.pattern.indices = indices;
data.matrix.values = values;
data.rows.lower = lower;
data.rows.upper = upper;
*model = Model::new(data)?;
Ok(removed)
}