File size: 8,364 Bytes
9755170 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | """Full two-resource rectangle checks. Random testing does not prove theorems."""
from __future__ import annotations
import json,math,time,platform
from pathlib import Path
import numpy as np
from scipy.optimize import brentq
from scipy.integrate import quad
from maxwell_rectangle import Rectangle,generator_transfer,phase_speed
from maxwell_resource import *
from floquet import log_spectral_radius
from resource_floquet import lifted_phase_map
ROOT=Path(__file__).resolve().parents[1]
rng=np.random.default_rng(260926);start=time.time()
report={'seed':260926,'python':platform.python_version()}
boxes=[Rectangle(1,2,1,3),Rectangle(1,2,1,2),Rectangle(.7,2.5,.4,4)]
canonical=0;gainerr=0.;timeerr=0.;dualerr=0.;switcherr=0.;balanceerr=0.;signerr=0;tests=[]
for box in boxes:
for j in range(600):
eta,xi,zeta=rng.normal(size=3)*float(rng.choice([.15,.6,2.]))
if j%7==0:eta=0.
cell=calibrated_resource_cell(box,eta,xi,zeta)
am,ap,bm,bp=box.amin,box.amax,box.bmin,box.bmax
if min(cell.mean_a-am,ap-cell.mean_a,cell.mean_b-bm,bp-cell.mean_b)<1e-7 or cell.log_gain<1e-7:continue
explicit=explicit_resource_cell(box,cell.period,cell.mean_a,cell.mean_b)
assert cell_winding(explicit)==1
gainerr=max(gainerr,abs(cell.log_gain-explicit.log_gain))
dual,res,sw=resource_dual_parameters(box,explicit)
dualerr=max(dualerr,max(abs(a-b) for a,b in zip(dual,(eta,xi,zeta))))
switcherr=max(switcherr,res)
P=(cell.mean_a-am)/(ap-am);Q=(cell.mean_b-bm)/(bp-bm);w=P+Q-1
if abs(w)>1e-10:assert eta*w>0
# Cyclically merge an origin-split diagonal piece before comparing visits.
st=list(cell.states)
if st[0][:2]==st[-1][:2] and len(st)>1:
a,b,t=st.pop();aa,bb,tt=st[0];st[0]=(aa,bb,t+tt)
diagonal=(ap,bp) if eta>0 else (am,bm)
visits=[t for a,b,t in st if (a,b)==diagonal]
if eta:
assert len(visits)==2
balanceerr=max(balanceerr,abs(visits[0]-visits[1]))
else:assert len(st)==2
for i in range(20):
th=float(rng.uniform(0,math.pi));c,s=math.cos(th),math.sin(th)
K=s*c+xi*c*c-zeta*s*s
if eta>0:ab=(am,bp) if K>eta*s*s/bp else ((ap,bm) if K<-eta*c*c/ap else (ap,bp))
elif eta<0:ab=(am,bp) if K>-eta*c*c/am else ((ap,bm) if K<eta*s*s/bm else (am,bm))
else:ab=(am,bp) if K>0 else (ap,bm)
H=lambda a,b:((b-a)*s*c-eta-xi*a-zeta*b)/(b*c*c+a*s*s)
assert H(*ab)>=max(H(a,b) for a in [am,ap] for b in [bm,bp])-1e-10
canonical+=1
assert gainerr<1e-8 and dualerr<1e-7 and switcherr<1e-10 and balanceerr<1e-9
report['canonical']={'calibrated_cells':canonical,'pointwise_corner_checks':canonical*20,'max_gain_error':gainerr,'max_dual_error':dualerr,'max_switch_equation_residual':switcherr,'max_diagonal_visit_mismatch':balanceerr}
count=0;hyper=0;worst=-math.inf;meanerr=0.;defect_cases=[]
for box in boxes:
am,ap,bm,bp=box.amin,box.amax,box.bmin,box.bmax
for p,q in [(.2,.25),(.3,.7),(.7,.7),(.8,.1),(.2,.9)]:
abar=am+(ap-am)*p;bbar=bm+(bp-bm)*q
for S in np.linspace(.6,8,14):
F,cs=rectangle_resource_optimum(box,float(S),abar,bbar)
for j in range(16):
if j%2:
z=float(rng.uniform(max(0,p+q-1),min(p,q)))
fracs=[z,q-z,p-z,1-p-q+z];corners=[(ap,bp),(am,bp),(ap,bm),(am,bm)]
states=[]
for (a,b),f in zip(corners,fracs):
for t in rng.dirichlet(np.ones(3))*f*S:states.append((a,b,float(t)))
rng.shuffle(states)
else:
N=int(rng.integers(2,15));ts=rng.dirichlet(np.ones(N))*S
raw1=rng.uniform(-1,1,N);raw2=rng.uniform(-1,1,N)
sh1=brentq(lambda x:np.dot(np.clip(raw1+x,0,1),ts)/S-p,-3,3,xtol=1e-14)
sh2=brentq(lambda x:np.dot(np.clip(raw2+x,0,1),ts)/S-q,-3,3,xtol=1e-14)
aa=am+(ap-am)*np.clip(raw1+sh1,0,1);bb=bm+(bp-bm)*np.clip(raw2+sh2,0,1)
states=list(zip(aa,bb,ts))
M=np.eye(2)
for a,b,t in states:M=generator_transfer(a,b,t)@M
L=log_spectral_radius(M);worst=max(worst,L-F);count+=1
meanerr=max(meanerr,abs(sum(a*t for a,b,t in states)/S-abar),abs(sum(b*t for a,b,t in states)/S-bbar))
assert L<=F+2e-8,(box,S,p,q,L,F)
if L>1e-6:
hyper+=1
if len(defect_cases)<50 and j%3==0:defect_cases.append((box,S,abar,bbar,states,M,L,cs))
report['fixed_resource_random']={'profiles':count,'hyperbolic':hyper,'max_bound_excess':worst,'max_mean_error':meanerr}
errors=[];mindef=math.inf
for box,S,abar,bbar,states,M,L,cs in defect_cases:
vals,vecs=np.linalg.eig(M);x=np.real(vecs[:,np.argmax(np.abs(vals))]);theta0=math.atan2(-x[1],x[0]);theta=theta0
for a,b,t in states:
w=math.sqrt(b/a);theta=lifted_phase_map(lifted_phase_map(theta,w)+math.sqrt(a*b)*t,w,True)
n=round((theta-theta0)/math.pi)
cells=[c for j,c in cs if j==n];assert cells
opt=cells[0];dual,_,switches=resource_dual_parameters(box,opt);eta,xi,zeta=dual
corners=[(a,b) for a in [box.amin,box.amax] for b in [box.bmin,box.bmax]]
def defect(th,a,b):
c,s=math.cos(th),math.sin(th)
H=lambda aa,bb:((bb-aa)*s*c-eta-xi*aa-zeta*bb)/(bb*c*c+aa*s*s)
return max(H(*ab) for ab in corners)-H(a,b)
integral=0.;theta=theta0
for a,b,t in states:
w=math.sqrt(b/a);end=lifted_phase_map(lifted_phase_map(theta,w)+math.sqrt(a*b)*t,w,True)
points=[]
for z in switches:
z%=math.pi
for j in range(math.floor(theta/math.pi)-1,math.ceil(end/math.pi)+2):
zz=z+j*math.pi
if theta+1e-12<zz<end-1e-12:points.append(zz)
integral+=quad(lambda th:defect(th,a,b),theta,end,points=sorted(set(points)),epsabs=2e-10,limit=200)[0]
theta=end
errors.append(abs(integral-(n*opt.log_gain-L)));mindef=min(mindef,integral)
assert max(errors)<1e-7
report['defects']={'cases':len(errors),'max_absolute_error':max(errors),'minimum_defect':mindef}
# Resource-ray strict concavity, dual tangency, and two adjacent winners.
concavity_excess=0.;neighbor_checks=0;tangency_error=0.
for box in boxes:
for p,q in [(.2,.25),(.3,.7),(.7,.7),(.2,.9)]:
abar=box.amin+(box.amax-box.amin)*p;bbar=box.bmin+(box.bmax-box.bmin)*q
lo,hi=rectangle_resource_gap_interval(box,abar,bbar)
values=[explicit_resource_cell(box,float(t),abar,bbar).log_gain for t in np.linspace(lo+.02*(hi-lo),hi-.02*(hi-lo),21)]
concavity_excess=max(concavity_excess,float(np.max(np.diff(values,2))))
free=rectangle_resource_free(box,abar,bbar)
eta,xi,zeta=resource_dual_parameters(box,free)[0]
tangency_error=max(tangency_error,abs(eta+xi*abar+zeta*bbar-free.log_gain/free.period))
for S in np.linspace(.5,15,30):
F,cs=rectangle_resource_optimum(box,float(S),abar,bbar)
if cs:
n,c=max(cs,key=lambda z:z[0]*z[1].log_gain)
assert n in {math.floor(S/free.period),math.ceil(S/free.period)}
neighbor_checks+=1
assert concavity_excess<1e-8 and tangency_error<1e-6
report['resource_ray']={'concavity_curves':12,'max_discrete_concavity_excess':concavity_excess,'neighbor_winding_checks':neighbor_checks,'max_free_rate_dual_tangency_error':tangency_error}
# Endpoint means reduce exactly to the retained scalar resource theorem.
from resource_floquet import resource_optimum
endpoint_checks=0;endpoint_error=0.
for box in boxes:
for S in np.linspace(.5,7,8):
for aa,bb in [(box.amin,(box.bmin+box.bmax)/2),(box.amax,(box.bmin+box.bmax)/2),((box.amin+box.amax)/2,box.bmin),((box.amin+box.amax)/2,box.bmax)]:
F,cs=rectangle_resource_optimum(box,float(S),aa,bb)
for n,cell in cs:
endpoint_error=max(endpoint_error,abs(log_spectral_radius(resource_cell_monodromy(cell))-cell.log_gain))
assert cell_winding(cell)==1
endpoint_checks+=1
assert endpoint_error<1e-8
report['endpoint_reductions']={'cases':endpoint_checks,'max_equality_error':endpoint_error}
box=boxes[0];examples=[]
for abar,bbar,S in [(1.7,2.4,1.6),(1.7,2.4,2.),(1.3,1.4,2.),(1.3,2.4,2.)]:
F,cs=rectangle_resource_optimum(box,S,abar,bbar)
examples.append({'bounds':[1,2,1,3],'period':S,'mean_a':abar,'mean_b':bbar,'maximum_log_gain':F,'candidates':[{'winding':n,'gain':n*c.log_gain,'states':c.states,'duals':resource_dual_parameters(box,c)[0]} for n,c in cs]})
report['examples']=examples
report['elapsed_seconds']=time.time()-start;report['all_assertions_passed']=True
(ROOT/'results'/'verification_maxwell_resource.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2))
|