EVE-QELTHA / research /code /verify_nexus.py
PureOne's picture
Add EVE-QELTHA v4.0 research release, proofs, verification data and manuscript
9427ec0 verified
Raw History Blame Contribute Delete
9.03 kB
#!/usr/bin/env python3
"""Cartesian-pressure FEM for passive spatial-coherence nexus kernels.
Both systems retain the original rotating rank-one local drainage. Their
added nonlocal kernels have identical pointwise diagonals; one uses a coherent
difference of two separated pressure averages, the other records independent
averages. The full finite-epsilon energy is discretized before minimization.
"""
from pathlib import Path
import argparse
import json
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy import sparse
from scipy.sparse.linalg import splu
def _base_problem(epsilon, cells=6000, endpoint=4., a=2., b=.8, s=3., A=1., B=1.):
xmax=endpoint*epsilon**(-1/s)
# The port boundaries are inserted exactly, so Gaussian quadrature never
# crosses a discontinuity of either box profile.
xs=np.unique(np.concatenate((np.geomspace(1.,xmax,cells+1),[2.,3.,4.])))
widths=np.diff(xs)
n=len(widths)
gp,gw=leggauss(6)
local=np.zeros((n,4,4))
port=np.zeros((2,2*len(xs)))
ids=2*np.arange(n)[:,None]+np.arange(4)[None,:]
cache=[]
for q,w in zip(gp,gw):
N1,N2=(1-q)/2,(1+q)/2
xx=(xs[:-1]+xs[1:])/2+widths*q/2
ww=widths*w/2
dn=1/widths
deriv=np.zeros((n,2,4))
deriv[:,0,:]=np.stack((-dn,0*dn,dn,0*dn),axis=1)
deriv[:,1,:]=np.stack((0*dn,-dn,0*dn,dn),axis=1)
theta=epsilon*(xx**s-1)
ct,st=np.cos(theta),np.sin(theta)
bright=np.stack((N1*ct,N1*st,N2*ct,N2*st),axis=1)
local+=(ww*xx**(-a)/A)[:,None,None]*np.einsum('nki,nkj->nij',deriv,deriv)
local+=(ww*B*xx**(-b))[:,None,None]*np.einsum('ni,nj->nij',bright,bright)
dark=np.broadcast_to(np.array([0.,N1,0.,N2]),(n,4))
f1=((xx>1)&(xx<2)).astype(float)
f2=((xx>3)&(xx<4)).astype(float)
for j,f in enumerate((f1,f2)):
np.add.at(port[j],ids.ravel(),(ww[:,None]*f[:,None]*dark).ravel())
cache.append((ww,xx,deriv,bright))
rr=np.broadcast_to(ids[:,:,None],local.shape).ravel()
cc=np.broadcast_to(ids[:,None,:],local.shape).ravel()
size=2*len(xs)
H=sparse.coo_matrix((local.ravel(),(rr,cc)),shape=(size,size)).tocsr()
fixed=np.array([1,size-2,size-1])
free=np.setdiff1d(np.arange(size),fixed,assume_unique=True)
Hff=H[free,:][:,free].tocsc()
rhs=-H[free,1].toarray().ravel()
diag=1/np.sqrt(Hff.diagonal())
D=sparse.diags(diag)
solver=splu((D@Hff@D).tocsc())
def solve(rhs):
if rhs.ndim==1:return diag*solver.solve(diag*rhs)
return diag[:,None]*solver.solve(diag[:,None]*rhs)
z0=solve(rhs)
# Positive quadrature energy; avoid cancellation in a stiffness quadratic.
def evaluate(z,portrows):
full=np.zeros(size);full[1]=1.;full[free]=z
loc=full[ids]
derivative=leakage=0.
for ww,xx,deriv,bright in cache:
dd=np.einsum('nki,ni->nk',deriv,loc)
bb=np.einsum('ni,ni->n',bright,loc)
derivative+=np.dot(ww*xx**(-a)/A,np.sum(dd*dd,axis=1))
leakage+=np.dot(ww*B*xx**(-b),bb*bb)
output=portrows@full
ports=float(output@output)
return full,dict(derivative_energy=float(derivative),local_leakage_energy=float(leakage),
nonlocal_port_energy=ports,capacity=float(derivative+leakage+ports))
return dict(Hff=Hff,rhs=rhs,free=free,port=port,z0=z0,solve=solve,
evaluate=evaluate,xmax=xmax,cells=n,size=size)
def capacity_pair(epsilon,cells=6000,endpoint=4.,strength=1.):
base=_base_problem(epsilon,cells=cells,endpoint=endpoint)
out=[]
f=base['free'];z0=base['z0'];solve=base['solve']
for name,rows in [('coherent_difference',(base['port'][0]-base['port'][1])[None,:]),
('coherent_sum',(base['port'][0]+base['port'][1])[None,:]),
('independent_outputs',base['port'])]:
rows=np.sqrt(strength)*rows
L=rows[:,f];y0=L@z0+rows[:,1]
W=solve(L.T)
S=L@W
correction=np.linalg.solve(np.eye(len(rows))+S,y0)
z=z0-W@correction
full,energies=base['evaluate'](z,rows)
residual=base['Hff']@z-base['rhs']+L.T@(rows@full)
relres=float(np.linalg.norm(residual)/max(np.linalg.norm(base['rhs']),1.))
out.append(dict(epsilon=epsilon,kind=name,cells=base['cells'],endpoint=endpoint,
xmax=float(base['xmax']),strength=strength,
impedance=float(1/energies['capacity']),
scaled_capacity=float(energies['capacity']/epsilon),
relative_stationarity_residual=relres,
port_outputs=(rows@full).tolist(),**energies))
return out
def run(output):
rows=[]
target_capacity=46440/69839
target_impedance=69839/46440
for eps in [1e-2,1e-3,1e-4,1e-5,1e-6]:
pair=capacity_pair(eps,cells=7000)
for r in pair:
r['target']={'coherent_difference':3.,'coherent_sum':120/467,
'independent_outputs':target_capacity}[r['kind']]
measured=r['scaled_capacity'] if r['kind']=='coherent_difference' else r['capacity']
r['relative_error_to_asymptotic_target']=abs(measured/r['target']-1)
rows.append(r)
mesh=[]
for n in [3500,7000,14000]:
for r in capacity_pair(1e-5,cells=n):r['check']='mesh';mesh.append(r)
tail=capacity_pair(1e-5,cells=14000,endpoint=5.)
for r in tail:r['check']='endpoint'
rows.extend(mesh+tail)
# Equality of diagonal data is exact algebraically and checked on a grid.
xx=np.linspace(1,4,2001)
f1=((xx>=1)&(xx<=2)).astype(float)
f2=((xx>=3)&(xx<=4)).astype(float)
diag_error=float(np.max(np.abs((f1-f2)**2-(f1*f1+f2*f2))))
assert diag_error==0
# In the orthonormal box-profile basis the two integral operators reduce
# exactly to these matrices; the remaining Hilbert-space spectrum is zero.
plus_spectrum=np.linalg.eigvalsh(np.array([[1.,1.],[1.,1.]]))
minus_spectrum=np.linalg.eigvalsh(np.array([[1.,-1.],[-1.,1.]]))
assert np.allclose(plus_spectrum,minus_spectrum,atol=1e-14)
last_coh=[r for r in rows[:15] if r['kind']=='coherent_difference'][-1]
last_plus=[r for r in rows[:15] if r['kind']=='coherent_sum'][-1]
last_ind=[r for r in rows[:15] if r['kind']=='independent_outputs'][-1]
assert last_coh['relative_error_to_asymptotic_target']<3e-3,last_coh
assert last_ind['relative_error_to_asymptotic_target']<3e-3,last_ind
assert last_plus['relative_error_to_asymptotic_target']<3e-3,last_plus
for kind in ['coherent_difference','coherent_sum','independent_outputs']:
checks=[r for r in mesh if r['kind']==kind]
relmesh=abs(checks[-1]['capacity']/checks[-2]['capacity']-1)
reltail=abs(next(r for r in tail if r['kind']==kind)['capacity']/checks[-1]['capacity']-1)
assert relmesh<3e-4,(kind,'mesh',relmesh)
assert reltail<3e-4,(kind,'tail',reltail)
result=dict(status='PASS',method='Original Cartesian-coordinate pressure FEM, six-point Gaussian quadrature; exact low-rank port minimization',
model=dict(A=1,B=1,a=2,b=.8,s=3,strength=1,
f1='indicator [1,2]',f2='indicator [3,4]'),
identical_kernel_diagonal_max_error=diag_error,
constant_dark_response=dict(coherent_difference=0,coherent_sum=2,independent_outputs=[1,1]),
coherent_plus_minus_identical_operator_spectrum=dict(nonzero_eigenvalue=2,rank=1,
plus_reduced_eigenvalues=plus_spectrum.tolist(),minus_reduced_eigenvalues=minus_spectrum.tolist(),
derivation='disjoint unit box supports imply ||f1+f2||_L2^2=||f1-f2||_L2^2=2'),
exact_coherent_sum_limit=dict(capacity_fraction='120/467',capacity=120/467,
impedance_fraction='467/120',impedance=467/120),
exact_independent_limit=dict(capacity_fraction='46440/69839',capacity=target_capacity,
impedance_fraction='69839/46440',impedance=target_impedance,
H=[[8/15,11/12],[11/12,61/5]]),
coherent_limit=dict(scaled_capacity=3,impedance='1/(3 epsilon)'),rows=rows,
scope='Fixed compact ports; no claim of universal numerical error certification or literature-first novelty')
output=Path(output);output.parent.mkdir(parents=True,exist_ok=True)
output.write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(dict(status=result['status'],rows=len(rows),last_coherent=last_coh,
last_coherent_sum=last_plus,last_independent=last_ind,output=str(output)),indent=2))
return result
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output',default=str(Path(__file__).resolve().parents[1]/'results'/'nexus.json'))
run(parser.parse_args().output)