"""Recompute the finite classifications and verify the digraph obstructions.""" import json from functools import cache from itertools import combinations, combinations_with_replacement, permutations, product from math import gcd from pathlib import Path from pysat.solvers import Cadical195 DATA = Path(__file__).resolve().parent / "data" def encode(words): return sum(1 << w for w in set(words)) def words_of(mask): return tuple(w for w in range(mask.bit_length()) if mask & (1 << w)) @cache def permuted_words(k): return [tuple(sum(((w >> j) & 1) << i for i, j in enumerate(p)) for w in range(1 << k)) for p in permutations(range(k))] def orbit(mask): words = words_of(mask) return {encode(p[w] for w in words) for p in permuted_words(5)} def representatives(bounds): lower = set().union(*(orbit(m) for m in bounds["minimal_open"])) result = set() for upper in bounds["maximal_open"]: for bottom in lower: if bottom & ~upper: continue free = upper ^ bottom subset = free while True: result.add(min(orbit(bottom | subset))) if not subset: break subset = (subset - 1) & free return result def nonunate_tables(): """Bit i of accepts[x] is the value at x of candidate i (Appendix A).""" fixed = {0: 0, 3: 0, 5: 1, 31 ^ 19: 0, 31 ^ 21: 1} free = sorted(set(range(16)) - fixed.keys()) accepts = [0] * 32 for i, values in enumerate(product((0, 1), repeat=len(free))): for x, value in (fixed | dict(zip(free, values))).items(): accepts[x if value else 31 ^ x] |= 1 << i return accepts def admits_nonunate(mask, accepts): # Pack the five rows into adjacent five-bit fields. Selecting column i # writes bit i in every field, so columns can be combined by addition. columns = [sum(((w >> j) & 1) << (5 * j) for j in range(5)) for w in words_of(mask)] shifted = [[c << i for c in columns] for i in range(1, 5)] surviving = (1 << 2048) - 1 for parts in product(*shifted): prefix = sum(parts) for column in columns: matrix = prefix | column some_one = 0 for offset in range(0, 25, 5): some_one |= accepts[(matrix >> offset) & 31] surviving &= some_one if not surviving: return False return True @cache def grid_masks(t): # In increasing coordinates each row is a suffix starting at its cutoff. # Foldedness pairs opposite rows, so only sorted, self-dual cutoffs matter. width = t + 2 grids = set() for cutoffs in combinations_with_replacement(range(width + 1), t + 1): if any(a + b != width for a, b in zip(cutoffs, reversed(cutoffs))): continue for reverse_first, reverse_second in product((False, True), repeat=2): outputs = [] for a, b in product(range(t + 1), range(width)): i = a if reverse_first else t - a # cutoffs are sorted increasingly j = t + 1 - b if reverse_second else b outputs.append(int(j >= cutoffs[i])) if outputs[0] == 0: grids.add(tuple(outputs)) masks = [sum(value << i for i, value in enumerate(cell)) for cell in zip(*sorted(grids))] return masks, len(grids) def block_exists(words, t): columns = [tuple((w >> j) & 1 for j in range(5)) for w in words] sums = {(0,) * 5} for _ in range(t + 1): previous = sums sums = {tuple(a + b for a, b in zip(v, c)) for v in previous for c in columns} masks, size = grid_masks(t) active = (1 << size) - 1 for v in sorted(previous): cells = [a * (t + 2) for a in v] for w in sums: some_one = 0 for offset, b in zip(cells, w): some_one |= masks[offset + b] active &= some_one if not active: return False return True def transpose(columns, m): return tuple(sum(((c >> i) & 1) << j for j, c in enumerate(columns)) for i in range(m)) def maximal_sparse_cases(easy_bounds): @cache def easy_projection(columns, m): rows = transpose(columns, m) mask = encode(rows) return 0 not in rows and any(mask & ~bound == 0 for bound in easy_bounds) residual = set() for m in (3, 4, 5): full = (1 << m) - 1 row_permutations = permuted_words(m) for odd_size in range(3, m + 1, 2): dependency = (1 << odd_size) - 1 allowed = [c for c in range(1, full + 1) if (c & dependency).bit_count() % 2 == 0] for size in range(6, len(allowed) + 1): for columns in combinations(allowed, size): if any(c | d == full for c, d in combinations(columns, 2)): continue rows = transpose(columns, m) if 0 in rows or len(set(rows)) != m: continue if any(easy_projection(subset, m) for subset in combinations(columns, 5)): continue key = min(tuple(sorted(p[c] for c in columns)) for p in row_permutations) residual.add((m, key)) def contained(small, large): m, cols = small return m == large[0] and any(all(p[c] in large[1] for c in cols) for p in permuted_words(m)) maxima = {key for key in residual if not any(key != other and contained(key, other) for other in residual)} assert all(any(contained(key, maximum) for maximum in maxima) for key in residual) return residual, maxima def theta(c, a, b): edges = [] new_vertex = 2 for length, start, end in ((c, 1, 0), (a, 0, 1), (b, 0, 1)): path = [start, *range(new_vertex, new_vertex + length - 1), end] edges.extend(zip(path, path[1:])) new_vertex += length - 1 return edges def check_graph(edges): # A spanning tree supplies integer heights. Arc discrepancies generate # precisely the subgroup of algebraic lengths of closed walks. sources, targets = map(set, zip(*edges)) assert sources == targets and sources and all(u != v for u, v in edges) height = {min(sources): 0} todo = list(height) while todo: vertex = todo.pop() for u, v in edges: if u == vertex and v not in height: height[v] = height[u] + 1 todo.append(v) if v == vertex and u not in height: height[u] = height[v] - 1 todo.append(u) assert set(height) == sources assert gcd(*(height[u] + 1 - height[v] for u, v in edges)) == 1 def pullback(assignment, vertices): return sum(((assignment >> v) & 1) << i for i, v in enumerate(vertices)) def folded_literal_map(edges): """Compute only the components reached by input words used in the certificate.""" sources, targets = zip(*edges) complement = (1 << len(edges)) - 1 literals = {} variables = 0 def shift(before, after): position = {v: i for i, v in enumerate(before)} repeats = [(i, position[v]) for i, v in enumerate(before) if position[v] != i] indices = [position[v] for v in after] def move(word): if any(((word >> i) ^ (word >> j)) & 1 for i, j in repeats): return None return pullback(word, indices) return move moves = (shift(sources, targets), shift(targets, sources)) def literal(word): nonlocal variables if word not in literals: component = {word} stack = [word] while stack: current = stack.pop() for move in moves: other = move(current) if other is not None and other not in component: component.add(other) stack.append(other) assert (word ^ complement) not in component variables += 1 for member in component: literals[member] = variables literals[member ^ complement] = -variables return literals[word] return literal def verify_matrices(path, edges, arity, allowed): """Reconstruct the endpoint minors and feed every checked row clause to SAT.""" literal = folded_literal_map(edges) with path.open() as src, Cadical195() as solver: solver.add_clause([-literal(0)]) count = 0 for line in src: rows = tuple(map(int, line.split())) assert len(rows) == arity and all(0 <= r < 1 << len(edges) for r in rows), path assert all(word in allowed for word in transpose(rows, len(edges))), path solver.add_clause(sorted(set(literal(r) for r in rows))) count += 1 assert not solver.solve(), f"Satisfiable certificate: {path.name}" return count def certificates(sparse_maxima): directory = DATA / "certificates" graphs = json.loads((directory / "graphs.json").read_text()) sparse = {} five_ary = set() for name, arcs in sorted(graphs.items()): edges = list(map(tuple, arcs)) check_graph(edges) if name.startswith("theta-"): c, a, b = map(int, name.split("-")[1:]) assert edges == theta(c, a, b) and gcd(c + a, c + b) == 1 for path in sorted((directory / name).iterdir()): key = path.name.split(".")[0] if key.startswith("sparse-"): assert name.startswith("theta-") columns = tuple(map(int, key.split("-")[1:])) assert columns not in sparse allowed = set(transpose(columns, 5)) sparse[columns] = verify_matrices(path, edges, len(columns), allowed) else: mask = int(key) assert mask not in five_ary verify_matrices(path, edges, 5, set(words_of(mask))) five_ary.add(mask) assert {(5, columns) for columns in sparse} == sparse_maxima assert len(five_ary) == 24 and len(sparse) == 5 print(f"Graph certificates: {len(five_ary)} five-ary, {len(sparse)} sparse, all UNSAT") for columns, count in sorted(sparse.items()): print(f" {columns}: {count} matrices") return five_ary def missing_widths(unate): smaller = set() widths = {} for mask in sorted(unate, key=lambda m: (m.bit_count(), m)): if any(base & mask == base for base in smaller): continue widths[mask] = next(t for t in range(1, 9) if not block_exists(words_of(mask), t)) smaller.update(orbit(mask)) assert widths == { 72384: 3, 71304: 4, 136896: 4, 398984: 4, 202912: 6, 406656: 6, 1447968: 6, 201800: 7, 399520: 8, 1448064: 8, 18374664: 8, } print(f"Minimal unate representatives: {len(widths)} (first missing widths 3 to 8)") def classify(cases, bases): accepts = nonunate_tables() unate = {mask for mask in cases if not admits_nonunate(mask, accepts)} rotations = [s[i:] + s[:i] for s in ("11000", "00111") for i in range(5)] cyclic = min(orbit(encode(int(s, 2) for s in rotations))) assert cyclic in cases - unate graphs = cases - unate - {cyclic} certified = set().union(*(orbit(b) for b in bases)) assert all(any(b & mask == b for b in certified) for mask in graphs) assert len(unate) == 135 and len(graphs) == 53 print(f"Five-ary residuals: {len(unate)} unate, 1 cyclic, {len(graphs)} digraph") missing_widths(unate) def count_hard_groups(cases, easy_bounds, shifts): groups = set() for mask in cases: words = words_of(mask) classes = frozenset(min(orbit(encode(w ^ b for w in words))) for b in shifts if b not in words) groups.add(classes) return sum(not any(m & ~e == 0 for m in group for e in easy_bounds) for group in groups) def main(): if not __debug__: raise SystemExit("Run Python without -O to enable the verification assertions.") bounds = json.loads((DATA / "ahm-bounds.json").read_text()) assert [len(set(bounds[key])) for key in ("maximal_easy", "minimal_open", "maximal_open")] == [32, 25, 19] easy = set().union(*(orbit(m) for m in bounds["maximal_easy"])) cases = representatives(bounds) assert len(cases) == 189 and min(m.bit_count() for m in cases) == 6 residual, maxima = maximal_sparse_cases(easy) assert len(residual) == 13 and all(m == 5 for m, _ in residual) and len(maxima) == 5 print(f"Sparse enumeration: {len(residual)} column sets, {len(maxima)} maximal", flush=True) bases = certificates(maxima) classify(cases, bases) unpinned = count_hard_groups(cases, easy, (0, 31)) usefulness = count_hard_groups(cases, easy, range(32)) assert unpinned == usefulness == 59 print(f"Additional hard unpinned classes: {unpinned}; additional useless classes: {usefulness}") print("All checks passed.") if __name__ == "__main__": main()