1use crate::linear_programming::{LinearProgram, LpStatus};
7use lib_jsl_core::ErrorsJSL;
8use std::cmp::Ordering;
9use std::collections::BinaryHeap;
10
11#[derive(Clone, Copy, Debug)]
13pub struct MilpOptions {
14 pub mip_rel_gap: f64,
17 pub node_limit: usize,
19 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum MilpStatus {
33 Optimal,
35 Infeasible,
37 Unbounded,
39 NodeLimit,
41}
42
43#[derive(Clone, Debug)]
45#[non_exhaustive]
46pub struct MilpResult {
47 pub status: MilpStatus,
48 pub x: Vec<f64>,
50 pub objective: f64,
52 pub dual_bound: f64,
54 pub mip_gap: f64,
56 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 fn cmp(&self, o: &Self) -> Ordering {
81 o.bound.total_cmp(&self.bound).then(self.depth.cmp(&o.depth))
82 }
83}
84
85pub 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 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 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 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#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn knapsack_and_scipy_example() {
189 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 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 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}