#!/usr/bin/env python3 """Exact fixture checks for preserved comparisons and the single-vertex result.""" import argparse from collections import Counter, defaultdict from functools import lru_cache from functools import cmp_to_key from hashlib import sha256 from pathlib import Path import json HERE = Path(__file__).resolve().parent FIXTURE = "40bc6a1d52efab3d75cf343e65ac06b314f9c9c375fc02bf6d45bf6bb21f9529" raw = (HERE / "graph_fixture.json").read_bytes() assert sha256(raw).hexdigest() == FIXTURE data = json.loads(raw) adj = data["neighbors"] n = len(adj) full = (1 << n) - 1 p, q = 169974885672389, 500000000000000 rows = [Counter([i] * 13 + list(adj[i])) for i in range(n)] assert n == 120 and all(len(set(a)) == 12 for a in adj) assert all(i not in a and all(i in adj[j] for j in a) for i, a in enumerate(adj)) def indices(mask): while mask: low = mask & -mask yield low.bit_length() - 1 mask ^= low def normalized(x): low = min(x) return bytes(v - low for v in x) def successors(x): num = [p * (13*x[i] + sum(x[j] for j in adj[i])) for i in range(n)] den = 25*q values, groups = [], defaultdict(list) for i, v in enumerate(num): d, r = divmod(v, den) values.append(d) cut = (den - r + 24)//25 if cut < q: groups[cut].append(i) yield normalized(values) for cut in sorted(groups): for i in groups[cut]: values[i] += 1 yield normalized(values) def equitable(initial): c = list(initial) while True: colors = {} d = [colors.setdefault((c[i], tuple(sorted(c[j] for j in adj[i]))), len(colors)) for i in range(n)] if len(colors) == len(set(c)): return len(colors) c = d def mask(x): return sum(int(v) << i for i, v in enumerate(x)) def order_from_masks(states): order = [full] * n for b in states: for i in indices(b): order[i] &= b return order def check_matching(left, right, order): """Perfect matching by augmenting paths. Duplicate occurrences get separate slots.""" options = [tuple(k for k, j in enumerate(right) if order[i] >> j & 1) for i in left] if any(not targets for targets in options): return False owner = [-1] * len(right) def extend(i, seen): for j in options[i]: if not seen[j]: seen[j] = True if owner[j] == -1 or extend(owner[j], seen): owner[j] = i return True return False return all(extend(i, [False] * len(right)) for i in sorted(range(len(left)), key=lambda i: len(options[i]))) def stable_order(initial): r = initial.copy() pairs = {(i, j): (tuple((rows[i]-rows[j]).elements()), tuple((rows[j]-rows[i]).elements())) for i in range(n) for j in indices(r[i]) if i != j} sizes = [len(pairs)] while True: failed = [ij for ij, (a, b) in pairs.items() if not check_matching(a, b, r)] if not failed: break for i, j in failed: del pairs[i, j] r[i] ^= 1 << j sizes.append(len(pairs)) assert all(r[j] & ~r[i] == 0 for i in range(n) for j in indices(r[i])) return r, sizes class Upsets: """Count and identify upper sets by branching on whether a pivot is high.""" def __init__(self, upper): self.upper = upper self.lower = [sum(1 << j for j in range(n) if upper[j] >> i & 1) for i in range(n)] @lru_cache(None) def count(self, active): if not active: return 1 comparable = [((self.upper[i] | self.lower[i]) & active) for i in indices(active)] free = sum(a for a in comparable if a.bit_count() == 1) if free: return self.count(active ^ free) << free.bit_count() component = active & -active while True: old = component for i in indices(old): component |= (self.upper[i] | self.lower[i]) & active if component == old: break if component != active: return self.count(component) * self.count(active ^ component) i = max(indices(active), key=lambda j: min((self.upper[j] & active).bit_count(), (self.lower[j] & active).bit_count())) return self.count(active & ~self.lower[i]) + self.count(active & ~self.upper[i]) def encode(self, b): if not 0 <= b < full or any(self.upper[i] & ~b for i in indices(b)): raise ValueError("noncanonical or rejected pattern") active, rank = full, 0 while active: i = (active & -active).bit_length() - 1 if b >> i & 1: rank += self.count(active & ~self.lower[i]) active &= ~self.upper[i] else: active &= ~self.lower[i] return rank def decode(self, rank): if not 0 <= rank < self.count(full) - 1: raise ValueError("rank outside normalized catalog") active, b = full, 0 while active: i = (active & -active).bit_length() - 1 without = active & ~self.lower[i] split = self.count(without) if rank < split: active = without else: rank -= split b |= active & self.upper[i] active &= ~self.upper[i] return b def cmp_phi(x, y): """Sign of (x[0]-y[0])+(x[1]-y[1])*phi, using just integers.""" a, b = x[0]-y[0], x[1]-y[1] c = 2*a + b sign = lambda v: (v > 0) - (v < 0) if c*b >= 0: return sign(c + b) return sign(c*c - 5*b*b) * sign(c) def inner_product_numerator(x, y): terms = [(a*c+b*d, a*d+b*c+b*d) for (a,b), (c,d) in zip(x,y)] return tuple(map(sum, zip(*terms))) def threshold(b, k): nxt = sum(1 << i for i, row in enumerate(rows) if sum(w for j,w in row.items() if b >> j & 1) >= k) return 0 if nxt == full else nxt def shell_check(): """Prove the singleton-cap rule at each root using nine inward-to-outward shells.""" points = data["vertices"] sizes = [1,12,20,12,30,12,20,12,1] quotient = None for r in range(n): dots = [inner_product_numerator(points[r], x) for x in points] order = {d: j for j,d in enumerate(sorted(set(dots), key=cmp_to_key(cmp_phi), reverse=True))} labels = [order[d] for d in dots] groups = [[i for i,e in enumerate(labels) if e==j] for j in range(9)] assert list(map(len, groups)) == sizes and groups[0] == [r] counts = [] for group in groups: profiles = {tuple(sum(labels[j]==e for j in adj[i]) for e in range(9)) for i in group} assert len(profiles) == 1 counts.append(profiles.pop()) if quotient is None: quotient = counts assert counts == quotient scores = [[13*(i> 119 & 1 states = {bytes(range(n))} for _ in range(4): states = {y for x in states for y in successors(x)} assert max(map(max,states)) == 1 and len(states) == 6698 distribution = Counter(equitable(x) for x in states) depth4, counts4 = stable_order(order_from_masks(map(mask, states))) codec = Upsets(depth4) choices = codec.count(full)-1 for a in (0, choices-1, choices//2): assert codec.encode(codec.decode(a)) == a for s in sorted(states)[:128]: assert codec.decode(codec.encode(mask(s))) == mask(s) try: codec.encode(1) except ValueError: pass else: raise AssertionError("the forbidden singleton was accepted") out = {"graph_sha256":FIXTURE,"ramps_steps_enumerated":4, "nonreflexive_order_refinement_initial":direct_counts, "depth4_equitable_cell_histogram":dict(sorted(distribution.items())), "nonreflexive_order_refinement_depth4":counts4, "normalized_binary_upper_sets":choices, "sufficient_fixed_width":(choices-1).bit_length(), "example_forbidden_high_vertices":[0], "example_comparison":[0,119],"shell_check":shells} return out,direct,depth4 if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--orders",type=Path, help="write the verified comparison lists as JSON") args = parser.parse_args() result,r0,r4 = investigate() if args.orders: args.orders.write_text(json.dumps({ "from_ramp": [[i,j] for i in range(n) for j in indices(r0[i]) if i!=j], "from_depth4": [[i,j] for i in range(n) for j in indices(r4[i]) if i!=j]}, separators=(",",":"))+"\n") print(json.dumps(result,indent=2))