Skip to main content

visloc_objects/
assignment.rs

1//! Minimum-cost assignment between tracks and detections.
2
3/// Matched `(row, column)` pairs, sorted by row, and what was left over.
4#[derive(Debug, Clone, Default, PartialEq, Eq)]
5pub struct Assignment {
6    pub matches: Vec<(usize, usize)>,
7    pub unmatched_rows: Vec<usize>,
8    pub unmatched_cols: Vec<usize>,
9}
10
11/// Minimum-cost assignment in which a row and a column may also stay
12/// unmatched, at a cost of `cost_limit / 2` each.
13///
14/// This is the formulation of `lap.lapjv(cost, extend_cost=True,
15/// cost_limit=...)` that ByteTrack uses: a pair is only made when it is
16/// cheaper than leaving both sides unmatched, so no match costs
17/// `cost_limit` or more. `costs` is row-major, `rows × cols`. Entries that are
18/// not finite are forbidden pairs. With a `cost_limit` that is not positive
19/// and finite, nothing is matched.
20pub fn assign_with_cost_limit(
21    rows: usize,
22    cols: usize,
23    costs: &[f64],
24    cost_limit: f64,
25) -> Assignment {
26    assert_eq!(costs.len(), rows * cols, "cost matrix is not rows × cols");
27    if rows == 0 || cols == 0 || !(cost_limit.is_finite() && cost_limit > 0.0) {
28        return Assignment {
29            matches: Vec::new(),
30            unmatched_rows: (0..rows).collect(),
31            unmatched_cols: (0..cols).collect(),
32        };
33    }
34    // Square matrix of size rows + cols: real pairs top left, "row i stays
35    // unmatched" top right, "column j stays unmatched" bottom left, and zeros
36    // bottom right to pair the dummies with each other. A pair that costs
37    // `cost_limit` or more is never better than both dummies, so clamping it
38    // (and forbidden pairs) to 2 * cost_limit does not change the optimum.
39    let n = rows + cols;
40    let half = 0.5 * cost_limit;
41    let mut extended = vec![0.0; n * n];
42    for r in 0..n {
43        for c in 0..n {
44            extended[r * n + c] = match (r < rows, c < cols) {
45                (true, true) => {
46                    let cost = costs[r * cols + c];
47                    if cost.is_finite() && cost < cost_limit {
48                        cost
49                    } else {
50                        2.0 * cost_limit
51                    }
52                }
53                (true, false) | (false, true) => half,
54                (false, false) => 0.0,
55            };
56        }
57    }
58    let row_to_col = hungarian(n, &extended);
59    let mut matches = Vec::new();
60    let mut col_matched = vec![false; cols];
61    let mut unmatched_rows = Vec::new();
62    for (r, &c) in row_to_col.iter().enumerate().take(rows) {
63        let cost = if c < cols {
64            costs[r * cols + c]
65        } else {
66            f64::NAN
67        };
68        if cost.is_finite() && cost < cost_limit {
69            matches.push((r, c));
70            col_matched[c] = true;
71        } else {
72            unmatched_rows.push(r);
73        }
74    }
75    Assignment {
76        matches,
77        unmatched_rows,
78        unmatched_cols: (0..cols).filter(|&c| !col_matched[c]).collect(),
79    }
80}
81
82/// Kuhn–Munkres with potentials on a square `n × n` matrix of finite costs:
83/// the column assigned to each row, minimizing the total cost. O(n³).
84fn hungarian(n: usize, costs: &[f64]) -> Vec<usize> {
85    // 1-based, column 0 is the virtual start of each augmenting path.
86    let mut u = vec![0.0; n + 1];
87    let mut v = vec![0.0; n + 1];
88    let mut row_of_col = vec![0usize; n + 1];
89    let mut way = vec![0usize; n + 1];
90    for row in 1..=n {
91        row_of_col[0] = row;
92        let mut col0 = 0;
93        let mut min_slack = vec![f64::INFINITY; n + 1];
94        let mut used = vec![false; n + 1];
95        loop {
96            used[col0] = true;
97            let row0 = row_of_col[col0];
98            let mut delta = f64::INFINITY;
99            let mut col1 = 0;
100            for col in 1..=n {
101                if used[col] {
102                    continue;
103                }
104                let slack = costs[(row0 - 1) * n + (col - 1)] - u[row0] - v[col];
105                if slack < min_slack[col] {
106                    min_slack[col] = slack;
107                    way[col] = col0;
108                }
109                if min_slack[col] < delta {
110                    delta = min_slack[col];
111                    col1 = col;
112                }
113            }
114            for col in 0..=n {
115                if used[col] {
116                    u[row_of_col[col]] += delta;
117                    v[col] -= delta;
118                } else {
119                    min_slack[col] -= delta;
120                }
121            }
122            col0 = col1;
123            if row_of_col[col0] == 0 {
124                break;
125            }
126        }
127        loop {
128            let col1 = way[col0];
129            row_of_col[col0] = row_of_col[col1];
130            col0 = col1;
131            if col0 == 0 {
132                break;
133            }
134        }
135    }
136    let mut col_of_row = vec![usize::MAX; n];
137    for col in 1..=n {
138        if row_of_col[col] != 0 {
139            col_of_row[row_of_col[col] - 1] = col - 1;
140        }
141    }
142    col_of_row
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148    use rand::rngs::SmallRng;
149    use rand::{Rng, SeedableRng};
150
151    /// Cost of an assignment under the extended formulation.
152    fn total(a: &Assignment, cols: usize, costs: &[f64], limit: f64) -> f64 {
153        a.matches
154            .iter()
155            .map(|&(r, c)| costs[r * cols + c])
156            .sum::<f64>()
157            + 0.5 * limit * (a.unmatched_rows.len() + a.unmatched_cols.len()) as f64
158    }
159
160    /// Best total over every partial matching, by enumeration.
161    fn brute_force(rows: usize, cols: usize, costs: &[f64], limit: f64) -> f64 {
162        fn go(
163            r: usize,
164            rows: usize,
165            cols: usize,
166            costs: &[f64],
167            limit: f64,
168            used: &mut Vec<bool>,
169        ) -> f64 {
170            if r == rows {
171                return 0.5 * limit * used.iter().filter(|u| !**u).count() as f64;
172            }
173            let mut best = 0.5 * limit + go(r + 1, rows, cols, costs, limit, used);
174            for c in 0..cols {
175                let cost = costs[r * cols + c];
176                if !used[c] && cost.is_finite() && cost < limit {
177                    used[c] = true;
178                    best = best.min(cost + go(r + 1, rows, cols, costs, limit, used));
179                    used[c] = false;
180                }
181            }
182            best
183        }
184        go(0, rows, cols, costs, limit, &mut vec![false; cols])
185    }
186
187    #[test]
188    fn matches_cheap_pairs_and_leaves_expensive_ones() {
189        // Row 0 fits column 1, row 1 fits nothing below the limit.
190        let costs = [0.9, 0.1, 0.95, 0.85, 0.9, 0.99];
191        let a = assign_with_cost_limit(2, 3, &costs, 0.8);
192        assert_eq!(a.matches, vec![(0, 1)]);
193        assert_eq!(a.unmatched_rows, vec![1]);
194        assert_eq!(a.unmatched_cols, vec![0, 2]);
195    }
196
197    #[test]
198    fn prefers_the_globally_cheaper_pairing() {
199        let costs = [0.1, 0.2, 0.3, 0.25];
200        let a = assign_with_cost_limit(2, 2, &costs, 1.0);
201        assert_eq!(a.matches, vec![(0, 0), (1, 1)]);
202        // Greedy would take (0, 0) at 0.1 and leave row 1 with 0.7.
203        let costs = [0.1, 0.2, 0.15, 0.7];
204        let a = assign_with_cost_limit(2, 2, &costs, 1.0);
205        assert_eq!(a.matches, vec![(0, 1), (1, 0)]);
206    }
207
208    #[test]
209    fn forbidden_pairs_empty_inputs_and_bad_limits() {
210        let costs = [f64::INFINITY, f64::NAN];
211        let a = assign_with_cost_limit(1, 2, &costs, 0.8);
212        assert!(a.matches.is_empty());
213        assert_eq!(a.unmatched_cols, vec![0, 1]);
214        let a = assign_with_cost_limit(0, 3, &[], 0.8);
215        assert_eq!(a.unmatched_cols, vec![0, 1, 2]);
216        let a = assign_with_cost_limit(1, 1, &[0.1], f64::NAN);
217        assert!(a.matches.is_empty());
218    }
219
220    #[test]
221    fn optimal_against_enumeration_on_random_matrices() {
222        let mut rng = SmallRng::seed_from_u64(7);
223        for _ in 0..400 {
224            let rows = rng.gen_range(1..=5);
225            let cols = rng.gen_range(1..=5);
226            let limit = rng.gen_range(0.2..1.2);
227            let costs: Vec<f64> = (0..rows * cols)
228                .map(|_| {
229                    if rng.gen_bool(0.1) {
230                        f64::INFINITY
231                    } else {
232                        rng.gen_range(0.0..1.0)
233                    }
234                })
235                .collect();
236            let a = assign_with_cost_limit(rows, cols, &costs, limit);
237            let got = total(&a, cols, &costs, limit);
238            let best = brute_force(rows, cols, &costs, limit);
239            assert!(
240                (got - best).abs() < 1e-9,
241                "{rows}×{cols} limit {limit}: {got} vs {best}"
242            );
243            assert_eq!(a.matches.len() + a.unmatched_rows.len(), rows);
244            assert_eq!(a.matches.len() + a.unmatched_cols.len(), cols);
245            assert!(a.matches.iter().all(|&(r, c)| costs[r * cols + c] < limit));
246        }
247    }
248}