lcp_solver/lemke.rs
1use crate::tableau::{Tableau, EPS};
2
3#[derive(Debug, Clone, PartialEq)]
4pub struct Solution {
5 pub w: Vec<f64>,
6 pub z: Vec<f64>,
7}
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum LcpError {
11 /// Lemke's algorithm reached a "secondary ray": the entering variable's column had no
12 /// positive entry to pivot on, so the almost-complementary path runs off to infinity
13 /// instead of finding a solution. This is a valid outcome for some `(M, q)` (e.g. `M` not
14 /// copositive-plus) and does not necessarily mean the LCP is infeasible in general — only
15 /// that Lemke's path failed to certify a solution.
16 RayTermination,
17 /// The pivot count exceeded the safety cap without terminating. With Bland's-rule-style
18 /// tie-breaking this should not happen on well-posed circuit-sized problems; treat it as a
19 /// bug or a pathological input if it does.
20 MaxIterationsExceeded,
21 /// `M` or `q` contained a NaN or infinity — e.g. from an overflowing upstream device
22 /// parameter, or an ill-conditioned circuit. Checked explicitly up front so this returns a
23 /// clean error instead of reaching a `partial_cmp().unwrap()` panic partway through pivoting
24 /// (`NaN.partial_cmp(_)` is `None`).
25 NonFiniteInput,
26}
27
28/// Solve `w = M z + q`, `w, z >= 0`, `w . z = 0` via Lemke's algorithm.
29///
30/// `M` must be `n x n` (row-major, `M[row][col]`), `q` length `n`. Uses the all-ones covering
31/// vector `d`, the standard choice unless a problem-specific covering vector is known to do
32/// better.
33pub fn solve(m: &[Vec<f64>], q: &[f64]) -> Result<Solution, LcpError> {
34 let n = q.len();
35 assert_eq!(m.len(), n, "M must have n rows");
36 for row in m {
37 assert_eq!(row.len(), n, "M must have n columns");
38 }
39 let d = vec![1.0; n];
40 solve_with_covering_vector(m, q, &d)
41}
42
43/// Same as [`solve`] but with an explicit covering vector `d` (must be strictly positive for
44/// Lemke's algorithm's feasibility argument to hold).
45pub fn solve_with_covering_vector(
46 m: &[Vec<f64>],
47 q: &[f64],
48 d: &[f64],
49) -> Result<Solution, LcpError> {
50 let n = q.len();
51 if n == 0 {
52 return Ok(Solution {
53 w: vec![],
54 z: vec![],
55 });
56 }
57
58 if q.iter().any(|v| !v.is_finite())
59 || m.iter().flatten().any(|v| !v.is_finite())
60 || d.iter().any(|v| !v.is_finite())
61 {
62 return Err(LcpError::NonFiniteInput);
63 }
64
65 // Trivial case: q already feasible with z = 0, no pivoting (and no z0) needed at all.
66 if q.iter().all(|&qi| qi >= -EPS) {
67 return Ok(Solution {
68 w: q.iter().map(|&qi| qi.max(0.0)).collect(),
69 z: vec![0.0; n],
70 });
71 }
72
73 for &di in d {
74 assert!(di > 0.0, "covering vector must be strictly positive");
75 }
76 let mut t = Tableau::new(m, q, d);
77
78 // Drive z0 in: pivot on the row minimizing q_i / d_i, so that after this one pivot every
79 // row's RHS becomes q_i - (q_r0/d_r0) * d_i >= 0 (this is why d must be strictly positive
80 // and why the ratio, not the raw q_i, is what must be minimized in general).
81 let r0 = (0..n)
82 .min_by(|&a, &b| (q[a] / d[a]).partial_cmp(&(q[b] / d[b])).unwrap())
83 .unwrap();
84 let z0_col = t.z0_col();
85 let mut leaving = t.pivot(r0, z0_col);
86
87 let max_iters = 200 * n + 1000;
88 for _ in 0..max_iters {
89 let entering = t.complement(leaving);
90 let row = match t.ratio_test(entering) {
91 Some(r) => r,
92 None => return Err(LcpError::RayTermination),
93 };
94 let left = t.pivot(row, entering);
95 if left == z0_col {
96 return Ok(extract(&t));
97 }
98 leaving = left;
99 }
100 Err(LcpError::MaxIterationsExceeded)
101}
102
103fn extract(t: &Tableau) -> Solution {
104 let n = t.n;
105 let mut w = vec![0.0; n];
106 let mut z = vec![0.0; n];
107 let rhs = t.rhs_col();
108 for row in 0..n {
109 let var = t.basis[row];
110 let val = t.rows[row][rhs].max(0.0);
111 if var < n {
112 w[var] = val;
113 } else if var < 2 * n {
114 z[var - n] = val;
115 }
116 // var == z0_col: z0 is nonbasic at solution (0), nothing to record.
117 }
118 Solution { w, z }
119}