Skip to main content

lib_jsl_optimization/
milp.rs

1//! Mixed-integer linear programming by branch and bound (SciPy's `optimize.milp`, which uses
2//! HiGHS): a [`LinearProgram`] in which some variables must take integer values.
3//!
4//! See the book entry [Levenberg-Marquardt for systems, mixed-integer programming and truncated Newton](https://jwkunz.github.io/lib_jsl/book/optimization/milp-tnc.html#branch-and-bound).
5
6use crate::linear_programming::{LinearProgram, LpStatus};
7use lib_jsl_core::ErrorsJSL;
8use std::cmp::Ordering;
9use std::collections::BinaryHeap;
10
11/// Options for [`milp`] (SciPy's `options`).
12#[derive(Clone, Copy, Debug)]
13pub struct MilpOptions {
14    /// Stop when the gap between the best integer solution and the best bound, relative to the
15    /// former, is at most this (HiGHS's default 10⁻⁴).
16    pub mip_rel_gap: f64,
17    /// The largest number of branch-and-bound nodes (LP relaxations) to solve.
18    pub node_limit: usize,
19    /// How far from an integer a value may be and still count as one (HiGHS's 10⁻⁶).
20    pub integrality_tolerance: f64,
21}
22
23impl Default for MilpOptions {
24    fn default() -> Self {
25        MilpOptions { mip_rel_gap: 1e-4, node_limit: 100_000, integrality_tolerance: 1e-6 }
26    }
27}
28
29/// The outcome of [`milp`].
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum MilpStatus {
33    /// An optimal solution within `mip_rel_gap`.
34    Optimal,
35    /// No integer point satisfies the constraints.
36    Infeasible,
37    /// The LP relaxation is unbounded.
38    Unbounded,
39    /// The node limit was reached; `x` is the best integer solution found, if any.
40    NodeLimit,
41}
42
43/// The result of [`milp`].
44#[derive(Clone, Debug)]
45#[non_exhaustive]
46pub struct MilpResult {
47    pub status: MilpStatus,
48    /// The best integer-feasible point (integer variables rounded exactly); empty if none.
49    pub x: Vec<f64>,
50    /// Its objective value (`∞` if none).
51    pub objective: f64,
52    /// The best bound on the optimum, from the open nodes' relaxations.
53    pub dual_bound: f64,
54    /// `(objective − dual_bound)/|objective|`.
55    pub mip_gap: f64,
56    /// LP relaxations solved.
57    pub nodes: usize,
58}
59
60struct Node {
61    bound: f64,
62    depth: usize,
63    bounds: Vec<(f64, f64)>,
64}
65
66impl PartialEq for Node {
67    fn eq(&self, o: &Self) -> bool {
68        self.cmp(o) == Ordering::Equal
69    }
70}
71impl Eq for Node {}
72impl PartialOrd for Node {
73    fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
74        Some(self.cmp(o))
75    }
76}
77impl Ord for Node {
78    /// Best bound first (a min-heap on the bound), then deeper nodes, which find integer points
79    /// sooner.
80    fn cmp(&self, o: &Self) -> Ordering {
81        o.bound.total_cmp(&self.bound).then(self.depth.cmp(&o.depth))
82    }
83}
84
85// ANCHOR: milp
86/// Minimises `cᵀx` over a [`LinearProgram`]'s constraints with `x[i]` integer where
87/// `integrality[i]` (SciPy's `milp`). Branch and bound: each node solves the LP relaxation with
88/// tightened bounds; a relaxation no better than the best integer point found (the incumbent)
89/// is pruned; an integral one becomes the incumbent; otherwise the most fractional variable
90/// `xⱼ = v` splits the node into `xⱼ ≤ ⌊v⌋` and `xⱼ ≥ ⌈v⌉`. Nodes are explored best bound first,
91/// and the search stops when the incumbent is within `mip_rel_gap` of the best open bound.
92pub fn milp(problem: &LinearProgram, integrality: &[bool], options: MilpOptions) -> Result<MilpResult, ErrorsJSL> {
93    let n = problem.n_vars();
94    if integrality.len() != n {
95        return Err(ErrorsJSL::IncompatibleArraySizes((integrality.len(), n)));
96    }
97    let tol = options.integrality_tolerance;
98    // Integer variables take integer bounds.
99    let root_bounds: Vec<(f64, f64)> = problem
100        .bounds()
101        .iter()
102        .zip(integrality)
103        .map(|(&(lo, hi), &int)| if int { ((lo - tol).ceil(), (hi + tol).floor()) } else { (lo, hi) })
104        .collect();
105    let mut result = MilpResult { status: MilpStatus::Infeasible, x: Vec::new(), objective: f64::INFINITY, dual_bound: f64::INFINITY, mip_gap: f64::INFINITY, nodes: 0 };
106    if root_bounds.iter().any(|&(lo, hi)| lo > hi) {
107        return Ok(result);
108    }
109    let solve = |bounds: &[(f64, f64)]| {
110        let mut lp = problem.clone();
111        for (i, &(lo, hi)) in bounds.iter().enumerate() {
112            lp = lp.with_bounds(i, lo, hi);
113        }
114        lp.solve()
115    };
116    let mut heap = BinaryHeap::new();
117    heap.push(Node { bound: f64::NEG_INFINITY, depth: 0, bounds: root_bounds });
118    let gap_closed = |incumbent: f64, bound: f64| incumbent - bound <= options.mip_rel_gap * incumbent.abs().max(1e-300) || incumbent - bound <= 1e-9 * (1.0 + incumbent.abs());
119    while let Some(node) = heap.pop() {
120        if result.objective.is_finite() && gap_closed(result.objective, node.bound) {
121            // Every open node's bound is at least this one's.
122            heap.push(node);
123            break;
124        }
125        if result.nodes >= options.node_limit {
126            heap.push(node);
127            result.status = MilpStatus::NodeLimit;
128            break;
129        }
130        let lp = solve(&node.bounds)?;
131        result.nodes += 1;
132        match lp.status {
133            LpStatus::Infeasible => continue,
134            LpStatus::Unbounded => {
135                result.status = MilpStatus::Unbounded;
136                return Ok(result);
137            }
138            LpStatus::Optimal => {}
139        }
140        if result.objective.is_finite() && lp.objective >= result.objective - 1e-12 * (1.0 + result.objective.abs()) {
141            continue;
142        }
143        // The most fractional integer variable.
144        let branch = (0..n)
145            .filter(|&i| integrality[i])
146            .map(|i| (i, (lp.x[i] - lp.x[i].round()).abs()))
147            .filter(|&(_, f)| f > tol)
148            .max_by(|a, b| a.1.total_cmp(&b.1).then(b.0.cmp(&a.0)));
149        match branch {
150            None => {
151                let x: Vec<f64> = (0..n).map(|i| if integrality[i] { lp.x[i].round() } else { lp.x[i] }).collect();
152                let obj: f64 = problem.objective().iter().zip(&x).map(|(c, v)| c * v).sum();
153                result.x = x;
154                result.objective = obj;
155                result.status = MilpStatus::Optimal;
156            }
157            Some((j, _)) => {
158                let v = lp.x[j];
159                let mut down = node.bounds.clone();
160                down[j].1 = v.floor();
161                let mut up = node.bounds;
162                up[j].0 = v.ceil();
163                for b in [down, up] {
164                    if b[j].0 <= b[j].1 {
165                        heap.push(Node { bound: lp.objective, depth: node.depth + 1, bounds: b });
166                    }
167                }
168            }
169        }
170    }
171    let open_bound = heap.iter().map(|nd| nd.bound).fold(f64::INFINITY, f64::min);
172    result.dual_bound = open_bound.min(result.objective);
173    if result.status == MilpStatus::NodeLimit && result.x.is_empty() {
174        result.objective = f64::INFINITY;
175    }
176    if result.objective.is_finite() {
177        result.mip_gap = if result.objective == result.dual_bound { 0.0 } else { (result.objective - result.dual_bound) / result.objective.abs().max(1e-300) };
178    }
179    Ok(result)
180}
181// ANCHOR_END: milp
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn knapsack_and_scipy_example() {
189        // SciPy's documentation example: max x₂ s.t. −x₁ + x₂ ≤ 1, 3x₁ + 2x₂ ≤ 12, 2x₁ + 3x₂ ≤ 12,
190        // integers ≥ 0: optimum x = (1, 2) or (2, 2), objective −2.
191        let lp = LinearProgram::new(vec![0.0, -1.0]).with_less_equal(vec![-1.0, 1.0], 1.0).with_less_equal(vec![3.0, 2.0], 12.0).with_less_equal(vec![2.0, 3.0], 12.0);
192        let r = milp(&lp, &[true, true], MilpOptions::default()).unwrap();
193        assert_eq!(r.status, MilpStatus::Optimal);
194        assert_eq!(r.objective, -2.0);
195        // 0-1 knapsack by brute force.
196        let (v, w) = ([10.0, 13.0, 7.0, 8.0, 9.0, 4.0], [5.0, 6.0, 4.0, 4.0, 5.0, 2.0]);
197        let mut lp = LinearProgram::new(v.iter().map(|x| -x).collect()).with_less_equal(w.to_vec(), 15.0);
198        for i in 0..6 {
199            lp = lp.with_bounds(i, 0.0, 1.0);
200        }
201        let r = milp(&lp, &[true; 6], MilpOptions { mip_rel_gap: 0.0, ..Default::default() }).unwrap();
202        let best = (0u32..64)
203            .filter(|m| (0..6).filter(|i| m >> i & 1 == 1).map(|i| w[i]).sum::<f64>() <= 15.0)
204            .map(|m| (0..6).filter(|i| m >> i & 1 == 1).map(|i| v[i]).sum::<f64>())
205            .fold(0.0, f64::max);
206        assert_eq!(-r.objective, best);
207        // Infeasible: 2x = 1 with x integer.
208        let lp = LinearProgram::new(vec![1.0]).with_equal(vec![2.0], 1.0);
209        assert_eq!(milp(&lp, &[true], MilpOptions::default()).unwrap().status, MilpStatus::Infeasible);
210    }
211}