1use lib_jsl_core::ErrorsJSL;
19
20#[derive(Debug, Clone)]
23pub struct LinearProgram {
24 objective: Vec<f64>,
25 a_ub: Vec<Vec<f64>>,
26 b_ub: Vec<f64>,
27 a_eq: Vec<Vec<f64>>,
28 b_eq: Vec<f64>,
29 bounds: Vec<(f64, f64)>,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum LpStatus {
35 Optimal,
36 Infeasible,
37 Unbounded,
38}
39
40#[derive(Debug, Clone, PartialEq)]
43pub struct LpSolution {
44 pub status: LpStatus,
45 pub x: Vec<f64>,
46 pub objective: f64,
47 pub iterations: usize,
49}
50
51impl LinearProgram {
52 pub fn new(objective: Vec<f64>) -> Self {
54 let n = objective.len();
55 LinearProgram { objective, a_ub: Vec::new(), b_ub: Vec::new(), a_eq: Vec::new(), b_eq: Vec::new(), bounds: vec![(0.0, f64::INFINITY); n] }
56 }
57
58 pub fn with_less_equal(mut self, row: Vec<f64>, rhs: f64) -> Self {
60 self.a_ub.push(row);
61 self.b_ub.push(rhs);
62 self
63 }
64
65 pub fn with_greater_equal(self, row: Vec<f64>, rhs: f64) -> Self {
67 self.with_less_equal(row.into_iter().map(|v| -v).collect(), -rhs)
68 }
69
70 pub fn with_equal(mut self, row: Vec<f64>, rhs: f64) -> Self {
72 self.a_eq.push(row);
73 self.b_eq.push(rhs);
74 self
75 }
76
77 pub fn with_bounds(mut self, index: usize, lower: f64, upper: f64) -> Self {
79 self.bounds[index] = (lower, upper);
80 self
81 }
82
83 pub fn with_free_variable(self, index: usize) -> Self {
85 self.with_bounds(index, f64::NEG_INFINITY, f64::INFINITY)
86 }
87
88 pub(crate) fn n_vars(&self) -> usize {
90 self.objective.len()
91 }
92
93 pub(crate) fn objective(&self) -> &[f64] {
95 &self.objective
96 }
97
98 pub(crate) fn bounds(&self) -> &[(f64, f64)] {
100 &self.bounds
101 }
102
103 fn validate(&self) -> Result<(), ErrorsJSL> {
104 let n = self.objective.len();
105 if n == 0 {
106 return Err(ErrorsJSL::Misconfiguration("The objective must have at least one variable."));
107 }
108 if self.a_ub.iter().chain(&self.a_eq).any(|r| r.len() != n) {
109 return Err(ErrorsJSL::IncompatibleArraySizes((n, 0)));
110 }
111 if self.objective.iter().chain(self.b_ub.iter()).chain(self.b_eq.iter()).chain(self.a_ub.iter().flatten()).chain(self.a_eq.iter().flatten()).any(|v| !v.is_finite()) {
112 return Err(ErrorsJSL::InvalidInputRange("Coefficients must be finite."));
113 }
114 if self.bounds.iter().any(|&(lo, hi)| lo.is_nan() || hi.is_nan() || lo > hi || lo == f64::INFINITY || hi == f64::NEG_INFINITY) {
115 return Err(ErrorsJSL::Misconfiguration("Bounds must satisfy lower <= upper."));
116 }
117 Ok(())
118 }
119
120 pub fn solve(&self) -> Result<LpSolution, ErrorsJSL> {
125 self.validate()?;
126 let n = self.objective.len();
127
128 struct Map {
131 offset: f64,
132 plus: usize,
133 sign: f64,
134 minus: Option<usize>,
135 }
136 let mut cols = 0usize;
137 let mut maps = Vec::with_capacity(n);
138 let mut upper_rows: Vec<(usize, f64)> = Vec::new(); for &(lo, hi) in &self.bounds {
140 if lo.is_finite() {
141 maps.push(Map { offset: lo, plus: cols, sign: 1.0, minus: None });
142 if hi.is_finite() {
143 upper_rows.push((cols, hi - lo));
144 }
145 cols += 1;
146 } else if hi.is_finite() {
147 maps.push(Map { offset: hi, plus: cols, sign: -1.0, minus: None });
148 cols += 1;
149 } else {
150 maps.push(Map { offset: 0.0, plus: cols, sign: 1.0, minus: Some(cols + 1) });
151 cols += 2;
152 }
153 }
154 let structural = cols;
155
156 let expand = |row: &[f64]| -> (Vec<f64>, f64) {
158 let mut r = vec![0.0; structural];
159 let mut shift = 0.0;
160 for (i, m) in maps.iter().enumerate() {
161 r[m.plus] += m.sign * row[i];
162 if let Some(mi) = m.minus {
163 r[mi] -= row[i];
164 }
165 shift += row[i] * m.offset;
166 }
167 (r, shift)
168 };
169 let mut rows: Vec<(Vec<f64>, f64, bool)> = Vec::new();
170 for (a, &b) in self.a_ub.iter().zip(&self.b_ub) {
171 let (r, shift) = expand(a);
172 rows.push((r, b - shift, false));
173 }
174 for (a, &b) in self.a_eq.iter().zip(&self.b_eq) {
175 let (r, shift) = expand(a);
176 rows.push((r, b - shift, true));
177 }
178 for &(c, ub) in &upper_rows {
179 let mut r = vec![0.0; structural];
180 r[c] = 1.0;
181 rows.push((r, ub, false));
182 }
183
184 let m = rows.len();
185 let slacks = rows.iter().filter(|r| !r.2).count();
186 let total = structural + slacks + m; let mut t = vec![vec![0.0; total + 1]; m];
189 let mut slack_col = structural;
190 for (i, (r, b, eq)) in rows.iter().enumerate() {
191 t[i][..structural].copy_from_slice(r);
192 if !eq {
193 t[i][slack_col] = 1.0;
194 slack_col += 1;
195 }
196 t[i][total] = *b;
197 if *b < 0.0 {
198 t[i].iter_mut().for_each(|v| *v = -*v);
199 }
200 t[i][structural + slacks + i] = 1.0; }
202 let mut basis: Vec<usize> = (0..m).map(|i| structural + slacks + i).collect();
203 let mut iterations = 0usize;
204
205 let mut cost1 = vec![0.0; total];
207 cost1[structural + slacks..].iter_mut().for_each(|c| *c = 1.0);
208 let status = simplex(&mut t, &mut basis, &cost1, total, &mut iterations, None).ok_or(PIVOT_LIMIT)?;
209 debug_assert!(status != LpStatus::Unbounded, "phase one is bounded below by zero");
210 let infeasibility: f64 = basis.iter().enumerate().filter(|(_, b)| **b >= structural + slacks).map(|(i, _)| t[i][total]).sum();
211 let scale = 1.0 + rows.iter().map(|r| r.1.abs()).fold(0.0, f64::max);
212 if infeasibility > 1e-9 * scale {
213 return Ok(LpSolution { status: LpStatus::Infeasible, x: vec![], objective: f64::NAN, iterations });
214 }
215 let mut i = 0;
217 while i < t.len() {
218 if basis[i] >= structural + slacks {
219 if let Some(j) = (0..structural + slacks).find(|&j| t[i][j].abs() > 1e-9) {
220 pivot(&mut t, &mut basis, i, j, total);
221 i += 1;
222 } else {
223 t.remove(i);
224 basis.remove(i);
225 }
226 } else {
227 i += 1;
228 }
229 }
230
231 let mut cost2 = vec![0.0; total];
233 for (i, m_) in maps.iter().enumerate() {
234 cost2[m_.plus] += m_.sign * self.objective[i];
235 if let Some(mi) = m_.minus {
236 cost2[mi] -= self.objective[i];
237 }
238 }
239 let status = simplex(&mut t, &mut basis, &cost2, total, &mut iterations, Some(structural + slacks)).ok_or(PIVOT_LIMIT)?;
240 if status == LpStatus::Unbounded {
241 return Ok(LpSolution { status, x: vec![], objective: f64::NAN, iterations });
242 }
243 let mut y = vec![0.0; total];
244 for (i, &b) in basis.iter().enumerate() {
245 y[b] = t[i][total];
246 }
247 let x: Vec<f64> = maps.iter().map(|m| m.offset + m.sign * y[m.plus] - m.minus.map_or(0.0, |mi| y[mi])).collect();
248 let objective = x.iter().zip(&self.objective).map(|(a, b)| a * b).sum();
249 Ok(LpSolution { status: LpStatus::Optimal, x, objective, iterations })
250 }
251}
252
253const PIVOT_LIMIT: ErrorsJSL = ErrorsJSL::RuntimeError("The simplex method reached its limit of 50 000 pivots.");
254
255fn pivot(t: &mut [Vec<f64>], basis: &mut [usize], row: usize, col: usize, total: usize) {
256 let p = t[row][col];
257 t[row].iter_mut().for_each(|v| *v /= p);
258 let pivot_row = t[row].clone();
259 for (i, r) in t.iter_mut().enumerate() {
260 if i != row {
261 let f = r[col];
262 if f != 0.0 {
263 for j in 0..=total {
264 r[j] -= f * pivot_row[j];
265 }
266 r[col] = 0.0;
267 }
268 }
269 }
270 basis[row] = col;
271}
272
273fn simplex(t: &mut [Vec<f64>], basis: &mut [usize], cost: &[f64], total: usize, iterations: &mut usize, limit: Option<usize>) -> Option<LpStatus> {
278 let limit = limit.unwrap_or(total);
279 let eps = 1e-9;
280 for _ in 0..50_000 {
281 let entering = (0..limit).find(|&j| {
284 let reduced = cost[j] - basis.iter().enumerate().map(|(i, &b)| cost[b] * t[i][j]).sum::<f64>();
285 reduced < -eps
286 });
287 let Some(col) = entering else { return Some(LpStatus::Optimal) };
288 let mut best: Option<(f64, usize, usize)> = None;
290 for (i, row) in t.iter().enumerate() {
291 if row[col] > eps {
292 let ratio = row[total] / row[col];
293 let better = match best {
294 None => true,
295 Some((r, _, b)) => ratio < r - 1e-12 || (ratio <= r + 1e-12 && basis[i] < b),
296 };
297 if better {
298 best = Some((ratio, i, basis[i]));
299 }
300 }
301 }
302 let Some((_, row, _)) = best else { return Some(LpStatus::Unbounded) };
303 pivot(t, basis, row, col, total);
304 *iterations += 1;
306 }
307 None
308}
309
310#[cfg(test)]
311mod tests {
312 use super::*;
313
314 fn close(a: &[f64], b: &[f64]) -> bool {
315 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-8)
316 }
317
318 #[test]
319 fn classic_production_problem() {
320 let s = LinearProgram::new(vec![-3.0, -5.0])
322 .with_less_equal(vec![1.0, 0.0], 4.0)
323 .with_less_equal(vec![0.0, 2.0], 12.0)
324 .with_less_equal(vec![3.0, 2.0], 18.0)
325 .solve()
326 .unwrap();
327 assert_eq!(s.status, LpStatus::Optimal);
328 assert!(close(&s.x, &[2.0, 6.0]) && (s.objective + 36.0).abs() < 1e-8);
329 }
330
331 #[test]
332 fn diet_problem_with_greater_equal_constraints() {
333 let s = LinearProgram::new(vec![2.0, 3.0]).with_greater_equal(vec![1.0, 1.0], 4.0).with_greater_equal(vec![1.0, 3.0], 6.0).solve().unwrap();
335 assert!(close(&s.x, &[3.0, 1.0]) && (s.objective - 9.0).abs() < 1e-8);
336 }
337
338 #[test]
339 fn equalities_bounds_and_free_variables() {
340 let s = LinearProgram::new(vec![1.0, 2.0, 1.0])
342 .with_equal(vec![1.0, 1.0, 1.0], 10.0)
343 .with_bounds(0, 0.0, 2.0)
344 .with_bounds(1, 1.0, 3.0)
345 .with_free_variable(2)
346 .solve()
347 .unwrap();
348 assert_eq!(s.status, LpStatus::Optimal);
349 assert!((s.objective - 11.0).abs() < 1e-8);
351 assert!((s.x.iter().sum::<f64>() - 10.0).abs() < 1e-8 && s.x[1] >= 1.0 - 1e-9 && s.x[0] <= 2.0 + 1e-9);
352 let s = LinearProgram::new(vec![-1.0]).with_bounds(0, f64::NEG_INFINITY, 5.0).solve().unwrap();
354 assert!(close(&s.x, &[5.0]));
355 let s = LinearProgram::new(vec![1.0]).with_bounds(0, -3.0, 10.0).solve().unwrap();
357 assert!(close(&s.x, &[-3.0]));
358 }
359
360 #[test]
361 fn infeasible_and_unbounded() {
362 let infeasible = LinearProgram::new(vec![1.0, 1.0]).with_less_equal(vec![1.0, 1.0], 1.0).with_greater_equal(vec![1.0, 1.0], 3.0).solve().unwrap();
363 assert_eq!(infeasible.status, LpStatus::Infeasible);
364 let unbounded = LinearProgram::new(vec![-1.0, 0.0]).with_less_equal(vec![-1.0, 1.0], 1.0).solve().unwrap();
365 assert_eq!(unbounded.status, LpStatus::Unbounded);
366 let conflicting_equalities = LinearProgram::new(vec![1.0]).with_equal(vec![1.0], 1.0).with_equal(vec![1.0], 2.0).solve().unwrap();
367 assert_eq!(conflicting_equalities.status, LpStatus::Infeasible);
368 }
369
370 #[test]
371 fn degenerate_and_redundant_problems_terminate() {
372 let s = LinearProgram::new(vec![-0.75, 150.0, -0.02, 6.0])
374 .with_less_equal(vec![0.25, -60.0, -0.04, 9.0], 0.0)
375 .with_less_equal(vec![0.5, -90.0, -0.02, 3.0], 0.0)
376 .with_less_equal(vec![0.0, 0.0, 1.0, 0.0], 1.0)
377 .solve()
378 .unwrap();
379 assert_eq!(s.status, LpStatus::Optimal);
380 assert!((s.objective + 0.05).abs() < 1e-8, "{s:?}");
381 let s = LinearProgram::new(vec![1.0, 1.0]).with_equal(vec![1.0, 1.0], 2.0).with_equal(vec![2.0, 2.0], 4.0).solve().unwrap();
383 assert_eq!(s.status, LpStatus::Optimal);
384 assert!((s.objective - 2.0).abs() < 1e-8);
385 }
386
387 #[test]
388 fn validation() {
389 assert!(LinearProgram::new(vec![]).solve().is_err());
390 assert!(LinearProgram::new(vec![1.0, 1.0]).with_less_equal(vec![1.0], 1.0).solve().is_err());
391 assert!(LinearProgram::new(vec![f64::NAN]).solve().is_err());
392 assert!(LinearProgram::new(vec![1.0]).with_bounds(0, 2.0, 1.0).solve().is_err());
393 }
394}