use crate::{
Bounds, Budget, Model, Result, Status, certified_cuts, certified_cuts::Cut, dyadic::Dy,
grouped, lp::Lp, node_dual_bound,
};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
pub(crate) struct Pair {
pub mass: usize,
pub switch: usize,
pub epochs: [usize; 2],
pub rate: f64,
dates: [Vec<(usize, f64)>; 2],
thresholds: Vec<f64>,
}
pub(crate) struct Separator {
pub pairs: Vec<Pair>,
emitted: BTreeSet<(usize, usize)>,
}
#[derive(Default)]
pub(crate) struct LocalStats {
pub rounds: u64,
pub cuts: u64,
pub bound: Option<f64>,
}
impl Separator {
pub(crate) fn new(model: &Model, budget: &Budget<'_>) -> Self {
let groups = grouped::groups_with_fixed(model);
let dates = grouped::definitions_with_aliases(model, &groups, budget);
let matrix = model.matrix();
let row = |i: usize| matrix.pattern.indptr[i]..matrix.pattern.indptr[i + 1];
let terms = |i: usize| row(i).map(|k| (matrix.pattern.indices[k], matrix.values[k]));
let mut unconditional = BTreeSet::new();
let mut branches: BTreeMap<(usize, usize, usize, usize, u64), u8> = BTreeMap::new();
for i in 0..model.m() {
if budget.stop().is_some() || branches.len() >= 2048 {
break;
}
if !matches!(row(i).len(), 3 | 4) || !model.rows().upper[i].is_finite() {
continue;
}
let upper = model.rows().upper[i];
let mut switch = None;
let mut mass = None;
let mut positive = None;
let mut negative = None;
for (j, c) in terms(i) {
if model.kinds()[j].is_integral() {
if model.variables().lower[j] >= 0. && model.variables().upper[j] <= 1. {
switch = Some((j, c));
}
} else if dates[j].is_some() {
if c > 0. {
positive = Some((j, c));
} else if c < 0. {
negative = Some((j, -c));
}
} else if c == 1. && crate::oriented(model, model.objective()[j]) < 0. {
mass = Some(j);
}
}
let (Some(m), Some((a, rate)), Some((b, other_rate))) = (mass, positive, negative)
else {
continue;
};
if rate != other_rate {
continue;
}
if row(i).len() == 3 && upper == 0. {
unconditional.insert((m, a, b, rate.to_bits()));
continue;
}
let Some((h, c)) = switch else {
continue;
};
if upper == 0. && c < 0. {
*branches.entry((m, h, a, b, rate.to_bits())).or_default() |= 1;
} else if upper == c && c > 0. {
*branches.entry((m, h, b, a, rate.to_bits())).or_default() |= 2;
}
}
let pairs = branches
.into_iter()
.filter_map(|((mass, switch, a, b, rate), flags)| {
let forward = flags & 1 != 0 || unconditional.contains(&(mass, a, b, rate));
let backward = flags & 2 != 0 || unconditional.contains(&(mass, b, a, rate));
if !forward || !backward {
return None;
}
let dates = [dates[a].as_ref()?.1.clone(), dates[b].as_ref()?.1.clone()];
if dates[0].len() + dates[1].len() > 128 {
return None;
}
let mut thresholds: Vec<_> = dates.iter().flatten().map(|&(_, t)| t).collect();
thresholds.sort_unstable_by(f64::total_cmp);
thresholds.dedup();
Some(Pair {
mass,
switch,
epochs: [a, b],
rate: f64::from_bits(rate),
dates,
thresholds,
})
})
.take(256)
.collect();
Self {
pairs,
emitted: BTreeSet::new(),
}
}
pub(crate) fn is_empty(&self) -> bool {
self.pairs.is_empty()
}
pub(crate) fn precedence(
&self,
model: &mut Model,
budget: &Budget<'_>,
) -> Result<(usize, usize)> {
let groups = grouped::groups_with_fixed(model);
let definitions = grouped::definitions_with_aliases(model, &groups, budget);
let mut by_group = vec![Vec::new(); groups.len()];
for (j, definition) in definitions.iter().enumerate() {
if let Some((g, _)) = definition {
by_group[*g].push(j);
}
}
let mut edges = vec![Vec::new(); model.n()];
for epochs in by_group.iter().filter(|epochs| epochs.len() <= 16) {
for &a in epochs {
for &b in epochs {
if a == b || budget.stop().is_some() {
continue;
}
let from = &definitions[a].as_ref().unwrap().1;
let to = &definitions[b].as_ref().unwrap().1;
let pairs = from
.iter()
.zip(to)
.filter(|&(&(j, _), _)| model.variables().upper[j] >= 1.);
if pairs.clone().all(|(&(_, x), &(_, y))| x <= y) {
let strict = pairs.clone().next().is_some()
&& pairs.clone().all(|(&(_, x), &(_, y))| x < y);
edges[a].push((b, strict));
}
}
}
}
let matrix = model.matrix();
for r in 0..model.m() {
if budget.stop().is_some() {
break;
}
let range = matrix.pattern.indptr[r]..matrix.pattern.indptr[r + 1];
let [a, b] = &matrix.pattern.indices[range.clone()] else {
continue;
};
let [positive, negative] = &matrix.values[range] else {
continue;
};
if !positive.is_finite()
|| *positive == 0.
|| *positive != -*negative
|| definitions[*a].is_none()
|| definitions[*b].is_none()
{
continue;
}
let (from, to) = if *positive > 0. { (*a, *b) } else { (*b, *a) };
if model.rows().upper[r] <= 0. {
edges[from].push((to, model.rows().upper[r] < 0.));
}
if model.rows().lower[r] >= 0. {
edges[to].push((from, model.rows().lower[r] > 0.));
}
}
let mut cuts = Vec::new();
let mut changed = 0;
let mut bounds = model.variables().clone();
for pair in &self.pairs {
if budget.stop().is_some() {
break;
}
let [a, b] = pair.epochs;
let (before, after, h, strict) = if let Some(strict) = chronological(&edges, a, b) {
(a, b, 0., strict)
} else if let Some(strict) = chronological(&edges, b, a) {
(b, a, 1., strict)
} else {
continue;
};
let mut terms = vec![(pair.mass, 1.), (before, pair.rate), (after, -pair.rate)];
terms.sort_unstable_by_key(|&(j, _)| j);
cuts.push(Cut {
terms,
rhs: 0.,
family: "choice_precedence",
});
let j = pair.switch;
if strict
&& bounds.lower[pair.mass] >= 0.
&& bounds.lower[j] <= h
&& h <= bounds.upper[j]
&& bounds.lower[j] != bounds.upper[j]
{
bounds.lower[j] = h;
bounds.upper[j] = h;
changed += 1;
}
}
if changed > 0 {
let mut data = model.data().clone();
data.variables = bounds;
*model = Model::new(data)?;
}
if !cuts.is_empty() {
certified_cuts::append(model, &cuts)?;
}
Ok((cuts.len(), changed))
}
pub(crate) fn shallow_bound(
&mut self,
model: &Model,
bounds: &Bounds,
(lp, point): (&Lp, &[f64]),
budget: &mut Budget<'_>,
) -> Result<LocalStats> {
self.emitted.clear();
let settings = crate::NativeOptions {
iteration_limit: Some(
budget
.settings
.iteration_limit
.unwrap_or(u64::MAX)
.min(budget.pivots.saturating_add(320)),
),
..budget.settings.clone()
};
let mut side = Budget {
settings: &settings,
..*budget
};
let mut stats = LocalStats::default();
let mut current = model.clone();
let mut relaxation = None::<Lp>;
let mut solution = point.to_vec();
for _ in 0..settings.choice_local_rounds {
if side.stop().is_some() {
break;
}
let mut cuts = self.separate(&solution, &side);
if cuts.is_empty() {
break;
}
let violation =
|cut: &Cut| cut.terms.iter().map(|&(j, a)| a * solution[j]).sum::<f64>() - cut.rhs;
cuts.sort_by(|a, b| violation(b).total_cmp(&violation(a)));
cuts.truncate(16);
let old_rows = current.m();
certified_cuts::append(&mut current, &cuts)?;
let Ok(mut extended) = relaxation
.as_ref()
.unwrap_or(lp)
.extend_rows(¤t, old_rows)
else {
break;
};
extended.set_bounds(&bounds.lower, &bounds.upper)?;
stats.rounds += 1;
stats.cuts += cuts.len() as u64;
let status = extended.solve(&mut side, false)?;
budget.pivots = side.pivots;
if status != Status::Optimal {
break;
}
if let Some(bound) =
node_dual_bound(¤t, bounds, &extended.duals(¤t), false)?
{
stats.bound = Some(stats.bound.map_or(bound, |b| b.max(bound)));
}
solution = extended.point();
relaxation = Some(extended);
}
Ok(stats)
}
pub(crate) fn propagate(
&self,
model: &Model,
bounds: &mut crate::Bounds,
changed: &mut Vec<usize>,
budget: &Budget<'_>,
) -> bool {
for pair in &self.pairs {
if budget.stop().is_some() {
break;
}
let mut lows = [0.; 2];
let mut highs = [0.; 2];
for (side, dates) in pair.dates.iter().enumerate() {
let forced = dates.iter().find(|&&(j, _)| bounds.lower[j] > 0.);
let (low, high) = if let Some(&(_, date)) = forced {
(date, date)
} else {
dates
.iter()
.filter(|&&(j, _)| bounds.upper[j] >= 1.)
.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &(_, d)| {
(lo.min(d), hi.max(d))
})
};
if low > high || !restrict(bounds, changed, pair.epochs[side], low, high) {
return false;
}
lows[side] = bounds.lower[pair.epochs[side]];
highs[side] = bounds.upper[pair.epochs[side]];
}
let h = pair.switch;
if model.variables().lower[pair.mass] >= 0. {
let sign = if lows[0] > highs[1] {
Some(1.)
} else if lows[1] > highs[0] {
Some(0.)
} else {
None
};
if let Some(value) = sign {
if !restrict(bounds, changed, h, value, value) {
return false;
}
}
}
let mut days = f64::NEG_INFINITY;
if bounds.lower[h] <= 0. {
days = days.max(crate::root::up(highs[1] - lows[0]));
}
if bounds.upper[h] >= 1. {
days = days.max(crate::root::up(highs[0] - lows[1]));
}
let cap = crate::root::up(pair.rate * days);
if cap.is_finite() && !restrict(bounds, changed, pair.mass, f64::NEG_INFINITY, cap) {
return false;
}
}
true
}
pub(crate) fn separate(&mut self, x: &[f64], budget: &Budget<'_>) -> Vec<Cut> {
let mut cuts = Vec::new();
for (p, pair) in self.pairs.iter().enumerate() {
if budget.stop().is_some() {
break;
}
let best = pair
.thresholds
.iter()
.enumerate()
.filter(|(i, _)| !self.emitted.contains(&(p, *i)))
.map(|(i, &t)| {
let rhs = pair
.dates
.iter()
.flatten()
.map(|&(j, date)| (date - t).abs() * x[j])
.sum::<f64>()
* pair.rate;
(i, x[pair.mass] - rhs)
})
.filter(|(_, violation)| *violation > 1e-6)
.max_by(|a, b| a.1.total_cmp(&b.1).then_with(|| b.0.cmp(&a.0)));
if let Some((i, _)) = best {
if let Some(cut) = pair.cut(pair.thresholds[i]) {
cuts.push(cut);
self.emitted.insert((p, i));
}
}
}
cuts
}
}
fn chronological(edges: &[Vec<(usize, bool)>], first: usize, last: usize) -> Option<bool> {
let mut seen = vec![[false; 2]; edges.len()];
seen[first][0] = true;
let mut queue = VecDeque::from([(first, false)]);
while let Some((j, strict)) = queue.pop_front() {
if j == last && strict {
return Some(true);
}
for &(next, stronger) in &edges[j] {
let strict = strict || stronger;
if !std::mem::replace(&mut seen[next][usize::from(strict)], true) {
queue.push_back((next, strict));
}
}
}
seen[last][0].then_some(false)
}
fn restrict(
bounds: &mut crate::Bounds,
changed: &mut Vec<usize>,
j: usize,
lo: f64,
hi: f64,
) -> bool {
let (lo, hi) = (lo.max(bounds.lower[j]), hi.min(bounds.upper[j]));
if lo > hi {
return false;
}
if lo != bounds.lower[j] || hi != bounds.upper[j] {
bounds.lower[j] = lo;
bounds.upper[j] = hi;
changed.push(j);
}
true
}
impl Pair {
fn cut(&self, threshold: f64) -> Option<Cut> {
let threshold = Dy::from_f64(threshold)?;
let rate = Dy::from_f64(self.rate)?;
let mut exact = BTreeMap::<usize, Dy>::new();
for &(j, date) in self.dates.iter().flatten() {
let diff = Dy::from_f64(date)?.sub(&threshold)?;
let distance = if diff.is_negative() { diff.neg() } else { diff };
let term = rate.mul(&distance)?;
if let Some(previous) = exact.get_mut(&j) {
*previous = previous.add(&term)?;
} else {
exact.insert(j, term);
}
}
let mut terms = Vec::with_capacity(exact.len() + 1);
for (j, coefficient) in exact {
if !coefficient.is_zero() {
terms.push((j, -coefficient.upper()?));
}
}
terms.push((self.mass, 1.));
terms.sort_unstable_by_key(|&(j, _)| j);
Some(Cut {
terms,
rhs: 0.,
family: "choice_mass",
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use lp_ip_craft::{Bounds, CancellationToken, CsrMatrix, ModelData, Sense, VariableKind};
use std::time::Instant;
#[test]
fn cut_preserves_exact_date_choices_and_requires_both_sign_branches() {
let matrix = CsrMatrix::from_dense(
7,
8,
&[
1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 0., -1.25, -4., 0., 0.,
1., 0., 0., 0., 0., 0., -1.25, -3., 0., 1., 0., 0., 0., 0., 0., 0., 0.5, -0.5, 1.,
-4., 0., 0., 0., 0., -0.5, 0.5, 1., 4., 0., 0., 0., 0., 0., 0., 0., 0.,
],
)
.unwrap();
let mut data = ModelData {
sense: Sense::Minimize,
objective: vec![0., 0., 0., 0., 0., 0., -1., 0.],
objective_offset: 0.,
matrix,
kinds: vec![
VariableKind::Binary,
VariableKind::Binary,
VariableKind::Binary,
VariableKind::Binary,
VariableKind::Continuous,
VariableKind::Continuous,
VariableKind::Continuous,
VariableKind::Binary,
],
variables: Bounds::new(vec![0.; 8], vec![1., 1., 1., 1., 5., 5., 5., 1.]),
rows: Bounds::new(
vec![
1.,
1.,
0.,
0.,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
],
vec![1., 1., 0., 0., 0., 4., 0.],
),
};
let settings = crate::NativeOptions::default();
let token = CancellationToken::default();
let budget = Budget {
start: Instant::now(),
settings: &settings,
cancel: &token,
pivots: 0,
};
let model = Model::new(data.clone()).unwrap();
let mut separator = Separator::new(&model, &budget);
assert_eq!(separator.pairs.len(), 1);
let cuts = separator.separate(&[0.5, 0.5, 0.5, 0.5, 2.625, 2.125, 3., 0.5], &budget);
assert_eq!(cuts.len(), 1);
let pair = &separator.pairs[0];
for &t in &pair.thresholds {
let cut = pair.cut(t).unwrap();
for &(i, a) in &pair.dates[0] {
for &(j, b) in &pair.dates[1] {
let mut point = [0.; 8];
point[i] = 1.;
point[j] = 1.;
point[pair.mass] = pair.rate * (a - b).abs();
assert!(cut.terms.iter().map(|&(j, c)| point[j] * c).sum::<f64>() <= cut.rhs);
}
}
}
data.rows.upper[5] = 4.000000000000001;
assert!(Separator::new(&Model::new(data).unwrap(), &budget).is_empty());
}
}