elysian-noctilucent-algebra / code /v4_error_verify.py
PureOne's picture
Publish ELYSIAEN complete research dataset release
973efa6 verified
Raw History Blame Contribute Delete
8.16 kB
#!/usr/bin/env python3
"""Independent maximum-principle and residual-certificate checks.
Finite numerical models only; no optical timing or energy claims.
"""
from pathlib import Path
from collections import deque
import json
import platform
import numpy as np
ROOT=Path(__file__).resolve().parent
def vn(v,w): return float(np.max(np.abs(v)/w,initial=0.))
def mn(a,wi,wo=None):
if wo is None: wo=wi
return float(np.max(np.sum(np.abs(a)*wi[None,:],axis=1)/wo,initial=0.))
def on(a,w): return float(np.max(np.sum(np.abs(a)*w[None,:],axis=1),initial=0.))
def distances(t,z):
d=np.full(len(t),np.inf);dq=deque()
for j in z:d[j]=0;dq.append(int(j))
while dq:
j=dq.popleft()
for i in np.flatnonzero(t[:,j]>0):
if d[i]>d[j]+1:d[i]=d[j]+1;dq.append(int(i))
return d
def main():
rng=np.random.default_rng(2026102519)
records=[];max_lift=0.;max_full=0.;max_cert_ratio=0.;max_partial_ratio=0.;max_partial_error=0.;max_dist_violation=0.
for trial in range(240):
n=[8,16,32][trial%3];rho=[.3,.8,.98,.9999][trial%4]
w=np.exp(rng.uniform(-2,2,n))
raw=rng.uniform(0,1,(n,n))*(rng.uniform(0,1,(n,n))<.1)
if trial%3==0:
# An acyclic chain gives genuinely nontrivial graph distances.
raw=np.zeros((n,n));raw[np.arange(1,n),np.arange(n-1)]=1
rows=raw.sum(axis=1);nz=rows>0
raw[nz]*=(rho*rng.uniform(.6,1,n)[nz]/rows[nz])[:,None]
t=w[:,None]*raw/w[None,:];g=np.linalg.inv(np.eye(n)-t)
k=int(rng.integers(1,n));z=np.sort(rng.choice(n,k,replace=False));r=np.setdiff1d(np.arange(n),z)
wz=w[z];e=np.eye(n)[:,z];kmat=g[np.ix_(z,z)];ki=np.linalg.inv(kmat)
lift=g[:,z]@ki
block=np.zeros((n,k));block[z]=np.eye(k);block[r]=np.linalg.solve(np.eye(len(r))-t[np.ix_(r,r)],t[np.ix_(r,z)])
lift_error=mn(lift-block,wz,w);max_lift=max(max_lift,lift_error)
assert lift_error<1e-9
assert lift.min()>-1e-9
assert mn(lift,wz,w)<=1+1e-9
dist=distances(t,z);spatial=np.zeros(n)
finite=np.isfinite(dist);spatial[finite]=rho**dist[finite]
violation=float(np.max((lift@wz)/w-spatial));max_dist_violation=max(max_dist_violation,violation)
assert violation<1e-9
b=w*rng.normal(size=n);q=g@b;theta=np.linalg.solve(kmat,q[z])
obs=rng.normal(0,.1,(3,n))/w[None,:]
opaque=np.ones(n);opaque[z]=0;tm=opaque[:,None]*t*opaque[None,:]
true=np.linalg.solve(np.eye(n)-tm,b)
exact=e@b[z]+q-g[:,z]@theta
full_error=vn(exact-true,w);max_full=max(max_full,full_error)
assert full_error<1e-8
sigma=[1e-5,.001,.1,1.][trial%4]
dk=sigma*wz[:,None]*rng.normal(size=(k,k))/wz[None,:]
dq=sigma*wz*rng.normal(size=k)
khat=kmat+dk;qhat=q[z]+dq
th=theta+sigma*wz*rng.normal(size=k)
defect=khat@th-qhat
eta=mn(dk,wz)*vn(th,wz)+vn(dq,wz)+vn(defect,wz)
zo=obs@g[:,z];y0=obs@q;local=obs@e@b[z]
dz=sigma*.01*rng.normal(size=zo.shape)/wz[None,:]
dy=sigma*.01*rng.normal(size=3);dl=sigma*.01*rng.normal(size=3)
pred=y0+dy-(zo+dz)@th+local+dl
coeff=float(np.max(np.abs(obs)@(w*spatial)))
bound=float(max(abs(dy))+max(abs(dl))+on(dz,wz)*vn(th,wz)+coeff*eta)
actual=float(max(abs(obs@true-pred)))
assert actual<=bound+1e-8
ratio=actual/bound if bound else 0.;max_cert_ratio=max(max_cert_ratio,ratio)
# Stronger componentwise ideal-candidate relation is exact.
ideal=e@b[z]+q-g[:,z]@th
assert vn((true-ideal)-lift@(kmat@th-q[z]),w)<1e-8
# Partial-transmission reconstruction and positive residual barrier.
d=rng.uniform(0,1,k);d[rng.uniform(0,1,k)<.2]=0;d[rng.uniform(0,1,k)<.2]=1
s=np.eye(k)-ki;hmat=np.eye(k)-d[:,None]*s*d[None,:]
rhs=(1-d)*b[z]+d*(ki@q[z]);u=np.linalg.solve(hmat,rhs)
abase=q-lift@q[z];blift=lift*d[None,:]+e*(1-d)[None,:]
mask=np.ones(n);mask[z]=d;mt=mask[:,None]*t*mask[None,:]
ptruth=np.linalg.solve(np.eye(n)-mt,b)
partial_error=vn(abase+blift@u-ptruth,w);max_partial_error=max(max_partial_error,partial_error)
assert partial_error<1e-8
assert mn(blift,wz,w)<=1+1e-9
assert np.min((hmat@wz)-(1-rho*d)*wz)>-1e-8
uh=u+.1*wz*rng.normal(size=k)
dh=.005*wz[:,None]*rng.normal(size=(k,k))/wz[None,:]
dhs=.005*wz*rng.normal(size=k)
hhat=hmat+dh;rhshat=rhs+dhs
eh=np.abs(dh);erhs=np.abs(dhs)
residual_envelope=np.abs(hhat@uh-rhshat)+eh@np.abs(uh)+erhs
beta=float(np.max(residual_envelope/((1-rho*d)*wz)))
pactual=vn(ptruth-(abase+blift@uh),w)
assert pactual<=beta+1e-8
max_partial_ratio=max(max_partial_ratio,pactual/beta if beta else 0.)
records.append({'n':n,'k':k,'rho':rho,'lift_identity_error':lift_error,'occupancy_identity_error':full_error,
'distance_bound_violation':violation,'actual_noisy_output_error':actual,'new_output_certificate':bound,
'partial_identity_error':partial_error,'partial_actual_error':pactual,'partial_residual_barrier':beta})
frontier=[]
for rho in [.9,.99,.999,.9999,.99999]:
t=np.full((2,2),rho/2);g=np.linalg.inv(np.eye(2)-t);k=g[0,0]
exact_lift=float(g[1,0]/k)
old=float(g[1,0]*(1+rho));new=rho
assert exact_lift<=new+1e-9
frontier.append({'rho':rho,'exact_surviving_residual_gain':exact_lift,'old_coarse_output_gain_bound':old,
'maximum_principle_distance_bound':new,'coefficient_improvement_factor':old/new})
# One transparent state rules out a uniform source-equation-residual bound.
rho=.9999;transparent_error=1/(1-rho)
assert transparent_error>9999
result={'project':'ELYSIAEN final maximum-principle boundary certificate','date':'2026-10-25','status':'All assertions passed',
'seed':2026102519,'python':platform.python_version(),'numpy':np.__version__,
'weighted_nonsymmetric_trials':240,'hard_output_certificates':240,'partial_opacity_barrier_certificates':240,
'certificate_violations':0,'maximum_harmonic_lift_identity_error':max_lift,
'maximum_occupancy_response_error':max_full,'maximum_partial_opacity_response_error':max_partial_error,
'maximum_distance_bound_numerical_violation':max_dist_violation,
'maximum_noisy_output_error_to_certificate_ratio':max_cert_ratio,
'maximum_partial_error_to_barrier_ratio':max_partial_ratio,
'near_conservative_frontier':frontier,
'transparent_equation_residual_negative_control':{'rho':rho,'unit_residual_error':transparent_error},
'scope':'Exact finite positive transport and stipulated simultaneous calibration envelopes; no optical performance measurements',
'trials':records}
(ROOT/'v4_error_results.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps({key:value for key,value in result.items() if key!='trials'},indent=2))
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
x=np.array([x['rho'] for x in frontier]);fig,ax=plt.subplots(figsize=(7.5,4.2),constrained_layout=True)
ax.semilogx(1/(1-x),[x['old_coarse_output_gain_bound'] for x in frontier],'-o',color='#6B51B8',label='Separate-factor coarse bound')
ax.semilogx(1/(1-x),[x['maximum_principle_distance_bound'] for x in frontier],'-s',color='#178D9B',label='Maximum-principle distance bound')
ax.semilogx(1/(1-x),[x['exact_surviving_residual_gain'] for x in frontier],'--',color='#273044',label='Exact surviving residual gain')
ax.set_yscale('log');ax.set_xlabel('Reference response scale 1/(1-rho)');ax.set_ylabel('Boundary-defect to output coefficient')
ax.set_title('An avoidable certificate amplification disappears');ax.grid(alpha=.2);ax.legend(fontsize=8)
fig.savefig(ROOT/'v4_error_frontier.png',dpi=200);plt.close(fig)
if __name__=='__main__':
try:from threadpoolctl import threadpool_limits
except ImportError:main()
else:
with threadpool_limits(limits=1):main()