File size: 15,973 Bytes
fb3ffd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""Regenerate all numerical results and figures in the Xhūréïalœm study.

Usage: python verify.py [--out DIRECTORY]
Requires Python 3.10+, NumPy, SciPy and Matplotlib. All simulations are classical
model calculations. The gas constants in the design example are assumptions.
"""
from pathlib import Path
import argparse
import csv
import json
import math
import platform

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import scipy
from scipy.integrate import solve_ivp
from scipy.optimize import minimize_scalar, brentq

K = math.pi / 2
SEED = 704795
COLORS = ["#136962", "#8F462C", "#3B5078"]
LIGHT = 299792458.0
PLANCK = 6.62607015e-34


def envelope(r):
    return np.sin(K * np.sin(K * r))**2


def nand(x, y):
    q = np.abs(np.sin(K * np.abs(x)) * np.sin(K * np.abs(y)))
    return 1 - np.sin(K * q)**2


def check(label, value, checks):
    if not value:
        raise AssertionError(label)
    checks.append(label)


def write_csv(path, rows):
    with path.open("w", newline="", encoding="utf-8") as out:
        writer = csv.DictWriter(out, list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)


def swap(pulse):
    amplitude = abs(pulse)
    phase = pulse / amplitude if amplitude else 1.0
    c, s = math.cos(K * amplitude), math.sin(K * amplitude)
    return np.array([[c, -1j * phase * s], [-1j * phase.conjugate() * s, c]])


def matrix_product(a, b):
    signal = (swap(a) @ np.array([0.0, 1.0]))[0]
    return -(swap(b) @ np.array([signal, 0.0]))[1]


def integrate_pass(grid, u, v, w, mu):
    """Vectorized independent closed triplets; use real gauges as in the proof."""
    u, v, w = np.broadcast_arrays(u, v, w)
    initial = np.stack([u.ravel(), v.ravel(), w.ravel()])
    def rhs(_, packed):
        signal, spin, control = packed.reshape(initial.shape)
        return np.stack([spin*control, -signal*control, -mu*signal*spin]).ravel()
    solution = solve_ivp(rhs, (0.0, K), initial.ravel(), rtol=1e-11, atol=1e-13,
                         t_eval=grid, method="DOP853")
    if not solution.success:
        raise RuntimeError(solution.message)
    series = solution.y.reshape(3, initial.shape[1], -1)
    first_invariant = series[0]**2 + series[1]**2
    second_invariant = mu * series[0]**2 + series[2]**2
    drift = max(np.abs(first_invariant-first_invariant[:, :1]).max(),
                np.abs(second_invariant-second_invariant[:, :1]).max())
    return [component[:, -1].reshape(u.shape) for component in series], float(drift)


def depleted_product(x, y, mu):
    times = np.linspace(0.0, K, 15)
    source, first = integrate_pass(times, 0.0, 1.0, x, mu)
    target, second = integrate_pass(times, source[0], 0.0, y, mu)
    return -target[1], max(first, second)


def diff_values(qi, qj, w, D, t, loss):
    u = 1 + 2*D*t/w**2
    qi, qj = np.asarray(qi), np.asarray(qj)
    overlap = math.exp(-w*w*np.sum((qi-qj)**2)/8)
    center_sq = np.sum(((qi+qj)/2)**2)
    return math.exp(-loss*t)/u * overlap * math.exp(-D*t*center_sq/u)


def gaussian_fft(q1, q2, points=256):
    # Dimensionless w=1, D*t=0.14. Containment and grid are deliberately large.
    extent = 16.0
    dx = extent / points
    coords = (np.arange(points)-points/2)*dx
    x, y = np.meshgrid(coords, coords, indexing="ij")
    def mode(q):
        values = np.exp(-x*x-y*y + 1j*(q[0]*x+q[1]*y))
        return values / np.linalg.norm(values)
    freq = 2*math.pi*np.fft.fftfreq(points, dx)
    heat = np.exp(-0.14*(freq[:, None]**2+freq[None, :]**2))
    return np.vdot(mode(q1), np.fft.ifft2(heat*np.fft.fft2(mode(q2))))


def design_retention(t, w, chi, D, gamma, qz):
    exponent = 2*D*t/w**2
    return np.exp(-(gamma+D*qz*qz)*t) * chi**exponent/(1+exponent)


def main(root):
    results = root / "results"
    figures = root / "figures"
    results.mkdir(parents=True, exist_ok=True)
    figures.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(SEED)
    checks = []
    summary = {"seed":SEED, "environment":{"python":platform.python_version(),
                  "numpy":np.__version__, "scipy":scipy.__version__,
                  "matplotlib":matplotlib.__version__}}
    r = np.linspace(0.0, 0.5, 65537)
    margin = r-envelope(r)
    optimum = minimize_scalar(lambda t: float(envelope(t)-t), bounds=(0.0,0.5),
                              method="bounded", options={"xatol":1e-14})
    max_grid = float(margin.max())
    # The bound follows from the linear interpolation remainder on each grid cell.
    interpolation_error = (2*K**4 + K**3)*(r[1]-r[0])**2/8
    summary["restoration"] = {"r_opt_numeric":float(optimum.x), "margin_numeric":float(-optimum.fun),
        "grid_max":max_grid, "analytic_grid_interpolation_error":float(interpolation_error),
        "quadratic_guarantee":1/(4*K**4), "at_r_0.08":float(.08-envelope(.08))}
    check("analytic upper envelope encloses optimized margin", max_grid-2e-15 <= -optimum.fun <= max_grid+interpolation_error+2e-15, checks)
    matrix_error = 0.
    for _ in range(256):
        a,b = rng.random(2)*1.25 * np.exp(1j*rng.uniform(-math.pi, math.pi, 2))
        q = matrix_product(a,b)
        v = matrix_product(q,q)
        matrix_error=max(matrix_error, abs((1-v)-nand(a,b)))
    check("complex unitary swaps reproduce gauge-independent NAND",matrix_error<5e-15,checks)
    summary["complex_swap_max_error"]=float(matrix_error)
    for width in (0.01,0.05,0.08,0.12,0.25,0.49):
        for i in (0,1):
            for j in (0,1):
                def rail(b):
                    return np.linspace(max(0,b-width), b+width,251)
                x,y=np.meshgrid(rail(i),rail(j))
                errors=np.abs(nand(x,y)-(1-i*j))
                check(f"envelope at r={width}, input {i}{j}",errors.max()<=envelope(width)+2e-15,checks)
        check(f"sharp envelope attained at {width}",abs(1-nand(width,1)-envelope(width))<2e-15,checks)
    rows=[]
    x,y=np.meshgrid(np.linspace(0,1.1,23),np.linspace(0,1.1,23))
    for mu in (0.0,0.001,0.003,0.01,0.03,0.1,0.3,1.0):
        q, d1=depleted_product(x,y,mu)
        squared,d2=depleted_product(abs(q),abs(q),mu)
        diff=float(np.max(np.abs((1-squared)-nand(x,y))))
        prod_diff=float(np.max(np.abs(q-np.sin(K*x)*np.sin(K*y))))
        bound=(1+K)*mu*K*K/2
        check(f"finite-control product and NAND bound at mu={mu}",prod_diff<=mu*K*K/2+1e-10 and diff<=bound+1e-10,checks)
        check(f"Manley-Rowe invariants at mu={mu}",max(d1,d2)<1e-8,checks)
        rows.append({"spin_to_control":mu,"max_product_grid_difference":prod_diff,
                     "max_nand_grid_difference":diff,"nand_uniform_bound":bound,
                     "max_invariant_drift":max(d1,d2)})
    write_csv(results/"depletion.csv",rows)
    summary["depletion_grid"]=list(x.shape)
    summary["depletion_mu_0.01"]=rows[3]

    # Test all local NAND gates in an XOR/AND state-update emulator with bright,
    # random input phases and complex adversarially bounded per-gate disturbances.
    worst=0.
    transitions=0
    def noisy_gate(a,b,i,j):
        nonlocal worst,transitions
        angle=rng.uniform(-math.pi,math.pi)
        out=nand(a,b)+.04*np.exp(1j*angle)
        target=1-int(i)*int(j)
        worst=max(worst,abs(abs(out)-target))
        transitions+=1
        if abs(abs(out)-target)>.08+1e-12:
            raise AssertionError("logical interval violated")
        return out,target
    def update(state,program,command):
        n=noisy_gate(program[0],command[0],program[1],command[1])
        v=noisy_gate(n[0],n[0],n[1],n[1])
        def gate(x,y):
            return noisy_gate(x[0],y[0],x[1],y[1])
        t=gate(state,v)
        a=gate(state,t)
        b=gate(v,t)
        return gate(a,b)
    mismatches=0
    for _ in range(128):
        p,s=rng.integers(0,2,2)
        program=(p*np.exp(1j*rng.random()*6),int(p))
        state=(s*np.exp(1j*rng.random()*6),int(s))
        for tick in range(32):
            if tick==16:
                # Declared classical transfer surrogate with bounded perturbation,
                # not an optical migration simulation.
                state=(state[0]+.01*np.exp(1j*rng.uniform(-math.pi,math.pi)),state[1])
                if abs(abs(state[0])-state[1])>.08:
                    raise AssertionError("transfer out of specified interval")
            c=int(rng.integers(2))
            state=update(state,program,(c*np.exp(1j*rng.random()*6),c))
            s^=int(p)*c
            mismatches+=int((abs(state[0])>.5)!=s)
    check("finite state update and model transfer decode",mismatches==0,checks)
    summary["automaton"]={"sequences":128,"steps_each":32,"nand_calls":transitions,
                          "decoded_state_errors":mismatches,"largest_gate_output_error":float(worst)}
    fft_err=0.
    exact_pair=0.
    for _ in range(16):
        qa=rng.normal(size=2)*2
        qb=rng.normal(size=2)*2
        numeric=gaussian_fft(qa,qb)
        formula=diff_values(qa,qb,1.,.14,1.,0.)
        fft_err=max(fft_err,abs(numeric-formula))
    for chi in (.001,.01,.1,.3):
        w,D,t,loss=1.,.14,1.,.07
        u=1+2*D*t/w**2
        q=math.sqrt(2*u*math.log(1/chi))/w
        a=diff_values([q,0],[q,0],w,D,t,loss)
        b=diff_values([q,0],[-q,0],w,D,t,loss)
        exact_pair=max(exact_pair,abs(b/a-chi),abs(a-design_retention(t,w,chi,D,loss,0)))
    check("independent 2D FFT heat evolution",fft_err<5e-12,checks)
    check("opposed-tilt design saturates both analytic limits",exact_pair<2e-14,checks)
    summary["gaussian"]={"fft_complex_max_error":float(fft_err),"attainment_max_error":float(exact_pair)}
    D,gamma,chi=1.e-3,1.e3,.01
    wavelength=794.979e-9
    qz=2*math.pi*6.83468261e9/LIGHT
    k=2*math.pi/wavelength
    design=[]
    for w in (.0005,.001,.0015):
        for us in (1,2,5,10,25,50):
            t=us*1e-6
            u=1+2*D*t/w**2
            q=math.sqrt(2*u*math.log(1/chi))/w
            design.append({"waist_mm":w*1000,"hold_us":us,"amplitude_leakage":chi,
               "optimal_each_tilt_mrad":1000*q/k,"max_matched_amplitude":float(design_retention(t,w,chi,D,gamma,qz))})
    write_csv(results/"gaussian_design.csv",design)
    summary["example"]={"D_m2_s":D,"gamma_s":gamma,"qz_m":qz,"lambda_m":wavelength,
        "design_1mm_10us":design[9],"hold_90pct_1mm_us":1e6*brentq(lambda t: design_retention(t,.001,.01,D,gamma,qz)-.9,0,.001,xtol=1e-17),
        "photon_energy_J":PLANCK*LIGHT/wavelength,"gain_min_example":2/(.5*.01),
        "zero_error_trials_8_strata":math.ceil(math.log(.05/8)/math.log(.99))}
    # Independent random keys, queried first row, scalar signed value. Ties count as errors.
    retrieval=[]
    for dim,count in [(64,8),(128,16),(256,16),(256,48)]:
        samples=12000
        # Conditional on the target key and signs the (P-1)*d cross terms are iid signs.
        noise=(2*rng.binomial((count-1)*dim,.5,samples)-(count-1)*dim)/dim
        from scipy.stats import binom
        exact=float(binom.cdf(math.floor(((count-1)*dim-dim)/2),(count-1)*dim,.5))
        bound=math.exp(-dim/(2*(count-1)))
        count_errors=int(np.sum(1+noise<=0))
        check(f"associative sign tail at d={dim}, P={count}",exact<=bound+1e-14,checks)
        retrieval.append({"features":dim,"stored_keys":count,"trials":samples,"errors_ties_included":count_errors,
                          "exact_binomial_probability":exact,"one_sided_bound":bound})
    write_csv(results/"associative.csv",retrieval)
    write_csv(results/"restoration.csv",[{"radius":float(rad),"worst_output":float(envelope(rad)),
                "allowable_additive_disturbance":float(rad-envelope(rad))} for rad in np.linspace(0,.25,251)])
    summary["checks"]=checks
    (results/"summary.json").write_text(json.dumps(summary,indent=2,ensure_ascii=False)+"\n",encoding="utf-8")
    plt.rcParams.update({"font.family":"DejaVu Sans","font.size":9,"axes.spines.top":False,
                         "axes.spines.right":False,"axes.labelcolor":"#253337",
                         "text.color":"#253337","svg.fonttype":"none","pdf.fonttype":42})
    fig,ax=plt.subplots(1,2,figsize=(7.05,2.83),layout="constrained")
    rr=np.linspace(0,.22,501)
    ax[0].plot(rr,rr-envelope(rr),color=COLORS[0],lw=2)
    ax[0].plot(optimum.x,-optimum.fun,'o',color=COLORS[1],ms=5)
    ax[0].axhline(0,color="0.65",lw=.7)
    ax[0].annotate("0.04191",(optimum.x,-optimum.fun),xytext=(.115,.048),fontsize=8,
                   arrowprops={"arrowstyle":"-","color":"0.4","lw":.6})
    ax[0].set(xlabel="Input amplitude radius",ylabel="Permissible added error",title="A   Restoring margin")
    positive=rows[1:]
    ax[1].loglog([v["spin_to_control"] for v in positive],[v["max_nand_grid_difference"] for v in positive],
                 'o-',ms=4,lw=1.5,color=COLORS[0],label="ODE grid maximum")
    ax[1].loglog([v["spin_to_control"] for v in positive],[v["nand_uniform_bound"] for v in positive],
                 '--',lw=1.3,color=COLORS[1],label="Uniform proof bound")
    ax[1].set(xlabel="Spin / control excitation ratio",ylabel="NAND amplitude difference",title="B   Finite control depletion")
    ax[1].legend(frameon=False,fontsize=7)
    fig.savefig(figures/"logic.pdf",metadata={"CreationDate":None});plt.close(fig)
    fig,ax=plt.subplots(1,2,figsize=(7.05,2.88),layout="constrained")
    ts=np.linspace(0,50e-6,501)
    for w,col in zip((.0005,.001,.0015),COLORS):
        ax[0].plot(ts*1e6,design_retention(ts,w,chi,D,gamma,qz),color=col,label=f"{w*1000:g} mm",lw=1.9)
    ax[0].set(xlabel="Dark hold (µs)",ylabel="Best weaker-rail amplitude",title="A   Retention at 1% leakage",ylim=(0,1.04))
    ax[0].legend(frameon=False,fontsize=7)
    chis=np.logspace(-4,-.1,301)
    for us,col in zip((2,10,25),COLORS):
        ax[1].semilogx(chis,design_retention(us*1e-6,.001,chis,D,gamma,qz),color=col,label=f"{us} µs",lw=1.9)
    ax[1].set(xlabel="Permitted field leakage",ylabel="Best weaker-rail amplitude",title="B   Mode selectivity at 1 mm",ylim=(.5,1.01))
    ax[1].legend(frameon=False,fontsize=7)
    fig.savefig(figures/"diffusion.pdf",metadata={"CreationDate":None});plt.close(fig)
    # Intervention diagram: fixed services reach each chamber; only the parent
    # path carries challenge-dependent state during the first epoch.
    from matplotlib.patches import FancyBboxPatch
    fig,ax=plt.subplots(figsize=(7.1,1.81),layout="constrained")
    ax.set(xlim=(0,10),ylim=(0,2.75))
    ax.axis("off")
    def box(x,y,w,label,face):
        patch=FancyBboxPatch((x,y),w,.56,boxstyle="round,pad=0.035,rounding_size=0.06",
                             edgecolor="#728384",facecolor=face,linewidth=.7)
        ax.add_patch(patch)
        ax.text(x+w/2,y+.28,label,ha="center",va="center",fontsize=8.0)
    def arrow(start,end,y):
        ax.annotate("",(end,y),(start,y),arrowprops={"arrowstyle":"->","lw":1.25,"color":"#176762"})
    ax.text(0,2.48,"1   Write with A active",weight="bold",fontsize=9,color=COLORS[0])
    box(.03,1.69,2.27,"A   Process fresh input","#E6F1EF")
    box(3.35,1.69,2.73,"Optical relay and gain","#F3F5F4")
    box(7.12,1.69,2.75,"B   Write a blank grating","#E6F1EF")
    arrow(2.38,3.29,1.97);arrow(6.15,7.05,1.97)
    ax.text(0,1.25,"2   Hold, isolate A, challenge B",weight="bold",fontsize=9,color=COLORS[0])
    box(.03,.44,2.27,"A   Shuttered and erased","#F0F0EF")
    box(3.35,.44,2.73,"B   Route a fresh probe","#E6F1EF")
    box(7.12,.44,2.75,"Further blank gas mode","#E6F1EF")
    arrow(6.15,7.05,.72)
    ax.text(4.71,.12,"Generic pumps and clock continue in B.",ha="center",fontsize=7.6,color="#44515A")
    fig.savefig(figures/"intervention.pdf",metadata={"CreationDate":None});plt.close(fig)
    print(json.dumps({k:v for k,v in summary.items() if k!="checks"},indent=2))
    print(f"{len(checks)} deterministic verification groups passed.")


if __name__=="__main__":
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out",type=Path,default=Path(__file__).resolve().parent)
    main(parser.parse_args().out)