pysimplicial 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1375 @@
1
+ """Exact cover of a complex by strongly collapsible subcomplexes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from time import perf_counter
7
+ from typing import Any, Callable, Hashable, Iterable, Iterator, Sequence
8
+ from itertools import groupby
9
+
10
+ import numpy as np
11
+
12
+
13
+ try: # CUDA is optional; the CPU path remains fully exact.
14
+ from numba import cuda
15
+
16
+ _NUMBA_CUDA_IMPORTED = True
17
+ except Exception: # pragma: no cover - depends on the local CUDA installation.
18
+ cuda = None
19
+ _NUMBA_CUDA_IMPORTED = False
20
+
21
+
22
+ from .._errors import SearchLimitExceeded
23
+ from .set_cover import _iter_bits, minimum_set_cover
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ExactGSCATResult:
28
+ """Result and independently checkable cover returned by :func:`exact_gscat`.
29
+
30
+ ``gscat`` uses the reduced convention: a cover by ``r`` strongly
31
+ collapsible subcomplexes has value ``r - 1``.
32
+ """
33
+
34
+ gscat: int
35
+ cover: tuple[tuple[tuple[Hashable, ...], ...], ...]
36
+ cover_maximal_simplices: tuple[tuple[tuple[Hashable, ...], ...], ...]
37
+ method: str
38
+ exact: bool = True
39
+ gpu_used: bool = False
40
+ statistics: dict[str, Any] = field(default_factory=dict)
41
+
42
+ @property
43
+ def cover_count(self) -> int:
44
+ return len(self.cover)
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class _Encoding:
49
+ labels: tuple[Hashable, ...]
50
+ label_to_vertex: dict[Hashable, int]
51
+ facets: tuple[int, ...]
52
+ simplices: tuple[int, ...]
53
+ simplex_to_index: dict[int, int]
54
+ facet_simplex_indices: tuple[int, ...]
55
+
56
+ @property
57
+ def dimension(self) -> int:
58
+ return max((x.bit_count() for x in self.facets), default=0) - 1
59
+
60
+ @property
61
+ def vertex_count(self) -> int:
62
+ return len(self.labels)
63
+
64
+
65
+ def _maximal_masks(masks: Iterable[int]) -> tuple[int, ...]:
66
+ """Return the inclusion-maximal non-empty masks, deterministically."""
67
+ unique = sorted(set(int(x) for x in masks if x), key=lambda x: (-x.bit_count(), x))
68
+ maximal: list[int] = []
69
+ for simplex in unique:
70
+ if not any(simplex != other and (simplex & other) == simplex for other in maximal):
71
+ maximal.append(simplex)
72
+ return tuple(sorted(maximal, key=lambda x: (x.bit_count(), x)))
73
+
74
+
75
+ def _encode(maximal_simplices: Iterable[Iterable[Hashable]]) -> _Encoding:
76
+ raw: list[tuple[Hashable, ...]] = []
77
+ label_to_vertex: dict[Hashable, int] = {}
78
+ labels: list[Hashable] = []
79
+
80
+ for simplex in maximal_simplices:
81
+ values = tuple(dict.fromkeys(simplex))
82
+ if not values:
83
+ continue
84
+ raw.append(values)
85
+ for vertex in values:
86
+ if vertex not in label_to_vertex:
87
+ label_to_vertex[vertex] = len(labels)
88
+ labels.append(vertex)
89
+
90
+ if not raw:
91
+ return _Encoding(tuple(), {}, tuple(), tuple(), {}, tuple())
92
+
93
+ masks = []
94
+ for simplex in raw:
95
+ mask = 0
96
+ for vertex in simplex:
97
+ mask |= 1 << label_to_vertex[vertex]
98
+ masks.append(mask)
99
+
100
+ facets = _maximal_masks(masks)
101
+
102
+ closure: set[int] = set()
103
+ for facet in facets:
104
+ face = facet
105
+ while face:
106
+ closure.add(face)
107
+ face = (face - 1) & facet
108
+
109
+ simplices = tuple(sorted(closure, key=lambda x: (x.bit_count(), x)))
110
+ simplex_to_index = {simplex: i for i, simplex in enumerate(simplices)}
111
+ facet_simplex_indices = tuple(simplex_to_index[facet] for facet in facets)
112
+
113
+ return _Encoding(
114
+ labels=tuple(labels),
115
+ label_to_vertex=label_to_vertex,
116
+ facets=facets,
117
+ simplices=simplices,
118
+ simplex_to_index=simplex_to_index,
119
+ facet_simplex_indices=facet_simplex_indices,
120
+ )
121
+
122
+
123
+ def _decode_simplex(mask: int, labels: Sequence[Hashable]) -> tuple[Hashable, ...]:
124
+ return tuple(labels[i] for i in _iter_bits(mask))
125
+
126
+
127
+ def _normalize_after_vertex_deletions(
128
+ original_maximal_simplices: Sequence[int], active_vertices: int
129
+ ) -> tuple[int, ...]:
130
+ return _maximal_masks(simplex & active_vertices for simplex in original_maximal_simplices)
131
+
132
+
133
+ def is_strongly_collapsible(maximal_simplex_masks: Iterable[int]) -> bool:
134
+ """Exact CPU test for strong collapsibility from maximal simplex bitmasks."""
135
+ original = _maximal_masks(maximal_simplex_masks)
136
+ if not original:
137
+ return False
138
+
139
+ active = 0
140
+ for simplex in original:
141
+ active |= simplex
142
+
143
+ while active.bit_count() > 1:
144
+ maximals = _normalize_after_vertex_deletions(original, active)
145
+ deleted = False
146
+
147
+ for v in _iter_bits(active):
148
+ v_bit = 1 << v
149
+ # A dominator belongs to every maximal simplex containing v.
150
+ # Their intersection tests all possible dominators at once.
151
+ common = active
152
+ found = False
153
+ for simplex in maximals:
154
+ if simplex & v_bit:
155
+ found = True
156
+ common &= simplex
157
+ if common == v_bit:
158
+ break
159
+ if found and (common & ~v_bit):
160
+ active ^= v_bit
161
+ deleted = True
162
+ break
163
+
164
+ if not deleted:
165
+ return False
166
+
167
+ return active != 0
168
+
169
+
170
+ if _NUMBA_CUDA_IMPORTED: # Definitions are conditional so NumPy-only use works.
171
+
172
+ @cuda.jit(device=True)
173
+ def _gpu_popcount(value):
174
+ count = 0
175
+ one = np.uint64(1)
176
+ while value != 0:
177
+ value = value & (value - one)
178
+ count += 1
179
+ return count
180
+
181
+
182
+ @cuda.jit
183
+ def _strong_collapse_batch_kernel(maxima, counts, vertex_count, output):
184
+ """One exact strong-collapse test per CUDA thread."""
185
+ row = cuda.grid(1)
186
+ if row >= counts.shape[0]:
187
+ return
188
+
189
+ face_count = counts[row]
190
+ active = np.uint64(0)
191
+ for j in range(face_count):
192
+ active |= maxima[row, j]
193
+
194
+ one = np.uint64(1)
195
+
196
+ while True:
197
+ if _gpu_popcount(active) <= 1:
198
+ output[row] = 1 if active != 0 else 0
199
+ return
200
+
201
+ deleted = 0
202
+
203
+ for v in range(vertex_count):
204
+ v_bit = one << np.uint64(v)
205
+ if (active & v_bit) == 0:
206
+ continue
207
+
208
+ common = active
209
+ has_maximal_with_v = 0
210
+ for j in range(face_count):
211
+ face_j = maxima[row, j] & active
212
+ if (face_j & v_bit) == 0:
213
+ continue
214
+
215
+ is_maximal = 1
216
+ for k in range(face_count):
217
+ face_k = maxima[row, k] & active
218
+ if face_j != face_k and (face_j & face_k) == face_j:
219
+ is_maximal = 0
220
+ break
221
+
222
+ if is_maximal == 0:
223
+ continue
224
+ has_maximal_with_v = 1
225
+ common &= face_j
226
+ if common == v_bit:
227
+ break
228
+
229
+ if has_maximal_with_v == 1 and (common & (active ^ v_bit)) != 0:
230
+ active ^= v_bit
231
+ deleted = 1
232
+ break
233
+
234
+ if deleted == 0:
235
+ output[row] = 0
236
+ return
237
+
238
+
239
+ @cuda.jit
240
+ def _maximal_extension_batch_kernel(
241
+ state_words,
242
+ task_state,
243
+ task_pair,
244
+ rule_offsets,
245
+ rule_output_simplex,
246
+ rule_required_simplex,
247
+ output_words,
248
+ ):
249
+ """Construct one maximal dominated-vertex extension per CUDA thread."""
250
+ task = cuda.grid(1)
251
+ if task >= task_state.shape[0]:
252
+ return
253
+
254
+ state_index = task_state[task]
255
+ for word in range(state_words.shape[1]):
256
+ output_words[task, word] = state_words[state_index, word]
257
+
258
+ pair = task_pair[task]
259
+ first_rule = rule_offsets[pair]
260
+ last_rule = rule_offsets[pair + 1]
261
+ one = np.uint64(1)
262
+
263
+ for rule in range(first_rule, last_rule):
264
+ required = rule_required_simplex[rule]
265
+ required_word = required // 64
266
+ required_bit = required - 64 * required_word
267
+
268
+ if (state_words[state_index, required_word] & (one << np.uint64(required_bit))) == 0:
269
+ continue
270
+
271
+ output_simplex = rule_output_simplex[rule]
272
+ output_word = output_simplex // 64
273
+ output_bit = output_simplex - 64 * output_word
274
+ output_words[task, output_word] |= one << np.uint64(output_bit)
275
+
276
+
277
+ def cuda_is_available() -> bool:
278
+ if not _NUMBA_CUDA_IMPORTED:
279
+ return False
280
+ try:
281
+ return bool(cuda.is_available())
282
+ except Exception:
283
+ return False
284
+
285
+
286
+ class _StrongCollapseTester:
287
+ def __init__(self, use_gpu: bool, vertex_count: int, threads_per_block: int = 64):
288
+ self.vertex_count = vertex_count
289
+ self.threads_per_block = threads_per_block
290
+ self._use_gpu = bool(use_gpu and vertex_count <= 64 and cuda_is_available())
291
+ self.gpu_used = False
292
+
293
+ def test(self, batch: Sequence[Sequence[int]]) -> np.ndarray:
294
+ if not batch:
295
+ return np.empty(0, dtype=np.uint8)
296
+
297
+ if not self._use_gpu:
298
+ return np.fromiter(
299
+ (1 if is_strongly_collapsible(row) else 0 for row in batch),
300
+ dtype=np.uint8,
301
+ count=len(batch),
302
+ )
303
+
304
+ width = max(len(row) for row in batch)
305
+ maxima = np.zeros((len(batch), width), dtype=np.uint64)
306
+ counts = np.empty(len(batch), dtype=np.int32)
307
+
308
+ for i, row in enumerate(batch):
309
+ counts[i] = len(row)
310
+ maxima[i, : len(row)] = np.asarray(row, dtype=np.uint64)
311
+
312
+ d_maxima = cuda.to_device(maxima)
313
+ d_counts = cuda.to_device(counts)
314
+ d_output = cuda.device_array(len(batch), dtype=np.uint8)
315
+ blocks = (len(batch) + self.threads_per_block - 1) // self.threads_per_block
316
+ _strong_collapse_batch_kernel[blocks, self.threads_per_block](
317
+ d_maxima, d_counts, self.vertex_count, d_output
318
+ )
319
+ result = d_output.copy_to_host()
320
+ self.gpu_used = True
321
+ return result
322
+
323
+
324
+ def _ideals_to_words(ideals: Sequence[int], word_count: int) -> np.ndarray:
325
+ words = np.zeros((len(ideals), word_count), dtype=np.uint64)
326
+ word_mask = (1 << 64) - 1
327
+ for row, ideal in enumerate(ideals):
328
+ for word in range(word_count):
329
+ words[row, word] = (ideal >> (64 * word)) & word_mask
330
+ return words
331
+
332
+
333
+ def _words_to_ideals(words: np.ndarray) -> list[int]:
334
+ ideals = []
335
+ for row in words:
336
+ ideal = 0
337
+ for word, value in enumerate(row):
338
+ ideal |= int(value) << (64 * word)
339
+ ideals.append(ideal)
340
+ return ideals
341
+
342
+
343
+ @dataclass(frozen=True)
344
+ class _ExtensionRules:
345
+ python_rules: tuple[tuple[tuple[int, int], ...], ...]
346
+ offsets: np.ndarray
347
+ output_simplex: np.ndarray
348
+ required_simplex: np.ndarray
349
+
350
+
351
+ def _build_extension_rules(encoding: _Encoding) -> _ExtensionRules:
352
+ """Precompute maximal extensions for every ordered vertex pair (v, u).
353
+
354
+ A rule ``(s, r)`` means: when simplex ``r`` belongs to the current
355
+ strongly collapsible subcomplex J, include simplex ``s`` in the maximal
356
+ extension which adds v dominated by u.
357
+ """
358
+ n = encoding.vertex_count
359
+ rules: list[tuple[tuple[int, int], ...]] = []
360
+ flat_output: list[int] = []
361
+ flat_required: list[int] = []
362
+ offsets = [0]
363
+
364
+ for v in range(n):
365
+ v_bit = 1 << v
366
+ for u in range(n):
367
+ pair_rules: list[tuple[int, int]] = []
368
+ if u != v:
369
+ u_bit = 1 << u
370
+ for simplex_index, simplex in enumerate(encoding.simplices):
371
+ if not (simplex & v_bit):
372
+ continue
373
+
374
+ extended = simplex | u_bit
375
+ if extended not in encoding.simplex_to_index:
376
+ continue
377
+
378
+ required_face = (simplex & ~v_bit) | u_bit
379
+ required_index = encoding.simplex_to_index.get(required_face)
380
+ if required_index is None:
381
+ continue
382
+
383
+ pair_rules.append((simplex_index, required_index))
384
+ flat_output.append(simplex_index)
385
+ flat_required.append(required_index)
386
+
387
+ rules.append(tuple(pair_rules))
388
+ offsets.append(len(flat_output))
389
+
390
+ return _ExtensionRules(
391
+ python_rules=tuple(rules),
392
+ offsets=np.asarray(offsets, dtype=np.int64),
393
+ output_simplex=np.asarray(flat_output, dtype=np.int32),
394
+ required_simplex=np.asarray(flat_required, dtype=np.int32),
395
+ )
396
+
397
+
398
+ class _MaximalExtensionEngine:
399
+ """CPU/CUDA engine for exact dominated-vertex extensions."""
400
+
401
+ def __init__(
402
+ self,
403
+ encoding: _Encoding,
404
+ rules: _ExtensionRules,
405
+ *,
406
+ use_gpu: bool,
407
+ batch_size: int,
408
+ threads_per_block: int = 128,
409
+ ):
410
+ self.encoding = encoding
411
+ self.rules = rules
412
+ self.batch_size = batch_size
413
+ self.threads_per_block = threads_per_block
414
+ self.word_count = (len(encoding.simplices) + 63) // 64
415
+ self._use_gpu = bool(use_gpu and cuda_is_available())
416
+ self.gpu_used = False
417
+ # Several output simplices can share the same prerequisite. Group
418
+ # them and compute the arbitrary-width Python bitmasks only once.
419
+ cpu_rules = []
420
+ for pair_rules in rules.python_rules:
421
+ grouped: dict[int, int] = {}
422
+ for output_index, required_index in pair_rules:
423
+ required_bit = 1 << required_index
424
+ grouped[required_bit] = grouped.get(required_bit, 0) | (1 << output_index)
425
+ cpu_rules.append(tuple(grouped.items()))
426
+ self.cpu_rules = tuple(cpu_rules)
427
+ self._device_rules = None
428
+
429
+ def _cpu_extend(self, state: int, pair: int) -> int:
430
+ result = state
431
+ for required_bit, output_bits in self.cpu_rules[pair]:
432
+ if state & required_bit:
433
+ result |= output_bits
434
+ return result
435
+
436
+ def extend_tasks(
437
+ self,
438
+ states: Sequence[int],
439
+ tasks: Sequence[tuple[int, int]],
440
+ ) -> list[int]:
441
+ """Return maximal extensions for ``(state_index, pair_index)`` tasks."""
442
+ if not tasks:
443
+ return []
444
+ if not self._use_gpu:
445
+ return [self._cpu_extend(states[state], pair) for state, pair in tasks]
446
+
447
+ state_words = _ideals_to_words(states, self.word_count)
448
+ d_states = cuda.to_device(state_words)
449
+ # These arrays are immutable for the lifetime of this engine.
450
+ if self._device_rules is None:
451
+ self._device_rules = (
452
+ cuda.to_device(self.rules.offsets),
453
+ cuda.to_device(self.rules.output_simplex),
454
+ cuda.to_device(self.rules.required_simplex),
455
+ )
456
+ d_offsets, d_output_simplex, d_required_simplex = self._device_rules
457
+
458
+ result: list[int] = []
459
+ for start in range(0, len(tasks), self.batch_size):
460
+ chunk = tasks[start : start + self.batch_size]
461
+ task_state = np.fromiter((x[0] for x in chunk), dtype=np.int32, count=len(chunk))
462
+ task_pair = np.fromiter((x[1] for x in chunk), dtype=np.int32, count=len(chunk))
463
+ d_task_state = cuda.to_device(task_state)
464
+ d_task_pair = cuda.to_device(task_pair)
465
+ d_output = cuda.device_array((len(chunk), self.word_count), dtype=np.uint64)
466
+ blocks = (len(chunk) + self.threads_per_block - 1) // self.threads_per_block
467
+
468
+ _maximal_extension_batch_kernel[blocks, self.threads_per_block](
469
+ d_states,
470
+ d_task_state,
471
+ d_task_pair,
472
+ d_offsets,
473
+ d_output_simplex,
474
+ d_required_simplex,
475
+ d_output,
476
+ )
477
+ result.extend(_words_to_ideals(d_output.copy_to_host()))
478
+ self.gpu_used = True
479
+
480
+ return result
481
+
482
+
483
+ def _face_poset_relations(encoding: _Encoding) -> tuple[tuple[int, ...], tuple[int, ...]]:
484
+ simplices = encoding.simplices
485
+ count = len(simplices)
486
+ up = [0] * count
487
+ down = [0] * count
488
+
489
+ for i, small in enumerate(simplices):
490
+ for j, large in enumerate(simplices):
491
+ if (small & large) == small:
492
+ up[i] |= 1 << j
493
+ down[j] |= 1 << i
494
+
495
+ return tuple(up), tuple(down)
496
+
497
+
498
+ def _choose_ideal_branch_element(available: int, up: Sequence[int], down: Sequence[int]) -> int:
499
+ """Choose a deterministic, approximately balanced branch in the face poset."""
500
+ best_index = -1
501
+ best_score = -1
502
+ for i in _iter_bits(available):
503
+ above = (available & up[i]).bit_count()
504
+ below = (available & down[i]).bit_count()
505
+ score = min(above, below)
506
+ if score > best_score:
507
+ best_score = score
508
+ best_index = i
509
+ return best_index
510
+
511
+
512
+ def _iter_order_ideals(up: Sequence[int], down: Sequence[int]) -> Iterator[int]:
513
+ """Enumerate every order ideal of a finite poset exactly once."""
514
+ full = (1 << len(up)) - 1
515
+
516
+ def visit(available: int, included: int) -> Iterator[int]:
517
+ if available == 0:
518
+ yield included
519
+ return
520
+
521
+ i = _choose_ideal_branch_element(available, up, down)
522
+
523
+ # Excluding i forces exclusion of every element above i.
524
+ yield from visit(available & ~up[i], included)
525
+
526
+ # Including i forces inclusion of every still-available element below i.
527
+ forced = available & down[i]
528
+ yield from visit(available & ~forced, included | forced)
529
+
530
+ yield from visit(full, 0)
531
+
532
+
533
+ def _maximal_faces_of_ideal(ideal: int, strict_up: Sequence[int], simplices: Sequence[int]) -> tuple[int, ...]:
534
+ result = []
535
+ for i in _iter_bits(ideal):
536
+ if (ideal & strict_up[i]) == 0:
537
+ result.append(simplices[i])
538
+ return tuple(result)
539
+
540
+
541
+ def _facet_coverage(ideal: int, facet_simplex_indices: Sequence[int]) -> int:
542
+ coverage = 0
543
+ for j, simplex_index in enumerate(facet_simplex_indices):
544
+ if ideal & (1 << simplex_index):
545
+ coverage |= 1 << j
546
+ return coverage
547
+
548
+
549
+ def _maximal_masks_indexed(ideals):
550
+ """As above, omitting equal-size masks from superset queries."""
551
+ ordered = sorted(set(int(x) for x in ideals if x), key=lambda x: (-x.bit_count(), x))
552
+ return _maximal_ordered_grouped_bitsets(ordered)
553
+
554
+
555
+ def _maximal_ordered_grouped_bitsets(ordered):
556
+ if not ordered:
557
+ return ()
558
+ minimum_size = ordered[-1].bit_count()
559
+ if ordered[0].bit_count() == minimum_size:
560
+ return tuple(ordered)
561
+ postings = [0] * max(x.bit_length() for x in ordered)
562
+ counts = [0] * len(postings)
563
+ kept = []
564
+ for size, group in groupby(ordered, int.bit_count):
565
+ additions = []
566
+ for candidate in group:
567
+ bits = tuple(_iter_bits(candidate))
568
+ rare = min(bits, key=counts.__getitem__)
569
+ possible = postings[rare]
570
+ if possible:
571
+ for bit in bits:
572
+ possible &= postings[bit]
573
+ if not possible:
574
+ break
575
+ if not possible:
576
+ additions.append((candidate, bits))
577
+ if size == minimum_size:
578
+ kept.extend(candidate for candidate, _ in additions)
579
+ break
580
+ for candidate, bits in additions:
581
+ flag = 1 << len(kept)
582
+ kept.append(candidate)
583
+ for bit in bits:
584
+ postings[bit] |= flag
585
+ counts[bit] += 1
586
+ return tuple(kept)
587
+
588
+
589
+ def _maximal_level_ideals(ideals, vertex_count):
590
+ """Filter one fixed-vertex-count level, grouping by vertex support.
591
+
592
+ The first ``vertex_count`` simplex positions must be the singleton faces.
593
+ All nonzero input ideals must use the same number of vertices. Otherwise
594
+ this routine falls back to global filtering to preserve exactness.
595
+ """
596
+ mask = (1 << vertex_count) - 1
597
+ groups = {}
598
+ support_sizes = set()
599
+ for ideal in ideals:
600
+ ideal = int(ideal)
601
+ if ideal:
602
+ support = ideal & mask
603
+ support_sizes.add(support.bit_count())
604
+ groups.setdefault(support, set()).add(ideal)
605
+ if len(support_sizes) > 1:
606
+ return _maximal_masks_indexed(x for group in groups.values() for x in group)
607
+ kept = []
608
+ for support, group in groups.items():
609
+ if len(group) == 1:
610
+ kept.extend(group)
611
+ continue
612
+ # Every mask in this group has these singleton bits. Removing them
613
+ # preserves inclusion, cardinality ordering and numeric tie-breaking.
614
+ kept.extend(ideal | support for ideal in _maximal_masks_indexed(
615
+ ideal ^ support for ideal in group
616
+ ))
617
+ return tuple(sorted(kept, key=lambda x: (-x.bit_count(), x)))
618
+
619
+
620
+ def _maximal_coverages(coverages: Iterable[int]) -> tuple[int, ...]:
621
+ """Remove coverages contained in another mask, using inverted bitsets."""
622
+ return _maximal_masks_indexed(coverages)
623
+
624
+
625
+ def _maximal_ideals(ideals: Iterable[int]) -> tuple[int, ...]:
626
+ """Keep inclusion-maximal ideals; preserve the original deterministic order."""
627
+ return _maximal_masks_indexed(ideals)
628
+
629
+
630
+ def _generate_candidates_by_collapse_certificates(
631
+ encoding: _Encoding,
632
+ *,
633
+ use_gpu: bool,
634
+ batch_size: int,
635
+ max_candidate_states: int | None,
636
+ progress: Callable[[dict], None] | None,
637
+ ) -> tuple[dict[int, int], dict[str, Any], bool]:
638
+ """Generate a complete dominating family of strongly collapsible subcomplexes.
639
+
640
+ Let J be strongly collapsible, let v be absent from J, and let u be a
641
+ vertex of J. There is a unique largest subcomplex L of K such that
642
+
643
+ * L without v equals J; and
644
+ * v is dominated by u in L.
645
+
646
+ It contains exactly those v-simplices sigma for which both sigma union u
647
+ is a simplex of K and (sigma without v) union u belongs to J.
648
+
649
+ Starting with one-point complexes and repeatedly taking every such maximal
650
+ extension is complete for gscat: reverse any strong-collapse sequence of
651
+ any candidate U. At each reversed step the generated maximal extension
652
+ contains the corresponding partial U. Hence U is contained in a generated
653
+ terminal candidate, which can replace U in a cover. This proves that the
654
+ family returned here is sufficient for an exact minimum-cover proof without
655
+ enumerating every order ideal of the face poset.
656
+ """
657
+ started = perf_counter()
658
+ n = encoding.vertex_count
659
+ rules = _build_extension_rules(encoding)
660
+ engine = _MaximalExtensionEngine(
661
+ encoding,
662
+ rules,
663
+ use_gpu=use_gpu,
664
+ batch_size=batch_size,
665
+ )
666
+
667
+ vertex_ideal_bits = tuple(
668
+ 1 << encoding.simplex_to_index[1 << vertex] for vertex in range(n)
669
+ )
670
+ current = tuple(vertex_ideal_bits)
671
+ terminal: set[int] = set()
672
+ generated_total = len(current)
673
+ attempted_extensions = 0
674
+ level_sizes: list[int] = []
675
+ extension_seconds = 0.0
676
+ dominance_seconds = 0.0
677
+
678
+ for level in range(1, n + 1):
679
+ if not current:
680
+ break
681
+ level_sizes.append(len(current))
682
+
683
+ states = list(current)
684
+ tasks: list[tuple[int, int]] = []
685
+
686
+ for state_index, state in enumerate(states):
687
+ vertices = 0
688
+ for vertex, singleton_bit in enumerate(vertex_ideal_bits):
689
+ if state & singleton_bit:
690
+ vertices |= 1 << vertex
691
+
692
+ for v in range(n):
693
+ if vertices & (1 << v):
694
+ continue
695
+ for u in _iter_bits(vertices):
696
+ pair = v * n + u
697
+ if rules.python_rules[pair]:
698
+ tasks.append((state_index, pair))
699
+
700
+ extension_started = perf_counter()
701
+ outputs = engine.extend_tasks(states, tasks)
702
+ extension_seconds += perf_counter() - extension_started
703
+ attempted_extensions += len(tasks)
704
+ expanded_states: set[int] = set()
705
+ next_states: set[int] = set()
706
+
707
+ for (state_index, pair), extension in zip(tasks, outputs):
708
+ state = states[state_index]
709
+ if extension == state:
710
+ continue
711
+
712
+ v = pair // n
713
+ singleton_bit = vertex_ideal_bits[v]
714
+ if not (extension & singleton_bit):
715
+ raise RuntimeError(
716
+ "Internal extension error: a non-trivial extension did not add its vertex."
717
+ )
718
+
719
+ expanded_states.add(state_index)
720
+ next_states.add(extension)
721
+
722
+ for state_index, state in enumerate(states):
723
+ if state_index not in expanded_states:
724
+ terminal.add(state)
725
+
726
+ dominance_started = perf_counter()
727
+ current = _maximal_level_ideals(next_states, n)
728
+ dominance_seconds += perf_counter() - dominance_started
729
+ generated_total += len(current)
730
+ if max_candidate_states is not None and generated_total > max_candidate_states:
731
+ raise SearchLimitExceeded(
732
+ "Collapse-certificate generation exceeded max_candidate_states="
733
+ f"{max_candidate_states:,}.",
734
+ gpu_used=engine.gpu_used,
735
+ )
736
+
737
+ if progress:
738
+ elapsed = perf_counter() - started
739
+ progress({
740
+ "phase": "exact_candidates", "level": level,
741
+ "states": len(states), "next_states": len(current),
742
+ "terminal": len(terminal), "extensions": attempted_extensions,
743
+ "seconds": elapsed,
744
+ })
745
+
746
+ terminal.update(current)
747
+ dominance_started = perf_counter()
748
+ maximal_terminal = _maximal_ideals(terminal)
749
+ dominance_seconds += perf_counter() - dominance_started
750
+
751
+ # No further extensions follow this stage. It is now safe to identify
752
+ # candidates by their facet coverage, which would NOT be safe inside the
753
+ # dynamic program (lower faces can affect later extensions).
754
+ witnesses: dict[int, int] = {}
755
+ for ideal in maximal_terminal:
756
+ coverage = _facet_coverage(ideal, encoding.facet_simplex_indices)
757
+ if coverage:
758
+ previous = witnesses.get(coverage)
759
+ if previous is None or previous.bit_count() < ideal.bit_count():
760
+ witnesses[coverage] = ideal
761
+ coverage_count_before_dominance = len(witnesses)
762
+ retained_coverages = _maximal_coverages(witnesses)
763
+ witnesses = {coverage: witnesses[coverage] for coverage in retained_coverages}
764
+
765
+ # Validate every retained witness independently before it enters the
766
+ # minimum-cover proof. Removed coverages are contained in retained ones
767
+ # and cannot improve a cover. Final chosen witnesses are checked on CPU
768
+ # again by _verify_general_cover, including when generation uses CUDA.
769
+ validation_started = perf_counter()
770
+ up, _ = _face_poset_relations(encoding)
771
+ strict_up = tuple(up[i] & ~(1 << i) for i in range(len(up)))
772
+ retained_ideals = tuple(witnesses.values())
773
+ validator = _StrongCollapseTester(
774
+ use_gpu=use_gpu,
775
+ vertex_count=encoding.vertex_count,
776
+ )
777
+ for start in range(0, len(retained_ideals), batch_size):
778
+ maxima = [
779
+ _maximal_faces_of_ideal(ideal, strict_up, encoding.simplices)
780
+ for ideal in retained_ideals[start : start + batch_size]
781
+ ]
782
+ valid = validator.test(maxima)
783
+ if not np.all(valid == 1):
784
+ bad = start + int(np.flatnonzero(valid != 1)[0])
785
+ raise RuntimeError(
786
+ "A collapse-certificate candidate failed independent validation "
787
+ f"at index {bad}. The exact computation was aborted."
788
+ )
789
+
790
+ stats = {
791
+ "collapse_certificate_states": generated_total,
792
+ "collapse_certificate_terminal_states": len(maximal_terminal),
793
+ "collapse_certificate_extensions": attempted_extensions,
794
+ "collapse_certificate_level_sizes": level_sizes,
795
+ "candidate_coverages_before_dominance": coverage_count_before_dominance,
796
+ "candidate_witnesses_validated": len(retained_ideals),
797
+ "extension_seconds": extension_seconds,
798
+ "dominance_seconds": dominance_seconds,
799
+ "candidate_validation_seconds": perf_counter() - validation_started,
800
+ "candidate_generation_seconds": perf_counter() - started,
801
+ }
802
+ return witnesses, stats, bool(engine.gpu_used or validator.gpu_used)
803
+
804
+
805
+ def _enumerate_strongly_collapsible_candidates(
806
+ encoding: _Encoding,
807
+ *,
808
+ use_gpu: bool,
809
+ batch_size: int,
810
+ max_subcomplexes: int | None,
811
+ progress: Callable[[dict], None] | None,
812
+ ) -> tuple[dict[int, int], dict[str, Any], bool]:
813
+ up, down = _face_poset_relations(encoding)
814
+ strict_up = tuple(up[i] & ~(1 << i) for i in range(len(up)))
815
+ tester = _StrongCollapseTester(use_gpu=use_gpu, vertex_count=encoding.vertex_count)
816
+
817
+ witnesses: dict[int, int] = {}
818
+
819
+ # Every simplex is strongly collapsible. Seeding these witnesses both
820
+ # supplies an immediate finite upper bound and avoids retesting them.
821
+ for j, simplex_index in enumerate(encoding.facet_simplex_indices):
822
+ witnesses[1 << j] = down[simplex_index]
823
+
824
+ # Closed stars are cones and therefore strongly collapsible.
825
+ for vertex in range(encoding.vertex_count):
826
+ coverage = 0
827
+ ideal = 0
828
+ vertex_bit = 1 << vertex
829
+ for j, facet in enumerate(encoding.facets):
830
+ if facet & vertex_bit:
831
+ coverage |= 1 << j
832
+ ideal |= down[encoding.facet_simplex_indices[j]]
833
+ if coverage:
834
+ witnesses.setdefault(coverage, ideal)
835
+
836
+ batch_maxima: list[tuple[int, ...]] = []
837
+ batch_ideals: list[int] = []
838
+ batch_coverages: list[int] = []
839
+
840
+ enumerated = 0
841
+ tested = 0
842
+ gpu_positive = 0
843
+ started = perf_counter()
844
+
845
+ def flush() -> None:
846
+ nonlocal tested, gpu_positive
847
+ if not batch_maxima:
848
+ return
849
+
850
+ results = tester.test(batch_maxima)
851
+ tested += len(batch_maxima)
852
+
853
+ for valid, coverage, ideal, maxima in zip(
854
+ results, batch_coverages, batch_ideals, batch_maxima
855
+ ):
856
+ if not valid:
857
+ continue
858
+
859
+ gpu_positive += 1
860
+ # A positive CUDA result is independently verified on the CPU.
861
+ if not is_strongly_collapsible(maxima):
862
+ raise RuntimeError(
863
+ "CUDA/CPU disagreement in the strong-collapse test; "
864
+ "the exact computation was aborted."
865
+ )
866
+ witnesses.setdefault(coverage, ideal)
867
+
868
+ batch_maxima.clear()
869
+ batch_ideals.clear()
870
+ batch_coverages.clear()
871
+
872
+ if progress:
873
+ elapsed = perf_counter() - started
874
+ rate = enumerated / elapsed if elapsed else 0.0
875
+ progress({
876
+ "phase": "all_subcomplexes", "enumerated": enumerated,
877
+ "tested": tested, "candidate_coverages": len(witnesses), "rate": rate,
878
+ })
879
+
880
+ for ideal in _iter_order_ideals(up, down):
881
+ if ideal == 0:
882
+ continue
883
+
884
+ enumerated += 1
885
+ if max_subcomplexes is not None and enumerated > max_subcomplexes:
886
+ raise SearchLimitExceeded(
887
+ "Subcomplex enumeration exceeded max_subcomplexes="
888
+ f"{max_subcomplexes:,}.",
889
+ gpu_used=tester.gpu_used,
890
+ )
891
+
892
+ coverage = _facet_coverage(ideal, encoding.facet_simplex_indices)
893
+ if coverage == 0 or coverage in witnesses:
894
+ continue
895
+
896
+ maxima = _maximal_faces_of_ideal(ideal, strict_up, encoding.simplices)
897
+ batch_maxima.append(maxima)
898
+ batch_ideals.append(ideal)
899
+ batch_coverages.append(coverage)
900
+
901
+ if len(batch_maxima) >= batch_size:
902
+ flush()
903
+
904
+ flush()
905
+
906
+ stats = {
907
+ "subcomplexes_enumerated": enumerated,
908
+ "subcomplexes_strong_tested": tested,
909
+ "positive_tests": gpu_positive,
910
+ "candidate_coverages_before_dominance": len(witnesses),
911
+ "enumeration_seconds": perf_counter() - started,
912
+ }
913
+ return witnesses, stats, tester.gpu_used
914
+
915
+
916
+ def _ideal_to_simplices(ideal: int, encoding: _Encoding) -> tuple[tuple[Hashable, ...], ...]:
917
+ return tuple(
918
+ _decode_simplex(encoding.simplices[i], encoding.labels)
919
+ for i in _iter_bits(ideal)
920
+ )
921
+
922
+
923
+ def _ideal_to_maximal_simplices(ideal: int, encoding: _Encoding) -> tuple[tuple[Hashable, ...], ...]:
924
+ up, _ = _face_poset_relations(encoding)
925
+ strict_up = tuple(up[i] & ~(1 << i) for i in range(len(up)))
926
+ maxima = _maximal_faces_of_ideal(ideal, strict_up, encoding.simplices)
927
+ return tuple(_decode_simplex(simplex, encoding.labels) for simplex in maxima)
928
+
929
+
930
+ def _verify_general_cover(encoding: _Encoding, ideals: Sequence[int]) -> None:
931
+ full = (1 << len(encoding.simplices)) - 1
932
+ union = 0
933
+ up, _ = _face_poset_relations(encoding)
934
+ strict_up = tuple(up[i] & ~(1 << i) for i in range(len(up)))
935
+
936
+ for ideal in ideals:
937
+ union |= ideal
938
+ maxima = _maximal_faces_of_ideal(ideal, strict_up, encoding.simplices)
939
+ if not is_strongly_collapsible(maxima):
940
+ raise RuntimeError("Final cover verification found a non-collapsible element.")
941
+
942
+ if union != full:
943
+ raise RuntimeError("Final cover verification found uncovered simplices.")
944
+
945
+
946
+ # ---------------------------------------------------------------------------
947
+ # Exact graph branch: graphic-matroid partition and a minimum tree cover.
948
+ # ---------------------------------------------------------------------------
949
+
950
+
951
+ def _fundamental_cycle_edges(forest: Sequence[tuple[int, int]], edge: tuple[int, int]):
952
+ a, b = edge
953
+ adjacency: dict[int, list[tuple[int, tuple[int, int]]]] = {}
954
+ for u, v in forest:
955
+ adjacency.setdefault(u, []).append((v, (u, v)))
956
+ adjacency.setdefault(v, []).append((u, (u, v)))
957
+
958
+ if a not in adjacency or b not in adjacency:
959
+ return None
960
+
961
+ stack = [a]
962
+ seen = {a}
963
+ parent: dict[int, tuple[int, tuple[int, int]]] = {}
964
+
965
+ while stack:
966
+ u = stack.pop()
967
+ if u == b:
968
+ break
969
+ for v, stored_edge in adjacency.get(u, []):
970
+ if v not in seen:
971
+ seen.add(v)
972
+ parent[v] = (u, stored_edge)
973
+ stack.append(v)
974
+
975
+ if b not in seen:
976
+ return None
977
+
978
+ path = []
979
+ current = b
980
+ while current != a:
981
+ previous, stored_edge = parent[current]
982
+ path.append(stored_edge)
983
+ current = previous
984
+ return path
985
+
986
+
987
+ def _matroid_augmenting_path(
988
+ edge: tuple[int, int], forests: Sequence[Sequence[tuple[int, int]]]
989
+ ):
990
+ from collections import deque
991
+
992
+ if not forests:
993
+ return None
994
+
995
+ predecessor: dict[tuple[int, int], tuple[tuple[int, int], int] | None] = {edge: None}
996
+ queue = deque([edge])
997
+ terminal_edge = None
998
+ terminal_forest = None
999
+
1000
+ while queue:
1001
+ current = queue.popleft()
1002
+ for i, forest in enumerate(forests):
1003
+ cycle = _fundamental_cycle_edges(forest, current)
1004
+ if cycle is None:
1005
+ terminal_edge = current
1006
+ terminal_forest = i
1007
+ queue.clear()
1008
+ break
1009
+ for exchanged in cycle:
1010
+ if exchanged not in predecessor:
1011
+ predecessor[exchanged] = (current, i)
1012
+ queue.append(exchanged)
1013
+ if terminal_edge is not None:
1014
+ break
1015
+
1016
+ if terminal_edge is None:
1017
+ return None
1018
+
1019
+ path = [terminal_edge]
1020
+ labels = []
1021
+ current = terminal_edge
1022
+ while predecessor[current] is not None:
1023
+ previous, forest_index = predecessor[current]
1024
+ labels.append(forest_index)
1025
+ path.append(previous)
1026
+ current = previous
1027
+ path.reverse()
1028
+ labels.reverse()
1029
+
1030
+ transitions = [(terminal_forest, terminal_edge, None)]
1031
+ for j in range(len(labels) - 1, -1, -1):
1032
+ transitions.append((labels[j], path[j], path[j + 1]))
1033
+ return transitions
1034
+
1035
+
1036
+ def _is_forest(vertices: Sequence[int], edges: Iterable[tuple[int, int]]) -> bool:
1037
+ parent = {v: v for v in vertices}
1038
+
1039
+ def find(x: int) -> int:
1040
+ while parent[x] != x:
1041
+ parent[x] = parent[parent[x]]
1042
+ x = parent[x]
1043
+ return x
1044
+
1045
+ for a, b in edges:
1046
+ ra, rb = find(a), find(b)
1047
+ if ra == rb:
1048
+ return False
1049
+ parent[ra] = rb
1050
+ return True
1051
+
1052
+
1053
+ def _matroid_partition(
1054
+ vertices: Sequence[int], edges: Iterable[tuple[int, int]]
1055
+ ) -> tuple[int, list[list[tuple[int, int]]]]:
1056
+ all_edges = set(edges)
1057
+ forests: list[list[tuple[int, int]]] = []
1058
+
1059
+ for edge in sorted(all_edges):
1060
+ transitions = _matroid_augmenting_path(edge, forests)
1061
+ if transitions is None:
1062
+ forests.append([edge])
1063
+ continue
1064
+
1065
+ for i, add_edge, remove_edge in transitions:
1066
+ if remove_edge is not None:
1067
+ forests[i].remove(remove_edge)
1068
+ if add_edge not in forests[i]:
1069
+ forests[i].append(add_edge)
1070
+
1071
+ if any(not _is_forest(vertices, forest) for forest in forests):
1072
+ raise RuntimeError("Internal graphic-matroid partition error.")
1073
+
1074
+ partition_edges = set().union(*(set(forest) for forest in forests)) if forests else set()
1075
+ if partition_edges != all_edges:
1076
+ raise RuntimeError("Graphic-matroid partition did not preserve every edge.")
1077
+ return len(forests), forests
1078
+
1079
+
1080
+ def _connected_components(vertices: Sequence[int], edges: set[tuple[int, int]]) -> list[set[int]]:
1081
+ adjacency = {v: set() for v in vertices}
1082
+ for a, b in edges:
1083
+ adjacency[a].add(b)
1084
+ adjacency[b].add(a)
1085
+
1086
+ components = []
1087
+ unseen = set(vertices)
1088
+ while unseen:
1089
+ start = min(unseen)
1090
+ stack = [start]
1091
+ unseen.remove(start)
1092
+ component = {start}
1093
+ while stack:
1094
+ v = stack.pop()
1095
+ for u in adjacency[v]:
1096
+ if u in unseen:
1097
+ unseen.remove(u)
1098
+ component.add(u)
1099
+ stack.append(u)
1100
+ components.append(component)
1101
+ return components
1102
+
1103
+
1104
+ def _extend_forest_to_spanning_tree(
1105
+ vertices: Sequence[int], component_edges: set[tuple[int, int]], forest: Sequence[tuple[int, int]]
1106
+ ) -> set[tuple[int, int]]:
1107
+ parent = {v: v for v in vertices}
1108
+
1109
+ def find(x: int) -> int:
1110
+ while parent[x] != x:
1111
+ parent[x] = parent[parent[x]]
1112
+ x = parent[x]
1113
+ return x
1114
+
1115
+ def union(a: int, b: int) -> bool:
1116
+ ra, rb = find(a), find(b)
1117
+ if ra == rb:
1118
+ return False
1119
+ parent[ra] = rb
1120
+ return True
1121
+
1122
+ tree = set(forest)
1123
+ for a, b in forest:
1124
+ if not union(a, b):
1125
+ raise RuntimeError("Matroid partition returned a cyclic part.")
1126
+
1127
+ for edge in sorted(component_edges):
1128
+ if len(tree) == len(vertices) - 1:
1129
+ break
1130
+ if union(*edge):
1131
+ tree.add(edge)
1132
+
1133
+ if len(vertices) > 1 and len(tree) != len(vertices) - 1:
1134
+ raise RuntimeError("Could not extend a forest to a spanning tree.")
1135
+ return tree
1136
+
1137
+
1138
+ def _exact_graph_gscat(encoding: _Encoding) -> ExactGSCATResult:
1139
+ vertices = list(range(encoding.vertex_count))
1140
+ edges = {
1141
+ tuple(_iter_bits(simplex))
1142
+ for simplex in encoding.simplices
1143
+ if simplex.bit_count() == 2
1144
+ }
1145
+ components = _connected_components(vertices, edges)
1146
+ cover_masks: list[set[int]] = []
1147
+
1148
+ for component in components:
1149
+ component_edges = {
1150
+ edge for edge in edges if edge[0] in component and edge[1] in component
1151
+ }
1152
+
1153
+ if not component_edges:
1154
+ cover_masks.append({1 << next(iter(component))})
1155
+ continue
1156
+
1157
+ raw_arboricity, forests = _matroid_partition(sorted(component), component_edges)
1158
+ if raw_arboricity == 0:
1159
+ raise RuntimeError("A non-empty connected graph received arboricity zero.")
1160
+
1161
+ for forest in forests:
1162
+ tree = _extend_forest_to_spanning_tree(
1163
+ sorted(component), component_edges, forest
1164
+ )
1165
+ simplices = {1 << v for v in component}
1166
+ simplices.update((1 << a) | (1 << b) for a, b in tree)
1167
+ cover_masks.append(simplices)
1168
+
1169
+ target = set(encoding.simplices)
1170
+ union = set().union(*cover_masks) if cover_masks else set()
1171
+ if union != target:
1172
+ raise RuntimeError("Final graph cover verification failed.")
1173
+
1174
+ cover = tuple(
1175
+ tuple(
1176
+ _decode_simplex(simplex, encoding.labels)
1177
+ for simplex in sorted(part, key=lambda x: (x.bit_count(), x))
1178
+ )
1179
+ for part in cover_masks
1180
+ )
1181
+ cover_maximal = tuple(
1182
+ tuple(
1183
+ _decode_simplex(simplex, encoding.labels)
1184
+ for simplex in _maximal_masks(part)
1185
+ )
1186
+ for part in cover_masks
1187
+ )
1188
+
1189
+ return ExactGSCATResult(
1190
+ gscat=max(0, len(cover) - 1),
1191
+ cover=cover,
1192
+ cover_maximal_simplices=cover_maximal,
1193
+ method="exact graphic-matroid partition",
1194
+ exact=True,
1195
+ gpu_used=False,
1196
+ statistics={
1197
+ "vertices": encoding.vertex_count,
1198
+ "edges": len(edges),
1199
+ "connected_components": len(components),
1200
+ "cover_elements": len(cover),
1201
+ },
1202
+ )
1203
+
1204
+
1205
+ def exact_gscat(
1206
+ maximal_simplices: Iterable[Iterable[Hashable]],
1207
+ *,
1208
+ use_gpu: bool = True,
1209
+ algorithm: str = "collapse_certificates",
1210
+ batch_size: int = 8192,
1211
+ max_candidate_states: int | None = None,
1212
+ max_subcomplexes: int | None = None,
1213
+ max_search_states: int | None = None,
1214
+ progress: Callable[[dict], None] | None = None,
1215
+ incumbent=(),
1216
+ lower_bound: int = 0,
1217
+ ) -> ExactGSCATResult:
1218
+ """Compute the exact geometric simplicial category.
1219
+
1220
+ Parameters
1221
+ ----------
1222
+ maximal_simplices:
1223
+ An iterable of maximal simplices. Faces may also be present; redundant
1224
+ non-maximal simplices are removed automatically.
1225
+ use_gpu:
1226
+ Use CUDA for batched strong-collapse tests when available. Falling
1227
+ back to CPU does not change the answer.
1228
+ algorithm:
1229
+ ``"collapse_certificates"`` (default) uses the exact maximal-extension
1230
+ dynamic program. ``"all_subcomplexes"`` independently enumerates
1231
+ every order ideal of the face poset and is intended for small-instance
1232
+ cross-checks.
1233
+ batch_size:
1234
+ Maximum number of independent CUDA tasks per batch.
1235
+ max_candidate_states:
1236
+ Optional safety limit for collapse-certificate generation.
1237
+ max_subcomplexes:
1238
+ Optional safety limit for ``algorithm="all_subcomplexes"``.
1239
+ max_search_states:
1240
+ Optional safety limit for the exact set-cover proof. Reaching it also
1241
+ raises SearchLimitExceeded without returning a value.
1242
+ progress:
1243
+ Optional callback receiving exact-search progress events.
1244
+ """
1245
+ if batch_size <= 0:
1246
+ raise ValueError("batch_size must be positive.")
1247
+ if algorithm not in {"collapse_certificates", "all_subcomplexes"}:
1248
+ raise ValueError(
1249
+ "algorithm must be 'collapse_certificates' or 'all_subcomplexes'."
1250
+ )
1251
+ if max_candidate_states is not None and max_candidate_states <= 0:
1252
+ raise ValueError("max_candidate_states must be positive or None.")
1253
+ if max_subcomplexes is not None and max_subcomplexes <= 0:
1254
+ raise ValueError("max_subcomplexes must be positive or None.")
1255
+ if max_search_states is not None and max_search_states <= 0:
1256
+ raise ValueError("max_search_states must be positive or None.")
1257
+
1258
+ started = perf_counter()
1259
+ encoding = _encode(maximal_simplices)
1260
+
1261
+ if not encoding.facets:
1262
+ return ExactGSCATResult(
1263
+ gscat=0,
1264
+ cover=tuple(),
1265
+ cover_maximal_simplices=tuple(),
1266
+ method="empty complex",
1267
+ exact=True,
1268
+ gpu_used=False,
1269
+ statistics={"seconds": perf_counter() - started},
1270
+ )
1271
+
1272
+ if encoding.dimension <= 1:
1273
+ result = _exact_graph_gscat(encoding)
1274
+ result.statistics["seconds"] = perf_counter() - started
1275
+ return result
1276
+
1277
+ # The zero case can be decided immediately and exactly.
1278
+ if is_strongly_collapsible(encoding.facets):
1279
+ ideal = (1 << len(encoding.simplices)) - 1
1280
+ cover = (_ideal_to_simplices(ideal, encoding),)
1281
+ cover_maximal = (
1282
+ tuple(_decode_simplex(simplex, encoding.labels) for simplex in encoding.facets),
1283
+ )
1284
+ return ExactGSCATResult(
1285
+ gscat=0,
1286
+ cover=cover,
1287
+ cover_maximal_simplices=cover_maximal,
1288
+ method="exact strong-collapse test",
1289
+ exact=True,
1290
+ gpu_used=False,
1291
+ statistics={
1292
+ "vertices": encoding.vertex_count,
1293
+ "simplices": len(encoding.simplices),
1294
+ "maximal_simplices": len(encoding.facets),
1295
+ "seconds": perf_counter() - started,
1296
+ },
1297
+ )
1298
+
1299
+ if algorithm == "collapse_certificates":
1300
+ witnesses, enumeration_stats, gpu_used = (
1301
+ _generate_candidates_by_collapse_certificates(
1302
+ encoding,
1303
+ use_gpu=use_gpu,
1304
+ batch_size=batch_size,
1305
+ max_candidate_states=max_candidate_states,
1306
+ progress=progress,
1307
+ )
1308
+ )
1309
+ method = "exact maximal strong-collapse certificates + integer set cover"
1310
+ else:
1311
+ witnesses, enumeration_stats, gpu_used = _enumerate_strongly_collapsible_candidates(
1312
+ encoding,
1313
+ use_gpu=use_gpu,
1314
+ batch_size=batch_size,
1315
+ max_subcomplexes=max_subcomplexes,
1316
+ progress=progress,
1317
+ )
1318
+ method = "all-subcomplex enumeration + exact integer set cover"
1319
+
1320
+ maximal_coverages = _maximal_coverages(witnesses)
1321
+ incumbent_masks = tuple(
1322
+ sum(1 << index for index, mask in enumerate(encoding.facets)
1323
+ if _decode_simplex(mask, encoding.labels) in part)
1324
+ for part in incumbent
1325
+ )
1326
+ if progress:
1327
+ progress({"phase": "exact_set_cover", "candidates": len(maximal_coverages)})
1328
+ try:
1329
+ solution_coverages, set_cover_stats = minimum_set_cover(
1330
+ len(encoding.facets),
1331
+ maximal_coverages,
1332
+ max_search_states=max_search_states,
1333
+ incumbent=incumbent_masks,
1334
+ lower_bound=lower_bound + 1,
1335
+ )
1336
+ except SearchLimitExceeded as error:
1337
+ error.gpu_used = gpu_used
1338
+ best_ideals = tuple(witnesses[coverage] for coverage in error.cover_masks)
1339
+ _verify_general_cover(encoding, best_ideals)
1340
+ error.cover_witnesses = tuple(
1341
+ _ideal_to_maximal_simplices(ideal, encoding) for ideal in best_ideals
1342
+ )
1343
+ raise
1344
+ solution_ideals = tuple(witnesses[coverage] for coverage in solution_coverages)
1345
+ _verify_general_cover(encoding, solution_ideals)
1346
+
1347
+ cover = tuple(_ideal_to_simplices(ideal, encoding) for ideal in solution_ideals)
1348
+ cover_maximal = tuple(
1349
+ _ideal_to_maximal_simplices(ideal, encoding) for ideal in solution_ideals
1350
+ )
1351
+
1352
+ statistics = {
1353
+ "vertices": encoding.vertex_count,
1354
+ "simplices": len(encoding.simplices),
1355
+ "maximal_simplices": len(encoding.facets),
1356
+ **enumeration_stats,
1357
+ "candidate_coverages_after_dominance": len(maximal_coverages),
1358
+ "set_cover_states": set_cover_stats.states,
1359
+ "set_cover_lower_bound": set_cover_stats.lower_bound,
1360
+ "greedy_upper_bound": set_cover_stats.greedy_upper_bound,
1361
+ "cover_elements": len(solution_ideals),
1362
+ "seconds": perf_counter() - started,
1363
+ }
1364
+
1365
+ return ExactGSCATResult(
1366
+ gscat=len(solution_ideals) - 1,
1367
+ cover=cover,
1368
+ cover_maximal_simplices=cover_maximal,
1369
+ method=method,
1370
+ exact=True,
1371
+ gpu_used=gpu_used,
1372
+ statistics=statistics,
1373
+ )
1374
+
1375
+