Skip to main content

lib_jsl_optimization/
assignment.rs

1//! The linear sum assignment problem (SciPy's `linear_sum_assignment`): match rows to columns of
2//! a cost matrix, one-to-one, to minimise (or maximise) the total cost, by the shortest
3//! augmenting path algorithm of Jonker and Volgenant as described by Crouse (2016).
4//!
5//! See the book entry [Assignment, trust regions and global optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/assignment-trust-global.html#the-assignment-problem).
6
7use lib_jsl_core::ErrorsJSL;
8use ndarray::Array2;
9
10/// One shortest augmenting path from row `i` in the reduced costs `c[i][j] − u[i] − v[j]`
11/// (Dijkstra's method over the columns): returns the free column it ends at and the path length.
12#[allow(clippy::too_many_arguments)]
13fn augmenting_path(nc: usize, cost: &[f64], u: &[f64], v: &[f64], path: &mut [usize], row4col: &[Option<usize>], shortest: &mut [f64], mut i: usize, sr: &mut [bool], sc: &mut [bool], remaining: &mut [usize]) -> Option<(usize, f64)> {
14    let mut min_val = 0.0;
15    let mut num_remaining = nc;
16    // Reverse order, so that a constant cost matrix gives the identity (SciPy issue 11602).
17    for (it, r) in remaining.iter_mut().enumerate() {
18        *r = nc - it - 1;
19    }
20    sr.fill(false);
21    sc.fill(false);
22    shortest.fill(f64::INFINITY);
23    loop {
24        let mut index = usize::MAX;
25        let mut lowest = f64::INFINITY;
26        sr[i] = true;
27        for (it, &j) in remaining.iter().enumerate().take(num_remaining) {
28            let r = min_val + cost[i * nc + j] - u[i] - v[j];
29            if r < shortest[j] {
30                path[j] = i;
31                shortest[j] = r;
32            }
33            // Among equal minima prefer a free column, which ends the search.
34            if shortest[j] < lowest || (shortest[j] == lowest && row4col[j].is_none()) {
35                lowest = shortest[j];
36                index = it;
37            }
38        }
39        min_val = lowest;
40        if min_val == f64::INFINITY {
41            return None;
42        }
43        let j = remaining[index];
44        sc[j] = true;
45        num_remaining -= 1;
46        remaining[index] = remaining[num_remaining];
47        match row4col[j] {
48            None => return Some((j, min_val)),
49            Some(r) => i = r,
50        }
51    }
52}
53
54// ANCHOR: lsap
55/// The optimal assignment: pairs `(rowᵢ, colᵢ)`, as many as the smaller dimension, sorted by
56/// row, minimising `Σ cost[rowᵢ][colᵢ]` (maximising with `maximize`). Each row in turn is joined
57/// to the current matching by a shortest augmenting path in the reduced costs, and the dual
58/// variables `u`, `v` are updated so that all reduced costs stay non-negative (the Hungarian
59/// method's invariant). A tall matrix is transposed first. `O(n³)`. Infinite costs forbid a
60/// pair; an error is returned if no complete assignment avoids them, or for NaN or `−∞`.
61pub fn linear_sum_assignment(cost: &Array2<f64>, maximize: bool) -> Result<(Vec<usize>, Vec<usize>), ErrorsJSL> {
62    let (mut nr, mut nc) = cost.dim();
63    if nr == 0 || nc == 0 {
64        return Ok((Vec::new(), Vec::new()));
65    }
66    let transpose = nc < nr;
67    let mut c: Vec<f64> = if transpose { cost.t().iter().copied().collect() } else { cost.iter().copied().collect() };
68    if transpose {
69        std::mem::swap(&mut nr, &mut nc);
70    }
71    if maximize {
72        c.iter_mut().for_each(|x| *x = -*x);
73    }
74    if c.iter().any(|x| x.is_nan() || *x == f64::NEG_INFINITY) {
75        return Err(ErrorsJSL::InvalidInputRange("the cost matrix contains NaN or −∞"));
76    }
77    let (mut u, mut v) = (vec![0.0; nr], vec![0.0; nc]);
78    let mut shortest = vec![0.0; nc];
79    let mut path = vec![0usize; nc];
80    let mut col4row: Vec<Option<usize>> = vec![None; nr];
81    let mut row4col: Vec<Option<usize>> = vec![None; nc];
82    let (mut sr, mut sc) = (vec![false; nr], vec![false; nc]);
83    let mut remaining = vec![0usize; nc];
84    for cur in 0..nr {
85        let (sink, min_val) = augmenting_path(nc, &c, &u, &v, &mut path, &row4col, &mut shortest, cur, &mut sr, &mut sc, &mut remaining).ok_or(ErrorsJSL::InvalidInputRange("the cost matrix is infeasible"))?;
86        u[cur] += min_val;
87        for i in 0..nr {
88            if sr[i] && i != cur {
89                u[i] += min_val - shortest[col4row[i].expect("matched")];
90            }
91        }
92        for j in 0..nc {
93            if sc[j] {
94                v[j] -= min_val - shortest[j];
95            }
96        }
97        // Augment along the path back to the current row.
98        let mut j = sink;
99        loop {
100            let i = path[j];
101            row4col[j] = Some(i);
102            let previous = col4row[i].replace(j);
103            if i == cur {
104                break;
105            }
106            j = previous.expect("rows on the path are matched");
107        }
108    }
109    let pairs: Vec<(usize, usize)> = if transpose {
110        let mut p: Vec<(usize, usize)> = col4row.iter().enumerate().map(|(r, cl)| (cl.expect("matched"), r)).collect();
111        p.sort_unstable();
112        p
113    } else {
114        col4row.iter().enumerate().map(|(r, cl)| (r, cl.expect("matched"))).collect()
115    };
116    Ok(pairs.into_iter().unzip())
117}
118// ANCHOR_END: lsap
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn small_examples() {
126        // SciPy's documentation example.
127        let cost = Array2::from_shape_vec((3, 3), vec![4.0, 1.0, 3.0, 2.0, 0.0, 5.0, 3.0, 2.0, 2.0]).unwrap();
128        let (r, c) = linear_sum_assignment(&cost, false).unwrap();
129        assert_eq!(r, vec![0, 1, 2]);
130        assert_eq!(c, vec![1, 0, 2]);
131        let total: f64 = r.iter().zip(&c).map(|(&i, &j)| cost[(i, j)]).sum();
132        assert_eq!(total, 5.0);
133        let (_, c) = linear_sum_assignment(&Array2::from_elem((4, 4), 1.0), false).unwrap();
134        assert_eq!(c, vec![0, 1, 2, 3]);
135    }
136
137    #[test]
138    fn brute_force_agrees_on_rectangles() {
139        let mut s: u64 = 7;
140        let mut next = || {
141            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
142            ((s >> 33) % 100) as f64
143        };
144        for (nr, nc) in [(4, 4), (3, 5), (5, 3)] {
145            let cost = Array2::from_shape_fn((nr, nc), |_| next());
146            for maximize in [false, true] {
147                let (r, c) = linear_sum_assignment(&cost, maximize).unwrap();
148                let got: f64 = r.iter().zip(&c).map(|(&i, &j)| cost[(i, j)]).sum();
149                // Brute force over injective maps from the smaller side.
150                let (small, big) = (nr.min(nc), nr.max(nc));
151                let mut best = if maximize { f64::NEG_INFINITY } else { f64::INFINITY };
152                let mut perm: Vec<usize> = (0..big).collect();
153                fn permute(k: usize, small: usize, perm: &mut Vec<usize>, f: &mut dyn FnMut(&[usize])) {
154                    if k == small {
155                        f(&perm[..small]);
156                        return;
157                    }
158                    for i in k..perm.len() {
159                        perm.swap(k, i);
160                        permute(k + 1, small, perm, f);
161                        perm.swap(k, i);
162                    }
163                }
164                permute(0, small, &mut perm, &mut |p| {
165                    let total: f64 = (0..small).map(|a| if nr <= nc { cost[(a, p[a])] } else { cost[(p[a], a)] }).sum();
166                    best = if maximize { best.max(total) } else { best.min(total) };
167                });
168                assert_eq!(got, best, "{nr} × {nc}, maximize {maximize}");
169            }
170        }
171    }
172}