Download code/exact_graph.py from PureOne/EVE-Spectral-Extremality-Amplification: direct link, hf CLI and curl.
- Browser
- Download file 9.21 kB
-
https://huggingface.co/datasets/PureOne/EVE-Spectral-Extremality-Amplification/resolve/main/code/exact_graph.py
- Command line
-
hf download hf://datasets/PureOne/EVE-Spectral-Extremality-Amplification/code/exact_graph.py
-
curl -L -o exact_graph.py https://huggingface.co/datasets/PureOne/EVE-Spectral-Extremality-Amplification/resolve/main/code/exact_graph.py
9.21 kB
| """Exact half-cell spectral certificates and a rational-length rigidity classifier. | |
| No floating-point eigensolver is used by exact_halfcell_spectrum. At frequency pi, | |
| subdivision into edges of length 1/2 reduces the eigenvalue count to rational | |
| inertia of a vertex adjacency matrix. See MANUSCRIPT, computational appendix. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from fractions import Fraction | |
| from typing import Iterable | |
| import networkx as nx | |
| import sympy as sp | |
| class Edge: | |
| u: int | |
| v: int | |
| length: Fraction | |
| def __post_init__(self): | |
| object.__setattr__(self, 'length', Fraction(self.length)) | |
| if self.length <= 0: | |
| raise ValueError('Edge lengths must be strictly positive.') | |
| def graph(edges: Iterable[Edge], dirichlet=()) -> nx.MultiGraph: | |
| es = list(edges) | |
| if not es: | |
| raise ValueError('At least one edge is required.') | |
| g = nx.MultiGraph() | |
| for e in es: | |
| g.add_edge(e.u, e.v, length=e.length) | |
| ds = set(dirichlet) | |
| if not nx.is_connected(g): | |
| raise ValueError('The graph must be connected.') | |
| if not ds <= set(g): | |
| raise ValueError('Unknown Dirichlet vertex.') | |
| if any(g.degree(v) != 1 for v in ds): | |
| raise ValueError('This release allows Dirichlet conditions only at leaves.') | |
| nx.set_node_attributes(g, {v: v in ds for v in g}, 'D') | |
| return g | |
| def suppress_degree_two(g: nx.MultiGraph) -> nx.MultiGraph: | |
| g = g.copy() | |
| while True: | |
| changed = False | |
| for v in list(g): | |
| if g.degree(v) != 2 or g.nodes[v].get('D', False): | |
| continue | |
| inc = list(g.edges(v, keys=True, data=True)) | |
| if len(inc) != 2 or any(a == b for a, b, _, _ in inc): | |
| continue # A single circle remains a loop and is excluded later. | |
| ends = [b if a == v else a for a, b, _, _ in inc] | |
| length = sum((z[3]['length'] for z in inc), Fraction()) | |
| g.remove_node(v) | |
| g.add_edge(ends[0], ends[1], length=length) | |
| changed = True | |
| break | |
| if not changed: | |
| return g | |
| def parameters(g): | |
| d = sum(bool(g.nodes[v].get('D', False)) for v in g) | |
| n = sum(g.degree(v) == 1 and not g.nodes[v].get('D', False) for v in g) | |
| beta = g.number_of_edges() - g.number_of_nodes() + 1 | |
| length = sum((x['length'] for _, _, x in g.edges(data=True)), Fraction()) | |
| return d, n, beta, length | |
| def classify(edges: Iterable[Edge], dirichlet=(), k: int | None = None): | |
| """Classify exact high-branch saturation using rational arithmetic. | |
| If k=None, test the threshold pi^2 (d=1). Otherwise d=L/(k-(N+beta)/2). | |
| A False answer means non-saturation in the declared regime, not a numerical | |
| lower bound on the amount of strictness. | |
| """ | |
| g = suppress_degree_two(graph(edges, dirichlet)) | |
| D, N, beta, L = parameters(g) | |
| B = N + beta | |
| if len(g) == 1 and g.number_of_edges() == 1: | |
| return dict(saturated=False, family='excluded-circle', reason='The circle has a different bound.') | |
| if k is None: | |
| candidate = L + Fraction(B, 2) | |
| if candidate.denominator != 1: | |
| return dict(saturated=False, family='none', reason='The proposed index is not integral.') | |
| k = int(candidate) | |
| d = Fraction(1) | |
| else: | |
| if not isinstance(k, int): | |
| raise ValueError('k must be an integer.') | |
| c = Fraction(k) - Fraction(B, 2) | |
| if c <= 0: | |
| return dict(saturated=False, family='outside-regime', reason='Nonpositive target frequency.') | |
| d = L / c | |
| base = dict(k=k, D=D, N=N, beta=beta, d=str(d), multiplicity=D+N+2*beta-1) | |
| if k < max(B, 1 if D else 2): | |
| return dict(base, saturated=False, family='outside-regime', reason='Outside the high-index theorem.') | |
| q = lambda x: 2*x/d | |
| def positive_integer(x): | |
| return x.denominator == 1 and x > 0 | |
| if len(g) == 1 and g.number_of_edges() == 2: | |
| good = all(positive_integer(x['length']/(2*d)) for _, _, x in g.edges(data=True)) | |
| return dict(base, saturated=good, family='figure-eight', reason='Both loop lengths must be positive even cell counts.') | |
| if len(g) == 2 and g.number_of_edges() == 3 and nx.number_of_selfloops(g) == 0: | |
| counts = [x['length']/d for _, _, x in g.edges(data=True)] | |
| good = all(positive_integer(x) for x in counts) and len({int(x) % 2 for x in counts}) == 1 | |
| return dict(base, saturated=good, family='theta', reason='Three positive integer cell counts of common parity.') | |
| skeleton = g.copy() | |
| loop_vertices = set() | |
| for a, b, key, x in list(g.edges(keys=True, data=True)): | |
| if a == b: | |
| if g.degree(a) != 3 or a in loop_vertices: | |
| return dict(base, saturated=False, family='excluded-topology', reason='A nonexceptional loop must be pendant at a degree-three vertex.') | |
| if not positive_integer(x['length']/(2*d)): | |
| return dict(base, saturated=False, family='lasso-tree', reason='An attached loop has incompatible phase.') | |
| loop_vertices.add(a) | |
| skeleton.remove_edge(a, b, key) | |
| if len(skeleton) < 2 or not nx.is_tree(skeleton): | |
| return dict(base, saturated=False, family='excluded-topology', reason='The nonloop skeleton must be a tree.') | |
| virtual_N = loop_vertices | {v for v in g if g.degree(v) == 1 and not g.nodes[v].get('D', False)} | |
| for a, b, x in skeleton.edges(data=True): | |
| nu = int(a in virtual_N) + int(b in virtual_N) | |
| m = x['length']/d - Fraction(nu, 2) | |
| if m.denominator != 1 or m < 0 or (nu == 0 and m < 1): | |
| return dict(base, saturated=False, family='lasso-tree' if beta else 'tree', reason='A skeleton edge violates the integer/half-integer phase rule.') | |
| return dict(base, saturated=True, family='lasso-tree' if beta else 'tree', reason='All exact topology and metric conditions hold.') | |
| def rational_inertia(matrix): | |
| """Return (positive, negative, zero) using exact 1x1/2x2 congruences.""" | |
| A = sp.Matrix(matrix) | |
| if A != A.T: | |
| raise ValueError('A symmetric matrix is required.') | |
| pos = neg = zero = 0 | |
| while A.rows: | |
| size = A.rows | |
| pivot = next((i for i in range(size) if A[i,i] != 0), None) | |
| if pivot is not None: | |
| perm = [pivot] + [i for i in range(size) if i != pivot] | |
| A = A.extract(perm, perm) | |
| a = A[0,0] | |
| pos += int(bool(a > 0)); neg += int(bool(a < 0)) | |
| v = A[1:,0] | |
| A = A[1:,1:] - v*v.T/a | |
| else: | |
| pair = next(((i,j) for i in range(size) for j in range(i+1,size) if A[i,j] != 0), None) | |
| if pair is None: | |
| zero += size | |
| break | |
| i,j = pair | |
| perm = [i,j] + [h for h in range(size) if h not in (i,j)] | |
| A = A.extract(perm, perm) | |
| pivot_block = A[:2,:2] | |
| X = A[2:,:2] | |
| A = A[2:,2:] - X*pivot_block.inv()*X.T | |
| pos += 1; neg += 1 | |
| return pos, neg, zero | |
| def exact_halfcell_spectrum(edges: Iterable[Edge], dirichlet=()): | |
| """Exact counts below/at pi^2; lengths must be positive multiples of 1/2.""" | |
| es = list(edges) | |
| g = graph(es, dirichlet) | |
| ds = set(dirichlet) | |
| vertices = {v:i for i,v in enumerate(g)} | |
| next_node = len(vertices) | |
| segments = [] | |
| for e in es: | |
| q = 2*e.length | |
| if q.denominator != 1: | |
| raise ValueError('All lengths must be integer multiples of 1/2.') | |
| count = int(q) | |
| nodes = [vertices[e.u]] + list(range(next_node, next_node+count-1)) + [vertices[e.v]] | |
| next_node += count-1 | |
| segments += list(zip(nodes[:-1],nodes[1:])) | |
| A = sp.zeros(next_node) | |
| for a,b in segments: | |
| A[a,b] += 1 | |
| A[b,a] += 1 # A loop contributes two on the diagonal. | |
| keep = [i for i in range(next_node) if i not in {vertices[v] for v in ds}] | |
| A = A.extract(keep,keep) | |
| pos, neg, zero = rational_inertia(A) | |
| return dict(below=pos, multiplicity=zero, top_index=pos+zero, adjacency_dimension=len(keep), adjacency_inertia=[pos,neg,zero]) | |
| def threshold_multiplicity(edges: Iterable[Edge], dirichlet=()): | |
| """Independent exact ODE coefficient-nullity check at frequency pi.""" | |
| es = list(edges) | |
| g = graph(es, dirichlet) | |
| ds = set(dirichlet) | |
| traces = {v:[] for v in g}; derivatives = {v:[] for v in g} | |
| n = 2*len(es) | |
| for j,e in enumerate(es): | |
| q = 2*e.length | |
| if q.denominator != 1: | |
| raise ValueError('Half-cell lengths are required.') | |
| c = (1,0,-1,0)[int(q)%4]; s = (0,1,0,-1)[int(q)%4] | |
| t0=sp.zeros(1,n); t1=sp.zeros(1,n); p0=sp.zeros(1,n); p1=sp.zeros(1,n) | |
| t0[2*j]=1; t1[2*j]=c; t1[2*j+1]=s | |
| p0[2*j+1]=1; p1[2*j]=s; p1[2*j+1]=-c | |
| traces[e.u].append(t0); traces[e.v].append(t1) | |
| derivatives[e.u].append(p0); derivatives[e.v].append(p1) | |
| rows=[] | |
| for v in g: | |
| if v in ds: | |
| rows.append(traces[v][0]) | |
| else: | |
| rows += [t-traces[v][0] for t in traces[v][1:]] | |
| rows.append(sum(derivatives[v],sp.zeros(1,n))) | |
| M=sp.Matrix.vstack(*rows) | |
| return n-M.rank() | |