NYRAELUNE-V / feedback_frontier.py
PureOne's picture
NYRAELUNE V 5.0.0: manuscript, exact solvers, and verification
fda6cea verified
Raw History Blame Contribute Delete
11.1 kB
#!/usr/bin/env python3
"""Exact finite certificate for centered analytic transport with feedback.
Usage: python3 feedback_frontier.py INPUT.json
Input: real rational polynomial matrices under ``generators``; optional positive
``probabilities`` summing to one; optional positive rational horizon ``alpha``.
Entries are integers, rational/decimal strings, or dictionaries mapping
nonnegative integer powers of t to rational coefficients. The solver uses only
the standard library and returns exact rational data. A nonnilpotent base is
rejected (JSON status plus CLI exit code 2). Historical novelty is not certified.
"""
from fractions import Fraction as F
from pathlib import Path
from math import factorial
import json
import sys
def rational(value):
if isinstance(value, bool):
raise ValueError('Boolean values are not rational input coefficients.')
return F(str(value)) if isinstance(value, float) else F(value)
def clean(p):
return {k: F(v) for k, v in p.items() if v}
def addp(a, b):
c = a.copy()
for k, v in b.items():
c[k] = c.get(k, F(0)) + v
return clean(c)
def scalep(a, x):
return clean({k: v*x for k, v in a.items()})
def mulp(a, b):
c = {}
for i, x in a.items():
for j, y in b.items():
c[i+j] = c.get(i+j, F(0)) + x*y
return clean(c)
def constant(x):
return {0: F(x)} if x else {}
def parse_entry(value):
if not isinstance(value, dict):
return constant(rational(value))
out = {}
for power, value in value.items():
power = rational(power)
if power.denominator != 1 or power < 0:
raise ValueError('Polynomial powers must be nonnegative integers.')
power = int(power)
out[power] = out.get(power, F(0)) + rational(value)
return clean(out)
def zeros(d):
return [[{} for _ in range(d)] for _ in range(d)]
def identity(d):
a = zeros(d)
for i in range(d):
a[i][i] = constant(1)
return a
def addm(a, b):
return [[addp(x, y) for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def scalem(a, x):
return [[scalep(cell, x) for cell in row] for row in a]
def mulm(a, b):
d = len(a)
out = zeros(d)
for i in range(d):
for k in range(d):
if not a[i][k]:
continue
for j in range(d):
if b[k][j]:
out[i][j] = addp(out[i][j], mulp(a[i][k], b[k][j]))
return out
def transpose(a):
return [list(row) for row in zip(*a)]
def trace(a):
result = {}
for i in range(len(a)):
result = addp(result, a[i][i])
return result
def cp(a, qs, ps):
out = zeros(len(a))
for q, p in zip(qs, ps):
out = addm(out, scalem(mulm(mulm(transpose(q), a), q), p))
return out
def superoperator(qs, ps):
d = len(qs[0])
a = zeros(d*d)
for u in range(d):
for v in range(d):
for r in range(d):
for s in range(d):
cell = {}
for q, p in zip(qs, ps):
cell = addp(cell, scalep(mulp(q[u][r], q[v][s]), p))
a[r*d+s][u*d+v] = cell
return a
def characteristic_coefficients(a):
"""Faddeev--LeVerrier over the exact rational polynomial ring."""
m = len(a)
b = identity(m)
result = []
for j in range(1, m+1):
ab = mulm(a, b)
coefficient = scalep(trace(ab), F(-1, j))
result.append(coefficient)
b = addm(ab, [[coefficient if r == s else {} for s in range(m)] for r in range(m)])
if b != zeros(m):
raise ArithmeticError('Characteristic-polynomial certificate failed.')
return result
def order(p):
return min(p) if p else None
def min_or_infinity(values):
values = list(values)
return min(values) if values else None
def encoded_order(x):
return str(x) if x is not None else 'infinity'
def coefficient_matrix(a, exponent):
# Fraction keys equal integer keys exactly when their values are equal.
return [[cell.get(exponent, F(0)) for cell in row] for row in a]
def numeric_zero(d):
return [[F(0) for _ in range(d)] for _ in range(d)]
def numeric_zero_p(a):
return all(not x for row in a for x in row)
def encode_matrix(a):
return [[str(x) for x in row] for row in a]
def encode_polynomial(a):
return {str(k): str(v) for k, v in sorted(a.items())}
def recurrence_extend(initial, coefficients, through):
"""Extend L_k + sum_j coefficients[j-1] L_(k-j)=0."""
values = [[list(row) for row in a] for a in initial]
m, d = len(coefficients), len(initial[0])
while len(values) <= through:
k = len(values)
out = numeric_zero(d)
for j, a in enumerate(coefficients, 1):
if a:
for r in range(d):
for s in range(d):
out[r][s] -= a*values[k-j][r][s]
values.append(out)
return values
def scaled_data(cs, aa, scale, gamma):
initial = [coefficient_matrix(c, scale*k-gamma) for k, c in enumerate(cs)]
coefficients = [a.get(scale*(j+1), F(0)) for j, a in enumerate(aa)]
return initial, coefficients
def alpha_phase(alpha, b, cs, aa, orders):
if alpha <= 0:
raise ValueError('The optional alpha must be strictly positive.')
if b is not None and alpha > b:
spectral_coefficients = [F(1)]+[a.get(b*(j+1), F(0)) for j, a in enumerate(aa)]
return {'alpha': str(alpha), 'kind': 'exponential', 'b': str(b),
'scaled_log_limit': 't^(alpha-b) log ||G_floor(s*t^-alpha)|| -> s*r',
'r': {'definition': 'largest modulus of a root of this monic polynomial',
'polynomial_coefficients_descending': [str(x) for x in spectral_coefficients]}}
gamma = max(alpha*k-v for k, v in enumerate(orders) if v is not None)
initial, coefficients = scaled_data(cs, aa, alpha, gamma)
common = {'alpha': str(alpha), 'gamma': str(gamma),
'scaling': 't^gamma G_floor(s*t^-alpha)'}
if b is None or alpha < b:
face = [k for k, v in enumerate(orders) if v is not None and alpha*k-v == gamma]
common.update({'kind': 'polynomial', 'face_indices': face,
'limit_polynomial_coefficients': {
str(k): encode_matrix([[x/F(factorial(k)) for x in row] for row in initial[k]])
for k in face}})
else:
common.update({'kind': 'entire_ode',
'initial_derivatives': [encode_matrix(a) for a in initial],
'ode_coefficients': [str(x) for x in coefficients],
'ode': 'E^(M)+sum_(j=1)^M ode_coefficients[j-1]*E^(M-j)=0'})
return common
def analyze(data):
raw = data['generators']
if not raw:
raise ValueError('At least one generator is required.')
d = len(raw[0])
if d < 1 or any(len(q) != d or any(len(row) != d for row in q) for q in raw):
raise ValueError('Generators must be square matrices of one common positive dimension.')
qs = [[[parse_entry(v) for v in row] for row in q] for q in raw]
ps = [rational(p) for p in data.get('probabilities', [F(1, len(qs))]*len(qs))]
if len(ps) != len(qs) or any(p <= 0 for p in ps) or sum(ps) != 1:
raise ValueError('Probabilities must be positive and sum exactly to one.')
optional_alpha = rational(data['alpha']) if 'alpha' in data else None
if optional_alpha is not None and optional_alpha <= 0:
raise ValueError('The optional alpha must be strictly positive.')
m = d*d
cs = [identity(d)]
for _ in range(d):
cs.append(cp(cs[-1], qs, ps))
base_certified = numeric_zero_p(coefficient_matrix(cs[d], F(0)))
result = {'dimension': d, 'M': m, 'labels': len(qs),
'nilpotent_base_certified': base_certified,
'base_certificate': 'Phi_0^D(I)=0' if base_certified else 'Phi_0^D(I) is nonzero'}
if not base_certified:
result.update({'status': 'rejected', 'reason': 'The base CP map is not nilpotent; no frontier asserted.'})
return result
h = max(k for k in range(d) if not numeric_zero_p(coefficient_matrix(cs[k], F(0))))
while len(cs) < m:
cs.append(cp(cs[-1], qs, ps))
cs = cs[:m]
aa = characteristic_coefficients(superoperator(qs, ps))
orders = [order(trace(c)) for c in cs]
if any(v is not None and v % 2 for v in orders):
raise ArithmeticError('A positive polynomial word-square trace had odd vanishing order.')
char_orders = [order(a) for a in aa]
b = min_or_infinity(F(v, j+1) for j, v in enumerate(char_orders) if v is not None)
candidates = ([b] if b is not None else []) + [F(v, k-h) for k, v in enumerate(orders) if k > h and v is not None]
beta = min_or_infinity(candidates)
result.update({'status': 'certified', 'h': h, 'v_k': orders,
'characteristic_coefficient_orders': char_orders,
'characteristic_coefficients': [encode_polynomial(a) for a in aa],
'b': encoded_order(b), 'beta': encoded_order(beta),
'algebraic_horizon_criterion': 'alpha <= beta',
'precision_power_N': str(1/beta) if beta is not None else None})
if beta is None:
result.update({'critical': None, 'all_horizons_baseline_bound': True,
'full_horizon_iff_N_t_beta_bounded': None})
else:
initial, coefficients = scaled_data(cs, aa, beta, beta*h)
extended = recurrence_extend(initial, coefficients, h+m)
block = extended[h+1:h+m+1]
attaining = next((h+1+j for j, a in enumerate(block) if not numeric_zero_p(a)), None)
result.update({'all_horizons_baseline_bound': False,
'full_horizon_iff_N_t_beta_bounded': attaining is not None,
'critical': {'normalization_exponent': str(beta*h),
'initial_derivatives': [encode_matrix(a) for a in initial],
'ode_coefficients': [str(x) for x in coefficients],
'ode': 'E^(M)+sum_(j=1)^M ode_coefficients[j-1]*E^(M-j)=0',
'all_horizon_test_indices': [h+1, h+m],
'all_horizon_test_block': [encode_matrix(a) for a in block],
'first_attaining_word_length': attaining}})
if optional_alpha is not None:
result['alpha_phase'] = alpha_phase(optional_alpha, b, cs, aa, orders)
return result
def main():
if len(sys.argv) != 2:
raise SystemExit('Usage: python3 feedback_frontier.py INPUT.json')
try:
data = json.loads(Path(sys.argv[1]).read_text(), parse_float=str)
result = analyze(data)
except (ValueError, KeyError, TypeError, ZeroDivisionError, OverflowError) as exc:
raise SystemExit(f'Invalid input: {exc}') from None
print(json.dumps(result, indent=2))
return 0 if result['nilpotent_base_certified'] else 2
if __name__ == '__main__':
raise SystemExit(main())