Skip to main content

kap/
lap.rs

1//! Rectangular linear assignment problem (LAP).
2//!
3//! Shortest augmenting path method of Jonker–Volgenant, in the rectangular form
4//! described by Crouse (2016), "On implementing 2D rectangular assignment
5//! algorithms", IEEE TAES 52(4). This is the same algorithm as
6//! `scipy.optimize.linear_sum_assignment`.
7//!
8//! For an `nr x nc` matrix, `min(nr, nc)` pairs are returned, so every row (or
9//! every column, whichever side is smaller) is matched. Costs are widened to an
10//! accumulator type ([`Cost::Acc`]): `f64` for floating-point input, `i64` for
11//! integer input. Integer arithmetic is checked: unrepresentable intermediate
12//! values or total costs return [`LapError::Overflow`]. If JV dual updates
13//! overflow, solving restarts with the shortest augmenting path method.
14//!
15//! For floating-point input, `+inf` marks a forbidden pair; `NaN` and `-inf`
16//! are rejected (`+inf` when maximizing is rejected too, `-inf` marks a
17//! forbidden pair instead).
18//!
19//! Square matrices without forbidden entries are first reduced with the
20//! Jonker–Volgenant (1987) initialisation (column reduction, reduction
21//! transfer, augmenting row reduction); the remaining rows are augmented by
22//! shortest paths. The optimum is the same either way, but ties may be broken
23//! differently from scipy; use [`LapSolver::with_jv_init`]`(false)` to
24//! reproduce scipy's assignment exactly.
25
26// The hot loops index several parallel arrays by column; ranges whose bound is
27// updated inside the loop follow LAPJV, where the bound is read once.
28#![allow(clippy::needless_range_loop, clippy::mut_range_bound)]
29
30use std::fmt;
31use std::ops::{Add, Neg, Sub};
32
33/// Accumulator type in which the solver works.
34pub trait Acc:
35    Copy
36    + PartialOrd
37    + Add<Output = Self>
38    + Sub<Output = Self>
39    + Neg<Output = Self>
40    + fmt::Debug
41    + Send
42    + Sync
43    + 'static
44{
45    const ZERO: Self;
46    /// Value larger than any finite path length; `+inf` for floats.
47    const INF: Self;
48    /// Convert a finite threshold without rounding or saturating integer casts.
49    fn from_f64_exact(x: f64) -> Option<Self>;
50    /// Whether the value is finite (always true for integer accumulators).
51    fn is_finite(self) -> bool;
52    /// Whether `self` is a permitted entry of a minimization problem
53    /// (finite or `+INF` for floats).
54    fn is_valid(self) -> bool;
55    /// Add without integer overflow; floating-point sums use ordinary rounding.
56    fn checked_add(self, rhs: Self) -> Option<Self> {
57        Some(self + rhs)
58    }
59    /// Compute a value while recording overflow for a checked scan.
60    fn overflowing_add(self, rhs: Self) -> (Self, bool) {
61        match self.checked_add(rhs) {
62            Some(value) => (value, false),
63            None => (Self::ZERO, true),
64        }
65    }
66    /// Compute a difference while recording overflow for a checked scan.
67    fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
68        match self.checked_sub(rhs) {
69            Some(value) => (value, false),
70            None => (Self::ZERO, true),
71        }
72    }
73    /// Negate without integer overflow.
74    fn checked_neg(self) -> Option<Self> {
75        Some(-self)
76    }
77    /// Subtract without integer overflow.
78    fn checked_sub(self, rhs: Self) -> Option<Self> {
79        Some(self - rhs)
80    }
81}
82
83impl Acc for f64 {
84    const ZERO: Self = 0.0;
85    const INF: Self = f64::INFINITY;
86    fn from_f64_exact(x: f64) -> Option<Self> {
87        x.is_finite().then_some(x)
88    }
89    fn is_finite(self) -> bool {
90        self.is_finite()
91    }
92    #[inline]
93    fn is_valid(self) -> bool {
94        !self.is_nan() && self != f64::NEG_INFINITY
95    }
96}
97
98impl Acc for i64 {
99    const ZERO: Self = 0;
100    const INF: Self = i64::MAX;
101    fn from_f64_exact(x: f64) -> Option<Self> {
102        // i64::MAX rounds to 2^63 as f64, so the upper bound is exclusive.
103        (x.is_finite() && x.fract() == 0.0 && x >= i64::MIN as f64 && x < -(i64::MIN as f64))
104            .then_some(x as i64)
105    }
106    fn is_finite(self) -> bool {
107        true
108    }
109    #[inline]
110    fn is_valid(self) -> bool {
111        // Keep the existing per-entry headroom; arithmetic across entries
112        // is checked separately in the solver.
113        self > i64::MIN / 4 && self < i64::MAX / 4
114    }
115    fn checked_add(self, rhs: Self) -> Option<Self> {
116        self.checked_add(rhs)
117    }
118    #[inline]
119    fn overflowing_add(self, rhs: Self) -> (Self, bool) {
120        self.overflowing_add(rhs)
121    }
122    #[inline]
123    fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
124        self.overflowing_sub(rhs)
125    }
126    fn checked_neg(self) -> Option<Self> {
127        self.checked_neg()
128    }
129    fn checked_sub(self, rhs: Self) -> Option<Self> {
130        self.checked_sub(rhs)
131    }
132}
133
134/// Element type of a cost matrix.
135pub trait Cost: Copy + fmt::Debug + Send + Sync + 'static {
136    type Acc: Acc;
137    fn widen(self) -> Self::Acc;
138}
139
140macro_rules! impl_cost {
141    ($acc:ty: $($t:ty),*) => {$(
142        impl Cost for $t {
143            type Acc = $acc;
144            #[inline]
145            fn widen(self) -> $acc {
146                self as $acc
147            }
148        }
149    )*};
150}
151impl_cost!(f64: f32, f64);
152impl_cost!(i64: i8, i16, i32, i64, u8, u16, u32);
153
154/// Optimization direction.
155#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
156pub enum Sense {
157    #[default]
158    Minimize,
159    Maximize,
160}
161
162/// Errors returned by the solver and by [`MatrixView`] constructors.
163#[derive(Clone, Debug, PartialEq, Eq)]
164pub enum LapError {
165    /// The data slice is too short or a stride points outside it.
166    BadShape,
167    /// An entry is NaN, has the wrong sign of infinity, or is too large in
168    /// magnitude for exact integer arithmetic. Holds `(row, col)`.
169    InvalidCost(usize, usize),
170    /// No complete assignment avoids the forbidden (infinite) entries.
171    Infeasible,
172    /// An integer intermediate value, dual, or total cost does not fit the accumulator.
173    Overflow,
174}
175
176impl fmt::Display for LapError {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self {
179            LapError::BadShape => write!(f, "matrix shape or strides do not fit the data"),
180            LapError::InvalidCost(i, j) => write!(f, "invalid cost entry at ({i}, {j})"),
181            LapError::Infeasible => write!(f, "cost matrix is infeasible"),
182            LapError::Overflow => write!(f, "integer overflow in LAP arithmetic"),
183        }
184    }
185}
186
187impl std::error::Error for LapError {}
188
189/// Read-only 2-D view with arbitrary (possibly negative) element strides.
190#[derive(Clone, Copy, Debug)]
191pub struct MatrixView<'a, T> {
192    data: &'a [T],
193    offset: usize,
194    rows: usize,
195    cols: usize,
196    row_stride: isize,
197    col_stride: isize,
198}
199
200impl<'a, T: Copy> MatrixView<'a, T> {
201    /// C-contiguous `rows x cols` matrix; `data` may be longer than needed.
202    pub fn from_row_major(data: &'a [T], rows: usize, cols: usize) -> Result<Self, LapError> {
203        let need = rows.checked_mul(cols).ok_or(LapError::BadShape)?;
204        if data.len() < need {
205            return Err(LapError::BadShape);
206        }
207        Ok(MatrixView {
208            data,
209            offset: 0,
210            rows,
211            cols,
212            row_stride: cols as isize,
213            col_stride: 1,
214        })
215    }
216
217    /// General strided view: element `(i, j)` is `data[offset + i*row_stride + j*col_stride]`.
218    /// Strides are in elements, not bytes.
219    pub fn from_strided(
220        data: &'a [T],
221        offset: usize,
222        rows: usize,
223        cols: usize,
224        row_stride: isize,
225        col_stride: isize,
226    ) -> Result<Self, LapError> {
227        if rows > 0 && cols > 0 {
228            let last = |n: usize, s: isize| (n as isize - 1).checked_mul(s);
229            let (ri, ci) = (
230                last(rows, row_stride).ok_or(LapError::BadShape)?,
231                last(cols, col_stride).ok_or(LapError::BadShape)?,
232            );
233            let base = offset as isize;
234            for corner in [base, base + ri, base + ci, base + ri + ci] {
235                if corner < 0 || corner as usize >= data.len() {
236                    return Err(LapError::BadShape);
237                }
238            }
239        }
240        Ok(MatrixView {
241            data,
242            offset,
243            rows,
244            cols,
245            row_stride,
246            col_stride,
247        })
248    }
249
250    #[inline]
251    pub fn rows(&self) -> usize {
252        self.rows
253    }
254
255    #[inline]
256    pub fn cols(&self) -> usize {
257        self.cols
258    }
259
260    /// Transposed view (no copy).
261    pub fn t(self) -> Self {
262        MatrixView {
263            rows: self.cols,
264            cols: self.rows,
265            row_stride: self.col_stride,
266            col_stride: self.row_stride,
267            ..self
268        }
269    }
270
271    /// Element `(i, j)`. Panics if out of range.
272    #[inline]
273    pub fn get(&self, i: usize, j: usize) -> T {
274        assert!(i < self.rows && j < self.cols, "index out of range");
275        let k = self.offset as isize + i as isize * self.row_stride + j as isize * self.col_stride;
276        self.data[k as usize]
277    }
278}
279
280/// An optimal assignment.
281#[derive(Clone, Debug, PartialEq)]
282pub struct LapSolution<A> {
283    /// Matched rows, increasing.
284    pub row_ind: Vec<usize>,
285    /// `col_ind[k]` is the column matched to `row_ind[k]`.
286    pub col_ind: Vec<usize>,
287    /// Total cost of the matched pairs, in the original sign.
288    pub cost: A,
289}
290
291/// Dual potentials of the last solve, in the original orientation and sign.
292///
293/// For a minimization, `c[i][j] - row[i] - col[j] >= 0` for all pairs, with
294/// equality on matched pairs, and potentials of unmatched rows/columns are 0
295/// (on the larger side). For a maximization the inequality is reversed.
296#[derive(Clone, Debug, PartialEq)]
297pub struct Duals<A> {
298    pub row: Vec<A>,
299    pub col: Vec<A>,
300}
301
302/// Reusable solver: keeps its buffers between calls, which matters for the many
303/// small LAPs of the k-assignment heuristics.
304#[derive(Clone, Debug, Default)]
305pub struct LapSolver<A> {
306    // Internal problem: nr <= nc, minimization, row-major.
307    cost: Vec<A>,
308    nr: usize,
309    nc: usize,
310    transposed: bool,
311    sense: Sense,
312    u: Vec<A>,
313    v: Vec<A>,
314    shortest: Vec<A>,
315    path: Vec<usize>,
316    col4row: Vec<usize>,
317    row4col: Vec<usize>,
318    sr: Vec<bool>,
319    sc: Vec<bool>,
320    remaining: Vec<usize>,
321    // Jonker-Volgenant initialisation (square, no forbidden entries).
322    jv_mode: JvMode,
323    has_forbidden: bool,
324    free: Vec<usize>,
325    matches: Vec<u32>,
326    collist: Vec<usize>,
327}
328
329const NONE: usize = usize::MAX;
330
331/// How square matrices are solved (experimental knob).
332#[doc(hidden)]
333#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
334pub enum JvMode {
335    Off,
336    Lapjv,
337    InitThenSap,
338    /// JV initialisation, then LAPJV-style augmentation with relaxation and
339    /// minimum search fused into one pass per scanned row.
340    #[default]
341    Fused,
342}
343
344/// Checked in debug builds only: guards the unchecked indexing in hot loops.
345#[inline(always)]
346fn assert_in_range(j: usize, n: usize) {
347    debug_assert!(j < n, "index {j} out of range {n}");
348}
349
350#[inline]
351fn add<A: Acc>(x: A, y: A) -> Result<A, LapError> {
352    x.checked_add(y).ok_or(LapError::Overflow)
353}
354
355#[inline]
356fn sub<A: Acc>(x: A, y: A) -> Result<A, LapError> {
357    x.checked_sub(y).ok_or(LapError::Overflow)
358}
359
360/// A scan may use wrapped temporary values, but must check before consuming
361/// its result or deriving an assignment/path from it. One check per scan keeps
362/// vectorizable reductions free of per-entry error branches.
363#[derive(Default)]
364struct Arithmetic {
365    overflow: bool,
366}
367
368impl Arithmetic {
369    #[inline]
370    fn add<A: Acc>(&mut self, x: A, y: A) -> A {
371        let (value, overflow) = x.overflowing_add(y);
372        self.overflow |= overflow;
373        value
374    }
375    #[inline]
376    fn sub<A: Acc>(&mut self, x: A, y: A) -> A {
377        let (value, overflow) = x.overflowing_sub(y);
378        self.overflow |= overflow;
379        value
380    }
381    #[inline]
382    fn check(self) -> Result<(), LapError> {
383        if self.overflow {
384            Err(LapError::Overflow)
385        } else {
386            Ok(())
387        }
388    }
389}
390
391impl<A: Acc> LapSolver<A> {
392    pub fn new() -> Self {
393        LapSolver {
394            cost: Vec::new(),
395            nr: 0,
396            nc: 0,
397            transposed: false,
398            sense: Sense::Minimize,
399            u: Vec::new(),
400            v: Vec::new(),
401            shortest: Vec::new(),
402            path: Vec::new(),
403            col4row: Vec::new(),
404            row4col: Vec::new(),
405            sr: Vec::new(),
406            sc: Vec::new(),
407            remaining: Vec::new(),
408            jv_mode: JvMode::default(),
409            has_forbidden: false,
410            free: Vec::new(),
411            matches: Vec::new(),
412            collist: Vec::new(),
413        }
414    }
415
416    /// Enable or disable the Jonker-Volgenant initialisation (column reduction,
417    /// reduction transfer, augmenting row reduction) used for square matrices
418    /// without forbidden entries. Enabled by default. When disabled, or not
419    /// applicable, every row is augmented by shortest path as in scipy, and
420    /// ties are broken exactly like scipy.
421    pub fn with_jv_init(mut self, on: bool) -> Self {
422        self.jv_mode = if on { JvMode::default() } else { JvMode::Off };
423        self
424    }
425
426    #[doc(hidden)]
427    pub fn with_jv_mode(mut self, mode: JvMode) -> Self {
428        self.jv_mode = mode;
429        self
430    }
431
432    /// Solve the LAP on `m`.
433    pub fn solve<T>(
434        &mut self,
435        m: MatrixView<'_, T>,
436        sense: Sense,
437    ) -> Result<LapSolution<A>, LapError>
438    where
439        T: Cost<Acc = A>,
440    {
441        self.load(m, sense)?;
442        let (nr, nc) = (self.nr, self.nc);
443        self.reset_assignment();
444        let jv = nr == nc && nr >= 2 && !self.has_forbidden;
445        let result = match self.jv_mode {
446            JvMode::Lapjv if jv => self.jv_init().and_then(|()| self.jv_augment()),
447            JvMode::Fused if jv => self.jv_init().and_then(|()| self.jv_augment_fused()),
448            JvMode::InitThenSap if jv => (|| {
449                self.jv_init()?;
450                self.jv_row_duals()?;
451                let free = std::mem::take(&mut self.free);
452                let r = self.sap_rows(free.iter().copied());
453                self.free = free;
454                r
455            })(),
456            _ => self.sap_rows(0..nr),
457        };
458        if matches!(result, Err(LapError::Overflow)) && jv && self.jv_mode != JvMode::Off {
459            // JV reduction transfer can drift by an arbitrary dual offset even
460            // when the optimum fits. Discard all partial duals and assignments.
461            self.reset_assignment();
462            self.sap_rows(0..nr)?;
463        } else {
464            result?;
465        }
466        self.solution(&m)
467    }
468
469    fn reset_assignment(&mut self) {
470        let (nr, nc) = (self.nr, self.nc);
471        self.u.clear();
472        self.u.resize(nr, A::ZERO);
473        self.v.clear();
474        self.v.resize(nc, A::ZERO);
475        self.col4row.clear();
476        self.col4row.resize(nr, NONE);
477        self.row4col.clear();
478        self.row4col.resize(nc, NONE);
479        self.path.clear();
480        self.path.resize(nc, NONE);
481        self.shortest.resize(nc, A::INF);
482        self.sr.resize(nr, false);
483        self.sc.resize(nc, false);
484        self.remaining.resize(nc, 0);
485    }
486
487    /// Crouse's shortest augmenting path for each of `rows` (free rows with
488    /// feasible duals `u`, `v`; matched pairs tight).
489    fn sap_rows(&mut self, rows: impl Iterator<Item = usize>) -> Result<(), LapError> {
490        let (nr, nc) = (self.nr, self.nc);
491        for cur_row in rows {
492            let (sink, min_val) = self.augmenting_path(cur_row)?.ok_or(LapError::Infeasible)?;
493            // Update duals.
494            self.u[cur_row] = add(self.u[cur_row], min_val)?;
495            for i in 0..nr {
496                if self.sr[i] && i != cur_row {
497                    let j = self.col4row[i];
498                    self.u[i] = add(self.u[i], sub(min_val, self.shortest[j])?)?;
499                }
500            }
501            for j in 0..nc {
502                if self.sc[j] {
503                    self.v[j] = sub(self.v[j], sub(min_val, self.shortest[j])?)?;
504                }
505            }
506            // Augment along the path back to cur_row.
507            let mut j = sink;
508            loop {
509                let i = self.path[j];
510                self.row4col[j] = i;
511                std::mem::swap(&mut self.col4row[i], &mut j);
512                if i == cur_row {
513                    break;
514                }
515            }
516        }
517        Ok(())
518    }
519
520    /// Row potentials after `jv_init`: tight for matched rows, the row minimum
521    /// of the reduced costs for free rows.
522    fn jv_row_duals(&mut self) -> Result<(), LapError> {
523        let n = self.nr;
524        for i in 0..n {
525            let row = &self.cost[i * n..(i + 1) * n];
526            self.u[i] = if self.col4row[i] != NONE {
527                sub(row[self.col4row[i]], self.v[self.col4row[i]])?
528            } else {
529                let mut mn = A::INF;
530                let mut arithmetic = Arithmetic::default();
531                for j in 0..n {
532                    let h = arithmetic.sub(row[j], self.v[j]);
533                    if h < mn {
534                        mn = h;
535                    }
536                }
537                arithmetic.check()?;
538                mn
539            };
540        }
541        Ok(())
542    }
543
544    /// Dual potentials of the last successful [`solve`](Self::solve).
545    pub fn duals(&self) -> Duals<A> {
546        let flip = |x: &A| match self.sense {
547            Sense::Minimize => *x,
548            Sense::Maximize => -*x,
549        };
550        let u: Vec<A> = self.u.iter().map(flip).collect();
551        let v: Vec<A> = self.v.iter().map(flip).collect();
552        if self.transposed {
553            Duals { row: v, col: u }
554        } else {
555            Duals { row: u, col: v }
556        }
557    }
558
559    fn load<T: Cost<Acc = A>>(
560        &mut self,
561        m: MatrixView<'_, T>,
562        sense: Sense,
563    ) -> Result<(), LapError> {
564        self.transposed = m.rows() > m.cols();
565        self.sense = sense;
566        let mm = if self.transposed { m.t() } else { m };
567        self.nr = mm.rows();
568        self.nc = mm.cols();
569        let (nr, nc) = (self.nr, self.nc);
570        let neg = sense == Sense::Maximize;
571        let conv = |x: T| {
572            let a = x.widen();
573            if neg {
574                a.checked_neg().unwrap_or(A::INF)
575            } else {
576                a
577            }
578        };
579        self.cost.clear();
580        self.cost.resize(nr * nc, A::ZERO);
581        let dst = &mut self.cost[..];
582        let (data, off) = (mm.data, mm.offset as isize);
583        if nr > 0 && nc > 0 && mm.col_stride == 1 {
584            // Rows contiguous in the source.
585            for (i, out) in dst.chunks_exact_mut(nc).enumerate() {
586                let start = (off + i as isize * mm.row_stride) as usize;
587                for (o, &x) in out.iter_mut().zip(&data[start..start + nc]) {
588                    *o = conv(x);
589                }
590            }
591        } else if nr > 0 && nc > 0 && mm.row_stride == 1 {
592            // Columns contiguous (e.g. a transposed C-contiguous matrix):
593            // transpose in tiles to keep both sides in cache.
594            const B: usize = 32;
595            for jb in (0..nc).step_by(B) {
596                for ib in (0..nr).step_by(B) {
597                    let ie = (ib + B).min(nr);
598                    for j in jb..(jb + B).min(nc) {
599                        let start = (off + j as isize * mm.col_stride) as usize;
600                        for (i, &x) in (ib..ie).zip(&data[start + ib..start + ie]) {
601                            dst[i * nc + j] = conv(x);
602                        }
603                    }
604                }
605            }
606        } else {
607            for i in 0..nr {
608                for j in 0..nc {
609                    dst[i * nc + j] = conv(mm.get(i, j));
610                }
611            }
612        }
613        // Branch-free validity scan; locate the first bad entry only on failure.
614        let (mut bad, mut forbidden) = (false, false);
615        for &x in dst.iter() {
616            bad |= !x.is_valid();
617            forbidden |= x >= A::INF;
618        }
619        if bad {
620            let k = dst.iter().position(|x| !x.is_valid()).unwrap();
621            let (i, j) = (k / nc, k % nc);
622            let (oi, oj) = if self.transposed { (j, i) } else { (i, j) };
623            return Err(LapError::InvalidCost(oi, oj));
624        }
625        self.has_forbidden = forbidden;
626        Ok(())
627    }
628
629    /// Jonker & Volgenant (1987) LAPJV for a square matrix with finite entries:
630    /// column reduction, reduction transfer and two augmenting row reduction
631    /// passes. Fills `col4row`, `row4col`, `v` and leaves the unassigned rows
632    /// in `free`; matched rows are tight.
633    fn jv_init(&mut self) -> Result<(), LapError> {
634        let LapSolver {
635            cost: c,
636            nr,
637            v,
638            path: pred,
639            col4row: x,
640            row4col: y,
641            free,
642            matches,
643            collist,
644            ..
645        } = self;
646        let n = *nr;
647        matches.clear();
648        matches.resize(n, 0);
649        collist.clear();
650        collist.resize(n, 0);
651
652        // Column reduction: v[j] = min_i c[i][j], first minimal row wins.
653        // Scanned row by row for cache locality; `pred` holds the argmin.
654        v.fill(A::INF);
655        for i in 0..n {
656            let row = &c[i * n..(i + 1) * n];
657            for j in 0..n {
658                if row[j] < v[j] {
659                    v[j] = row[j];
660                    pred[j] = i;
661                }
662            }
663        }
664        for j in (0..n).rev() {
665            let i = pred[j];
666            matches[i] += 1;
667            if matches[i] == 1 {
668                x[i] = j;
669                y[j] = i;
670            } else if v[j] < v[x[i]] {
671                let j1 = x[i];
672                x[i] = j;
673                y[j] = i;
674                y[j1] = NONE;
675            }
676        }
677
678        // Reduction transfer from rows assigned once.
679        free.clear();
680        for i in 0..n {
681            if matches[i] == 0 {
682                free.push(i);
683            } else if matches[i] == 1 {
684                let j1 = x[i];
685                let row = &c[i * n..(i + 1) * n];
686                let vv = &v[..n];
687                let mut mn = A::INF;
688                let mut arithmetic = Arithmetic::default();
689                for j in 0..n {
690                    let h = arithmetic.sub(row[j], vv[j]);
691                    if j != j1 && h < mn {
692                        mn = h;
693                    }
694                }
695                arithmetic.check()?;
696                v[j1] = sub(v[j1], mn)?;
697            }
698        }
699
700        // Augmenting row reduction, two passes. A row displaced after a strict
701        // price decrease is retried at once; the budget bounds that (with
702        // floats, near-ties can make it creep), and rows over budget are left
703        // to the shortest path phase, which is always correct.
704        for _ in 0..2 {
705            let prev = free.len();
706            if prev == 0 {
707                break;
708            }
709            let mut budget = 8 * n;
710            let (mut k, mut nf) = (0usize, 0usize);
711            while k < prev {
712                let i = free[k];
713                k += 1;
714                let row = &c[i * n..(i + 1) * n];
715                let vv = &v[..n];
716                let mut umin = sub(row[0], vv[0])?;
717                let mut j1 = 0;
718                let mut j2 = NONE;
719                let mut usub = A::INF;
720                let mut arithmetic = Arithmetic::default();
721                for j in 1..n {
722                    let h = arithmetic.sub(row[j], vv[j]);
723                    if h < usub {
724                        if h >= umin {
725                            usub = h;
726                            j2 = j;
727                        } else {
728                            usub = umin;
729                            umin = h;
730                            j2 = j1;
731                            j1 = j;
732                        }
733                    }
734                }
735                arithmetic.check()?;
736                let mut i0 = y[j1];
737                let strict = umin < usub;
738                if strict {
739                    v[j1] = sub(v[j1], sub(usub, umin)?)?;
740                } else if i0 != NONE {
741                    j1 = j2;
742                    i0 = y[j2];
743                }
744                x[i] = j1;
745                y[j1] = i;
746                if i0 != NONE {
747                    x[i0] = NONE;
748                    if strict && budget > 0 {
749                        budget -= 1;
750                        k -= 1;
751                        free[k] = i0;
752                    } else {
753                        free[nf] = i0;
754                        nf += 1;
755                    }
756                }
757            }
758            free.truncate(nf);
759        }
760        Ok(())
761    }
762
763    /// LAPJV's augmentation phase for the rows left in `free` by `jv_init`.
764    fn jv_augment(&mut self) -> Result<(), LapError> {
765        let LapSolver {
766            cost: c,
767            nr,
768            u,
769            v,
770            shortest: d,
771            path: pred,
772            col4row: x,
773            row4col: y,
774            free,
775            collist,
776            ..
777        } = self;
778        let n = *nr;
779        // Shortest augmenting paths (Dijkstra on reduced costs, with the
780        // row potentials implicit: u[i] = c[i][x[i]] - v[x[i]]).
781        // collist: [0, low) ready, [low, up) at the current minimum, [up, n) todo.
782        for &fr in free.iter() {
783            let row = &c[fr * n..(fr + 1) * n];
784            let mut arithmetic = Arithmetic::default();
785            for j in 0..n {
786                d[j] = arithmetic.sub(row[j], v[j]);
787                pred[j] = fr;
788                collist[j] = j;
789            }
790            arithmetic.check()?;
791            let (mut low, mut up, mut ready) = (0usize, 0usize, 0usize);
792            let mut mn = A::ZERO;
793            let endofpath = 'search: loop {
794                if up == low {
795                    ready = low;
796                    mn = d[collist[up]];
797                    up += 1;
798                    for k in up..n {
799                        let j = collist[k];
800                        assert_in_range(j, n);
801                        // SAFETY: collist is a permutation of 0..n; d has length n.
802                        let h = unsafe { *d.get_unchecked(j) };
803                        if h <= mn {
804                            if h < mn {
805                                up = low;
806                                mn = h;
807                            }
808                            collist[k] = collist[up];
809                            collist[up] = j;
810                            up += 1;
811                        }
812                    }
813                    for &j in &collist[low..up] {
814                        if y[j] == NONE {
815                            break 'search j;
816                        }
817                    }
818                }
819                let j1 = collist[low];
820                low += 1;
821                let i = y[j1];
822                let rowi = &c[i * n..(i + 1) * n];
823                let h = sub(sub(rowi[j1], v[j1])?, mn)?;
824                let (vv, dd, pp, yy) = (&v[..n], &mut d[..n], &mut pred[..n], &y[..n]);
825                for k in up..n {
826                    let j = collist[k];
827                    assert_in_range(j, n);
828                    // SAFETY: collist is a permutation of 0..n; all slices have length n.
829                    unsafe {
830                        let v2 = sub(sub(*rowi.get_unchecked(j), *vv.get_unchecked(j))?, h)?;
831                        if v2 < *dd.get_unchecked(j) {
832                            *pp.get_unchecked_mut(j) = i;
833                            if v2 == mn {
834                                if *yy.get_unchecked(j) == NONE {
835                                    break 'search j;
836                                }
837                                collist.swap(k, up);
838                                up += 1;
839                            }
840                            *dd.get_unchecked_mut(j) = v2;
841                        }
842                    }
843                }
844            };
845            for &j in &collist[..ready] {
846                v[j] = add(v[j], sub(d[j], mn)?)?;
847            }
848            let mut j = endofpath;
849            loop {
850                let i = pred[j];
851                y[j] = i;
852                std::mem::swap(&mut x[i], &mut j);
853                if i == fr {
854                    break;
855                }
856            }
857        }
858        for i in 0..n {
859            u[i] = sub(c[i * n + x[i]], v[x[i]])?;
860        }
861        Ok(())
862    }
863
864    /// Augmentation phase for the rows left in `free` by `jv_init`: LAPJV's
865    /// column list and implicit row potentials, with the search for the next
866    /// minimum fused into the relaxation pass (as in Crouse's method) whenever
867    /// the row being scanned is the last one at the current distance. A row
868    /// that still has others waiting behind it is relaxed without tracking
869    /// the minimum, as in LAPJV, since a later pass would overwrite it.
870    fn jv_augment_fused(&mut self) -> Result<(), LapError> {
871        let LapSolver {
872            cost: c,
873            nr,
874            u,
875            v,
876            shortest: d,
877            path: pred,
878            col4row: x,
879            row4col: y,
880            free,
881            collist,
882            ..
883        } = self;
884        let n = *nr;
885        let (d, pred, collist) = (&mut d[..n], &mut pred[..n], &mut collist[..n]);
886        // collist: [0, ready) scanned below the current minimum `mn`,
887        // [ready, low) scanned at it, [low, up) to scan at it, [up, n) todo.
888        for &fr in free.iter() {
889            let row = &c[fr * n..(fr + 1) * n];
890            // `lowest` is the least distance of a todo column and `idx` the
891            // position in collist of one that attains it, a free column
892            // being preferred among equals.
893            let mut lowest = A::INF;
894            let mut idx = 0;
895            {
896                let (vv, yy) = (&v[..n], &y[..n]);
897                let mut arithmetic = Arithmetic::default();
898                for j in 0..n {
899                    d[j] = arithmetic.sub(row[j], vv[j]);
900                    pred[j] = fr;
901                    collist[j] = j;
902                }
903                arithmetic.check()?;
904                for j in 0..n {
905                    let h = d[j];
906                    if h < lowest || (h == lowest && yy[j] == NONE) {
907                        lowest = h;
908                        idx = j;
909                    }
910                }
911            }
912            let (mut low, mut up) = (0usize, 0usize);
913            let (mut ready, mut mn);
914            let endofpath = 'search: loop {
915                // The scan set is empty and the last pass was a fused one, so
916                // `lowest` and `idx` are current: next distance level.
917                debug_assert!(low == up && idx >= up && idx < n);
918                ready = low;
919                mn = lowest;
920                let j0 = collist[idx];
921                if y[j0] == NONE {
922                    break 'search j0;
923                }
924                collist[idx] = collist[up];
925                collist[up] = j0;
926                up += 1;
927                while low < up {
928                    let j1 = collist[low];
929                    low += 1;
930                    let i = y[j1];
931                    let rowi = &c[i * n..(i + 1) * n];
932                    let h = sub(sub(rowi[j1], v[j1])?, mn)?;
933                    let (vv, yy) = (&v[..n], &y[..n]);
934                    if low < up {
935                        // Other rows wait at this distance: relax only.
936                        for k in up..n {
937                            // SAFETY: collist is a permutation of 0..n, so
938                            // j < n and up <= k < n; all slices have length n.
939                            unsafe {
940                                let j = *collist.get_unchecked(k);
941                                assert_in_range(j, n);
942                                let v2 =
943                                    sub(sub(*rowi.get_unchecked(j), *vv.get_unchecked(j))?, h)?;
944                                if v2 < *d.get_unchecked(j) {
945                                    *pred.get_unchecked_mut(j) = i;
946                                    *d.get_unchecked_mut(j) = v2;
947                                    if v2 <= mn {
948                                        if *yy.get_unchecked(j) == NONE {
949                                            break 'search j;
950                                        }
951                                        assert_in_range(up, n);
952                                        *collist.get_unchecked_mut(k) = *collist.get_unchecked(up);
953                                        *collist.get_unchecked_mut(up) = j;
954                                        up += 1;
955                                    }
956                                }
957                            }
958                        }
959                        continue;
960                    }
961                    // Last row at this distance: relax and find the minimum
962                    // of the todo columns in the same pass.
963                    lowest = A::INF;
964                    idx = NONE;
965                    for k in up..n {
966                        // SAFETY: as above.
967                        unsafe {
968                            let j = *collist.get_unchecked(k);
969                            assert_in_range(j, n);
970                            let v2 = sub(sub(*rowi.get_unchecked(j), *vv.get_unchecked(j))?, h)?;
971                            let mut dj = *d.get_unchecked(j);
972                            if v2 < dj {
973                                *pred.get_unchecked_mut(j) = i;
974                                *d.get_unchecked_mut(j) = v2;
975                                dj = v2;
976                            }
977                            if dj <= lowest {
978                                if dj <= mn {
979                                    // Ties with the current minimum: scan it
980                                    // at this level too.
981                                    if *yy.get_unchecked(j) == NONE {
982                                        break 'search j;
983                                    }
984                                    // The column at `up` was already visited
985                                    // and moves to k; follow it if it is the
986                                    // todo minimum.
987                                    if idx == up {
988                                        idx = k;
989                                    }
990                                    assert_in_range(up, n);
991                                    *collist.get_unchecked_mut(k) = *collist.get_unchecked(up);
992                                    *collist.get_unchecked_mut(up) = j;
993                                    up += 1;
994                                } else if dj < lowest || *yy.get_unchecked(j) == NONE {
995                                    lowest = dj;
996                                    idx = k;
997                                }
998                            }
999                        }
1000                    }
1001                }
1002            };
1003            for &j in &collist[..ready] {
1004                v[j] = add(v[j], sub(d[j], mn)?)?;
1005            }
1006            let mut j = endofpath;
1007            loop {
1008                let i = pred[j];
1009                y[j] = i;
1010                std::mem::swap(&mut x[i], &mut j);
1011                if i == fr {
1012                    break;
1013                }
1014            }
1015        }
1016        for i in 0..n {
1017            u[i] = sub(c[i * n + x[i]], v[x[i]])?;
1018        }
1019        Ok(())
1020    }
1021
1022    /// Dijkstra-like search for a shortest augmenting path from row `start`.
1023    /// Returns the sink column and the path length, or `None` if no finite path exists.
1024    fn augmenting_path(&mut self, start: usize) -> Result<Option<(usize, A)>, LapError> {
1025        let nc = self.nc;
1026        let mut i = start;
1027        let mut min_val = A::ZERO;
1028        let mut num_remaining = nc;
1029        // Reverse order, so that ties are broken towards lower column indices
1030        // the same way as scipy.
1031        for (it, r) in self.remaining.iter_mut().enumerate() {
1032            *r = nc - it - 1;
1033        }
1034        self.sr.fill(false);
1035        self.sc.fill(false);
1036        self.shortest.fill(A::INF);
1037
1038        loop {
1039            let mut index = NONE;
1040            let mut lowest = A::INF;
1041            self.sr[i] = true;
1042            let row = &self.cost[i * nc..(i + 1) * nc];
1043            let ui = self.u[i];
1044            let (v, shortest, path, row4col) = (
1045                &self.v[..nc],
1046                &mut self.shortest[..nc],
1047                &mut self.path[..nc],
1048                &self.row4col[..nc],
1049            );
1050            let mut arithmetic = Arithmetic::default();
1051            for (it, &j) in self.remaining[..num_remaining].iter().enumerate() {
1052                assert_in_range(j, nc);
1053                // SAFETY: `remaining` holds column indices < nc, and every
1054                // slice indexed here has length nc.
1055                unsafe {
1056                    let r = arithmetic.add(min_val, *row.get_unchecked(j));
1057                    let r = arithmetic.sub(r, ui);
1058                    let r = arithmetic.sub(r, *v.get_unchecked(j));
1059                    let sj = shortest.get_unchecked_mut(j);
1060                    if r < *sj {
1061                        *path.get_unchecked_mut(j) = i;
1062                        *sj = r;
1063                    }
1064                    let s = *sj;
1065                    if s < lowest || (s == lowest && *row4col.get_unchecked(j) == NONE) {
1066                        lowest = s;
1067                        index = it;
1068                    }
1069                }
1070            }
1071            arithmetic.check()?;
1072            min_val = lowest;
1073            if index == NONE || min_val >= A::INF {
1074                return Ok(None);
1075            }
1076            let j = self.remaining[index];
1077            self.sc[j] = true;
1078            num_remaining -= 1;
1079            self.remaining[index] = self.remaining[num_remaining];
1080            if self.row4col[j] == NONE {
1081                return Ok(Some((j, min_val)));
1082            }
1083            i = self.row4col[j];
1084        }
1085    }
1086
1087    fn solution<T: Cost<Acc = A>>(
1088        &self,
1089        m: &MatrixView<'_, T>,
1090    ) -> Result<LapSolution<A>, LapError> {
1091        let mut pairs: Vec<(usize, usize)> = self
1092            .col4row
1093            .iter()
1094            .enumerate()
1095            .map(|(i, &j)| if self.transposed { (j, i) } else { (i, j) })
1096            .collect();
1097        if self.transposed {
1098            pairs.sort_unstable();
1099        }
1100        let mut cost = A::ZERO;
1101        for &(i, j) in &pairs {
1102            cost = add(cost, m.get(i, j).widen())?;
1103        }
1104        let (row_ind, col_ind) = pairs.into_iter().unzip();
1105        if self.sense == Sense::Maximize {
1106            // duals() exposes these with their original sign.
1107            for &value in self.u.iter().chain(&self.v) {
1108                value.checked_neg().ok_or(LapError::Overflow)?;
1109            }
1110        }
1111        Ok(LapSolution {
1112            row_ind,
1113            col_ind,
1114            cost,
1115        })
1116    }
1117}
1118
1119/// Solve one LAP. Use [`LapSolver`] to reuse buffers across many calls.
1120pub fn linear_sum_assignment<T: Cost>(
1121    m: MatrixView<'_, T>,
1122    sense: Sense,
1123) -> Result<LapSolution<T::Acc>, LapError> {
1124    LapSolver::new().solve(m, sense)
1125}
1126
1127#[cfg(test)]
1128mod tests {
1129    use super::*;
1130    use proptest::prelude::*;
1131
1132    /// Optimal cost by enumerating injections from the smaller side.
1133    fn brute_force(c: &[i64], nr: usize, nc: usize, sense: Sense) -> i64 {
1134        fn rec(c: &[i64], nr: usize, nc: usize, i: usize, used: &mut [bool], sense: Sense) -> i64 {
1135            if i == nr {
1136                return 0;
1137            }
1138            let mut best: Option<i64> = None;
1139            for j in 0..nc {
1140                if !used[j] {
1141                    used[j] = true;
1142                    let x = c[i * nc + j] + rec(c, nr, nc, i + 1, used, sense);
1143                    used[j] = false;
1144                    best = Some(match (best, sense) {
1145                        (None, _) => x,
1146                        (Some(b), Sense::Minimize) => b.min(x),
1147                        (Some(b), Sense::Maximize) => b.max(x),
1148                    });
1149                }
1150            }
1151            best.unwrap()
1152        }
1153        if nr > nc {
1154            let t: Vec<i64> = (0..nc)
1155                .flat_map(|j| (0..nr).map(move |i| c[i * nc + j]))
1156                .collect();
1157            return brute_force(&t, nc, nr, sense);
1158        }
1159        rec(c, nr, nc, 0, &mut vec![false; nc], sense)
1160    }
1161
1162    fn check_solution(sol: &LapSolution<i64>, c: &[i64], nr: usize, nc: usize) {
1163        assert_eq!(sol.row_ind.len(), nr.min(nc));
1164        assert!(sol.row_ind.windows(2).all(|w| w[0] < w[1]));
1165        let mut seen = vec![false; nc];
1166        for &j in &sol.col_ind {
1167            assert!(!seen[j]);
1168            seen[j] = true;
1169        }
1170        let total: i64 = sol
1171            .row_ind
1172            .iter()
1173            .zip(&sol.col_ind)
1174            .map(|(&i, &j)| c[i * nc + j])
1175            .sum();
1176        assert_eq!(total, sol.cost);
1177    }
1178
1179    fn check_duals(
1180        d: &Duals<i64>,
1181        sol: &LapSolution<i64>,
1182        c: &[i64],
1183        nr: usize,
1184        nc: usize,
1185        sense: Sense,
1186    ) {
1187        let sgn = if sense == Sense::Minimize { 1 } else { -1 };
1188        for i in 0..nr {
1189            for j in 0..nc {
1190                assert!(
1191                    sgn * (c[i * nc + j] - d.row[i] - d.col[j]) >= 0,
1192                    "dual infeasible at ({i},{j})"
1193                );
1194            }
1195        }
1196        for (&i, &j) in sol.row_ind.iter().zip(&sol.col_ind) {
1197            assert_eq!(
1198                c[i * nc + j],
1199                d.row[i] + d.col[j],
1200                "slack on matched pair ({i},{j})"
1201            );
1202        }
1203        // Unmatched lines on the larger side carry zero potential.
1204        if nr <= nc {
1205            let matched: Vec<bool> = (0..nc).map(|j| sol.col_ind.contains(&j)).collect();
1206            (0..nc)
1207                .filter(|&j| !matched[j])
1208                .for_each(|j| assert_eq!(d.col[j], 0));
1209        } else {
1210            let matched: Vec<bool> = (0..nr).map(|i| sol.row_ind.contains(&i)).collect();
1211            (0..nr)
1212                .filter(|&i| !matched[i])
1213                .for_each(|i| assert_eq!(d.row[i], 0));
1214        }
1215    }
1216
1217    /// Values in `[-range, range]` from a fixed LCG (fast, reproducible).
1218    fn lcg_matrix(seed: u64, len: usize, range: i64) -> Vec<i64> {
1219        let mut s = seed;
1220        (0..len)
1221            .map(|_| {
1222                s = s
1223                    .wrapping_mul(6364136223846793005)
1224                    .wrapping_add(1442695040888963407);
1225                ((s >> 33) as i64 % (2 * range + 1)) - range
1226            })
1227            .collect()
1228    }
1229
1230    fn matrix() -> impl Strategy<Value = (usize, usize, Vec<i64>)> {
1231        (0usize..=6, 0usize..=6).prop_flat_map(|(nr, nc)| {
1232            // Narrow value range to produce many ties.
1233            (
1234                Just(nr),
1235                Just(nc),
1236                prop::collection::vec(-5i64..=5, nr * nc),
1237            )
1238        })
1239    }
1240
1241    proptest! {
1242        #![proptest_config(ProptestConfig::with_cases(2000))]
1243
1244        #[test]
1245        fn matches_brute_force((nr, nc, c) in matrix(), maximize in any::<bool>()) {
1246            let sense = if maximize { Sense::Maximize } else { Sense::Minimize };
1247            let mut solver = LapSolver::new();
1248            let sol = solver.solve(MatrixView::from_row_major(&c, nr, nc).unwrap(), sense).unwrap();
1249            check_solution(&sol, &c, nr, nc);
1250            prop_assert_eq!(sol.cost, brute_force(&c, nr, nc, sense));
1251            check_duals(&solver.duals(), &sol, &c, nr, nc, sense);
1252        }
1253
1254        #[test]
1255        fn square_jv_matches_brute_force(n in 2usize..=7, seed in any::<u64>(), range in 1i64..=1000, maximize in any::<bool>()) {
1256            let sense = if maximize { Sense::Maximize } else { Sense::Minimize };
1257            let c = lcg_matrix(seed, n * n, range);
1258            let best = brute_force(&c, n, n, sense);
1259            for mode in [JvMode::Fused, JvMode::Lapjv, JvMode::InitThenSap] {
1260                let mut solver = LapSolver::new().with_jv_mode(mode);
1261                let sol = solver.solve(MatrixView::from_row_major(&c, n, n).unwrap(), sense).unwrap();
1262                check_solution(&sol, &c, n, n);
1263                prop_assert_eq!(sol.cost, best, "{:?}", mode);
1264                check_duals(&solver.duals(), &sol, &c, n, n, sense);
1265            }
1266        }
1267
1268        #[test]
1269        fn square_jv_matches_sap(n in 2usize..=80, seed in any::<u64>(), range in 1i64..=100_000) {
1270            let c = lcg_matrix(seed, n * n, range);
1271            let m = MatrixView::from_row_major(&c, n, n).unwrap();
1272            let b = LapSolver::new().with_jv_init(false).solve(m, Sense::Minimize).unwrap();
1273            for mode in [JvMode::Fused, JvMode::Lapjv, JvMode::InitThenSap] {
1274                let mut jv = LapSolver::new().with_jv_mode(mode);
1275                let a = jv.solve(m, Sense::Minimize).unwrap();
1276                check_solution(&a, &c, n, n);
1277                prop_assert_eq!(a.cost, b.cost, "{:?}", mode);
1278                check_duals(&jv.duals(), &a, &c, n, n, Sense::Minimize);
1279            }
1280            // Floats: same optimum up to rounding.
1281            let f: Vec<f64> = c.iter().map(|&x| x as f64 / 7.0).collect();
1282            let fm = MatrixView::from_row_major(&f, n, n).unwrap();
1283            let fa = LapSolver::new().solve(fm, Sense::Minimize).unwrap();
1284            let fb = LapSolver::new().with_jv_init(false).solve(fm, Sense::Minimize).unwrap();
1285            prop_assert!((fa.cost - fb.cost).abs() <= 1e-9 * (1.0 + fb.cost.abs()));
1286        }
1287
1288        #[test]
1289        fn transposed_view_is_consistent((nr, nc, c) in matrix()) {
1290            let m = MatrixView::from_row_major(&c, nr, nc).unwrap();
1291            let a = linear_sum_assignment(m, Sense::Minimize).unwrap();
1292            let b = linear_sum_assignment(m.t(), Sense::Minimize).unwrap();
1293            prop_assert_eq!(a.cost, b.cost);
1294        }
1295
1296        #[test]
1297        fn float_matches_int((nr, nc, c) in matrix()) {
1298            let f: Vec<f64> = c.iter().map(|&x| x as f64 * 0.5).collect();
1299            let a = linear_sum_assignment(MatrixView::from_row_major(&c, nr, nc).unwrap(), Sense::Minimize).unwrap();
1300            let b = linear_sum_assignment(MatrixView::from_row_major(&f, nr, nc).unwrap(), Sense::Minimize).unwrap();
1301            prop_assert_eq!(a.cost as f64 * 0.5, b.cost);
1302        }
1303
1304        #[test]
1305        fn wide_random_values((nr, nc) in (1usize..=6, 1usize..=6), seed in any::<u64>()) {
1306            // Distinct-ish large values exercise the dual arithmetic.
1307            let mut s = seed;
1308            let c: Vec<i64> = (0..nr * nc).map(|_| {
1309                s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1310                ((s >> 33) as i64 % 2_000_001) - 1_000_000
1311            }).collect();
1312            let sol = linear_sum_assignment(MatrixView::from_row_major(&c, nr, nc).unwrap(), Sense::Minimize).unwrap();
1313            prop_assert_eq!(sol.cost, brute_force(&c, nr, nc, Sense::Minimize));
1314        }
1315    }
1316
1317    #[test]
1318    fn scipy_example() {
1319        let c = [4i64, 1, 3, 2, 0, 5, 3, 2, 2];
1320        let sol = linear_sum_assignment(
1321            MatrixView::from_row_major(&c, 3, 3).unwrap(),
1322            Sense::Minimize,
1323        )
1324        .unwrap();
1325        assert_eq!(sol.row_ind, vec![0, 1, 2]);
1326        assert_eq!(sol.col_ind, vec![1, 0, 2]);
1327        assert_eq!(sol.cost, 5);
1328    }
1329
1330    #[test]
1331    fn empty() {
1332        let c: [f64; 0] = [];
1333        for (nr, nc) in [(0, 0), (0, 3), (3, 0)] {
1334            let sol = linear_sum_assignment(
1335                MatrixView::from_row_major(&c, nr, nc).unwrap(),
1336                Sense::Minimize,
1337            )
1338            .unwrap();
1339            assert!(sol.row_ind.is_empty() && sol.col_ind.is_empty());
1340            assert_eq!(sol.cost, 0.0);
1341        }
1342    }
1343
1344    #[test]
1345    fn forbidden_entries() {
1346        let inf = f64::INFINITY;
1347        let c = [inf, 1.0, 2.0, inf];
1348        let sol = linear_sum_assignment(
1349            MatrixView::from_row_major(&c, 2, 2).unwrap(),
1350            Sense::Minimize,
1351        )
1352        .unwrap();
1353        assert_eq!(sol.col_ind, vec![1, 0]);
1354        assert_eq!(sol.cost, 3.0);
1355
1356        let c = [inf, 1.0, inf, 2.0];
1357        let r = linear_sum_assignment(
1358            MatrixView::from_row_major(&c, 2, 2).unwrap(),
1359            Sense::Minimize,
1360        );
1361        assert_eq!(r, Err(LapError::Infeasible));
1362
1363        let ninf = f64::NEG_INFINITY;
1364        let c = [ninf, 1.0, 2.0, ninf];
1365        let sol = linear_sum_assignment(
1366            MatrixView::from_row_major(&c, 2, 2).unwrap(),
1367            Sense::Maximize,
1368        )
1369        .unwrap();
1370        assert_eq!(sol.cost, 3.0);
1371    }
1372
1373    #[test]
1374    fn invalid_entries() {
1375        let c = [1.0, f64::NAN, 0.0, 1.0, 2.0, 3.0];
1376        let m = MatrixView::from_row_major(&c, 3, 2).unwrap();
1377        assert_eq!(
1378            linear_sum_assignment(m, Sense::Minimize),
1379            Err(LapError::InvalidCost(0, 1))
1380        );
1381        let c = [f64::NEG_INFINITY, 0.0];
1382        let m = MatrixView::from_row_major(&c, 1, 2).unwrap();
1383        assert_eq!(
1384            linear_sum_assignment(m, Sense::Minimize),
1385            Err(LapError::InvalidCost(0, 0))
1386        );
1387        let c = [i64::MAX, 0];
1388        let m = MatrixView::from_row_major(&c, 1, 2).unwrap();
1389        assert_eq!(
1390            linear_sum_assignment(m, Sense::Minimize),
1391            Err(LapError::InvalidCost(0, 0))
1392        );
1393    }
1394
1395    #[test]
1396    fn strided_views() {
1397        // 3x4 matrix stored column-major inside a larger buffer, read reversed.
1398        let rm = [7i64, 3, 9, 1, 4, 8, 2, 6, 5, 0, 7, 3];
1399        let (nr, nc) = (3, 4);
1400        let mut buf = vec![99i64; 2 + nr * nc];
1401        for i in 0..nr {
1402            for j in 0..nc {
1403                buf[2 + j * nr + i] = rm[i * nc + j];
1404            }
1405        }
1406        let cm = MatrixView::from_strided(&buf, 2, nr, nc, 1, nr as isize).unwrap();
1407        let a = linear_sum_assignment(cm, Sense::Minimize).unwrap();
1408        let b = linear_sum_assignment(
1409            MatrixView::from_row_major(&rm, nr, nc).unwrap(),
1410            Sense::Minimize,
1411        )
1412        .unwrap();
1413        assert_eq!(a, b);
1414        // Rows reversed via a negative stride.
1415        let rev = MatrixView::from_strided(&rm, 2 * nc, nr, nc, -(nc as isize), 1).unwrap();
1416        assert_eq!(rev.get(0, 0), 5);
1417        assert_eq!(
1418            linear_sum_assignment(rev, Sense::Minimize).unwrap().cost,
1419            b.cost
1420        );
1421        assert_eq!(
1422            MatrixView::from_strided(&rm, 0, nr, nc, -(nc as isize), 1).unwrap_err(),
1423            LapError::BadShape
1424        );
1425        assert_eq!(
1426            MatrixView::from_row_major(&rm, 4, 4).unwrap_err(),
1427            LapError::BadShape
1428        );
1429    }
1430
1431    #[test]
1432    fn solver_reuse_across_shapes() {
1433        let mut s = LapSolver::new();
1434        let a = [1i64, 2, 3, 4, 5, 6];
1435        let b = [5i64, 1, 1, 5];
1436        assert_eq!(
1437            s.solve(
1438                MatrixView::from_row_major(&a, 2, 3).unwrap(),
1439                Sense::Minimize
1440            )
1441            .unwrap()
1442            .cost,
1443            6
1444        );
1445        assert_eq!(
1446            s.solve(
1447                MatrixView::from_row_major(&a, 3, 2).unwrap(),
1448                Sense::Maximize
1449            )
1450            .unwrap()
1451            .cost,
1452            9
1453        );
1454        assert_eq!(
1455            s.solve(
1456                MatrixView::from_row_major(&b, 2, 2).unwrap(),
1457                Sense::Minimize
1458            )
1459            .unwrap()
1460            .cost,
1461            2
1462        );
1463    }
1464}
1465
1466#[cfg(test)]
1467#[path = "lap_boundary_tests.rs"]
1468mod boundary_tests;