lp-ip-craft 0.34.0

Validated LP/MIP models, solver contracts and independent numerical checks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Conservative Lagrangian bounds for the exact model represented by binary64
//! inputs. Unlike residual checks, these computations enclose rounding error.
//!
//! The derivation, assumptions and limitations are in
//! [`docs/safe-dual-bounds.md`](https://github.com/dietmarwo/LP-IP-craft/blob/main/docs/safe-dual-bounds.md).
//! This module neither validates an incumbent exactly nor certifies a solver's
//! search tree. It does not change the floating-point environment.

use crate::error::{Result, ensure, ensure_finite};
use crate::{Model, Sense};

/// Outcome of an independent dual-bound calculation, not a solver status.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SafeBoundStatus {
    /// A finite conservative bound was computed.
    Finite,
    /// A nonzero multiplier selects an infinite row bound.
    UnboundedRow,
    /// The residual enclosure cannot be bounded over an infinite variable side.
    UnboundedVariable,
    /// An intermediate enclosure or outward sum was not finite.
    ArithmeticOverflow,
    /// The current arithmetic environment fails the gradual-underflow probes.
    UnsupportedArithmetic,
}

impl SafeBoundStatus {
    /// Stable lowercase name used by the Python API.
    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",
        }
    }
}

/// Result of [`safe_dual_bound`]. An unavailable bound is never an assertion
/// that the optimization problem is unbounded or infeasible.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SafeDualBound {
    /// Lower bound for minimization, upper bound for maximization, including
    /// the objective offset. Present exactly when status is `Finite`.
    pub bound: Option<f64>,
    /// Why the calculation succeeded or could not supply a finite bound.
    pub status: SafeBoundStatus,
    /// Zero-based row/variable index for `UnboundedRow`/`UnboundedVariable`;
    /// `None` for all other outcomes.
    pub index: Option<usize>,
}

/// Computes a conservative bound from arbitrary finite row multipliers in
/// the [`crate::Duals`] original-sense convention. No primal point, reduced
/// costs, solver status or feasibility tolerance is needed.
///
/// For minimization, with `r = c - A^T y`, the bound is an outward-rounded
/// lower enclosure of `c0 + sum inf(y[i] * row[i]) + sum inf(r[j] * x[j])`,
/// where each infimum uses the model's row or variable interval. Maximization
/// is handled by exact sign reversal. Integrality is relaxed, so the bound
/// is also valid for every feasible integer point of a MIP.
///
/// Validity refers to the exact real model whose coefficients are the stored
/// binary64 values. Standard IEEE binary64 arithmetic with gradual underflow
/// is required; do not build with fast-math or change that environment during
/// the call. Lightweight probes reject flush-to-zero/denormals-are-zero modes.
/// This is not an exact primal certificate or a safe pruning decision.
///
/// Bounds may be weak or unavailable. With duals from an LP solver, a column
/// with an infinite bound usually makes the result `UnboundedVariable`: its
/// exact residual must have the safe sign (be exactly zero for a free column),
/// and solver duals meet that only to the solver's tolerance, so the exact
/// Lagrangian bound of those duals is often infinite itself. Request the duals
/// from an LP whose one-sided costs are shifted by a small margin (see
/// [`docs/safe-dual-bounds.md`](https://github.com/dietmarwo/LP-IP-craft/blob/main/docs/safe-dual-bounds.md)), or give free columns finite bounds.
///
/// Runs in O(nnz + n + m) time and O(n) extra memory. Invalid multiplier
/// length/nonfinite entries return [`crate::Error::InvalidInput`]. Arithmetic
/// failure instead returns a typed result without a bound.
pub fn safe_dual_bound(model: &Model, row_duals: &[f64]) -> Result<SafeDualBound> {
    safe_dual_bound_with_bounds(model, model.variables(), row_duals)
}

/// Conservative dual bound using replacement variable bounds. The matrix,
/// objective and rows are borrowed unchanged; bounds are validated first.
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),
    })
}

/// Reusable conservative Lagrangian bound for fixed matrix, objective, rows and
/// multipliers, with independently mutable variable intervals.
///
/// Construction costs O(nnz+n+m); [`Self::set_bound`] costs O(log n), and
/// [`Self::bound`] costs O(1). Storage is O(n). Every residual interval and
/// partial sum encloses rounding error, just as in [`safe_dual_bound`]. A balanced
/// sum tree uses a different addition order, so last bits and failure precedence
/// can differ from the fresh calculation. Neither result dominates the other.
/// Infinite/overflowing variable contributions can recover after a bound update;
/// failure while preparing the immutable row terms cannot recover.
///
/// The IEEE environment must remain unchanged throughout this object's lifetime;
/// do not use fast-math. Probes reject unsupported arithmetic, without changing
/// the environment. This object owns its data; modifying the source model or
/// multipliers does not modify it. Construct a new object for new coefficients.
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 {
    /// Validate inputs and prepare outward-rounded residuals and bound terms.
    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,
        })
    }

    /// Replace one variable interval. Invalid inputs leave the object unchanged.
    /// Arithmetic failures are reported by [`Self::bound`], not as input errors.
    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(())
    }

    /// Read the current conservative bound, including its typed failure reason.
    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; // Includes free rows with zero multipliers, no 0 * inf.
        }
        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)));
    }
    // A bilinear function attains its minimum at a corner of a finite
    // rectangle. Above, all unbounded directions with negative infimum
    // have been excluded. A wholly free box is possible only for r=[0,0].
    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,
        })
    }
}

// Preserve only elementary exact identities. In every other case the two
// adjacent floats enclose the exact result, including a product rounded to 0.
// Reject nonfinite endpoints rather than claim a finite bound after overflow.
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 })
}

// f64::next_down requires Rust 1.86; the crate supports 1.85. Input is finite.
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 {
    // black_box prevents constant-folding the probes. No unsafe access to
    // thread-local hardware control words, and no environment mutation.
    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());
    }
}