File size: 17,755 Bytes
17f5052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""Reproduce all synthetic experiments and figure data; no external service required.

Every random seed and physical assumption is explicit. No data are laboratory
measurements. Changing the protocol creates a new experiment, not a replication.
"""
from pathlib import Path
from itertools import combinations
from math import comb
import argparse, csv, json, platform
import numpy as np
import scipy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from eiroq.controls import Control,bank,dimension,rank_law,feature_matrix,even_subsets,modular_rank
from eiroq.model import (vertices,phase_law,direct_coherence,exact_normalized_row,
                        entanglement_fidelity)
from eiroq.reconstruct import dense_inverse,stencil_inverse
from eiroq.hidden import dark_law,dark_response,reveal_control
from eiroq.staircase import (calibration_controls,echo_control,staircase_weights,
                            matched_pairs_law,tight_law,coherence_certificate,
                            complete_uniform_bound,complete_tight_law)
from eiroq.certificates import exact_data_bounds,interval_lower_bound
from eiroq.statistics import simultaneous_radius,sample_means,required_revelation_shots


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--out',type=Path,default=Path('.'))
    args=parser.parse_args();out=args.out
    for folder in ('data','results','figures'): (out/folder).mkdir(parents=True,exist_ok=True)
    def table(name,rows):
        with (out/'data'/name).open('w',newline='') as f:
            writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)
    def figure(name,description):
        plt.xlabel(description[0]);plt.ylabel(description[1]);plt.title(description[2])
        plt.grid(alpha=.25);plt.tight_layout()
        plt.savefig(out/'figures'/f'{name}.pdf',bbox_inches='tight')
        plt.savefig(out/'figures'/f'{name}.png',dpi=160,bbox_inches='tight');plt.close()
    summary={'version':'1.0.0','seed':2026101602,
             'evidence':'theory and synthetic computation; zero laboratory trials'}
    rng=np.random.default_rng(summary['seed'])
    rank_rows=[]
    for n in range(2,9):
        for d in range(2,min(n,6)+1,2):
            subsets=even_subsets(n,d)
            for p in range(min(d,n-1)):
                canonical=bank(n,p);full=bank(n,p,False)
                exact_lower=modular_rank(feature_matrix(canonical,subsets,n))
                full_lower=modular_rank(feature_matrix(full,subsets,n))
                predicted=rank_law(n,d,p)
                assert exact_lower==full_lower==predicted
                rank_rows.append(dict(n=n,degree=d,pulses=p,parameters=len(subsets),
                                      canonical_settings=len(canonical),full_settings=len(full),
                                      modular_rank=exact_lower,full_modular_rank=full_lower,
                                      theoretical_rank=predicted))
    table('rank_law.csv',rank_rows);summary['rank_cases']=len(rank_rows)
    plt.figure(figsize=(7.2,4.5))
    for d in (2,4,6):
        ps=np.arange(6);plt.step(ps,[rank_law(7,d,int(p)) for p in ps],where='post',label=f'moment degree {d}')
    plt.legend();figure('rank_staircase',('Maximum refocusing pulses','Observable dimension','Exact pulse-budget rank at seven bins'))
    counts=[]
    for n in range(2,31):
        row={'n':n,'full_symmetric_parameters':2**(n-1)-1}
        for d in (2,4,6):row[f'degree_{d}']=dimension(n,d)
        counts.append(row)
    table('setting_counts.csv',counts)
    plt.figure(figsize=(7.2,4.5))
    for key,label in [('full_symmetric_parameters','No moment-degree bound'),('degree_2','Degree 2'),('degree_4','Degree 4'),('degree_6','Degree 6')]:
        plt.semilogy([r['n'] for r in counts],[r[key] for r in counts],label=label)
    plt.legend();figure('setting_counts',('Number of bins','Scalar settings / free parameters','Settings saved only under a valid degree contract'))
    inverse=[]
    for case in range(180):
        n=4+case%6;available=list(range(2,min(n,6)+1,2));d=available[(case//6)%len(available)]
        subsets=even_subsets(n,d);coeff=rng.normal(size=len(subsets));coeff*=.6/np.abs(coeff).sum()
        true=dict(zip(subsets,coeff));x,p=phase_law(n,true)
        alpha=rng.uniform(.45,.85,size=n);controls=bank(n,d-1)
        data=np.array([direct_coherence(u,alpha,x,p).real for u in controls])
        dense=dense_inverse(alpha,d,data);stencil=stencil_inverse(alpha,d,data)
        inverse.append({'case':case,'n':n,'degree':d,'settings':len(controls),
                        'minimum_probability':float(p.min()),
                        'dense_error':max(abs(dense[a]-true[a]) for a in subsets),
                        'stencil_error':max(abs(stencil[a]-true[a]) for a in subsets),
                        'cross_inverse_error':max(abs(dense[a]-stencil[a]) for a in subsets)})
    table('inverse_roundtrips.csv',inverse)
    summary['inverse_roundtrips']=len(inverse)
    summary['maximum_dense_error']=max(r['dense_error'] for r in inverse)
    summary['maximum_stencil_error']=max(r['stencil_error'] for r in inverse)
    assert summary['maximum_stencil_error']<1e-8
    plt.figure(figsize=(7.2,4.5))
    plt.semilogy([r['case'] for r in inverse],[max(r['dense_error'],1e-17) for r in inverse],'.',label='Dense inverse')
    plt.semilogy([r['case'] for r in inverse],[max(r['stencil_error'],1e-17) for r in inverse],'.',label='Local stencil')
    plt.legend();figure('inverse_errors',('Seeded physical instance','Largest recovered moment error','Two inverses against direct finite-law propagation'))
    hidden=[]
    for d in (2,4,6):
        n=2*d-1;x,p=dark_law(d,1)
        # Direct verification of the entire full low-pulse bank at d=2,4.
        controls=bank(n,d-2,False)
        chosen=controls if d<=4 else controls[::max(1,len(controls)//80)]
        for alpha0 in (.25,.55,np.pi/4,1.05):
            alpha=np.full(n,alpha0)
            residual=max(abs(direct_coherence(u,alpha,x,p).real-np.cos(alpha0)**u.b) for u in chosen)
            hidden.append({'degree':d,'bins':n,'common_alpha':float(alpha0),
                           'total_available_controls':len(controls),'direct_controls_tested':len(chosen),
                           'maximum_hidden_residual':residual})
    table('hidden_control_checks.csv',hidden)
    summary['hidden_direct_controls']=sum(r['direct_controls_tested'] for r in hidden)
    summary['hidden_maximum_residual']=max(r['maximum_hidden_residual'] for r in hidden)
    sweep=[]
    for a in np.linspace(.1,1.4,121):
        n=7;alpha=np.full(n,a);target=reveal_control(4);base=np.cos(a)**n
        sweep.append({'alpha':float(a),'baseline':base,'lambda_plus':dark_response(target,alpha,4,1).real,
                      'lambda_minus':dark_response(target,alpha,4,-1).real,
                      'revelation_slope':np.sin(a)**4*np.cos(a)**3})
    table('global_amplitude_sweep.csv',sweep)
    plt.figure(figsize=(7.2,4.5))
    for key,label in [('baseline','Every <=2-pulse full-prefix control'),('lambda_plus','Revealing control, lambda=+1'),('lambda_minus','Revealing control, lambda=-1')]:
        plt.plot([r['alpha'] for r in sweep],[r[key] for r in sweep],label=label)
    plt.legend(fontsize=8);figure('dark_revelation',('Common phase amplitude (radians)','Real coherence','Identical shallow controls, opposite deeper decisions'))
    trade=[]
    for pulses in range(4):
        for local in range(4):
            alpha=np.full(7,np.pi/4)
            # Disjoint coverage; unneeded local settings have no further effect.
            for pair in range(pulses,min(3,pulses+local)):
                alpha[2*pair],alpha[2*pair+1]=.3,1.1
            u=Control(7,tuple(2*j+1 for j in range(pulses)))
            contrast=abs(dark_response(u,alpha,4,1)-dark_response(u,alpha,4,-1))
            trade.append({'pulses':pulses,'imbalanced_pair_budget':local,'coherence_contrast':float(contrast),
                          'predicted_revealed':int(pulses+local>=3)})
    table('capability_exchange.csv',trade)
    plt.figure(figsize=(6,4.6));matrix=np.array([r['coherence_contrast'] for r in trade]).reshape(4,4)
    plt.imshow(matrix,origin='lower',aspect='auto');plt.colorbar(label='Absolute coherence contrast')
    plt.xticks(range(4));plt.yticks(range(4))
    for row in range(4):
        for col in range(4):plt.text(col,row,f'{matrix[row,col]:.3f}',ha='center',va='center')
    plt.xlabel('Locally imbalanced pair budget');plt.ylabel('Refocusing pulses');plt.title('Revelation needs all three pairs covered')
    plt.tight_layout();plt.savefig(out/'figures/capability_exchange.pdf',bbox_inches='tight');plt.savefig(out/'figures/capability_exchange.png',dpi=160,bbox_inches='tight');plt.close()
    sharp=[];deletion=[]
    for k in range(1,6):
        x=vertices(2*k,symmetric=True);controls=calibration_controls(k)
        a=np.array([exact_normalized_row(u,x)/2**(u.b//2) for u in controls])
        target=exact_normalized_row(echo_control(k),x)/2**k
        for eps in sorted(set([float(z) for z in np.linspace(0,1,17)]+[2**(1-k),1/(2**(k-1)-1) if k>1 else 1.])):
            cert=interval_lower_bound(a,np.zeros(k),np.full(k,eps),target)
            xx,pp=complete_tight_law(k,eps);expected=complete_uniform_bound(k,eps)
            achieved=direct_coherence(echo_control(k),np.full(2*k,np.pi/4),xx,pp).real
            assert abs(cert['lp_value']-expected)<1e-8 and abs(achieved-expected)<1e-8
            sharp.append({'pairs':k,'epsilon':float(eps),'theoretical_lower':expected,
                          'lp_lower':cert['lp_value'],'constructive_value':achieved})
        for missing in range(k):
            used=[j for j in range(k) if j!=missing]
            ans=exact_data_bounds(a[used],np.zeros(len(used)),target)
            expected=0 if missing==k-1 else -1
            assert abs(ans.lower-expected)<1e-8
            deletion.append({'pairs':k,'omitted_prefix_index':missing+1,
                             'minimum_echo_coherence':ans.lower})
    table('staircase_sharp_bounds.csv',sharp);table('calibration_deletion.csv',deletion)
    summary['staircase_lp_sharpness_cases']=len(sharp);summary['staircase_deletion_cases']=len(deletion)
    plt.figure(figsize=(7.2,4.5))
    for k in range(1,6):
        rows=[r for r in sharp if r['pairs']==k]
        plt.plot([r['epsilon'] for r in rows],[r['lp_lower'] for r in rows],'-o',markersize=3,label=f'{k} pairs')
    plt.legend();figure('sharp_prediction',('Uniform calibration uncertainty','Sharp lower echo coherence','Attained worst-case prediction over all binary laws'))
    # A held-out target: selection uses only three prefixes and the Ramsey baseline.
    k=3;n=6;alpha=np.full(n,np.pi/4);x,p=matched_pairs_law(k)
    controls=calibration_controls(k)+[Control(n)]
    truth=np.array([direct_coherence(u,alpha,x,p).real for u in controls])
    shots=50000;delta=.05;measured=sample_means(truth,shots,rng)
    radius=simultaneous_radius(shots,len(controls),delta)
    target_lower=coherence_certificate(measured[:k],np.full(k,radius))['lower']
    gain_lower=target_lower-(measured[-1]+radius)
    target_true=direct_coherence(echo_control(k),alpha,x,p).real
    target_validation=sample_means([target_true],shots,rng)[0]
    decision={'pairs':k,'bins':n,'shots_per_setting':shots,'calibration_settings':len(controls),
              'calibration_shots':shots*len(controls),'held_out_validation_shots':shots,
              'simultaneous_confidence':1-delta,'pauli_radius':radius,
              'truth':truth.tolist(),'measured':measured.tolist(),
              'target_true':target_true,'target_lower':target_lower,
              'gain_lower':gain_lower,'entanglement_fidelity_gain_lower':gain_lower/2,
              'target_validation_mean_not_used_for_selection':float(target_validation),
              'baseline_true_entanglement_fidelity':entanglement_fidelity(truth[-1]),
              'target_true_entanglement_fidelity':entanglement_fidelity(target_true),
              'note':'Synthetic matched-pair law; direct target measurement is a cheaper baseline when available.'}
    (out/'results/finite_shot_decision.json').write_text(json.dumps(decision,indent=2)+'\n');summary['finite_shot_decision']=decision
    plt.figure(figsize=(7.2,4.5))
    plt.errorbar(np.arange(4),measured,yerr=radius,fmt='o',capsize=4,label='Acquired simultaneous intervals')
    plt.plot([4],[target_true],'s',label='Held-out target truth')
    plt.plot([4],[target_lower],'^',label='Certified target lower bound')
    plt.xticks(range(5),['Prefix 2','Prefix 4','Prefix 6','Ramsey 6','Echo target'])
    plt.ylim(-.15,1.1);plt.legend(fontsize=8);figure('finite_shot_prediction',('Control experiment','Real coherence','Certifying an unmeasured three-pulse echo'))
    coverage=[]
    for shots0 in (200,1000,5000,20000):
        covered=0;positive=0;worst=-1e9;trials=1000
        r=simultaneous_radius(shots0,4,delta)
        for _ in range(trials):
            m=sample_means(truth,shots0,rng)
            covered+=int(np.all(np.abs(m-truth)<=r))
            lo=coherence_certificate(m[:3],np.full(3,r))['lower']-m[-1]-r
            positive+=int(lo>0);worst=max(worst,lo-(target_true-truth[-1]))
        coverage.append({'shots_per_setting':shots0,'trials':trials,
                         'simultaneous_coverages':covered,'positive_certificates':positive,
                         'max_bound_minus_true_gain':float(worst)})
    table('finite_shot_coverage.csv',coverage);summary['coverage_trials']=sum(r['trials'] for r in coverage)
    summary['coverage_successes']=sum(r['simultaneous_coverages'] for r in coverage)
    plt.figure(figsize=(7.2,4.5))
    plt.semilogx([r['shots_per_setting'] for r in coverage],[r['positive_certificates']/r['trials'] for r in coverage],'-o')
    plt.ylim(0,1.05);figure('decision_rate',('Shots per acquired setting','Fraction with positive gain certificate','Synthetic decision rate, not hardware performance'))
    visibility=[]
    for d in (2,4,6,8,10,12):
        n=2*d-1;alpha0=np.pi/4;slope=2**(-n/2)
        optimum=float(np.arcsin(np.sqrt(d/n)))
        visibility.append({'degree':d,'bins':n,'quarterturn_slope':slope,
                           'slope_optimal_alpha':optimum,
                           'slope_optimal_value':(d/n)**(d/2)*(1-d/n)**((n-d)/2),
                           'hoeffding_sufficient_shots_known_mean':required_revelation_shots(slope)})
    table('visibility_cost.csv',visibility)
    plt.figure(figsize=(7.2,4.5));plt.semilogy([r['degree'] for r in visibility],[r['hoeffding_sufficient_shots_known_mean'] for r in visibility],'-o')
    figure('visibility_cost',('Hidden moment degree','Sufficient shots for a known mean shift','High-order revelation has an exponential visibility cost'))
    # Source-independent 2x2 unitary propagation at 12 seeded physical laws.
    unitary=[];z=np.diag([1.,-1.]);xgate=np.array([[0.,1.],[1.,0.]])
    from scipy.linalg import expm
    for case in range(12):
        n=3+case%4;xx=vertices(n);weights=rng.uniform(size=len(xx));weights/=weights.sum()
        alpha=rng.uniform(.2,.9,n);b=n;cuts=tuple(a for a in range(1,b) if rng.random()<.4);u=Control(b,cuts)
        exact_fe=0.
        ideal=np.linalg.matrix_power(xgate,len(cuts))
        for xi,weight in zip(xx,weights):
            evolution=np.eye(2,dtype=complex)
            for j in range(n):
                evolution=expm(-.5j*alpha[j]*xi[j]*z)@evolution
                if j+1 in cuts:evolution=xgate@evolution
            exact_fe+=weight*abs(np.trace(ideal.conj().T@evolution))**2/4
        w=direct_coherence(u,alpha,xx,weights)
        unitary.append({'case':case,'bins':n,'pulses':len(cuts),'unitary_entanglement_fidelity':float(exact_fe),
                        'characteristic_entanglement_fidelity':entanglement_fidelity(w),
                        'absolute_residual':abs(exact_fe-entanglement_fidelity(w))})
    table('unitary_propagation.csv',unitary)
    summary['unitary_cases']=len(unitary);summary['unitary_maximum_residual']=max(r['absolute_residual'] for r in unitary)
    # Distinguish exact reconstruction from a false low-degree hypothesis.
    x,p=dark_law(4,-1);alpha=np.full(7,np.pi/4);small=bank(7,1)
    data=[direct_coherence(u,alpha,x,p).real for u in small]
    low=dense_inverse(alpha,2,data)
    from eiroq.model import predicted_coherence
    miss={'fitted_degree':2,'true_degree':4,'maximum_fitted_pair_moment':max(map(abs,low.values())),
          'all_calibration_residuals':float(max(abs(predicted_coherence(u,alpha,low)-v) for u,v in zip(small,data))),
          'predicted_revealing_coherence':predicted_coherence(reveal_control(4),alpha,low),
          'true_revealing_coherence':direct_coherence(reveal_control(4),alpha,x,p).real,
          'interpretation':'Low-pulse holdout agreement does not validate the moment-degree contract.'}
    (out/'results/misspecification.json').write_text(json.dumps(miss,indent=2)+'\n')
    summary['misspecification']=miss
    summary['setting_example_n20_d4']={'required':dimension(20,4),'full_symmetric':2**19-1}
    summary['data_csv_files']=len(list((out/'data').glob('*.csv')))
    summary['figure_count']=len(list((out/'figures').glob('*.pdf')))
    (out/'results/experiment_summary.json').write_text(json.dumps(summary,indent=2)+'\n')
    environment={'python':platform.python_version(),'numpy':np.__version__,'scipy':scipy.__version__,
                 'matplotlib':matplotlib.__version__,'platform':platform.platform(),
                 'execution':'CPU only; no quantum device, FPGA, or GPU benchmark'}
    (out/'results/environment.json').write_text(json.dumps(environment,indent=2)+'\n')
    print(json.dumps(summary,indent=2))

if __name__=='__main__': main()