Eixalyune / verify.py
PureOne's picture
Release Eixalyune v1.0.0
238855c verified
Raw History Blame Contribute Delete
19.5 kB
"""Exact finite checks for Eïxalyūne. Python 3.10+, standard library only."""
from collections import Counter, deque
from functools import lru_cache
from itertools import combinations, permutations, product
import argparse
import json
from pathlib import Path
def bits(mask):
while mask:
bit = mask & -mask
yield bit.bit_length() - 1
mask ^= bit
def subsets(mask):
sub = mask
while True:
yield sub
if not sub:
return
sub = (sub - 1) & mask
def bitset(items):
return sum(1 << i for i in set(items))
class BooleanPoset:
def __init__(self, labels):
self.labels = labels
self.count = 1 << labels
self.universe = (1 << self.count) - 1
self.down = [bitset(subsets(x)) for x in range(self.count)]
self.up = [bitset(y for y in range(self.count) if x & y == x)
for x in range(self.count)]
self.parent = [tuple(x ^ (1 << a) for a in bits(x)) for x in range(self.count)]
self.child = [tuple(x | (1 << a) for a in bits((self.count - 1) ^ x))
for x in range(self.count)]
self.ideals = [k for k in range(1, self.universe + 1, 2)
if all(self.down[x] & k == self.down[x] for x in bits(k))]
@lru_cache(None)
def width(self, states):
# Size minus a maximum matching in the strict comparability graph.
vertices = tuple(bits(states))
right = {}
def augment(x, seen):
for y in vertices:
if y == x or x & y != x or y in seen:
continue
seen.add(y)
if y not in right or augment(right[y], seen):
right[y] = x
return True
return False
return len(vertices) - sum(augment(x, set()) for x in vertices)
def closed_form(self, lower, upper):
maxima = [x for x in bits(lower) if not any(lower >> y & 1 for y in self.child[x])]
outside = self.universe ^ upper
border = [x for x in bits(outside) if all(upper >> y & 1 for y in self.parent[x])]
choices = [[y for y in self.parent[x] if lower >> y & 1] for x in border]
if any(not group for group in choices):
return None
return min(self.width(bitset(maxima + list(p))) for p in product(*choices))
def direct_search(self):
# A 0-1 shortest path follows the actual cursor. It makes no parent choices.
source = (1, self.universe, 0)
distance = {source: 1}
queue = deque([source])
while queue:
state = queue.popleft()
lower, upper, cursor = state
for y in self.child[cursor]:
options = []
if upper >> y & 1:
options.append((lower | self.down[y], upper, y))
if not (lower >> y & 1):
options.append((lower, upper & ~self.up[y], cursor))
for item in options:
if distance.get(item, float('inf')) > distance[state]:
distance[item] = distance[state]
queue.appendleft(item)
reset = (lower, upper, 0)
if cursor and distance.get(reset, float('inf')) > distance[state] + 1:
distance[reset] = distance[state] + 1
queue.append(reset)
by_interval = {}
for (lower, upper, _), n in distance.items():
key = (lower, upper)
by_interval[key] = min(n, by_interval.get(key, n))
return by_interval, len(distance)
@lru_cache(None)
def binary_rank(columns):
pivots = {}
for word in columns:
while word:
place = word.bit_length() - 1
if place not in pivots:
pivots[place] = word
break
word ^= pivots[place]
return len(pivots)
class BinaryHomology:
def __init__(self, cube):
self.cube = cube
self.masks = [bitset(x for x in range(cube.count) if x.bit_count() == d + 1)
for d in range(cube.labels + 1)]
self.boundary = [bitset(cube.parent[x]) if x.bit_count() >= 2 else 0
for x in range(cube.count)]
@lru_cache(None)
def rank(self, simplex_mask):
return binary_rank(tuple(self.boundary[x] for x in bits(simplex_mask)))
def betti(self, ideal, d):
faces = ideal & self.masks[d]
return faces.bit_count() - self.rank(faces) - self.rank(ideal & self.masks[d + 1])
def extrema(self, lower, upper, d):
allowed = upper & self.masks[d]
required = lower & self.masks[d]
cofaces = tuple(bits(upper & self.masks[d + 1]))
maximum = allowed.bit_count() - self.rank(allowed) - self.rank(lower & self.masks[d + 1])
minimum = maximum
for extra in subsets(allowed ^ required):
faces = required | extra
supported = bitset(x for x in cofaces if self.boundary[x] & ~faces == 0)
minimum = min(minimum, faces.bit_count() - self.rank(faces) - self.rank(supported))
return minimum, maximum
def check_intervals(cube, homology):
reached, states = cube.direct_search()
distribution = Counter()
pairs = checks = 0
for lower in cube.ideals:
for upper in cube.ideals:
if lower & ~upper:
continue
pairs += 1
direct = reached.get((lower, upper))
assert cube.closed_form(lower, upper) == direct
if direct is not None:
distribution[direct] += 1
completions = [k for k in cube.ideals if lower & ~k == 0 and k & ~upper == 0]
for d in range(1, cube.labels):
minimum, maximum = homology.extrema(lower, upper, d)
actual = {homology.betti(k, d) for k in completions}
assert actual == set(range(minimum, maximum + 1))
checks += 1
return dict(rooted_laws=len(cube.ideals), intervals=pairs, cursor_states=states,
realizable=len(reached), impossible=pairs - len(reached),
minimum_runs=dict(sorted(distribution.items())),
degree_specific_spectra_checked=checks)
def check_forks(cube):
"""Check the full Cartesian product of tail families, plus directed counts."""
checked = 0
for a, b in combinations(range(cube.labels),2):
aa,bb = 1 << a,1 << b
tails = tuple(subsets((cube.count-1) ^ (aa|bb)))
def row(law, at):
return bitset(t for t in tails if law >> (t|at) & 1)
rows = {k:(row(k,aa),row(k,bb)) for k in cube.ideals}
for lower in cube.ideals:
if not (lower >> aa & 1 and lower >> bb & 1):
continue
for upper in cube.ideals:
if lower & ~upper:
continue
candidates = [k for k in cube.ideals if (lower & ~k) == 0 and (k & ~upper) == 0]
pairs = {rows[k] for k in candidates}
left = {x for x,y in pairs}
right = {y for x,y in pairs}
assert pairs == set(product(left,right))
# Check marginals against every hereditary tail law between endpoints.
every_tail = [j for j in cube.ideals if j & ~bitset(tails) == 0]
for t, actual in enumerate((left,right)):
assert actual == {j for j in every_tail if (rows[lower][t] & ~j) == 0 and (j & ~rows[upper][t]) == 0}
low = (rows[lower][0] & ~rows[upper][1]).bit_count()
high = (rows[upper][0] & ~rows[lower][1]).bit_count()
assert {(x & ~y).bit_count() for x,y in pairs} == set(range(low,high+1))
checked += 1
return dict(two_context_intervals_checked=checked)
def check_single_runs(cube, homology):
m = cube.labels
cases = Counter()
for k in range(m + 1):
for ordered in permutations(range(m), k):
prefixes = [0]
for v in ordered:
prefixes.append(prefixes[-1] | (1 << v))
final = prefixes[-1]
unused = tuple(bits((cube.count - 1) ^ final))
for times in product(range(k + 2), repeat=len(unused)):
# k+1 means never attempted. t=0 is a failed singleton at the root.
upper = cube.universe
free = 0
for v, t in zip(unused, times):
if t <= k:
upper &= ~cube.up[prefixes[t] | (1 << v)]
else:
free |= 1 << v
lower = cube.down[final]
completions = [a for a in cube.ideals if lower & ~a == 0 and a & ~upper == 0]
observed_links = {bitset(s for s in subsets((cube.count - 1) ^ final)
if a >> (s | final) & 1) for a in completions}
expected = {a for a in cube.ideals if a & ~cube.down[free] == 0}
assert observed_links == expected
if not k:
kind = 'simplex_or_empty'
elif free or k not in times:
kind = 'contractible'
else:
kind = 'sphere'
if k:
for d in range(m):
reduced = homology.betti(upper, d) - (d == 0)
assert reduced == int(kind == 'sphere' and d == k - 1)
if kind == 'sphere':
pivot = unused[times.index(k)]
active = [v for v, t in zip(unused, times) if 0 < t <= k and v != pivot]
remainder = upper
for v in active:
assert all(remainder >> (s | (1 << pivot)) & 1
for s in bits(remainder) if s >> v & 1)
remainder &= ~cube.up[1 << v]
target = final | (1 << pivot)
assert remainder == (cube.down[target] ^ (1 << target))
cases[kind] += 1
return dict(normalized_records=sum(cases.values()), types=dict(sorted(cases.items())))
def closure(facets):
return {face for s in facets for k in range(1, len(s) + 1)
for face in combinations(sorted(s), k)}
def canonical_faces(complex_):
return sorted(complex_, key=lambda s: (len(s), s))
def order_complex(count, strictly_less):
out = set()
def visit(chain):
out.add(tuple(sorted(chain)))
for q in range(count):
if strictly_less(chain[-1], q):
visit(chain + (q,))
for p in range(count):
visit((p,))
return out
def spanning_extension(first, ambient):
# Attach an edge to one new vertex at a time.
lower = set(first)
seen = {s[0] for s in lower if len(s) == 1}
edges = sorted(s for s in ambient if len(s) == 2)
while len(seen) < sum(len(s) == 1 for s in ambient):
a, b = next((a, b) for a, b in edges if (a in seen) != (b in seen))
lower.update({(a,), (b,), (a, b)})
seen.update((a, b))
return lower
def certify_flag_interval(lower, upper):
vertices = sorted(s[0] for s in upper if len(s) == 1)
facets = [s for s in lower if all(tuple(sorted(s + (v,))) not in lower
for v in vertices if v not in s)]
missing = set()
logged_positive = set()
for v in vertices:
logged_positive.add((v,))
for w in vertices:
if w <= v:
continue
if (v, w) not in upper:
missing.add((v, w)) # Probe w at the singleton v and record its failure.
for facet in facets:
for n in range(1, len(facet) + 1):
logged_positive.add(facet[:n])
assert closure(logged_positive) == lower
# Each clique is enumerated once by adding later vertices.
cliques = set()
def expand(s, following):
for i, v in enumerate(following):
face = s + (v,)
cliques.add(face)
expand(face, [w for w in following[i + 1:] if (v, w) not in missing])
expand((), vertices)
assert cliques == upper
return dict(constructed_runs=len(vertices) + len(facets), rejected_pairs=len(missing))
def boundary_vector(simplex, row_id):
return {row_id[simplex[:i] + simplex[i+1:]]: (-1) ** i for i in range(len(simplex))}
def sparse_rank(columns, prime):
pivots = {}
for column in columns:
v = {j: a % prime for j, a in column.items() if a % prime}
while v:
j = max(v)
if j not in pivots:
inv = pow(v[j], -1, prime)
pivots[j] = {p: value * inv % prime for p, value in v.items()}
break
factor = v[j]
for p, value in pivots[j].items():
entry = (v.get(p, 0) - factor * value) % prime
if entry:
v[p] = entry
elif p in v:
del v[p]
return len(pivots)
def topology_check(lower, upper, boundary_cycle, triangle_deletion=False):
u_edges = sorted(s for s in upper if len(s) == 2)
edge_ids = {s: i for i, s in enumerate(u_edges)}
vertices = sorted(s for s in upper if len(s) == 1)
vertex_ids = {s: i for i, s in enumerate(vertices)}
triangles = sorted(s for s in upper if len(s) == 3)
bd = [boundary_vector(s, edge_ids) for s in triangles]
z = {}
for a, b in boundary_cycle:
j = edge_ids[tuple(sorted((a, b)))]
z[j] = z.get(j, 0) + (1 if a < b else -1)
assert all(tuple(sorted(e)) in lower for e in boundary_cycle)
cycle_boundary = Counter()
for a, b in boundary_cycle:
cycle_boundary[a] -= 1
cycle_boundary[b] += 1
assert all(x == 0 for x in cycle_boundary.values())
out = {}
for p in (2, 3):
rank2 = sparse_rank(bd, p)
def betti(k):
edges = [s for s in k if len(s) == 2]
rank1 = sparse_rank([boundary_vector(s, vertex_ids) for s in edges], p)
r2 = sparse_rank([boundary_vector(s, edge_ids) for s in k if len(s) == 3], p)
return len(edges) - rank1 - r2
image = sparse_rank(bd + [z], p)-rank2
assert betti(lower) == 1
# z spans the lower H1 since it is a nonzero simple cycle and the lower is a graph.
assert all(len(s) <= 2 for s in lower)
record = dict(lower_betti_1=betti(lower), upper_betti_1=betti(upper),
endpoint_image_rank=image)
if triangle_deletion:
assert rank2 == len(triangles)
for i in range(len(bd)):
proper = bd[:i] + bd[i+1:]
assert sparse_rank(proper + [z], p) > sparse_rank(proper, p)
record["one_triangle_deletions_tested"] = len(triangles)
out[str(p)] = record
return out
def winding_example():
def cycle(n):
return closure([(i, (i+1) % n) for i in range(n)])
xx, yy = canonical_faces(cycle(6)), canonical_faces(cycle(3))
m = len(xx)
fx = [set(i % 3 for i in s) for s in xx]
def relation(i, j):
if i < m:
return set(xx[i]) < set(xx[j]) if j < m else fx[i] <= set(yy[j-m])
return j >= m and set(yy[i-m]) < set(yy[j-m])
upper = order_complex(m+len(yy), relation)
lower = spanning_extension({s for s in upper if all(i < m for i in s)}, upper)
walk = []
for i in range(6):
j = (i + 1) % 6
mid = xx.index(tuple(sorted((i, j))))
walk.extend([(xx.index((i,)),mid),(mid,xx.index((j,)))])
data = topology_check(lower, upper, walk)
assert data['2']['upper_betti_1']==data['3']['upper_betti_1'] == 1
assert [data[str(p)]['endpoint_image_rank'] for p in (2, 3)] == [0,1]
return dict(f_vector=[sum(len(s)==i for s in upper) for i in (1,2,3)],
fields=data, **certify_flag_interval(lower, upper))
def torus_example():
def v(i, j):
return 3 * (i % 3) + (j % 3)
triangles = []
for i, j in product(range(3),repeat=2):
a, b, c, e = v(i, j), v(i + 1, j), v(i + 1, j + 1), v(i, j + 1)
triangles.extend([(a, b, c), (a, c, e)])
hole = triangles.pop(0)
faces = canonical_faces(closure(triangles))
n = len(faces)
face_sets = [set(s) for s in faces]
upper = order_complex(n, lambda i,j: face_sets[i] < face_sets[j])
rim = set(closure([hole])) - {tuple(sorted(hole))}
base = {s for s in upper if all(faces[i] in rim for i in s)}
lower= spanning_extension(base,upper)
walk = []
for i in range(3):
a, b = hole[i], hole[(i + 1) % 3]
mid = faces.index(tuple(sorted((a, b))))
walk.extend([(faces.index((a,)),mid),(mid,faces.index((b,)))])
data = topology_check(lower, upper, walk,triangle_deletion=True)
for p in ('2','3'):
assert data[p]['upper_betti_1'] == 2 and data[p]['endpoint_image_rank']==0
return dict(f_vector=[sum(len(s)==i for s in upper) for i in (1,2,3)],
fields=data, **certify_flag_interval(lower, upper))
def minimum_hits(clauses):
"""Minimum number of vertices meeting each nonempty bit-mask clause."""
@lru_cache(None)
def solve(remaining):
if not remaining:
return 0
first = min(remaining, key=int.bit_count)
return 1 + min(solve(tuple(mask for mask in remaining if not mask >> x & 1))
for x in bits(first))
return solve(tuple(sorted(clauses)))
def check_complexity_reduction():
checked = 0
for n in range(1, 6):
possible = list(combinations(range(n), 2))
for mask in range(1 << len(possible)):
edges = [possible[i] for i in bits(mask)]
tau = minimum_hits(bitset(edge) for edge in edges)
groups = [list(range(n)), [], []]
k = n
subdivided = []
for a, b in edges:
groups[1].append(k)
groups[2].append(k+1)
subdivided.extend([(a,k),(k, k + 1),(k+1,b)])
k += 2
for i in range(3):
groups[i].append(k)
groups[(i+1)%3].extend([k+1,k+2])
subdivided.extend([(k, k + 1),(k,k+2)])
k += 3
constraints = [bitset(edge) for edge in subdivided] + [bitset(g) for g in groups]
assert minimum_hits(constraints) == len(edges) + tau + 3
checked += 1
return dict(labelled_graphs_checked=checked, vertices_in_original_graph='1 to 5')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, help='write optional readable JSON results')
args = parser.parse_args()
out = {}
for n in (3,4):
cube = BooleanPoset(n)
hom = BinaryHomology(cube)
out[f'{n}_labels'] = dict(interval_analysis=check_intervals(cube, hom),
single_run=check_single_runs(cube, hom), forks=check_forks(cube))
out['degree_two_circle_map'] = winding_example()
out['punctured_torus'] = torus_example()
out['three_facet_reduction'] = check_complexity_reduction()
report = json.dumps(out, indent=2, sort_keys=True)
if args.output:
args.output.write_text(report+'\n',encoding='utf-8')
print(report)
if __name__ == '__main__':
main()