File size: 10,976 Bytes
347a3de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""Reproduce every v6 numerical figure and the raw model-results tables.

All quantities are dimensionless examples; no hardware data are included.
Run from any directory: python src/run_experiments.py [--quick]
"""
from pathlib import Path
import argparse
import json
import platform
import sys
import numpy as np
import scipy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from scipy.stats import chi2
from risk_math import (ou_continuous_bounds, survival_fv, mean_exit_fv,
                       mean_exit_time, laplace_exit, laplace_exit_fv,
                       simulate_nested_sampled_exit, poisson_clearance)
from calibration import diffusion_upper
from quantum_checks import (cat_holonomy, gram_projector_check,
                            cutoff_check, displacement_identity_check)

ROOT=Path(__file__).resolve().parents[1]
FIG=ROOT/'figures'
RES=ROOT/'results'
NAVY='#152642'
TEAL='#00787f'
GOLD='#bd7632'
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,
                     'axes.spines.top':False,'axes.spines.right':False,
                     'axes.labelcolor':NAVY,'text.color':NAVY,
                     'figure.facecolor':'white','savefig.facecolor':'white'})


def save(name):
    plt.tight_layout()
    plt.savefig(FIG/(name+'.pdf'),bbox_inches='tight')
    plt.savefig(FIG/(name+'.png'),dpi=180,bbox_inches='tight')
    plt.close()


def write(name,data):
    (RES/name).write_text(json.dumps(data,indent=2,allow_nan=False)+'\n')


def wilson(k,n):
    z=1.959963984540054
    p=k/n
    denom=1+z*z/n
    center=(p+z*z/(2*n))/denom
    half=z*np.sqrt(p*(1-p)/n+z*z/(4*n*n))/denom
    return [float(center-half),float(center+half)]


def reliability():
    ts=np.geomspace(.05,12,70)
    cases=[]
    fig,axes=plt.subplots(1,2,figsize=(10,4))
    for ax,d in zip(axes,(.08,.04)):
        fv=survival_fv(1,ts,1,d,cells=800)
        rows=[ou_continuous_bounds(1,float(t),1,d) for t in ts]
        estimate=fv['exit_probability']
        mask=estimate>1e-10
        ax.loglog(ts,[r['v5_direct_upper'] for r in rows],color=GOLD,
                  label='v5 direct upper')
        ax.loglog(ts,[r['poisson_upper'] for r in rows],color=TEAL,
                  label='positive-Poisson upper')
        ax.loglog(ts,[max(r['upper'],1e-16) for r in rows],color=NAVY,
                  linestyle='--',label='best analytic upper')
        ax.loglog(ts[mask],estimate[mask],color='#a14065',
                  label='survival PDE estimate')
        ax.set(title=f'R=1, kappa=1, d={d} (beta={1/(2*d):g})',
               xlabel='Operating time',ylabel='Continuous exit probability')
        ax.set_ylim(1e-9,1.3)
        ax.grid(alpha=.15,which='both')
        if d==.08: ax.legend(fontsize=8)
        for T in (.03,.2,2.,10.):
            b=ou_continuous_bounds(1,T,1,d)
            convergence=[]
            for cells in (100,200,400,800):
                p=survival_fv(1,[T],1,d,cells)['exit_probability'][0]
                mt=mean_exit_fv(1,1,d,cells)
                lt=laplace_exit_fv(.2,1,1,d,cells)
                convergence.append({'cells':cells,'exit_estimate':float(p) if np.isfinite(p) else None,
                                    'exit_resolved':bool(np.isfinite(p)),
                                    'mean_relative_error':abs(mt/b['mean_exit_time']-1),
                                    'laplace_relative_error':abs(lt/laplace_exit(.2,1,1,d)-1)})
            cases.append({'radius':1,'kappa':1,'diffusion':d,'T':T,
                          'bounds':b,'grid_convergence':convergence})
    save('01_continuous_reliability')
    write('reliability_comparison.json',{'interpretation':'analytic bounds evaluated in float64; survival grids are estimates, not certified intervals','cases':cases})


def monitoring(quick):
    out=simulate_nested_sampled_exit(1,2,1,.08,.001,
                                    sample_strides=(1,5,10,50,100),
                                    trials=3000 if quick else 30000,seed=20261013)
    out['wilson_95']={s:wilson(k,out['trials']) for s,k in out['counts'].items()}
    out['continuous_pde_estimate']=float(survival_fv(1,[2],1,.08,800)['exit_probability'][0])
    write('nested_monitoring.json',out)
    keys=['1','10','100']
    vals=[out['rates'][s] for s in keys]
    intervals=np.array([out['wilson_95'][s] for s in keys])
    err=np.vstack([np.array(vals)-intervals[:,0],intervals[:,1]-np.array(vals)])
    plt.figure(figsize=(7,4))
    plt.bar(['0.001','0.01','0.1'],vals,color=[TEAL,NAVY,GOLD],width=.6)
    plt.errorbar(np.arange(3),vals,yerr=err,fmt='none',ecolor=NAVY,capsize=4)
    plt.axhline(out['continuous_pde_estimate'],color='#a14065',linestyle='--',
                label='Continuous PDE estimate (800 cells)')
    plt.ylabel('Detected first-exit fraction')
    plt.xlabel('Observation interval on the same nested paths')
    plt.title(f'Sampling misses crossings / {out["trials"]:,} OU trajectories')
    plt.legend(fontsize=9)
    save('02_sampling_bias')


def clearance():
    times=np.geomspace(.1,20,65)
    new=np.array([poisson_clearance(float(t),1,.04,.001) for t in times])
    old=np.sqrt(.08*(2*times+np.log(1000)))
    plt.figure(figsize=(7,4))
    plt.semilogx(times,old,color=GOLD,label='v5 direct sufficient margin')
    plt.semilogx(times,new,color=TEAL,label='positive-Poisson sufficient margin')
    plt.xlabel('Operating time (kappa=1)')
    plt.ylabel('Required radius (d=0.04)')
    plt.title('One-event analytic risk budget: 0.001')
    plt.legend()
    plt.grid(alpha=.15)
    save('03_clearance_design')
    write('clearance_design.json',{'kappa':1,'diffusion':.04,'budget':.001,
                                 'events':1,'times':times.tolist(),
                                 'poisson_radius':new.tolist(),'v5_direct_radius':old.tolist(),
                                 'T10_poisson':poisson_clearance(10,1,.04,.001),
                                 'T10_v5_direct':float(np.sqrt(.08*(20+np.log(1000))))})


def graph_design():
    rng=np.random.default_rng(62291)
    n,G,k,q0=8,4.,1.,2.
    edges=[(i,j) for i in range(n) for j in range(i+1,n)]
    incidence=np.zeros((len(edges),n))
    for index,(i,j) in enumerate(edges):
        incidence[index,i]=1;incidence[index,j]=-1
    def worst(gains):
        L=incidence.T@(gains[:,None]*incidence)
        Sigma=q0/2*np.linalg.inv(k*np.eye(n)+L)
        return float(np.max(np.diag(incidence@Sigma@incidence.T)))
    optimum=q0/(k+2*G/(n-1))
    uniform=worst(np.full(len(edges),G/len(edges)))
    random_values=[worst(G*rng.dirichlet(np.ones(len(edges)))) for _ in range(1000)]
    assert abs(uniform-optimum)<1e-12
    assert min(random_values)>=optimum-1e-12
    plt.figure(figsize=(7,4))
    plt.hist(random_values,bins=32,color=NAVY,alpha=.8,label='1,000 random budget allocations')
    plt.axvline(optimum,color=TEAL,linewidth=2,label='Proved uniform-complete optimum')
    plt.xlabel('Worst stationary pair variance (one coordinate)')
    plt.ylabel('Allocation count')
    plt.title('Graph stabilization at fixed gain budget / n=8, G=4')
    plt.legend(fontsize=8)
    save('04_graph_budget')
    write('graph_budget.json',{'seed':62291,'nodes':n,'gain_budget':G,'kappa':k,
                              'noise_covariance_q0':q0,'exact_optimum':optimum,
                              'uniform_value':uniform,'random_values':random_values,
                              'scope':'stationary variance in declared linear drift; no global braid action or hardware optimum claimed'})


def quantum():
    out={'status':'algebra checks; ideal adiabatic branch, no laboratory or gap certification',
         'cat_holonomy':[cat_holonomy(A) for A in (.25,.5,1,2,4,6,9)],
         'coherent_gram_projector':gram_projector_check(),
         'finite_cutoff':cutoff_check(),'shifted_root':displacement_identity_check()}
    write('quantum_checks.json',out)
    aa=np.geomspace(.05,10,200)
    phase=np.pi-2*np.pi*aa/np.sinh(2*aa)
    fig,ax=plt.subplots(1,2,figsize=(10,4))
    ax[0].semilogx(aa,phase/np.pi,color=TEAL)
    ax[0].set(xlabel='A = |alpha| squared',ylabel='Relative holonomy phase / pi',
              title='Same root-exchange braid, different gate')
    ax[1].plot(aa,aa*np.tanh(aa),color=TEAL,label='Even cat mean photons')
    ax[1].plot(aa,aa/np.tanh(aa),color=GOLD,label='Odd cat mean photons')
    ax[1].set(xlabel='A = |alpha| squared',ylabel='Parity-jump rate / kappa_1',
              title='Larger separation also changes loss cost')
    ax[1].legend(fontsize=8)
    save('05_quantum_phase_resource')
    rows=out['finite_cutoff']
    plt.figure(figsize=(7,4))
    plt.semilogy([r['fock_dimension'] for r in rows],
                 [r['analytic_boundary_residual'] for r in rows],
                 'o-',color=TEAL,label='Analytic truncated-state boundary residual')
    plt.semilogy([r['fock_dimension'] for r in rows],
                 [r['normalized_coherent_jump_residual'] for r in rows],
                 's--',color=GOLD,label='Direct float64 residual (roundoff floor)')
    plt.xlabel('Fock cutoff dimension')
    plt.ylabel('Norm of (a_N squared - alpha squared) on truncated coherent state')
    plt.title('Near-dark convergence does not create an exact finite-cutoff kernel')
    plt.legend(fontsize=8)
    save('06_cutoff_diagnostic')


def calibration(quick):
    rng=np.random.default_rng(63109)
    reps=500 if quick else 5000
    n,k,h,d=40,1.7,.13,.24
    scale=-np.expm1(-2*k*h)/k
    sample=rng.normal(0,np.sqrt(d*scale),(reps,n))
    ss=np.sum(sample*sample,axis=1)
    upper=ss/(scale*chi2.ppf(.05,n))
    covered=int(np.sum(d<=upper))
    write('calibration_coverage.json',{'seed':63109,'repetitions':reps,
                                     'scalar_innovations_per_repetition':n,
                                     'kappa':k,'dt':h,'true_diffusion':d,
                                     'confidence':.95,'covered':covered,
                                     'empirical_coverage':covered/reps,
                                     'wilson_95':wilson(covered,reps),
                                     'assumptions':'known kappa and exact uncensored Gaussian state observations'})


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--quick',action='store_true',help='fewer Monte Carlo/calibration trials; overwrites result files')
    args=parser.parse_args()
    FIG.mkdir(exist_ok=True);RES.mkdir(exist_ok=True)
    reliability(); print('Continuous risk and PDE cross-checks complete',flush=True)
    monitoring(args.quick); print('Nested observation experiment complete',flush=True)
    clearance(); graph_design(); quantum();calibration(args.quick)
    write('runtime.json',{'python':sys.version,'platform':platform.platform(),
                          'numpy':np.__version__,'scipy':scipy.__version__,
                          'matplotlib':matplotlib.__version__,'quick':args.quick})
    print('All six figures and result tables generated',flush=True)


if __name__=='__main__':main()