Skip to main content

kap/algo/
mod.rs

1//! Multiple Hungarian heuristics with deterministic pair enumeration.
2
3use crate::{Acc, Cost, KPartite, KSolution, KapError, LapSolver, MatrixView, Quotient, Sense};
4
5pub(crate) mod dv;
6pub(crate) mod ils;
7pub(crate) mod memetic;
8mod merge;
9mod pairfix;
10
11#[cfg(test)]
12mod gating_tests;
13#[cfg(test)]
14mod initial_tests;
15
16#[cfg(test)]
17pub(crate) use merge::bm_path;
18pub(crate) use merge::{am, bm, dm, shift};
19pub(crate) use pairfix::{cm, em, fm};
20
21/// Dimensionwise-variation neighbourhood.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Dv {
24    /// Re-match one original part against the rest.
25    One,
26    /// Re-match all canonical nontrivial subsets (at most 16 parts).
27    Subsets,
28}
29
30/// Multiple Hungarian algorithm.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum Algo {
33    /// Repeatedly merge the first two parts.
34    Am,
35    /// Exhaustively choose the best merge tree, memoizing commuting merges.
36    Bm,
37    /// Steepest descent from Bm over the fix-one-pair neighbourhood.
38    Cm,
39    /// Choose the best immediate quotient at each level.
40    Dm,
41    /// Best of `n_trials` independent randomised first-improvement descents from Bm.
42    Em,
43    /// `max_iter` moves to a random best neighbour (sideways and worse moves
44    /// allowed), the current and previous solutions tabu; returns the best seen.
45    Fm,
46    /// Best Am solution over all cyclic part orders.
47    Shift,
48    /// Am followed by single-part dimensionwise variation.
49    Dv1,
50    /// Am followed by subset dimensionwise variation.
51    DvS,
52    /// Iterated local search over DV, with independent seeded chains.
53    Ils,
54    /// Population of DV local optima with mutation and common-clique crossover.
55    Memetic,
56}
57
58/// Algorithm settings.
59#[derive(Clone, Debug)]
60pub struct Options {
61    /// Optimization direction.
62    pub sense: Sense,
63    /// Optional pair-cost threshold. Optimize sums of `d - threshold` over
64    /// transversal partial cliques, with singletons allowed. `+inf` forbids a
65    /// pair when minimizing, `-inf` when maximizing. All algorithms, DV
66    /// refinement and supported initial solutions accept a threshold;
67    /// None preserves complete matching.
68    pub threshold: Option<f64>,
69    /// Move limit of Cm, Em (per trial) and Fm; DV sweeps; ILS perturbations; memetic generations.
70    pub max_iter: usize,
71    /// Number of independent Em trials or ILS chains.
72    pub n_trials: usize,
73    /// Seed of Em, Fm, ILS and Memetic; iteration budgets are reproducible.
74    pub seed: u64,
75    /// Optional DV search after the selected algorithm.
76    pub refine: Option<Dv>,
77    /// Neighbourhood used within ILS and Memetic.
78    pub dv: Dv,
79    /// Optional time budget for ILS (after the start) or Memetic (from entry).
80    pub time_limit: Option<std::time::Duration>,
81    /// Memetic population size; None uses 12 or time-based population sizing.
82    pub population: Option<usize>,
83}
84
85impl Default for Options {
86    fn default() -> Self {
87        Self {
88            sense: Sense::Minimize,
89            threshold: None,
90            max_iter: 100,
91            n_trials: 1,
92            seed: 0,
93            refine: None,
94            dv: Dv::One,
95            time_limit: None,
96            population: None,
97        }
98    }
99}
100
101pub(crate) fn better<A: Acc>(candidate: A, best: A, sense: Sense) -> bool {
102    match sense {
103        Sense::Minimize => candidate < best,
104        Sense::Maximize => candidate > best,
105    }
106}
107
108/// Solve a condensed k-partite problem using the selected heuristic.
109/// With `opts.threshold = Some(tau)`, optimize the sum of `d - tau` over
110/// pairs within transversal partial cliques; singletons are allowed. `+inf`
111/// forbids a pair when minimizing, `-inf` when maximizing. Returned costs use
112/// the original matrices. Without a threshold, matching behavior is unchanged.
113pub fn k_assignment<T: Cost>(
114    mats: &[MatrixView<'_, T>],
115    algo: Algo,
116    opts: &Options,
117) -> Result<KSolution<T::Acc>, KapError>
118where
119    T::Acc: Cost<Acc = T::Acc>,
120{
121    run(mats, None, algo, opts)
122}
123
124/// Improve supplied cliques instead of constructing a starting solution.
125///
126/// Each clique contains `(part, vertex)` pairs, with at most one vertex per
127/// part. Unlisted vertices become singleton nodes. Supports deterministic
128/// starts (Am, Bm, Dm, Shift, Dv1, DvS) and ILS; other algorithms reject
129/// `initial`. Deterministic starts are replaced, then `opts.refine` is applied.
130/// Without a threshold the initial solution must be complete: after adding
131/// singleton nodes its node count must equal `max(part sizes)`, as in a previous
132/// solver result. With a threshold, partial solutions (including an empty
133/// clique list) are accepted, but a clique containing a forbidden pair is rejected.
134/// The result is no worse than the start for integer costs; for floating-point
135/// costs this holds up to rounding of the cost sums. With a threshold,
136/// "no worse than the start" refers to the shifted objective.
137pub fn k_assignment_from<T: Cost>(
138    mats: &[MatrixView<'_, T>],
139    cliques: &[Vec<(usize, usize)>],
140    algo: Algo,
141    opts: &Options,
142) -> Result<KSolution<T::Acc>, KapError>
143where
144    T::Acc: Cost<Acc = T::Acc>,
145{
146    run(mats, Some(cliques), algo, opts)
147}
148
149fn from_cliques<A: Acc + Cost<Acc = A>>(
150    root: &Quotient<A>,
151    cliques: &[Vec<(usize, usize)>],
152    sense: Sense,
153) -> Result<Quotient<A>, KapError> {
154    use crate::kpartite::NONE;
155    let k = root.n_parts();
156    // A zero-sweep start never reaches a LAP. Apply its entry rules here,
157    // including entries not selected by the supplied cliques.
158    for a in 0..k {
159        for b in a + 1..k {
160            let matrix = root.matrix(a, b);
161            for r in 0..root.n_nodes(a) {
162                for c in 0..root.n_nodes(b) {
163                    let value = matrix.get(r, c);
164                    let value = match sense {
165                        Sense::Minimize => Some(value),
166                        Sense::Maximize => value.checked_neg(),
167                    };
168                    if !value.is_some_and(Acc::is_valid) {
169                        return Err(crate::LapError::InvalidCost(r, c).into());
170                    }
171                }
172            }
173        }
174    }
175    let mut used: Vec<_> = (0..k).map(|p| vec![false; root.n_nodes(p)]).collect();
176    let mut nodes = Vec::new();
177    for clique in cliques {
178        if clique.is_empty() {
179            return Err(KapError::BadMatching);
180        }
181        let mut row = vec![NONE; k];
182        for &(p, v) in clique {
183            let seen = used
184                .get_mut(p)
185                .and_then(|part| part.get_mut(v))
186                .ok_or(KapError::BadMatching)?;
187            if *seen || row[p] != NONE {
188                return Err(KapError::BadMatching);
189            }
190            *seen = true;
191            row[p] = v as u32;
192        }
193        nodes.extend(row);
194    }
195    for (p, part) in used.iter().enumerate() {
196        for (v, &seen) in part.iter().enumerate() {
197            if !seen {
198                let mut row = vec![NONE; k];
199                row[p] = v as u32;
200                nodes.extend(row);
201            }
202        }
203    }
204    let expected = (0..k).map(|p| root.n_nodes(p)).max().unwrap();
205    let actual = nodes.len() / k;
206    if !root.is_gated() && actual != expected {
207        return Err(KapError::IncompleteInitial { expected, actual });
208    }
209    let start = Quotient::from_nodes_checked(root, nodes)?;
210    if root.is_gated() && !start.score.is_finite() {
211        // Tell a forbidden pair from a float sum that overflowed.
212        let forbidden = start.nodes().chunks_exact(k).any(|row| {
213            (0..k).any(|a| {
214                (a + 1..k).any(|b| {
215                    row[a] != NONE
216                        && row[b] != NONE
217                        && !root
218                            .matrix(a, b)
219                            .get(row[a] as usize, row[b] as usize)
220                            .is_finite()
221                })
222            })
223        });
224        return Err(if forbidden {
225            KapError::ForbiddenInitial
226        } else {
227            KapError::Unsupported("cost overflow")
228        });
229    }
230    Ok(start)
231}
232
233fn run<T: Cost>(
234    mats: &[MatrixView<'_, T>],
235    initial: Option<&[Vec<(usize, usize)>]>,
236    algo: Algo,
237    opts: &Options,
238) -> Result<KSolution<T::Acc>, KapError>
239where
240    T::Acc: Cost<Acc = T::Acc>,
241{
242    let original = KPartite::new(mats)?;
243    let problem = match opts.threshold {
244        Some(tau) => original.gated(tau, opts.sense)?,
245        None => original.clone(),
246    };
247    if initial.is_some() && matches!(algo, Algo::Cm | Algo::Em | Algo::Fm | Algo::Memetic) {
248        return Err(KapError::BadOption("initial"));
249    }
250    if matches!(algo, Algo::Em | Algo::Fm) && opts.max_iter == 0 {
251        return Err(KapError::BadOption("max_iter"));
252    }
253    if matches!(algo, Algo::Em | Algo::Ils) && opts.n_trials == 0 {
254        return Err(KapError::BadOption("n_trials"));
255    }
256    if algo == Algo::Memetic && opts.population.is_some_and(|m| m < 2) {
257        return Err(KapError::BadOption("population"));
258    }
259    if (algo == Algo::DvS
260        || opts.refine == Some(Dv::Subsets)
261        || (matches!(algo, Algo::Ils | Algo::Memetic) && opts.dv == Dv::Subsets))
262        && problem.sizes().len() > 16
263    {
264        return Err(KapError::Unsupported("sDV requires k <= 16"));
265    }
266    let root = Quotient::root(&problem);
267    let mut solver = LapSolver::new();
268    let start = initial
269        .map(|cliques| from_cliques(&root, cliques, opts.sense))
270        .transpose()?;
271    let mut q = match (algo, start) {
272        (Algo::Ils, Some(start)) => ils::ils_from(&root, start, opts, &mut solver)?,
273        (Algo::Dv1 | Algo::DvS, Some(start)) => {
274            let kind = if algo == Algo::Dv1 {
275                Dv::One
276            } else {
277                Dv::Subsets
278            };
279            dv::improve(&root, start, kind, opts.max_iter, opts.sense, &mut solver)?
280        }
281        (_, Some(start)) => start,
282        (_, None) => match algo {
283            Algo::Am => am(&root, opts.sense, &mut solver)?,
284            Algo::Bm => bm(&root, opts.sense, &mut solver)?,
285            Algo::Dm => dm(&root, opts.sense, &mut solver)?,
286            Algo::Cm => cm(&root, opts, &mut solver)?,
287            Algo::Em => em(&root, opts, &mut solver)?,
288            Algo::Fm => fm(&root, opts, &mut solver)?,
289            Algo::Ils => ils::ils(&root, opts, &mut solver)?,
290            Algo::Memetic => memetic::memetic(&root, opts, &mut solver)?,
291            Algo::Shift => shift(&root, opts.sense, &mut solver)?,
292            Algo::Dv1 | Algo::DvS => {
293                let start = am(&root, opts.sense, &mut solver)?;
294                let kind = if algo == Algo::Dv1 {
295                    Dv::One
296                } else {
297                    Dv::Subsets
298                };
299                dv::improve(&root, start, kind, opts.max_iter, opts.sense, &mut solver)?
300            }
301        },
302    };
303    if let Some(kind) = opts.refine {
304        q = dv::improve(&root, q, kind, opts.max_iter, opts.sense, &mut solver)?;
305    }
306    let mut solution = q.reconstruct();
307    if opts.threshold.is_some() {
308        original.recost(&mut solution);
309    }
310    Ok(solution)
311}
312
313/// Column permutations can leave empty rows when no part is an anchor.
314fn drop_empty_rows(nodes: Vec<u32>, k: usize) -> Vec<u32> {
315    nodes
316        .chunks_exact(k)
317        .filter(|row| row.iter().any(|&v| v != crate::kpartite::NONE))
318        .flatten()
319        .copied()
320        .collect()
321}
322
323/// SplitMix64; one independent stream per (seed, stream).
324pub(crate) struct Rng(u64);
325
326impl Rng {
327    pub(crate) fn new(seed: u64, stream: u64) -> Self {
328        let mut r = Rng(seed ^ stream.wrapping_mul(0xD1B5_4A32_D192_ED03));
329        r.next();
330        r
331    }
332
333    fn next(&mut self) -> u64 {
334        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
335        let mut z = self.0;
336        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
337        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
338        z ^ (z >> 31)
339    }
340
341    /// Uniform in `0..n` (n >= 1), by multiply-shift.
342    pub(crate) fn below(&mut self, n: usize) -> usize {
343        ((self.next() as u128 * n as u128) >> 64) as usize
344    }
345
346    /// Uniform in [0, 1), using the high 53 bits.
347    pub(crate) fn uniform(&mut self) -> f64 {
348        (self.next() >> 11) as f64 * (1.0 / (1u64 << 53) as f64)
349    }
350
351    pub(crate) fn shuffle<T>(&mut self, v: &mut [T]) {
352        for i in (1..v.len()).rev() {
353            v.swap(i, self.below(i + 1));
354        }
355    }
356}