use crate::error::{Result, ensure, ensure_finite};
use crate::{Model, Sense};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SafeBoundStatus {
Finite,
UnboundedRow,
UnboundedVariable,
ArithmeticOverflow,
UnsupportedArithmetic,
}
impl SafeBoundStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::Finite => "finite",
Self::UnboundedRow => "unbounded_row",
Self::UnboundedVariable => "unbounded_variable",
Self::ArithmeticOverflow => "arithmetic_overflow",
Self::UnsupportedArithmetic => "unsupported_arithmetic",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SafeDualBound {
pub bound: Option<f64>,
pub status: SafeBoundStatus,
pub index: Option<usize>,
}
pub fn safe_dual_bound(model: &Model, row_duals: &[f64]) -> Result<SafeDualBound> {
safe_dual_bound_with_bounds(model, model.variables(), row_duals)
}
pub fn safe_dual_bound_with_bounds(
model: &Model,
bounds: &crate::Bounds,
row_duals: &[f64],
) -> Result<SafeDualBound> {
bounds.validate(model.n(), "replacement variable bounds")?;
ensure(row_duals.len() == model.m(), || {
format!(
"row duals: expected {} entries, got {}",
model.m(),
row_duals.len()
)
})?;
ensure_finite(row_duals, "row duals")?;
if !gradual_underflow() {
return Ok(unavailable(SafeBoundStatus::UnsupportedArithmetic, None));
}
Ok(match compute(model, bounds, row_duals) {
Ok(bound) => SafeDualBound {
bound: Some(bound),
status: SafeBoundStatus::Finite,
index: None,
},
Err((status, index)) => unavailable(status, index),
})
}
pub struct PreparedDualBound {
sense: Sense,
residual: Vec<Interval>,
constant: std::result::Result<f64, Failure>,
leaves: usize,
tree: Vec<std::result::Result<f64, Failure>>,
}
impl PreparedDualBound {
pub fn new(model: &Model, bounds: &crate::Bounds, row_duals: &[f64]) -> Result<Self> {
bounds.validate(model.n(), "replacement variable bounds")?;
ensure(row_duals.len() == model.m(), || {
format!(
"row duals: expected {} entries, got {}",
model.m(),
row_duals.len()
)
})?;
ensure_finite(row_duals, "row duals")?;
let prepared = if gradual_underflow() {
prepare(model, row_duals)
} else {
Err((SafeBoundStatus::UnsupportedArithmetic, None))
};
let (constant, residual) = match prepared {
Ok((constant, residual)) => (Ok(constant), residual),
Err(failure) => (Err(failure), vec![Interval::point(0.); model.n()]),
};
let leaves = model
.n()
.max(1)
.checked_next_power_of_two()
.ok_or_else(|| crate::Error::InvalidInput("too many bound contributions".into()))?;
let slots = leaves
.checked_mul(2)
.ok_or_else(|| crate::Error::InvalidInput("too many bound contributions".into()))?;
let mut tree = vec![Ok(0.); slots];
if constant.is_ok() {
for j in 0..model.n() {
tree[leaves + j] = variable_term(j, residual[j], bounds.lower[j], bounds.upper[j]);
}
for at in (1..leaves).rev() {
tree[at] = combine(tree[2 * at], tree[2 * at + 1]);
}
}
Ok(Self {
sense: model.sense(),
residual,
constant,
leaves,
tree,
})
}
pub fn set_bound(&mut self, j: usize, lower: f64, upper: f64) -> Result<()> {
ensure(j < self.residual.len(), || {
format!("bound variable {j} out of range")
})?;
ensure(
!lower.is_nan()
&& !upper.is_nan()
&& lower != f64::INFINITY
&& upper != f64::NEG_INFINITY
&& lower <= upper,
|| format!("replacement variable bounds: entry {j} has lower={lower}, upper={upper}"),
)?;
if !gradual_underflow() {
self.constant = Err((SafeBoundStatus::UnsupportedArithmetic, None));
}
if self.constant.is_ok() {
let mut at = self.leaves + j;
self.tree[at] = variable_term(j, self.residual[j], lower, upper);
while at > 1 {
at /= 2;
self.tree[at] = combine(self.tree[2 * at], self.tree[2 * at + 1]);
}
}
Ok(())
}
pub fn bound(&self) -> SafeDualBound {
if !gradual_underflow() {
return unavailable(SafeBoundStatus::UnsupportedArithmetic, None);
}
match combine(self.constant, self.tree[1]) {
Ok(total) => SafeDualBound {
bound: Some(if self.sense == Sense::Minimize {
total
} else {
-total
}),
status: SafeBoundStatus::Finite,
index: None,
},
Err((status, index)) => unavailable(status, index),
}
}
}
fn combine(
a: std::result::Result<f64, Failure>,
b: std::result::Result<f64, Failure>,
) -> std::result::Result<f64, Failure> {
Ok(addition(a?, b?).ok_or(OVERFLOW)?.lo)
}
fn unavailable(status: SafeBoundStatus, index: Option<usize>) -> SafeDualBound {
SafeDualBound {
bound: None,
status,
index,
}
}
type Failure = (SafeBoundStatus, Option<usize>);
const OVERFLOW: Failure = (SafeBoundStatus::ArithmeticOverflow, None);
fn prepare(model: &Model, y: &[f64]) -> std::result::Result<(f64, Vec<Interval>), Failure> {
let orient = |v: f64| match model.sense() {
Sense::Minimize => v,
Sense::Maximize => -v,
};
let mut residual: Vec<_> = model
.objective()
.iter()
.map(|&c| Interval::point(orient(c)))
.collect();
let mut total = orient(model.objective_offset());
let matrix = model.matrix();
for (i, &original) in y.iter().enumerate() {
let v = orient(original);
if v == 0.0 {
continue; }
let selected = if v > 0.0 {
model.rows().lower[i]
} else {
model.rows().upper[i]
};
if !selected.is_finite() {
return Err((SafeBoundStatus::UnboundedRow, Some(i)));
}
let row_term = product(v, selected).ok_or(OVERFLOW)?.lo;
total = addition(total, row_term).ok_or(OVERFLOW)?.lo;
for k in matrix.pattern.indptr[i]..matrix.pattern.indptr[i + 1] {
let j = matrix.pattern.indices[k];
let a = matrix.values[k];
let p = product(a, v).ok_or(OVERFLOW)?;
residual[j] = residual[j].subtract(p).ok_or(OVERFLOW)?;
}
}
Ok((total, residual))
}
fn variable_term(j: usize, r: Interval, l: f64, u: f64) -> std::result::Result<f64, Failure> {
if (l == f64::NEG_INFINITY && r.hi > 0.0) || (u == f64::INFINITY && r.lo < 0.0) {
return Err((SafeBoundStatus::UnboundedVariable, Some(j)));
}
let mut term = f64::INFINITY;
for x in [l, u].into_iter().filter(|x| x.is_finite()) {
for coefficient in [r.lo, r.hi] {
term = term.min(product(coefficient, x).ok_or(OVERFLOW)?.lo);
}
}
if term == f64::INFINITY {
debug_assert!(r.lo == 0.0 && r.hi == 0.0);
term = 0.0;
}
Ok(term)
}
fn compute(model: &Model, bounds: &crate::Bounds, y: &[f64]) -> std::result::Result<f64, Failure> {
let (mut total, residual) = prepare(model, y)?;
for (j, r) in residual.into_iter().enumerate() {
let term = variable_term(j, r, bounds.lower[j], bounds.upper[j])?;
total = addition(total, term).ok_or(OVERFLOW)?.lo;
}
Ok(if model.sense() == Sense::Minimize {
total
} else {
-total
})
}
#[derive(Clone, Copy, Debug)]
struct Interval {
lo: f64,
hi: f64,
}
impl Interval {
fn point(v: f64) -> Self {
Self { lo: v, hi: v }
}
fn subtract(self, other: Self) -> Option<Self> {
Some(Self {
lo: addition(self.lo, -other.hi)?.lo,
hi: addition(self.hi, -other.lo)?.hi,
})
}
}
fn addition(a: f64, b: f64) -> Option<Interval> {
if a == 0.0 {
Some(Interval::point(b))
} else if b == 0.0 {
Some(Interval::point(a))
} else if a == -b {
Some(Interval::point(0.0))
} else {
enclose(a + b)
}
}
fn product(a: f64, b: f64) -> Option<Interval> {
if a == 0.0 || b == 0.0 {
Some(Interval::point(0.0))
} else if a == 1.0 {
Some(Interval::point(b))
} else if b == 1.0 {
Some(Interval::point(a))
} else if a == -1.0 {
Some(Interval::point(-b))
} else if b == -1.0 {
Some(Interval::point(-a))
} else {
enclose(a * b)
}
}
fn enclose(v: f64) -> Option<Interval> {
if !v.is_finite() {
return None;
}
let (lo, hi) = (next_down(v), -next_down(-v));
(lo.is_finite() && hi.is_finite()).then_some(Interval { lo, hi })
}
fn next_down(v: f64) -> f64 {
if v == 0.0 {
-f64::from_bits(1)
} else if v > 0.0 {
f64::from_bits(v.to_bits() - 1)
} else {
f64::from_bits(v.to_bits() + 1)
}
}
fn gradual_underflow() -> bool {
use std::hint::black_box as bb;
let normal_to_subnormal = bb(f64::MIN_POSITIVE) * bb(0.5);
let tiny = bb(f64::from_bits(1));
normal_to_subnormal.to_bits() == (1_u64 << 51)
&& (tiny + tiny).to_bits() == 2
&& (tiny * bb(2.0)).to_bits() == 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn neighbours_cover_zero_subnormal_and_extremes() {
assert_eq!(next_down(0.0).to_bits(), (-f64::from_bits(1)).to_bits());
assert_eq!(next_down(-0.0), -f64::from_bits(1));
assert_eq!(next_down(f64::from_bits(1)), 0.0);
assert_eq!(next_down(-f64::from_bits(1)), -f64::from_bits(2));
assert_eq!(next_down(1.0).to_bits(), 1.0_f64.to_bits() - 1);
assert_eq!(next_down(-1.0).to_bits(), (-1.0_f64).to_bits() + 1);
assert_eq!(next_down(-f64::MAX), f64::NEG_INFINITY);
assert!(gradual_underflow());
}
#[test]
fn exact_identities_and_rounded_underflow() {
let tiny = f64::from_bits(1);
assert_eq!(addition(1.0, -1.0).unwrap().lo, 0.0);
assert_eq!(product(tiny, -1.0).unwrap().lo, -tiny);
let p = product(tiny, 0.5).unwrap();
assert_eq!((p.lo, p.hi), (-tiny, tiny));
assert!(product(f64::MAX, 2.0).is_none());
assert!(addition(f64::MAX, f64::MAX).is_none());
assert!(enclose(f64::MAX).is_none());
}
}