Skip to main content

kap/
lower_bound.rs

1//! Axial Lagrangian bounds, averaged over triples for four or more parts.
2//!
3//! Only equal part sizes are supported: restricting a solution with unequal
4//! sizes need not give a maximum-cardinality matching on each pair.
5
6use crate::{
7    Acc, Algo, Cost, KPartite, KapError, LapError, LapSolver, MatrixView, Options, Sense,
8    k_assignment,
9};
10
11/// Settings for [`lower_bound`], with `A` the cost accumulator (`i64` or `f64`).
12#[derive(Clone, Copy, Debug)]
13pub struct LowerBoundOptions<A = f64> {
14    /// Optimization direction; maximization returns an upper bound.
15    pub sense: Sense,
16    /// Maximum subgradient updates per triple (default 300).
17    /// Zero still evaluates the zero and pairwise-dual multiplier seeds.
18    pub max_iter: usize,
19    /// Optional upper bound on the *whole* optimum, in the original sign.
20    /// This is a numerical upper bound in either sense, including maximization.
21    /// It only clamps the final result; minimization can also exit when the
22    /// pairwise lower bound reaches it. Never used as a triple's Polyak target.
23    /// The caller is responsible for its validity.
24    pub upper: Option<A>,
25}
26
27impl<A> Default for LowerBoundOptions<A> {
28    fn default() -> Self {
29        Self {
30            sense: Sense::Minimize,
31            max_iter: 300,
32            upper: None,
33        }
34    }
35}
36
37fn overflow() -> KapError {
38    KapError::Unsupported("lower_bound arithmetic exceeds accumulator headroom")
39}
40
41/// Arithmetic for the crate's two accumulator types.
42///
43/// This bound supplements [`Acc`] without changing the LAP API. Integer
44/// evaluations and division never pass through floating point; only the
45/// heuristic multiplier *updates* use `f64`.
46#[doc(hidden)]
47pub trait LowerBoundAcc: Acc + Cost<Acc = Self> {
48    fn lb_add(self, rhs: Self) -> Result<Self, KapError>;
49    fn lb_sub(self, rhs: Self) -> Result<Self, KapError>;
50    fn lb_neg(self) -> Result<Self, KapError>;
51    fn lb_ceil_div(self, divisor: usize) -> Self;
52    fn lb_float(self) -> f64;
53    fn lb_finite(self) -> bool;
54    fn lb_lap_safe(self, n: usize, factor: usize) -> bool;
55    fn lb_update(self, delta: f64) -> Option<Self>;
56}
57
58impl LowerBoundAcc for i64 {
59    fn lb_add(self, rhs: Self) -> Result<Self, KapError> {
60        self.checked_add(rhs).ok_or_else(overflow)
61    }
62    fn lb_sub(self, rhs: Self) -> Result<Self, KapError> {
63        self.checked_sub(rhs).ok_or_else(overflow)
64    }
65    fn lb_neg(self) -> Result<Self, KapError> {
66        self.checked_neg().ok_or_else(overflow)
67    }
68    fn lb_ceil_div(self, divisor: usize) -> Self {
69        let d = divisor as i64;
70        self / d + i64::from(self % d > 0)
71    }
72    fn lb_float(self) -> f64 {
73        self as f64
74    }
75    fn lb_finite(self) -> bool {
76        true
77    }
78    fn lb_lap_safe(self, n: usize, factor: usize) -> bool {
79        // LAP and the internal Am + 1DV heuristic use unchecked accumulator
80        // arithmetic. Reserve space for path lengths, potentials and merges.
81        let limit = i64::MAX as u128 / (n.max(1) as u128 * factor as u128);
82        self.unsigned_abs() as u128 <= limit
83    }
84    fn lb_update(self, delta: f64) -> Option<Self> {
85        let d = delta.round();
86        if d.is_finite() && d >= i64::MIN as f64 && d < i64::MAX as f64 {
87            self.checked_add(d as i64)
88        } else {
89            None
90        }
91    }
92}
93
94impl LowerBoundAcc for f64 {
95    fn lb_add(self, rhs: Self) -> Result<Self, KapError> {
96        let value = self + rhs;
97        if value.is_nan() || (self.is_finite() && rhs.is_finite() && !value.is_finite()) {
98            Err(overflow())
99        } else {
100            Ok(value)
101        }
102    }
103    fn lb_sub(self, rhs: Self) -> Result<Self, KapError> {
104        self.lb_add(-rhs)
105    }
106    fn lb_neg(self) -> Result<Self, KapError> {
107        Ok(-self)
108    }
109    fn lb_ceil_div(self, divisor: usize) -> Self {
110        self / divisor as f64
111    }
112    fn lb_float(self) -> f64 {
113        self
114    }
115    fn lb_finite(self) -> bool {
116        self.is_finite()
117    }
118    fn lb_lap_safe(self, n: usize, factor: usize) -> bool {
119        self == Self::INFINITY || self.abs() <= f64::MAX / (n.max(1) as f64 * factor as f64)
120    }
121    fn lb_update(self, delta: f64) -> Option<Self> {
122        let value = self + delta;
123        value.is_finite().then_some(value)
124    }
125}
126
127/// Bound the optimum of a condensed k-partite problem (same order as
128/// [`k_assignment`]), using O(n²) scratch space per active triple.
129///
130/// For two parts this is the exact LAP optimum. For three parts it returns the
131/// best evaluated axial Lagrangian bound, with integral multipliers for integer
132/// costs. For larger k it averages all triple bounds and rounds integer results
133/// upward, *before* restoring the sign for maximization (giving a floor).
134/// Integer costs give a rigorous bound. Floating-point bounds can exceed the
135/// true minimum (or fall below the true maximum) by rounding error on the order
136/// of machine epsilon times the sum of the cost magnitudes involved. This error
137/// can be large when costs of opposite sign nearly cancel.
138///
139/// Each triple starts with the pairwise LAP sum and evaluates both `u = 0` and
140/// a seed from the column duals of its second and third matrices. At `u = 0`,
141/// the third part may be reused freely: that bound alone can be weaker than
142/// the pairwise sum. The best bound is monotone in `max_iter` (decreasing for
143/// maximization). Am + 1DV provides a deterministic, triple-local Polyak target;
144/// validity never depends on that target being optimal. If forbidden entries
145/// prevent the heuristic from finding a feasible target, the seeds still give
146/// valid bounds and subgradient updates are skipped.
147///
148/// # Errors
149/// Follows [`KPartite::new`] for invalid matrix counts/shapes: zero matrices
150/// (including an unrepresentable one-part problem) return [`KapError::BadCount`].
151/// Equal zero-sized parts return zero. Unequal sizes are unsupported. Invalid
152/// costs follow LAP's infinity/sign rules. Excessive magnitudes or sums return
153/// an error rather than overflowing. A multiplier step that exhausts arithmetic
154/// headroom stops that triple and retains its best previously evaluated bound.
155pub fn lower_bound<T: Cost>(
156    mats: &[MatrixView<'_, T>],
157    opts: &LowerBoundOptions<T::Acc>,
158) -> Result<T::Acc, KapError>
159where
160    T::Acc: LowerBoundAcc,
161{
162    let problem = KPartite::new(mats)?;
163    let sizes = problem.sizes();
164    let (k, n) = (sizes.len(), sizes[0]);
165    if sizes.iter().any(|&size| size != n) {
166        return Err(KapError::Unsupported(
167            "lower_bound requires equal part sizes",
168        ));
169    }
170    drop(problem);
171    if opts.upper.is_some_and(|u| !u.lb_finite()) {
172        return Err(KapError::Unsupported("lower_bound upper must be finite"));
173    }
174    let maximize = opts.sense == Sense::Maximize;
175    // Widen and normalize once. Checked negation protects i64::MIN.
176    let data: Vec<Vec<T::Acc>> = mats
177        .iter()
178        .map(|m| {
179            (0..n)
180                .flat_map(|i| (0..n).map(move |j| (i, j)))
181                .map(|(i, j)| {
182                    let x = m.get(i, j).widen();
183                    let x = if maximize { x.lb_neg()? } else { x };
184                    // For k=2 use LAP's documented 2*n-entry headroom. Triple
185                    // heuristics and multiplier arithmetic reserve more space.
186                    if !x.is_valid() || !x.lb_lap_safe(n, if k == 2 { 2 } else { 128 }) {
187                        return Err(KapError::Lap(LapError::InvalidCost(i, j)));
188                    }
189                    Ok(x)
190                })
191                .collect()
192        })
193        .collect::<Result<_, _>>()?;
194    let views: Vec<_> = data.iter().map(|d| view(d, n)).collect();
195    let mut solver = LapSolver::new();
196    let mut pairs = Vec::with_capacity(mats.len());
197    let mut columns = Vec::with_capacity(mats.len());
198    let mut pairwise = T::Acc::ZERO;
199    for &m in &views {
200        let cost = solver.solve(m, Sense::Minimize)?.cost;
201        pairwise = pairwise.lb_add(cost)?;
202        pairs.push(cost);
203        columns.push(solver.duals().col);
204    }
205    if k == 2 || n == 0 {
206        return finish(pairwise, opts);
207    }
208    if !maximize && opts.upper.is_some_and(|upper| pairwise >= upper) {
209        return Ok(opts.upper.unwrap());
210    }
211    let mut triples = Vec::new();
212    for p in 0..k {
213        for q in p + 1..k {
214            for r in q + 1..k {
215                triples.push([index(k, p, q), index(k, p, r), index(k, q, r)]);
216            }
217        }
218    }
219    let solve = |ids: &[usize; 3]| {
220        let [a, b, c] = *ids;
221        let floor = pairs[a].lb_add(pairs[b])?.lb_add(pairs[c])?;
222        let u: Vec<_> = columns[b]
223            .iter()
224            .zip(&columns[c])
225            .map(|(&b, &c)| b.lb_add(c))
226            .collect::<Result<_, _>>()?;
227        triple_bound([views[a], views[b], views[c]], floor, u, opts.max_iter)
228    };
229    // Indexed collection then serial summation: identical float reduction order
230    // with/without rayon and for every rayon thread count.
231    #[cfg(feature = "rayon")]
232    let bounds: Vec<_> = {
233        use rayon::prelude::*;
234        triples.par_iter().map(solve).collect::<Result<_, _>>()?
235    };
236    #[cfg(not(feature = "rayon"))]
237    let bounds: Vec<_> = triples.iter().map(solve).collect::<Result<_, _>>()?;
238    let sum = bounds
239        .into_iter()
240        .try_fold(T::Acc::ZERO, |sum, b| sum.lb_add(b))?;
241    let averaged = sum.lb_ceil_div(k - 2);
242    // Floating addition/division can round the average just below the pairwise
243    // sum. Both bounds are valid, so retain the stronger one.
244    finish(
245        if averaged > pairwise {
246            averaged
247        } else {
248            pairwise
249        },
250        opts,
251    )
252}
253
254fn view<A: Copy>(data: &[A], n: usize) -> MatrixView<'_, A> {
255    MatrixView::from_row_major(data, n, n).expect("square buffer")
256}
257
258fn index(k: usize, p: usize, q: usize) -> usize {
259    k * p + q - p * (p + 1) / 2 - p - 1
260}
261
262fn finish<A: LowerBoundAcc>(value: A, opts: &LowerBoundOptions<A>) -> Result<A, KapError> {
263    let value = if opts.sense == Sense::Maximize {
264        value.lb_neg()?
265    } else {
266        value
267    };
268    Ok(match opts.upper {
269        Some(upper) if value > upper => upper,
270        _ => value,
271    })
272}
273
274/// Reusable min-plus product and argmin buffers; no cubic tensor.
275struct Axial<A> {
276    solver: LapSolver<A>,
277    d: Vec<A>,
278    chosen: Vec<usize>,
279    counts: Vec<usize>,
280}
281
282impl<A: LowerBoundAcc> Axial<A> {
283    fn new(n: usize) -> Self {
284        Self {
285            solver: LapSolver::new(),
286            d: vec![A::ZERO; n * n],
287            chosen: vec![0; n * n],
288            counts: vec![0; n],
289        }
290    }
291
292    fn evaluate(&mut self, mats: [MatrixView<'_, A>; 3], u: &[A]) -> Result<A, KapError> {
293        let [a, b, c] = mats;
294        let n = u.len();
295        for i in 0..n {
296            for j in 0..n {
297                let mut best = A::INF;
298                let mut chosen = 0;
299                for (l, &ul) in u.iter().enumerate() {
300                    let v = b.get(i, l).lb_add(c.get(j, l))?.lb_sub(ul)?;
301                    if v < best {
302                        best = v;
303                        chosen = l;
304                    }
305                }
306                let value = a.get(i, j).lb_add(best)?;
307                if !value.lb_lap_safe(n, 16) {
308                    return Err(overflow());
309                }
310                self.d[i * n + j] = value;
311                self.chosen[i * n + j] = chosen;
312            }
313        }
314        let lap = self.solver.solve(view(&self.d, n), Sense::Minimize)?;
315        self.counts.fill(0);
316        for (&i, &j) in lap.row_ind.iter().zip(&lap.col_ind) {
317            self.counts[self.chosen[i * n + j]] += 1;
318        }
319        u.iter().try_fold(lap.cost, |value, &ul| value.lb_add(ul))
320    }
321}
322
323fn triple_bound<A: LowerBoundAcc>(
324    mats: [MatrixView<'_, A>; 3],
325    mut best: A,
326    mut u: Vec<A>,
327    max_iter: usize,
328) -> Result<A, KapError> {
329    let n = u.len();
330    let mut axial = Axial::new(n);
331    let zero = axial.evaluate(mats, &vec![A::ZERO; n])?;
332    if zero > best {
333        best = zero;
334    }
335    if axial.counts.iter().all(|&c| c == 1) {
336        return Ok(best);
337    }
338    // A LAP dual seed ensures L(u) >= the three pairwise LAP optima in exact
339    // arithmetic: b[i,l]+c[j,l]-u[l] >= row_b[i]+row_c[j].
340    let mut value = match axial.evaluate(mats, &u) {
341        Ok(value) => value,
342        Err(KapError::Unsupported(_)) => return Ok(best),
343        Err(error) => return Err(error),
344    };
345    if value > best {
346        best = value;
347    }
348    if max_iter == 0 || axial.counts.iter().all(|&c| c == 1) {
349        return Ok(best);
350    }
351    // Fixed options, independent of the subgradient budget, preserve prefixes.
352    let upper = match k_assignment(&mats, Algo::Dv1, &Options::default()) {
353        Ok(solution) => solution.cost,
354        Err(KapError::Lap(LapError::Infeasible)) => return Ok(best),
355        Err(error) => return Err(error),
356    };
357    let (mut theta, mut stalled) = (1.0, 0);
358    for _ in 0..max_iter {
359        let norm: f64 = axial.counts.iter().map(|&c| (1.0 - c as f64).powi(2)).sum();
360        if norm == 0.0 || best >= upper {
361            break;
362        }
363        // Subtract in the accumulator before converting, avoiding catastrophic
364        // cancellation for integer objectives above 2^53.
365        let step = theta * upper.lb_sub(value)?.lb_float() / norm;
366        let next: Option<Vec<_>> = u
367            .iter()
368            .zip(&axial.counts)
369            .map(|(&ul, &c)| ul.lb_update(step * (1.0 - c as f64)))
370            .collect();
371        let Some(next) = next else { break };
372        if next.iter().any(|&ul| !ul.lb_lap_safe(n, 64)) {
373            break;
374        }
375        u = next;
376        value = match axial.evaluate(mats, &u) {
377            Ok(value) => value,
378            Err(KapError::Unsupported(_)) => break,
379            Err(error) => return Err(error),
380        };
381        if value > best {
382            best = value;
383            stalled = 0;
384        } else {
385            stalled += 1;
386            if stalled == 10 {
387                theta *= 0.5;
388                stalled = 0;
389            }
390        }
391    }
392    Ok(best)
393}
394
395#[cfg(test)]
396#[path = "lower_bound_tests.rs"]
397mod tests;