Skip to main content

kap/
kpartite.rs

1//! Dense k-partite problems and shared quotient graphs.
2
3use std::{fmt, sync::Arc};
4
5use crate::{Acc, Cost, LapError, LapSolver, MatrixView, Sense};
6
7/// Missing original vertex in a quotient node.
8pub const NONE: u32 = u32::MAX;
9
10/// Invalid input or failure of a constituent LAP.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub enum KapError {
13    /// Matrix count does not describe 2 through 64 partites.
14    BadCount(usize),
15    /// A matrix dimension disagrees with a previously seen partite size.
16    ShapeMismatch {
17        /// Condensed matrix index.
18        matrix: usize,
19        /// Original partite index.
20        partite: usize,
21        /// Previously established size.
22        expected: usize,
23        /// Actual dimension.
24        actual: usize,
25    },
26    /// Invalid part positions, vertex indices, or repeated matching vertices.
27    BadMatching,
28    /// The supplied initial solution does not have max(partite sizes) nodes.
29    IncompleteInitial {
30        /// Required number of nodes, counting singleton vertices.
31        expected: usize,
32        /// Actual number after adding all unlisted vertices as singletons.
33        actual: usize,
34    },
35    /// The supplied gated initial solution contains a forbidden pair.
36    ForbiddenInitial,
37    /// A partite is too large for u32 vertex identifiers.
38    TooManyVertices(usize),
39    /// Constituent LAP error.
40    Lap(LapError),
41    /// An option has an invalid value.
42    BadOption(&'static str),
43    /// The request exceeds a documented limit of the algorithm.
44    Unsupported(&'static str),
45}
46
47impl fmt::Display for KapError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::BadCount(n) => write!(
51                f,
52                "invalid matrix count {n}: expected k(k-1)/2 for 2 <= k <= 64"
53            ),
54            Self::ShapeMismatch {
55                matrix,
56                partite,
57                expected,
58                actual,
59            } => write!(
60                f,
61                "matrix {matrix}: partite {partite} has size {actual}, expected {expected}"
62            ),
63            Self::BadMatching => write!(f, "invalid part positions or matching"),
64            Self::IncompleteInitial { expected, actual } => write!(
65                f,
66                "initial must be a complete solution: {expected} nodes expected, {actual} given"
67            ),
68            Self::ForbiddenInitial => write!(f, "initial places a forbidden pair in one clique"),
69            Self::TooManyVertices(n) => write!(f, "partite size {n} exceeds u32 vertex capacity"),
70            Self::Lap(e) => e.fmt(f),
71            Self::Unsupported(what) => f.write_str(what),
72            Self::BadOption("initial") => write!(f, "initial is unsupported for this algorithm"),
73            Self::BadOption("threshold") => write!(
74                f,
75                "threshold must be finite, and an integer for integer costs"
76            ),
77            Self::BadOption(name) => write!(f, "{name} must be a positive integer"),
78        }
79    }
80}
81
82impl std::error::Error for KapError {
83    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
84        match self {
85            Self::Lap(e) => Some(e),
86            _ => None,
87        }
88    }
89}
90
91impl From<LapError> for KapError {
92    fn from(e: LapError) -> Self {
93        Self::Lap(e)
94    }
95}
96
97fn index(k: usize, a: usize, b: usize) -> usize {
98    debug_assert!(a < b && b < k);
99    k * a + b - a * (a + 1) / 2 - a - 1
100}
101
102fn write_row<A: Copy>(dst: &mut [std::mem::MaybeUninit<A>], src: &[A]) {
103    for (d, &x) in dst.iter_mut().zip(src) {
104        d.write(x);
105    }
106}
107
108/// `dst` = transpose of the row-major `rows x cols` matrix `src`, cache-blocked.
109fn transpose_into<A: Copy>(dst: &mut Vec<A>, src: &[A], rows: usize, cols: usize) {
110    const B: usize = 32;
111    dst.clear();
112    if rows * cols == 0 {
113        return;
114    }
115    dst.resize(rows * cols, src[0]);
116    for r0 in (0..rows).step_by(B) {
117        for c0 in (0..cols).step_by(B) {
118            for r in r0..(r0 + B).min(rows) {
119                for c in c0..(c0 + B).min(cols) {
120                    dst[c * rows + r] = src[r * cols + c];
121                }
122            }
123        }
124    }
125}
126
127#[derive(Clone, Debug)]
128struct Dense<A> {
129    data: Arc<[A]>,
130    rows: usize,
131    cols: usize,
132}
133
134impl<A: Copy> Dense<A> {
135    fn view(&self) -> MatrixView<'_, A> {
136        MatrixView::from_row_major(&self.data, self.rows, self.cols).expect("dense shape")
137    }
138}
139
140/// Original pair costs in combinations order, widened and copied once.
141#[derive(Clone, Debug)]
142pub struct KPartite<A> {
143    sizes: Arc<[usize]>,
144    matrices: Arc<[Dense<A>]>,
145    gated: bool,
146}
147
148impl<A: Acc + Cost<Acc = A>> KPartite<A> {
149    /// Validate the condensed matrix count and all shared dimensions.
150    pub fn new<T: Cost<Acc = A>>(mats: &[MatrixView<'_, T>]) -> Result<Self, KapError> {
151        let k = (2..=64)
152            .find(|&k| k * (k - 1) / 2 == mats.len())
153            .ok_or(KapError::BadCount(mats.len()))?;
154        let mut sizes = vec![None; k];
155        let mut matrices = Vec::with_capacity(mats.len());
156        for a in 0..k {
157            for b in a + 1..k {
158                let cid = index(k, a, b);
159                let m = &mats[cid];
160                for (p, actual) in [(a, m.rows()), (b, m.cols())] {
161                    if actual > u32::MAX as usize {
162                        return Err(KapError::TooManyVertices(actual));
163                    }
164                    if let Some(expected) = sizes[p] {
165                        if actual != expected {
166                            return Err(KapError::ShapeMismatch {
167                                matrix: cid,
168                                partite: p,
169                                expected,
170                                actual,
171                            });
172                        }
173                    } else {
174                        sizes[p] = Some(actual);
175                    }
176                }
177                let data = (0..m.rows())
178                    .flat_map(|r| (0..m.cols()).map(move |c| m.get(r, c).widen()))
179                    .collect::<Vec<_>>();
180                matrices.push(Dense {
181                    data: data.into(),
182                    rows: m.rows(),
183                    cols: m.cols(),
184                });
185            }
186        }
187        Ok(Self {
188            sizes: sizes.into_iter().map(Option::unwrap).collect(),
189            matrices: matrices.into(),
190            gated: false,
191        })
192    }
193
194    /// Copy costs shifted by `tau` for optional matching. The unfavorable
195    /// infinity is forbidden: `+inf` for minimization, `-inf` for maximization.
196    pub fn gated(&self, tau: f64, sense: Sense) -> Result<Self, KapError> {
197        let tau = A::from_f64_exact(tau).ok_or(KapError::BadOption("threshold"))?;
198        let forbidden = match sense {
199            Sense::Minimize => A::INF,
200            Sense::Maximize => -A::INF,
201        };
202        let mut matrices = Vec::with_capacity(self.matrices.len());
203        for m in self.matrices.iter() {
204            let mut data = Vec::with_capacity(m.data.len());
205            for (i, &value) in m.data.iter().enumerate() {
206                if !value.is_finite() && value != forbidden {
207                    return Err(LapError::InvalidCost(i / m.cols, i % m.cols).into());
208                }
209                let shifted = value
210                    .checked_sub(tau)
211                    .ok_or(KapError::Unsupported("cost overflow"))?;
212                // Clipping hides non-improving entries from the LAP, so apply
213                // its entry rule here: quotient sums then have the same
214                // headroom as without a threshold, and a float shift that
215                // overflows to the wrong infinity is rejected.
216                let oriented = match sense {
217                    Sense::Minimize => Some(shifted),
218                    Sense::Maximize => shifted.checked_neg(),
219                };
220                if !oriented.is_some_and(Acc::is_valid) {
221                    return Err(LapError::InvalidCost(i / m.cols, i % m.cols).into());
222                }
223                data.push(shifted);
224            }
225            matrices.push(Dense {
226                data: data.into(),
227                rows: m.rows,
228                cols: m.cols,
229            });
230        }
231        Ok(Self {
232            sizes: self.sizes.clone(),
233            matrices: matrices.into(),
234            gated: true,
235        })
236    }
237
238    /// Recompute clique and total costs from this problem's pair matrices.
239    pub(crate) fn recost(&self, solution: &mut KSolution<A>) {
240        solution.costs.clear();
241        solution.cost = A::ZERO;
242        for clique in &solution.cliques {
243            let mut cost = A::ZERO;
244            for (i, &(a, r)) in clique.iter().enumerate() {
245                for &(b, c) in &clique[i + 1..] {
246                    cost = cost
247                        + self.matrices[index(self.sizes.len(), a, b)]
248                            .view()
249                            .get(r, c);
250                }
251            }
252            solution.costs.push(cost);
253            solution.cost = solution.cost + cost;
254        }
255    }
256
257    /// Original partite sizes.
258    pub fn sizes(&self) -> &[usize] {
259        &self.sizes
260    }
261}
262
263#[derive(Clone, Debug)]
264struct Part<A> {
265    members: u64,
266    nodes: Arc<[u32]>,
267    costs: Arc<[A]>,
268}
269
270/// A merge state; unchanged parts and matrices are shared across clones.
271#[derive(Clone, Debug)]
272pub struct Quotient<A> {
273    k_orig: usize,
274    gated: bool,
275    parts: Vec<Part<A>>,
276    matrices: Vec<Dense<A>>,
277    /// Total cost already fixed inside quotient nodes.
278    pub score: A,
279}
280
281/// Reconstructed cliques and unmatched vertices in quotient node order.
282/// With a threshold, the objective sums `d - threshold` over pairs within
283/// transversal partial cliques, and singleton vertices are free. Reported
284/// costs from `k_assignment` sum original pair costs without the shift.
285#[derive(Clone, Debug, PartialEq)]
286pub struct KSolution<A> {
287    /// Cliques, each in increasing original partite order.
288    pub cliques: Vec<Vec<(usize, usize)>>,
289    /// Internal edge sum of each clique.
290    pub costs: Vec<A>,
291    /// Singleton vertices, in quotient node order.
292    pub free: Vec<(usize, usize)>,
293    /// Sum of clique costs.
294    pub cost: A,
295}
296
297impl<A: Acc + Cost<Acc = A>> Quotient<A> {
298    /// Unmerged state of an original problem.
299    pub fn root(problem: &KPartite<A>) -> Self {
300        let k = problem.sizes.len();
301        let parts = problem
302            .sizes
303            .iter()
304            .enumerate()
305            .map(|(p, &n)| {
306                let mut nodes = vec![NONE; n * k];
307                for i in 0..n {
308                    nodes[i * k + p] = i as u32;
309                }
310                Part {
311                    members: 1 << p,
312                    nodes: nodes.into(),
313                    costs: vec![A::ZERO; n].into(),
314                }
315            })
316            .collect();
317        Self {
318            k_orig: k,
319            gated: problem.gated,
320            parts,
321            matrices: problem.matrices.to_vec(),
322            score: A::ZERO,
323        }
324    }
325
326    /// Build a final quotient from a row-major table of original vertices.
327    /// `NONE` denotes an absent vertex. Every original vertex must occur once,
328    /// and every row must contain at least one vertex.
329    pub fn from_nodes(root: &Self, nodes: Vec<u32>) -> Result<Self, KapError> {
330        Self::from_nodes_impl::<false>(root, nodes)
331    }
332
333    /// Build a warm start, checking integer clique and total sums for overflow.
334    pub(crate) fn from_nodes_checked(root: &Self, nodes: Vec<u32>) -> Result<Self, KapError> {
335        Self::from_nodes_impl::<true>(root, nodes)
336    }
337
338    fn from_nodes_impl<const CHECKED: bool>(
339        root: &Self,
340        nodes: Vec<u32>,
341    ) -> Result<Self, KapError> {
342        let add = |a: A, b: A| {
343            if CHECKED {
344                a.checked_add(b)
345                    .ok_or(KapError::Unsupported("cost overflow"))
346            } else {
347                Ok(a + b)
348            }
349        };
350        let k = root.k_orig;
351        if root.n_parts() != k || (0..k).any(|p| root.members(p) != 1 << p) || nodes.len() % k != 0
352        {
353            return Err(KapError::BadMatching);
354        }
355        let mut used: Vec<Vec<bool>> = (0..k).map(|p| vec![false; root.n_nodes(p)]).collect();
356        let mut costs = Vec::with_capacity(nodes.len() / k);
357        let mut score = A::ZERO;
358        for node in nodes.chunks_exact(k) {
359            if node.iter().all(|&v| v == NONE) {
360                return Err(KapError::BadMatching);
361            }
362            for (p, &v) in node.iter().enumerate() {
363                if v != NONE {
364                    let Some(seen) = used[p].get_mut(v as usize) else {
365                        return Err(KapError::BadMatching);
366                    };
367                    if *seen {
368                        return Err(KapError::BadMatching);
369                    }
370                    *seen = true;
371                }
372            }
373            let mut cost = A::ZERO;
374            for a in 0..k {
375                for b in a + 1..k {
376                    if node[a] != NONE && node[b] != NONE {
377                        cost = add(
378                            cost,
379                            root.matrix(a, b).get(node[a] as usize, node[b] as usize),
380                        )?;
381                    }
382                }
383            }
384            costs.push(cost);
385            score = add(score, cost)?;
386        }
387        if used.iter().flatten().any(|&seen| !seen) {
388            return Err(KapError::BadMatching);
389        }
390        Ok(Self {
391            k_orig: k,
392            gated: root.gated,
393            parts: vec![Part {
394                members: u64::MAX >> (64 - k),
395                nodes: nodes.into(),
396                costs: costs.into(),
397            }],
398            matrices: Vec::new(),
399            score,
400        })
401    }
402
403    /// Row-major original vertex table of a final quotient.
404    pub(crate) fn nodes(&self) -> &[u32] {
405        assert_eq!(self.n_parts(), 1);
406        &self.parts[0].nodes
407    }
408
409    pub(crate) fn is_gated(&self) -> bool {
410        self.gated
411    }
412
413    /// Number of current super-partites.
414    pub fn n_parts(&self) -> usize {
415        self.parts.len()
416    }
417
418    /// Number of nodes in a current super-partite.
419    pub fn n_nodes(&self, part: usize) -> usize {
420        self.parts[part].costs.len()
421    }
422
423    /// Original partites contained in a current super-partite.
424    pub fn members(&self, part: usize) -> u64 {
425        self.parts[part].members
426    }
427
428    /// Current pair matrix, transposed when the requested positions are reversed.
429    pub fn matrix(&self, a: usize, b: usize) -> MatrixView<'_, A> {
430        if a < b {
431            self.matrices[index(self.n_parts(), a, b)].view()
432        } else {
433            self.matrices[index(self.n_parts(), b, a)].view().t()
434        }
435    }
436
437    /// Solve the current pair LAP and merge its matched nodes.
438    pub fn merge_lap(
439        &self,
440        a: usize,
441        b: usize,
442        solver: &mut LapSolver<A>,
443        sense: Sense,
444    ) -> Result<Self, KapError> {
445        let (matching, cost) = self.solve_pair(a, b, solver, sense)?;
446        self.merge(a, b, &matching, cost)
447    }
448
449    pub(crate) fn solve_pair(
450        &self,
451        a: usize,
452        b: usize,
453        solver: &mut LapSolver<A>,
454        sense: Sense,
455    ) -> Result<(Vec<(u32, u32)>, A), KapError> {
456        self.check_pair(a, b)?;
457        if self.gated {
458            let m = self.matrix(a, b);
459            let improving = |value| match sense {
460                Sense::Minimize => value < A::ZERO,
461                Sense::Maximize => value > A::ZERO,
462            };
463            let mut clipped = Vec::with_capacity(m.rows() * m.cols());
464            let mut any = false;
465            for r in 0..m.rows() {
466                for c in 0..m.cols() {
467                    let value = m.get(r, c);
468                    // Validate before comparing: an unordered value must not
469                    // silently become zero through the clipping branch.
470                    if value.partial_cmp(&A::ZERO).is_none() {
471                        return Err(LapError::InvalidCost(r, c).into());
472                    }
473                    let keep = improving(value);
474                    any |= keep;
475                    clipped.push(if keep { value } else { A::ZERO });
476                }
477            }
478            if !any {
479                return Ok((Vec::new(), A::ZERO));
480            }
481            #[cfg(test)]
482            LAP_CALLS.with(|n| n.set(n.get() + 1));
483            // Any partial matching extends to a maximum one. Clipping makes
484            // completion non-worsening; dropping zero edges preserves its cost.
485            let sol = solver.solve(
486                MatrixView::from_row_major(&clipped, m.rows(), m.cols())?,
487                sense,
488            )?;
489            let mut matching = Vec::new();
490            let mut cost = A::ZERO;
491            for (r, c) in sol.row_ind.into_iter().zip(sol.col_ind) {
492                let value = m.get(r, c);
493                if improving(value) {
494                    matching.push((r as u32, c as u32));
495                    cost = cost + value;
496                }
497            }
498            return Ok((matching, cost));
499        }
500        #[cfg(test)]
501        LAP_CALLS.with(|n| n.set(n.get() + 1));
502        let sol = solver.solve(self.matrix(a, b), sense)?;
503        Ok((
504            sol.row_ind
505                .into_iter()
506                .zip(sol.col_ind)
507                .map(|(r, c)| (r as u32, c as u32))
508                .collect(),
509            sol.cost,
510        ))
511    }
512
513    fn check_pair(&self, a: usize, b: usize) -> Result<(), KapError> {
514        if a == b || a >= self.n_parts() || b >= self.n_parts() {
515            Err(KapError::BadMatching)
516        } else {
517            Ok(())
518        }
519    }
520
521    /// Merge a fixed, possibly partial matching, computing its current pair cost.
522    /// The matching is not checked against forbidden pairs of a gated problem.
523    pub fn fix(&self, a: usize, b: usize, matching: &[(u32, u32)]) -> Result<Self, KapError> {
524        self.check_pair(a, b)?;
525        let m = self.matrix(a, b);
526        let mut cost = A::ZERO;
527        for &(r, c) in matching {
528            if r as usize >= m.rows() || c as usize >= m.cols() {
529                return Err(KapError::BadMatching);
530            }
531            cost = cost + m.get(r as usize, c as usize);
532        }
533        self.merge(a, b, matching, cost)
534    }
535
536    pub(crate) fn merge(
537        &self,
538        a: usize,
539        b: usize,
540        matching: &[(u32, u32)],
541        cost: A,
542    ) -> Result<Self, KapError> {
543        self.check_pair(a, b)?;
544        if a > b {
545            let reversed: Vec<_> = matching.iter().map(|&(r, c)| (c, r)).collect();
546            return self.merge(b, a, &reversed, cost);
547        }
548        let mut used_a = vec![false; self.n_nodes(a)];
549        let mut used_b = vec![false; self.n_nodes(b)];
550        let mut rows = Vec::with_capacity(used_a.len() + used_b.len());
551        for &(r, c) in matching {
552            let (r, c) = (r as usize, c as usize);
553            if r >= used_a.len() || c >= used_b.len() || used_a[r] || used_b[c] {
554                return Err(KapError::BadMatching);
555            }
556            used_a[r] = true;
557            used_b[c] = true;
558            rows.push((Some(r), Some(c)));
559        }
560        rows.extend(
561            used_a
562                .iter()
563                .enumerate()
564                .filter(|&(_, &used)| !used)
565                .map(|(r, _)| (Some(r), None)),
566        );
567        rows.extend(
568            used_b
569                .iter()
570                .enumerate()
571                .filter(|&(_, &used)| !used)
572                .map(|(c, _)| (None, Some(c))),
573        );
574        let mut nodes = Vec::with_capacity(rows.len() * self.k_orig);
575        let mut costs = Vec::with_capacity(rows.len());
576        let ab = self.matrix(a, b);
577        for &(r, c) in &rows {
578            for p in 0..self.k_orig {
579                let left = r.map_or(NONE, |r| self.parts[a].nodes[r * self.k_orig + p]);
580                nodes.push(if left != NONE {
581                    left
582                } else {
583                    c.map_or(NONE, |c| self.parts[b].nodes[c * self.k_orig + p])
584                });
585            }
586            costs.push(match (r, c) {
587                (Some(r), Some(c)) => {
588                    (ab.get(r, c) + self.parts[a].costs[r]) + self.parts[b].costs[c]
589                }
590                (Some(r), None) => self.parts[a].costs[r],
591                (None, Some(c)) => self.parts[b].costs[c],
592                _ => unreachable!(),
593            });
594        }
595        let merged = Part {
596            members: self.parts[a].members | self.parts[b].members,
597            nodes: nodes.into(),
598            costs: costs.into(),
599        };
600        let pre: Vec<_> = (0..self.n_parts()).filter(|&p| p != b).collect();
601        let parts = pre
602            .iter()
603            .map(|&p| {
604                if p == a {
605                    merged.clone()
606                } else {
607                    self.parts[p].clone()
608                }
609            })
610            .collect();
611        // `rows` lists the matched pairs, then a's unmatched nodes, then b's.
612        let k = self.n_parts();
613        let mut scratch = Vec::new();
614        let mut matrices = Vec::new();
615        for i in 0..pre.len() {
616            for j in i + 1..pre.len() {
617                let (pi, pj) = (pre[i], pre[j]);
618                if pi != a && pj != a {
619                    matrices.push(self.matrices[index(k, pi, pj)].clone());
620                    continue;
621                }
622                let other = if pi == a { pj } else { pi };
623                let no = self.n_nodes(other);
624                let (nr, nc) = if pi == a {
625                    (rows.len(), no)
626                } else {
627                    (no, rows.len())
628                };
629                let mut data = Arc::<[A]>::new_uninit_slice(nr * nc);
630                let out = Arc::get_mut(&mut data).expect("fresh allocation");
631                if nr * nc > 0 && pi == a {
632                    // Merged nodes are the rows: add a's row r to b's row c.
633                    // a < other, so (a, other) is stored with a's nodes as rows.
634                    let ma = &self.matrices[index(k, a, other)].data;
635                    let mb: &[A] = if b < other {
636                        &self.matrices[index(k, b, other)].data
637                    } else {
638                        // (other, b) is stored with other's nodes as rows;
639                        // transpose it once so b's rows are contiguous.
640                        let src = &self.matrices[index(k, other, b)].data;
641                        transpose_into(&mut scratch, src, no, self.n_nodes(b));
642                        &scratch
643                    };
644                    for (dst, &(r, c)) in out.chunks_exact_mut(no).zip(&rows) {
645                        match (r, c) {
646                            (Some(r), Some(c)) => {
647                                let ra = &ma[r * no..(r + 1) * no];
648                                let rb = &mb[c * no..(c + 1) * no];
649                                for ((d, &x), &y) in dst.iter_mut().zip(ra).zip(rb) {
650                                    d.write(x + y);
651                                }
652                            }
653                            (Some(r), None) => write_row(dst, &ma[r * no..(r + 1) * no]),
654                            (None, Some(c)) => write_row(dst, &mb[c * no..(c + 1) * no]),
655                            _ => unreachable!(),
656                        }
657                    }
658                } else if nr * nc > 0 {
659                    // Merged nodes are the columns; other < a < b, so both
660                    // (other, a) and (other, b) are stored with other's rows.
661                    let ma = &self.matrices[index(k, other, a)].data;
662                    let mb = &self.matrices[index(k, other, b)].data;
663                    let (na, nb) = (self.n_nodes(a), self.n_nodes(b));
664                    for (o, dst) in out.chunks_exact_mut(nc).enumerate() {
665                        let ra = &ma[o * na..(o + 1) * na];
666                        let rb = &mb[o * nb..(o + 1) * nb];
667                        for (d, &(r, c)) in dst.iter_mut().zip(&rows) {
668                            d.write(match (r, c) {
669                                (Some(r), Some(c)) => ra[r] + rb[c],
670                                (Some(r), None) => ra[r],
671                                (None, Some(c)) => rb[c],
672                                _ => unreachable!(),
673                            });
674                        }
675                    }
676                }
677                // SAFETY: the loops above wrote every one of the nr * nc
678                // slots: chunks_exact_mut covers `out` exactly, since its
679                // length is nr * nc and the chunk length is nc (no or
680                // rows.len()), with nr chunks zipped against nr row entries.
681                let data = unsafe { data.assume_init() };
682                matrices.push(Dense {
683                    data,
684                    rows: nr,
685                    cols: nc,
686                });
687            }
688        }
689        Ok(Self {
690            k_orig: self.k_orig,
691            gated: self.gated,
692            parts,
693            matrices,
694            score: self.score + cost,
695        })
696    }
697
698    /// Split a final solution into two portions per node, using original costs.
699    /// Side 0 always contains original part 0; empty portions are dropped.
700    /// Returns the two-part quotient and the matching induced by this solution.
701    pub fn bipartition(&self, root: &Self, mask: u64) -> Result<(Self, Vec<(u32, u32)>), KapError> {
702        let k = self.k_orig;
703        let full = u64::MAX >> (64 - k);
704        if self.n_parts() != 1
705            || root.k_orig != k
706            || root.n_parts() != k
707            || (0..k).any(|p| root.members(p) != 1 << p)
708            || mask == 0
709            || mask == full
710            || mask & !full != 0
711        {
712            return Err(KapError::BadMatching);
713        }
714        let masks = if mask & 1 != 0 {
715            [mask, full ^ mask]
716        } else {
717            [full ^ mask, mask]
718        };
719        let mut counts = vec![0; k];
720        for node in self.parts[0].nodes.chunks_exact(k) {
721            for (p, &v) in node.iter().enumerate() {
722                if v != NONE {
723                    if v as usize >= root.n_nodes(p) {
724                        return Err(KapError::BadMatching);
725                    }
726                    counts[p] += 1;
727                }
728            }
729        }
730        if (0..k).any(|p| counts[p] != root.n_nodes(p)) {
731            return Err(KapError::BadMatching);
732        }
733        let mut nodes = [Vec::new(), Vec::new()];
734        let mut matching = Vec::new();
735        for node in self.parts[0].nodes.chunks_exact(k) {
736            let mut ids = [None, None];
737            for side in 0..2 {
738                if (0..k).any(|p| masks[side] & (1 << p) != 0 && node[p] != NONE) {
739                    ids[side] = Some((nodes[side].len() / k) as u32);
740                    nodes[side].extend(
741                        node.iter()
742                            .enumerate()
743                            .map(|(p, &v)| if masks[side] & (1 << p) != 0 { v } else { NONE }),
744                    );
745                }
746            }
747            if let [Some(r), Some(c)] = ids {
748                matching.push((r, c));
749            }
750        }
751        let mut parts = Vec::with_capacity(2);
752        let mut score = A::ZERO;
753        for (side, nodes) in nodes.into_iter().enumerate() {
754            let mut costs = vec![A::ZERO; nodes.len() / k];
755            for a in 0..k {
756                for b in a + 1..k {
757                    if masks[side] & (1 << a) == 0 || masks[side] & (1 << b) == 0 {
758                        continue;
759                    }
760                    let m = root.matrix(a, b);
761                    for (node, cost) in nodes.chunks_exact(k).zip(&mut costs) {
762                        if node[a] != NONE && node[b] != NONE {
763                            *cost = *cost + m.get(node[a] as usize, node[b] as usize);
764                        }
765                    }
766                }
767            }
768            for &cost in &costs {
769                score = score + cost;
770            }
771            parts.push(Part {
772                members: masks[side],
773                nodes: nodes.into(),
774                costs: costs.into(),
775            });
776        }
777        let (nr, nc) = (parts[0].costs.len(), parts[1].costs.len());
778        let mut data = vec![A::ZERO; nr * nc];
779        let mut scratch = Vec::new();
780        if nr != 0 && nc != 0 {
781            for a in 0..k {
782                if masks[0] & (1 << a) == 0 {
783                    continue;
784                }
785                for b in 0..k {
786                    if masks[1] & (1 << b) == 0 {
787                        continue;
788                    }
789                    // Orient each original matrix once; its rows are contiguous.
790                    let m: &[A] = if a < b {
791                        &root.matrices[index(k, a, b)].data
792                    } else {
793                        let src = &root.matrices[index(k, b, a)].data;
794                        transpose_into(&mut scratch, src, root.n_nodes(b), root.n_nodes(a));
795                        &scratch
796                    };
797                    let nb = root.n_nodes(b);
798                    for (dst, row) in data
799                        .chunks_exact_mut(nc)
800                        .zip(parts[0].nodes.chunks_exact(k))
801                    {
802                        if row[a] == NONE {
803                            continue;
804                        }
805                        let r = row[a] as usize;
806                        let src = &m[r * nb..(r + 1) * nb];
807                        for (out, col) in dst.iter_mut().zip(parts[1].nodes.chunks_exact(k)) {
808                            if col[b] != NONE {
809                                *out = *out + src[col[b] as usize];
810                            }
811                        }
812                    }
813                }
814            }
815        }
816        // Without gating, a largest original part fills every node, so the
817        // induced matching is maximum-cardinality and LAP preserves node count.
818        // With gating it is a feasible partial matching; solve_pair may drop
819        // edges and dissolve nodes while improving the shifted objective.
820        Ok((
821            Self {
822                k_orig: k,
823                gated: self.gated,
824                parts,
825                matrices: vec![Dense {
826                    data: data.into(),
827                    rows: nr,
828                    cols: nc,
829                }],
830                score,
831            },
832            matching,
833        ))
834    }
835
836    /// Induced edges between two original partites, sorted by the first vertex.
837    pub fn edges_between(&self, a: usize, b: usize) -> Vec<(u32, u32)> {
838        assert!(a < self.k_orig && b < self.k_orig && a != b);
839        let mut edges = Vec::new();
840        for part in &self.parts {
841            for node in part.nodes.chunks_exact(self.k_orig) {
842                if node[a] != NONE && node[b] != NONE {
843                    edges.push((node[a], node[b]));
844                }
845            }
846        }
847        edges.sort_unstable();
848        edges
849    }
850
851    /// Canonical fingerprint of the vertex partition: for every original vertex,
852    /// in (partite, vertex) order, the global index of the first member of its
853    /// node. Two states have equal labels iff they group the vertices alike.
854    pub fn labels(&self) -> Vec<u32> {
855        let k = self.k_orig;
856        let mut sizes = vec![0usize; k];
857        for part in &self.parts {
858            for node in part.nodes.chunks_exact(k) {
859                for (p, &v) in node.iter().enumerate() {
860                    if v != NONE {
861                        sizes[p] += 1;
862                    }
863                }
864            }
865        }
866        let mut offsets = vec![0usize; k];
867        for p in 1..k {
868            offsets[p] = offsets[p - 1] + sizes[p - 1];
869        }
870        let mut labels = vec![0u32; offsets[k - 1] + sizes[k - 1]];
871        for part in &self.parts {
872            for node in part.nodes.chunks_exact(k) {
873                let mut first = None;
874                for (p, &v) in node.iter().enumerate() {
875                    if v != NONE {
876                        let g = offsets[p] + v as usize;
877                        let label = *first.get_or_insert(g as u32);
878                        labels[g] = label;
879                    }
880                }
881            }
882        }
883        labels
884    }
885
886    /// Reconstruct cliques and singleton vertices (also valid for intermediate states).
887    pub fn reconstruct(&self) -> KSolution<A> {
888        let mut sol = KSolution {
889            cliques: Vec::new(),
890            costs: Vec::new(),
891            free: Vec::new(),
892            cost: A::ZERO,
893        };
894        for part in &self.parts {
895            for (node, &cost) in part.nodes.chunks_exact(self.k_orig).zip(part.costs.iter()) {
896                let clique: Vec<_> = node
897                    .iter()
898                    .enumerate()
899                    .filter(|&(_, &v)| v != NONE)
900                    .map(|(p, &v)| (p, v as usize))
901                    .collect();
902                if clique.len() >= 2 {
903                    sol.cliques.push(clique);
904                    sol.costs.push(cost);
905                    sol.cost = sol.cost + cost;
906                } else {
907                    sol.free.extend(clique);
908                }
909            }
910        }
911        sol
912    }
913}
914
915#[cfg(test)]
916thread_local! { pub(crate) static LAP_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
917
918#[cfg(test)]
919#[path = "kpartite_tests.rs"]
920mod tests;