elysian-noctilucent-algebra / code /v5_dynamic_verify.py
PureOne's picture
Publish ELYSIAEN complete research dataset release
973efa6 verified
Raw History Blame Contribute Delete
14.3 kB
#!/usr/bin/env python3
"""Standalone exact and truncated causal-return capsule verification.
Run: python v5_dynamic_verify.py [--quick] [--output-prefix v5_dynamic]
Requires NumPy and Matplotlib. No earlier ELYSIAEN modules are imported.
This is a finite positive discrete-time system, not a measured optical device.
The time index is explicitly an implemented state update; a steady radiance
fixed point is not automatically identified with physical or game-frame time.
"""
from __future__ import annotations
import os
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import argparse
import json
import platform
from pathlib import Path
import numpy as np
SEED = 2026102553
def wnorm(x, weight):
x = np.asarray(x)
return float(np.max(np.abs(x)/weight.reshape((-1,)+(1,)*(x.ndim-1)), initial=0.))
def row_map(rng, rows, cols, out_weight, in_weight, budget):
a = rng.uniform(.03, 1., (rows, cols))
a *= (budget*out_weight/(a@in_weight))[:, None]
return a
def precompute(U, D, V, W, OZ, OF, steps):
K, F, J, Q = [], [], [], []
power = np.eye(D.shape[0])
for j in range(steps):
K.append(U@power@V); F.append(U@power@W)
J.append(OF@power@V); Q.append(OF@power@W)
power = power@D
return K, F, J, Q
def initial_traces(U, D, OF, exterior0, steps):
phi=[]; psi=[]; initial=exterior0.copy()
for t in range(steps+1):
phi.append(U@initial); psi.append(OF@initial); initial=D@initial
return phi, psi
def causal(K, F, J, Q, OZ, Bs, Ls, Rs, local_source,
xi, z0, phi, psi, horizon, *, wrong_current_egress=False):
"""Exact when horizon>=steps; otherwise only last horizon impulses kept.
Initial exterior traces phi/psi are compiled before this routine.
A deployed capsule needs their declared initial-state basis or a budget
for dropping them. No exterior-sized array is read in this evaluator.
"""
steps, k = len(Bs), len(z0)
z = np.zeros((steps+1, k)); z[0] = z0
y = np.zeros((steps+1, OZ.shape[0]))
for t in range(steps+1):
incoming = phi[t].copy()
y[t] = OZ@z[t]+psi[t]
for j in range(min(t, horizon)):
old = t-1-j
egress = Rs[min(t, steps-1)] if wrong_current_egress else Rs[old]
outgoing = egress@z[old]
incoming += K[j]@outgoing+F[j]@xi[old]
y[t] += J[j]@outgoing+Q[j]@xi[old]
if t < steps:
z[t+1] = Bs[t]@z[t]+local_source[t]+Ls[t]@incoming
return z, y
def full_oracle(U, D, V, W, OZ, OF, Bs, Ls, Rs, source, xi, z0, f0):
steps, k, nf = len(Bs), len(z0), len(f0)
states = np.zeros((steps+1, k+nf)); states[0] = np.r_[z0, f0]
for t in range(steps):
z, v = states[t, :k], states[t, k:]
states[t+1, :k] = Bs[t]@z+Ls[t]@U@v+source[t]
states[t+1, k:] = D@v+V@Rs[t]@z+W@xi[t]
return states[:, :k], states[:, :k]@OZ.T+states[:, k:]@OF.T
def trial(rng, number, steps):
k = (2, 3, 4)[number % 3]
nf = (7, 12, 20)[(number//3) % 3]
delta = (.2, .6, .9)[(number//9) % 3]
a = np.exp(rng.uniform(-.7, .7, k))
w = np.exp(rng.uniform(-.7, .7, nf))
D = row_map(rng, nf, nf, w, w, delta)
U = row_map(rng, k, nf, a, w, .18*np.sqrt(1-delta))
V = row_map(rng, nf, k, w, a, .25*np.sqrt(1-delta))
W = rng.uniform(.001, .02, (nf, 2))*w[:, None]
OZ = rng.uniform(-.5, .8, (3, k))
OF = rng.uniform(-.2, .4, (3, nf))
Bbar = row_map(rng, k, k, a, a, (.4, .7)[number % 2])
Lbar = row_map(rng, k, k, a, a, .85)
Rbar = row_map(rng, k, k, a, a, .9)
H = np.linalg.solve(np.eye(nf)-D, np.eye(nf))
C = U@H@V
Abar = Bbar+Lbar@C@Rbar
q = float(np.max(Abar@a/a))
assert q < .9
# A single upper family, not individual reduced stability, bounds every
# delayed word. This criterion is sufficient and need not be necessary.
full_upper = np.block([[Bbar, Lbar@U], [V@Rbar, D]])
full_radius=float(max(abs(np.linalg.eigvals(full_upper))))
assert full_radius < 1
rate_records=[]
for gamma in ((delta+full_radius)/2,(full_radius+1)/2):
rate_return=Bbar/gamma+(Lbar@U@np.linalg.solve(gamma*np.eye(nf)-D,V)@Rbar)/gamma
local_rate_radius=float(max(abs(np.linalg.eigvals(rate_return))))
assert (full_radius<gamma)==(local_rate_radius<1)
rate_records.append({'gamma':gamma,'full_radius':full_radius,
'rate_return_radius':local_rate_radius,
'admitted':bool(local_rate_radius<1)})
Bs, Ls, Rs, sources, xis = [], [], [], [], []
local_upper = .12*a
for t in range(steps):
Bs.append(Bbar*rng.uniform(.3, 1., (k, k)))
Ls.append(Lbar*rng.uniform(.2, 1., (k, k)))
Rs.append(Rbar*rng.uniform(.2, 1., (k, k)))
# Abrupt changes and smooth variation both stay in fixed envelopes.
xis.append(np.array([.4+.3*np.sin(t/7.)**2, .8 if t >= steps//3 else .1]))
sources.append(local_upper*rng.uniform(.1, 1., k))
z0 = rng.uniform(0, .1, k)*a
exterior0 = np.zeros(nf) if number%2==0 else rng.uniform(0,.1,nf)*w
K, F, J, Q = precompute(U, D, V, W, OZ, OF, steps)
phi,psi=initial_traces(U,D,OF,exterior0,steps)
exact_z, exact_y = full_oracle(U, D, V, W, OZ, OF, Bs, Ls, Rs, sources, xis, z0, exterior0)
memory_z, memory_y = causal(K, F, J, Q, OZ, Bs, Ls, Rs, sources, xis, z0, phi,psi, steps)
exact_error = max(wnorm((exact_z-memory_z).T, a), float(np.max(abs(exact_y-memory_y))))
assert exact_error < 2e-11
forcing_upper = local_upper+Lbar@U@H@W@np.ones(2)+Lbar@U@(wnorm(exterior0,w)*w)
z_budget = max(wnorm(z0, a), wnorm(forcing_upper, a)/(1-q))
zbar = z_budget*a
assert np.max(exact_z-zbar) <= 1e-11
full_output_gain = (abs(OZ)+abs(OF)@H@V@Rbar)@a
records = []
for h in (0, 1, 2, 4, 8, 16):
approximate_z, approximate_y = causal(K, F, J, Q, OZ, Bs, Ls, Rs, sources, xis, z0, phi,psi, h)
assert np.max(approximate_z-zbar) <= 2e-11
assert np.max(approximate_z-exact_z) <= 2e-11
tail_power = np.linalg.matrix_power(D, h)
exterior_drive = V@Rbar@zbar+W@np.ones(2)
incoming_tail = Lbar@U@tail_power@H@exterior_drive
local_bound = wnorm(incoming_tail, a)/(1-q)
output_tail = abs(OF)@tail_power@H@exterior_drive
output_bound = full_output_gain*local_bound+output_tail
local_error = wnorm((exact_z-approximate_z).T, a)
output_error = np.max(abs(exact_y-approximate_y), axis=0)
assert local_error <= local_bound+2e-10*max(1., local_bound)
assert np.all(output_error <= output_bound+2e-10*np.maximum(1., output_bound))
records.append({"horizon": h, "local_error": local_error,
"local_uniform_bound": local_bound,
"maximum_output_error": float(max(output_error)),
"maximum_output_uniform_bound": float(max(output_bound)),
"local_error_to_bound": local_error/local_bound if local_bound else 0.,
"output_error_to_componentwise_bound": float(np.max(output_error/output_bound))})
wrong_z, wrong_y = causal(K, F, J, Q, OZ, Bs, Ls, Rs, sources, xis, z0, phi,psi, steps, wrong_current_egress=True)
wrong_error = wnorm((wrong_z-exact_z).T, a)
# Compute an a-priori scalar horizon from ||D||<=delta. The matrix-tail
# certificate above is generally sharper and retains propagation shape.
alpha = float(np.max(U@w/a)); ell = float(np.max(Lbar@a/a))
drive_norm = wnorm(V@Rbar@zbar+W@np.ones(2), w)
prefactor = ell*alpha*drive_norm/((1-delta)*(1-q))
target = .001
required_h = max(0, int(np.ceil(np.log(target/prefactor)/np.log(delta)))) if prefactor>target else 0
assert prefactor*delta**required_h <= target+1e-12
return {"local_states": k, "exterior_states": nf, "steps": steps,
"exterior_contraction_delta": delta, "upper_return_witness_q": q,
"initial_exterior_is_zero":bool(np.all(exterior0==0)),
"rate_threshold_checks":rate_records,
"exact_causal_maximum_error": exact_error,
"wrong_current_egress_error": wrong_error,
"scalar_horizon_for_local_error_0_001": required_h,
"retained_kernel_scalars_per_history_step": k*k+k*2+3*k+3*2,
"records": records}, (exact_z, memory_z, records)
def counterexamples():
# Stable reference with coupling .5. Every reduced closure is zero, but
# the actual switched exterior carries a delayed amplifying path.
U=V=np.array([[.5]]); D=np.zeros((1,1)); W=np.zeros((1,1))
OZ=np.array([[1.]]); OF=np.array([[1.]])
steps=16
Bs=[np.zeros((1,1)) for _ in range(steps)]
Ls=[np.array([[4. if t%2==0 else 0.]]) for t in range(steps)]
Rs=[np.array([[0. if t%2==0 else 4.]]) for t in range(steps)]
zero=[np.zeros(1) for _ in range(steps)]
K,F,J,Q=precompute(U,D,V,W,OZ,OF,steps)
phi,psi=initial_traces(U,D,OF,np.ones(1),steps)
z,y=full_oracle(U,D,V,W,OZ,OF,Bs,Ls,Rs,zero,zero,np.zeros(1),np.ones(1))
causal_z,causal_y=causal(K,F,J,Q,OZ,Bs,Ls,Rs,zero,zero,np.zeros(1),phi,psi,steps)
wrong_z,wrong_y=causal(K,F,J,Q,OZ,Bs,Ls,Rs,zero,zero,np.zeros(1),phi,psi,steps,wrong_current_egress=True)
assert np.max(abs(y-causal_y))==0
assert y[-1,0]==65536. and wrong_y[-1,0]==0
# A fixed stable world is still not in equilibrium immediately.
fixed=np.array([[.1,.2],[.2,.8]]); source=np.array([.3,.1])
equilibrium=np.linalg.solve(np.eye(2)-fixed,source)
return {"switching": {"reference_couplings": .5,
"reference_spectral_radius": .5,
"each_reduced_closure": 0., "two_step_full_gain": 4.,
"steps": steps, "final_full_output": float(y[-1,0]),
"final_exact_causal_output": float(causal_y[-1,0]),
"final_wrong_current_egress_output": float(wrong_y[-1,0]),
"common_upper_reduced_return": 4.,
"correct_envelope_admission_rejects": True},
"equilibrium_is_not_first_update": {"equilibrium_local_state":float(equilibrium[0]),
"first_dynamic_local_state_from_zero":.3,
"absolute_difference":float(equilibrium[0]-.3)}}
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("--quick",action="store_true")
parser.add_argument("--output-prefix",default="v5_dynamic")
args=parser.parse_args()
rng=np.random.default_rng(SEED)
ncases=12 if args.quick else 81
steps=32 if args.quick else 96
records=[]; example=None
for number in range(ncases):
record,figuredata=trial(rng,number,steps)
records.append(record)
if number==18 or example is None: example=figuredata
negatives=counterexamples()
all_windows=[item for row in records for item in row['records']]
result={"title":"ELYSIAEN exact causal return capsules and finite-memory bounds",
"date":"2026-10-25","seed":SEED,"python":platform.python_version(),
"numpy":np.__version__,"random_switched_worlds":ncases,
"steps_per_world":steps,"finite_horizons_per_world":6,
"exact_causal_comparisons":ncases,"local_tail_certificates":len(all_windows),
"rate_threshold_equivalence_checks":2*ncases,
"nonzero_initial_exterior_cases":sum(not r['initial_exterior_is_zero'] for r in records),
"componentwise_output_tail_certificates":len(all_windows)*3,
"certificate_violations":0,
"maximum_exact_causal_error":max(r['exact_causal_maximum_error'] for r in records),
"maximum_wrong_current_egress_error":max(r['wrong_current_egress_error'] for r in records),
"maximum_local_error_to_uniform_bound":max(r['local_error_to_bound'] for r in all_windows),
"maximum_output_error_to_componentwise_bound":max(r['output_error_to_componentwise_bound'] for r in all_windows),
"maximum_scalar_horizon_for_local_error_0_001":max(r['scalar_horizon_for_local_error_0_001'] for r in records),
"negative_controls":negatives,"records":records,
"scope":"Exact positive discrete-time dynamics; fixed exterior and supplied common upper family. CPU double-precision tests within declared tolerances, not outward-rounded proof, physical photonic timing, hardware energy or universal game dynamics."}
prefix=Path(args.output_prefix); prefix.parent.mkdir(parents=True,exist_ok=True)
prefix.with_name(prefix.name+'_results.json').write_text(json.dumps(result,indent=2)+'\n')
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size':10,'axes.spines.top':False,'axes.spines.right':False})
fig,axes=plt.subplots(1,3,figsize=(13,3.7),constrained_layout=True)
zs,zm,rs=example
axes[0].plot(zs[:,0],color='#6b51b8',label='Full carried state')
axes[0].plot(zm[:,0],'--',color='#27a9b8',label='Exact causal capsule')
axes[0].set(xlabel='Implemented update',ylabel='Local state',title='History preserves chronology');axes[0].legend(fontsize=8)
axes[1].semilogy([r['horizon'] for r in rs],[max(r['local_error'],1e-16) for r in rs],'o-',color='#6b51b8',label='Actual local error')
axes[1].semilogy([r['horizon'] for r in rs],[r['local_uniform_bound'] for r in rs],'s--',color='#27a9b8',label='Uniform tail bound')
axes[1].set(xlabel='Retained history length',ylabel='Weighted maximum error',title='Certified memory truncation');axes[1].legend(fontsize=8)
eta=[];h=[]
for row in records:eta.append(row['exterior_contraction_delta']);h.append(row['scalar_horizon_for_local_error_0_001'])
axes[2].scatter(eta,h,color='#6b51b8',alpha=.45)
axes[2].set(xlabel='Exterior contraction bound',ylabel='Sufficient history length',title='Near-critical memory costs more')
fig.suptitle('ELYSIAEN / causal return capsules — finite numerical model',fontsize=12)
fig.savefig(prefix.with_suffix('.png'),dpi=170);plt.close(fig)
print(json.dumps({k:result[k] for k in ['random_switched_worlds','exact_causal_comparisons','local_tail_certificates','componentwise_output_tail_certificates','certificate_violations','maximum_exact_causal_error','maximum_scalar_horizon_for_local_error_0_001']},indent=2))
if __name__=='__main__':main()