PureOne's picture
Release EVE-AITHRAEL reproducible causal calibration research
6773986 verified
Raw History Blame Contribute Delete
11.6 kB
#!/usr/bin/env python3
"""Exact rational calibration and fault-tolerance primitives.
The algorithms enumerate channel subsets and are intended as transparent
small-instance certificates, not scalable solvers or raw-data estimators.
All vector-space computations use fractions.Fraction. No third-party package.
"""
from fractions import Fraction as F
from itertools import combinations
import random
def rational_matrix(rows, columns=None):
out = [[F(x) for x in row] for row in rows]
if columns is not None and any(len(row) != columns for row in out):
raise ValueError("inconsistent row width")
return out
def rref(rows, ncols):
a = rational_matrix(rows, ncols)
pivots = []
k = 0
for c in range(ncols):
p = next((i for i in range(k, len(a)) if a[i][c]), None)
if p is None:
continue
a[k], a[p] = a[p], a[k]
v = a[k][c]
a[k] = [x / v for x in a[k]]
for i in range(len(a)):
if i != k and a[i][c]:
v = a[i][c]
a[i] = [x - v*y for x, y in zip(a[i], a[k])]
pivots.append(c)
k += 1
if k == len(a):
break
return a, pivots
def rank(rows, ncols):
return len(rref(rows, ncols)[1])
def row_basis(rows, ncols):
a, pivots = rref(rows, ncols)
return a[:len(pivots)]
def null_basis(rows, ncols):
a, pivots = rref(rows, ncols)
answer = []
for free in range(ncols):
if free in pivots:
continue
v = [F(0)]*ncols
v[free] = F(1)
for i, p in enumerate(pivots):
v[p] = -a[i][free]
answer.append(v)
return answer
def dot(x, y):
if len(x) != len(y):
raise ValueError("dot-product dimension mismatch")
return sum((a*b for a, b in zip(x, y)), F(0))
def linear_combination(coeff, basis, ambient):
return [sum((c*v[k] for c, v in zip(coeff, basis)), F(0))
for k in range(ambient)]
def restrict_rows(rows, basis):
"""Rows composed with a basis stored as ambient row vectors."""
return [[dot(row, v) for v in basis] for row in rows]
def bits(mask, m):
return [a for a in range(m) if mask & (1 << a)]
def jsonable(obj):
if isinstance(obj, F):
return int(obj) if obj.denominator == 1 else str(obj)
if isinstance(obj, dict):
return {str(k): jsonable(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [jsonable(v) for v in obj]
return obj
def surrounded_supports(n, edges):
children = [set() for _ in range(n)]
indegree = [0]*n
seen = set()
for u, v in edges:
if not (0 <= u < n and 0 <= v < n) or u == v or (u, v) in seen:
raise ValueError("invalid or duplicate directed edge")
seen.add((u, v)); children[u].add(v); indegree[v] += 1
queue = [i for i in range(n) if indegree[i] == 0]
visited = 0
while queue:
u = queue.pop(); visited += 1
for v in children[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if visited != n:
raise ValueError("graph is not acyclic")
return [sorted(i for i in children[j] if children[i] <= children[j])
for j in range(n)]
def residual_spaces(n, edges, trusted_rows):
M = rational_matrix(trusted_rows, n)
supports = surrounded_supports(n, edges)
spaces = []
for I in supports:
local = [[row[i] for i in I] for row in M]
local_basis = null_basis(local, len(I))
extended = []
for v in local_basis:
z = [F(0)]*n
for i, value in zip(I, v):
z[i] = value
extended.append(z)
spaces.append(extended)
return supports, spaces
def rado_table(E, channel_spaces):
"""Return r(T) and rho(K) for every channel subset.
r(T) = dimension of the sum of available restricted row spaces.
rho(K) = maximal selectable-row rank (classical Rado theorem).
A subset minimum transform avoids a second nested subset enumeration.
"""
d, m = len(E), len(channel_spaces)
W = [restrict_rows(H, E) for H in channel_spaces]
sums = []
for mask in range(1 << m):
rows = [w for a in bits(mask, m) for w in W[a]]
sums.append(rank(rows, d))
minima = [sums[mask] - mask.bit_count() for mask in range(1 << m)]
for a in range(m):
for mask in range(1 << m):
if mask & (1 << a):
minima[mask] = min(minima[mask], minima[mask ^ (1 << a)])
rho = [mask.bit_count() + minima[mask] for mask in range(1 << m)]
return {"dimension": d, "sum_ranks": sums, "generic_ranks": rho}
def generic_profile(E, channel_spaces):
"""Exact cut formula for minimum deletions creating k kernel dimensions."""
table = rado_table(E, channel_spaces)
d, m = len(E), len(channel_spaces)
profile, witnesses = [], []
for k in range(1, d+1):
candidates = [(m-mask.bit_count()+r-d+k, mask)
for mask, r in enumerate(table["sum_ranks"]) if r <= d-k]
value, cut = min(candidates)
profile.append(max(0, value))
witnesses.append({"k": k, "cut_channels": bits(cut, m),
"available_rank": table["sum_ranks"][cut],
"raw_cut_value": value})
return {**table, "profile": profile,
"distance": profile[0] if profile else None, "cut_witnesses": witnesses}
def numerical_table(E, C):
A = restrict_rows(C, E)
d, m = len(E), len(C)
return [rank([A[a] for a in bits(mask, m)], d) for mask in range(1 << m)]
def numerical_profile(E, C):
d, m = len(E), len(C)
ranks = numerical_table(E, C)
values, witnesses = [], []
ambient = len(E[0]) if E else (len(C[0]) if C else 0)
A = restrict_rows(C, E)
for k in range(1, d+1):
kept = max((mask for mask, r in enumerate(ranks) if r <= d-k),
key=lambda mask: (mask.bit_count(), -mask))
coeffs = null_basis([A[a] for a in bits(kept, m)], d)
vectors = [linear_combination(c, E, ambient) for c in coeffs]
removed = [a for a in range(m) if not kept & (1 << a)]
values.append(len(removed))
witnesses.append({"k": k, "erased_channels": removed,
"surviving_kernel_basis": vectors,
"retained_rank": ranks[kept]})
return {"dimension": d, "profile": values,
"distance": values[0] if values else None,
"ranks": ranks, "witnesses": witnesses}
def common_generic_design(spaces, channel_spaces, seed=13371337, max_attempts=2000):
"""Certificate-backed finite search, not a completeness algorithm.
Every returned matrix attains every theoretical rank for every column and
channel subset. Failure to find one within max_attempts is inconclusive.
The mathematical finite-grid existence bound is proved in the manuscript.
"""
active = [E for E in spaces if E]
if not active:
return {"rows": [], "attempts": 0, "rank_checks": 0,
"status": "already_identified"}
ambient = len(active[0][0])
Hs = [row_basis(H, ambient) for H in channel_spaces]
expected = [rado_table(E, Hs)["generic_ranks"] for E in active]
rng = random.Random(seed)
for attempt in range(1, max_attempts+1):
bound = 2 + attempt//5
rows = [linear_combination([F(rng.randint(1, bound)) for _ in H], H, ambient)
for H in Hs]
got = [numerical_table(E, rows) for E in active]
if got == expected:
return {"rows": rows, "attempts": attempt,
"rank_checks": len(active)*(1 << len(Hs)), "status": "certified"}
return {"rows": None, "attempts": max_attempts,
"rank_checks": 0, "status": "search_exhausted_not_infeasible"}
def dense_completion(spaces, number_rows):
"""Positive integer moment rows with every restriction full spark.
At each step avoid the finite family of nonzero residual subspaces left
by subsets of previously chosen rows. The root bound makes the step finite.
This implementation is exponential in the requested number of channels.
"""
active = [E for E in spaces if E]
if not active:
return [], []
q = len(active[0][0])
rows, search_log = [], []
for h in range(number_rows):
required = []
for E in active:
d = len(E)
for size in range(min(h, d-1)+1):
for S in combinations(range(h), size):
coeffs = null_basis(restrict_rows([rows[a] for a in S], E), d)
V = [linear_combination(c, E, q) for c in coeffs]
if V:
required.append(V)
bound = len(required)*max(q-1, 0)+1
for t in range(1, bound+1):
row = [F(t)**i for i in range(q)]
if all(any(dot(row, v) for v in V) for V in required):
rows.append(row)
search_log.append({"step": h+1, "families": len(required),
"search_bound": bound, "chosen_t": t})
break
else:
raise AssertionError("polynomial root bound contradicted")
return rows, search_log
def solve_consistent(rows, rhs, ncols):
"""One rational solution; None if inconsistent. Free variables set to zero."""
if len(rows) != len(rhs):
raise ValueError("right-hand side dimension mismatch")
aug = [list(row)+[F(y)] for row, y in zip(rows, rhs)]
reduced, pivots = rref(aug, ncols+1)
if ncols in pivots:
return None
x = [F(0)]*ncols
for i, p in enumerate(pivots):
x[p] = reduced[i][-1]
return x
def decode_column(E, C, observations, erased=(), max_errors=0):
"""Exhaustive exact decoder, only for the explicit linear observation model.
Rejects non-uniqueness instead of returning an arbitrary candidate.
"""
d, m = len(E), len(C)
if not E:
raise ValueError("zero-dimensional case has no column to decode")
if max_errors < 0:
raise ValueError("negative error budget")
if len(observations) != m:
raise ValueError("observation dimension mismatch")
erased = set(erased)
if any(a < 0 or a >= m for a in erased):
raise ValueError("erased channel index out of range")
A = restrict_rows(C, E)
available = [a for a in range(m) if a not in erased]
solutions = set()
for size in range(max_errors+1):
for bad in combinations(available, size):
kept = [a for a in available if a not in bad]
coeff = solve_consistent([A[a] for a in kept],
[observations[a] for a in kept], d)
if coeff is None:
continue
# A consistent rank-deficient retained system already supplies
# infinitely many explanations. Ignoring it can falsely return
# a unique candidate from another corruption support.
if rank([A[a] for a in kept], d) < d:
raise ValueError("decoder found a non-identifiable feasible family")
mismatches = sum(dot(A[a], coeff) != F(observations[a]) for a in available)
if mismatches <= max_errors:
solutions.add(tuple(coeff))
if len(solutions) != 1:
raise ValueError("decoder did not find exactly one identifiable candidate")
coeff = list(next(iter(solutions)))
return linear_combination(coeff, E, len(E[0]))