1use std::{fmt, sync::Arc};
4
5use crate::{Acc, Cost, LapError, LapSolver, MatrixView, Sense};
6
7pub const NONE: u32 = u32::MAX;
9
10#[derive(Clone, Debug, PartialEq, Eq)]
12pub enum KapError {
13 BadCount(usize),
15 ShapeMismatch {
17 matrix: usize,
19 partite: usize,
21 expected: usize,
23 actual: usize,
25 },
26 BadMatching,
28 IncompleteInitial {
30 expected: usize,
32 actual: usize,
34 },
35 ForbiddenInitial,
37 TooManyVertices(usize),
39 Lap(LapError),
41 BadOption(&'static str),
43 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
108fn 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#[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 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 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 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 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 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#[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 pub score: A,
279}
280
281#[derive(Clone, Debug, PartialEq)]
286pub struct KSolution<A> {
287 pub cliques: Vec<Vec<(usize, usize)>>,
289 pub costs: Vec<A>,
291 pub free: Vec<(usize, usize)>,
293 pub cost: A,
295}
296
297impl<A: Acc + Cost<Acc = A>> Quotient<A> {
298 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 pub fn from_nodes(root: &Self, nodes: Vec<u32>) -> Result<Self, KapError> {
330 Self::from_nodes_impl::<false>(root, nodes)
331 }
332
333 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 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 pub fn n_parts(&self) -> usize {
415 self.parts.len()
416 }
417
418 pub fn n_nodes(&self, part: usize) -> usize {
420 self.parts[part].costs.len()
421 }
422
423 pub fn members(&self, part: usize) -> u64 {
425 self.parts[part].members
426 }
427
428 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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;