File size: 19,065 Bytes
6ee3aa6 | 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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | """Numerical and exact checks for Chiral–Nilpotent Invariant Architectures II.
Run python verify.py --output results.json. Every experiment uses dimensionless
length L unless a different length is explicit. NumPy and SciPy are required.
"""
import argparse
import json
import math
import platform
from pathlib import Path
import numpy as np
import scipy
import sympy
from certificate import example as exact_certificate
from scipy.linalg import expm, expm_frechet
from scipy.optimize import linear_sum_assignment
def unit(k, j):
return np.eye(k, dtype=complex)[:, j]
def edge(k, i, j):
return np.outer(unit(k, i), unit(k, j).conj())
def norm(a):
return float(np.linalg.norm(a, 2))
def hermitian(rng, n):
a = rng.normal(size=(n, n)) + 1j * rng.normal(size=(n, n))
a = a + a.conj().T
return a / norm(a)
def rotate(k, i, j, angle):
r = np.eye(k)
r[i, i] = r[j, j] = np.cos(angle)
r[i, j], r[j, i] = np.sin(angle), -np.sin(angle)
return r
def synthesize_path(angles):
"""Return the exact endpoint angle and pulses, written in matrix-product order."""
distance = len(angles)
h = angles[-1]
if distance == 1:
return h, [(0, 1, h)]
alpha, sub = synthesize_path(angles[:-1])
w, v = distance - 1, distance
phi = np.arctan2(np.cos(alpha) * np.sin(h / 2), np.cos(h / 2))
theta = 2 * np.arcsin(np.sin(alpha) * np.sin(h / 2))
inv = [(i, j, -t) for i, j, t in reversed(sub)]
return theta, [(w, v, -phi)] + sub + [(w, v, h)] + inv + [(w, v, -phi)]
def synthesize(distance, h):
return synthesize_path([h]*distance)
def ambiguity_check():
records = []
for d in range(1, 7):
h = 0.14
theta, pulses = synthesize(d, h)
u = np.eye(d + 1)
for i, j, t in pulses:
u = u @ rotate(d + 1, i, j, t)
error = norm(u - rotate(d + 1, 0, d, theta))
action = sum(abs(t) for _, _, t in pulses)
hs = np.geomspace(0.012, 0.07, 9)
ts = [synthesize(d, x)[0] for x in hs]
slope = float(np.polyfit(np.log(hs), np.log(ts), 1)[0])
assert error < 3e-13 and abs(slope - d) < 0.012
assert action <= (3 * 2 ** (d - 1) - 2) * h + 1e-12
records.append(dict(distance=d, h=h, angle=theta, pulses=len(pulses),
action=action, full_matrix_error=error, log_slope=slope))
return records
def weighted_check():
weights = np.array([1., 1.5, 2.])
rhos = np.geomspace(.018,.1,9)
path_angles, direct_angles = [], []
for rho in rhos:
theta, seq = synthesize_path(rho**weights)
u = np.eye(4)
for i,j,t in seq:
u = u @ rotate(4,i,j,t)
assert norm(u-rotate(4,0,3,theta)) < 2e-14
path_angles.append(theta)
direct_angles.append(rho**2)
slope = float(np.polyfit(np.log(rhos),np.log(path_angles),1)[0])
shortcut = float(np.polyfit(np.log(rhos),np.log(direct_angles),1)[0])
assert abs(slope-weights.sum()) < .01 and abs(shortcut-2)<1e-12
return dict(weights=weights.tolist(),path_exponent=slope,shortcut_exponent=shortcut)
def geometry_check():
# Maxwell's 1D constitutive transport matrix in (E, eta_0 JH) coordinates.
kappa, n_over_c = .13,.87
A = np.array([[kappa,n_over_c],[n_over_c,kappa]])
errs = []
for s in (-1,1):
row=np.array([1.,-s])
errs.append(np.linalg.norm(row@A-(kappa-s*n_over_c)*row))
# A_z=t, A_t=0 on a rectangle: the horizontal loop shift is minus the area.
T,L=.65,.73
line_integral=T*L
assert max(errs)<1e-15 and abs(line_integral-.4745)<1e-15
mollifiers=[.1,.01,.001]
white_contractions=[L-h*(-np.expm1(-L/h)) for h in mollifiers]
assert abs(white_contractions[-1]-L)<.0011
return dict(max_characteristic_residual=float(max(errs)),lift_displacement=-line_integral,
white_limit=L,white_cutoffs=mollifiers,white_contractions=white_contractions)
def graph_trial(rng, k, modes, segments, a, eps):
"""Arbitrary complex, time-varying, sideband-dependent local Hermitian defects."""
dim = k * modes
endpoint_signal = edge(k, 0, k - 1) + edge(k, k - 1, 0)
signal = np.kron(np.eye(modes), endpoint_signal)
obs = np.kron(np.eye(modes), 1j * (edge(k, 0, k - 1) - edge(k, k - 1, 0)))
x = np.kron(unit(modes, 0), unit(k, 0))
dx = np.zeros_like(x)
for _ in range(segments):
common = np.kron(4 * hermitian(rng, modes), np.eye(k))
v = np.zeros((dim, dim), dtype=complex)
for j in range(k - 1):
link = rng.normal(size=(modes, modes)) + 1j * rng.normal(size=(modes, modes))
v += np.kron(link, edge(k, j + 1, j))
v = v + v.conj().T
g = (-1j / segments) * (common + eps * signal + a * v / norm(v))
u, du = expm_frechet(g, (-1j / segments) * signal)
dx, x = du @ x + u @ dx, u @ x
D = np.vdot(x, obs @ x).real
slope = 2 * np.vdot(dx, obs @ x).real
dark = np.linalg.norm(x.reshape(modes, k)[:, -1])
assert abs(np.linalg.norm(x) - 1) < 2e-13
return float(D), float(slope), float(dark)
def graph_check():
rng = np.random.default_rng(724291)
rows = []
for k in (3, 4, 5, 6):
a = 0.35
values = np.array([graph_trial(rng, k, 3, 5, a, 0) for _ in range(20)])
d = k - 1
bound = a ** d / math.factorial(d)
assert np.max(values[:, 2]) <= bound and np.min(values[:, 1]) >= 2 * (1 - a*a)
# An allowed constant chain aligns the shortest-path amplitude with the detector.
e = np.diag(np.ones(d), -1).astype(complex)
e[-1, -2] = np.exp(1j * (d - 1) * np.pi/2)
adjacency = e + e.conj().T
strengths = np.geomspace(0.012, 0.09, 12)
offsets = []
for g in strengths:
x = expm(-1j * g * adjacency)[:, 0]
offsets.append(float(-2 * np.imag(np.conj(x[0]) * x[-1])))
fitted = float(np.polyfit(np.log(strengths), np.log(offsets), 1)[0])
assert abs(fitted - d) < 0.015
rows.append(dict(k=k, distance=d, trials=len(values), action=a, null_bound=bound,
largest_dark_norm=float(values[:, 2].max()),
min_slope=float(values[:, 1].min()), guaranteed_slope=2*(1-a*a),
fixed_chain_exponent=fitted, strengths=strengths.tolist(), offsets=offsets))
# Input-equal nuisance and signal defeat any null-distance guarantee.
G = edge(3, 0, 2) + edge(3, 2, 0)
shortcut = norm(expm(-0.04j * G) - expm(-1j * (0.04 * G)))
assert shortcut < 1e-14
return rows
def factor_check():
rng = np.random.default_rng(2401)
m, k = 5, 3
x = np.kron(unit(m, 0), unit(k, 0))
w, s = unit(m, 0), unit(k, 0)
for _ in range(5):
K, B = -1.3j * hermitian(rng, m), -0.26j * hermitian(rng, k)
x = expm(np.kron(K, np.eye(k)) + np.kron(np.eye(m), B)) @ x
w, s = expm(K) @ w, expm(B) @ s
blocks = x.reshape(m, k)
density = blocks.T @ blocks.conj()
err = norm(density - np.outer(s, s.conj()))
factor_err = np.linalg.norm(x - np.kron(w, s))
assert max(err, factor_err) < 2e-13
slopes = []
for detuning in (.8, 2*np.pi):
H = np.diag([0.,0.,detuning])
G = edge(3,0,2)+edge(3,2,0)
O = 1j*(edge(3,0,2)-edge(3,2,0))
U,dU = expm_frechet(-1j*H,-1j*G)
slope = 2*np.vdot(dU[:,0],O@U[:,0]).real
visibility = np.exp(-.5j*detuning)*np.sinc(detuning/(2*np.pi))
assert abs(slope-2*visibility.real)<1e-13
slopes.append(float(slope))
return dict(joint_error=float(factor_err), pooled_density_error=err,
carrier_throughput=float(abs(w[0])**2), pooled_throughput=float(np.vdot(w,w).real),
mismatch_detunings=[.8,2*np.pi],mismatch_signed_slopes=slopes)
def word_check():
# Exact integer arithmetic for basis reachability. Matrices in this example
# map each coordinate basis vector to another basis vector or zero.
one, hidden, target = 0, 1, 2
pairs = [(hidden, one), (target, hidden)]
reachable = {one}
layers = [sorted(reachable)]
while target not in reachable:
reachable |= {out for out, inp in pairs if inp in reachable}
layers.append(sorted(reachable))
assert len(layers) - 1 == 2
# The reference output stays (1,0). Its exterior-product test reads the last component.
b1, b2 = edge(3, hidden, one), edge(3, target, hidden)
g = .13
y = (expm(g*b2) @ expm(g*b1))[:, 0]
reverse = (expm(g*b1) @ expm(g*b2))[:, 0]
assert abs(y[-1] - g*g) < 1e-15 and reverse[-1] == 0
return dict(reachable_layers=layers, witnessed_degree=2,
ordered_wedge=float(y[-1].real), reversed_wedge=float(reverse[-1].real))
def nilpotent_check():
rows = []
for k in range(2, 8):
n = np.diag(np.ones(k-1), 1)
weights = np.sqrt(np.arange(1,k)*np.arange(k-1,0,-1))
plus = np.diag(weights, 1)
t1 = (plus + plus.T)/2
t3 = np.diag((k-1)/2 - np.arange(k))
U = expm(1j*np.pi/2*t1)
d = np.r_[1., np.cumprod(weights)]
S = U.conj().T @ np.diag(1/d)
err = norm(np.linalg.solve(S, (t1+1j*t3) @ S) - n)
assert err < 2e-10
kappa = np.linalg.cond(S)
assert np.isclose(kappa, math.factorial(k-1))
B = edge(k, k-1, 0)
free, du = expm_frechet(n, B)
assert abs(du[-1,0]-1)<1e-13 and abs(du[0,0]-1/math.factorial(k))<1e-13
rows.append(dict(k=k, similarity_error=err, condition=float(kappa)))
n = np.diag(np.ones(2), 1)
om = sum(np.linalg.matrix_power(n.T,r)/(3-r) for r in range(3))
u = expm((-1+1j)*n)
vals = [np.trace(u@om), np.trace(u@u@om), np.trace(n@n.T@om)]
assert np.allclose(vals, [0,-1-2j,2/3])
return dict(ranks=rows, trace_examples=[[x.real,x.imag] for x in vals])
def ordered_model(cutoff, steps, reverse, detuning, seed=116):
k = 3
m = np.arange(-cutoff, cutoff+1)
shift = np.diag(np.ones(len(m)-1), -1)
N = np.diag(np.ones(k-1), 1)
m0 = N + .06 * edge(k,k-1,0)
static = np.kron(np.diag(1j*detuning*m*m), np.eye(k)) + np.kron(np.eye(len(m)), m0)
rng = np.random.default_rng(seed)
mats = [hermitian(rng,k) for _ in range(4)]
# Two independent matrix profiles; the backward channel need not be the forward adjoint.
x = np.zeros((len(m)*k, k), dtype=complex)
window = slice(cutoff*k, (cutoff+1)*k)
x[window] = np.eye(k)
for j in range(steps):
t = (j+.5)/steps
plus = .48*(mats[0]*np.cos(3*t)+mats[1]*np.sin(7*t))
minus = .61*(mats[2]*np.cos(5*t)+mats[3]*np.sin(2*t))
H = static + np.kron(shift,plus) + reverse*np.kron(shift.T,minus)
x = expm(H/steps) @ x
return x[window], expm(m0)
def lattice_check():
out = []
for name, rev, b in [('one-sided',0,2.), ('leaky-detuned',.15,2.),
('leaky-resonant',.15,0.), ('two-sided',1.,0.)]:
y, clean = ordered_model(4,48,rev,b)
fine, _ = ordered_model(4,96,rev,b)
wider, _ = ordered_model(5,96,rev,b)
fine2, _ = ordered_model(4,192,rev,b)
out.append(dict(case=name,carrier_error=norm(fine-clean),step_48_to_96=norm(y-fine),
step_96_to_192=norm(fine-fine2),cutoff_4_to_5=norm(fine-wider)))
assert out[0]['carrier_error']<1e-12
assert all(row['step_96_to_192']<.32*row['step_48_to_96'] for row in out[1:])
assert all(row['cutoff_4_to_5']<1e-7 for row in out)
cyclic = np.roll(np.eye(3),1,axis=0)
assert abs((expm(.8*cyclic))[0,0]-1)>.08
return dict(configurations=out, periodic_wrap_error=float(expm(.8*cyclic)[0,0]-1))
def spectrum_check():
worst, resolvent_err, count = 0., 0., 0
for m in range(2, 19):
for p in range(1,m):
if math.gcd(m,p)!=1:
continue
count += 1
q = np.exp(2j*np.pi*p/m)
nums = (1-q**np.arange(1,m))/(1-q)
T = np.diag(np.ones(m-1), -1) + np.diag(nums, 1)
lam = np.linalg.eigvals(T)
exact = 2*np.cos((2*np.arange(m)+1)*np.pi/(2*m))/np.sqrt(1-q)
cost = abs(lam[:,None]-exact[None,:])
ii,jj = linear_sum_assignment(cost)
worst = max(worst, float(cost[ii,jj].max()))
assert abs(np.mean(lam**2)-2/(1-q))<1e-10
z, gamma = 4.6+.8j, .17
mat = z*np.eye(m)-T
P, Q = np.linalg.det(mat[1:,1:]), np.linalg.det(mat)
r = 1-1j*gamma*np.linalg.inv(mat + .5j*gamma*edge(m,0,0))[0,0]
rp = (Q-.5j*gamma*P)/(Q+.5j*gamma*P)
resolvent_err = max(resolvent_err,float(abs(r-rp)))
assert worst<3e-8 and resolvent_err<1e-11
# The first incompatible real moment and the two-step Jacobi contraction.
for q in (-1.3, -.2, 1., 2., 1j):
nums = np.array([sum(q**r for r in range(j)) for j in range(1,4)])
T = np.diag(np.ones(3),-1)+np.diag(nums,1)
assert abs(np.linalg.matrix_power(T,4)[0,0]-(2+q))<1e-13
def transfer(n):
an,anext=np.sqrt(2.**n-1),np.sqrt(2.**(n+1)-1)
return np.array([[1j/anext,-an/anext],[1,0]])
contraction_err=norm(transfer(81)@transfer(80)+np.eye(2)/np.sqrt(2.))
assert contraction_err<1e-11
return dict(primitive_cases=count,max_matched_eigenvalue_error=worst,
max_port_formula_error=resolvent_err,real_q2_two_step_error=contraction_err)
def ou_moments(L, ell, sigma, b):
h = 1/ell-1j*b
def J(z):
return L if z == 0 else np.expm1(z*L)/z
V = 2*sigma**2 * (L/h + np.expm1(-h*L)/(h*h)).real
P = 2*sigma**2/h.conjugate()*(J(2j*b)-J(-h))
return V, V**2+abs(P)**2
def ou_check():
rng = np.random.default_rng(98514)
L, ell, sigma, n, paths = 3., .4, .7, 360, 24000
dt = L/n
rho = np.exp(-dt/ell)
t = (np.arange(n)+.5)*dt
freqs = np.array([0.,2.,8.])
exponentials = np.exp(1j*np.outer(t,freqs))
w = rng.normal(size=paths)*sigma
F = np.zeros((paths,len(freqs)),dtype=complex)
for ph in exponentials:
F += dt*w[:,None]*ph
w = rho*w + sigma*np.sqrt(1-rho*rho)*rng.normal(size=paths)
R = abs(F)**2
rows = []
C = sigma*sigma * np.exp(-abs(t[:,None]-t[None,:])/ell)
for j,b in enumerate(freqs):
V, v = ou_moments(L,ell,sigma,b)
ph = exponentials[:,j]*dt
vg = np.vdot(ph,C@ph).real**2 + abs(ph.T@C@ph)**2
Z = R[:,j]
mc = np.var(Z,ddof=1)
se = np.std((Z-Z.mean())**2,ddof=1)/np.sqrt(paths)
assert abs(vg-v)/v<.003 and abs(mc-vg)<6*se
rows.append(dict(detuning=float(b),mean=V,continuous_variance=v,
grid_variance=float(vg),sample_variance=float(mc),mc_se=float(se)))
return dict(paths=paths,midpoints=n,ell=ell,sigma=sigma,L=L,quadratures=rows)
def sewing_check():
rng = np.random.default_rng(788)
beta, terms, jet = .22, 13, 4
def driver(t, kind):
k = np.arange(terms)[:,None]
vals = (np.sin if kind=='x' else np.cos)(2**k*t)
return np.sum(.38*2**(-beta*k)*vals, axis=0)
def mesh(n):
t = np.linspace(0,1,n+1)
t[1:-1] += rng.uniform(-.32,.32,n-1)/n
return t
def inc(points,kind):
x = driver(points,kind)
dx = 1j*np.diff(x)
poly = sum(dx**r/math.factorial(r) for r in range(1,jet+1))
return np.exp(1j*x[:-1])*poly
target = np.prod([np.diff(np.exp(1j*driver(np.array([0.,1.]),kind)))[0]
for kind in ('x','y')])
rows = []
for n in (8,16,32,64,128,256,512,1024,2048,4096,8192,16384):
t,z = mesh(n),mesh(n+3)
# The contraction below is the exact grid sum of the product of local germs.
sewn = inc(t,'x').sum()*inc(z,'y').sum()
rows.append(dict(horizontal=n,vertical=n+3,max_mesh=max(np.diff(t).max(),np.diff(z).max()),
absolute_error=float(abs(sewn-target))))
assert rows[-1]['absolute_error']<rows[0]['absolute_error']/30
return dict(beta=beta,jet=jet,finite_frequencies=terms,grid_sums=rows,
unit_germ_sum_on_16_by_16=256)
def fisher_check():
a, n = .2, 1e6
guarantees = []
for d in range(2,7):
b=2*a**d/math.factorial(d)
guarantees.append(dict(distance=d,offset_bound=b,fraction=(1-a*a)**2/(1+n*b*b)))
Vff=4*.05**4*.1**3
Vret=Vff*.03**2/65
Vdark=.02**4
ratio=(.25+1e10*Vff)/(.25+1e10*(Vret+Vdark))
assert .1563<ratio<.1565 and .905<guarantees[2]['fraction']<.906
# Direct finite-outcome marginal FI for one common two-point waveform per shot.
# Count n=7 photons at the two analyzers, plus a third uncollected-port outcome.
from scipy.special import gammaln
small_n, k, strength = 7, 4, .28
S = edge(k,0,k-1)+edge(k,k-1,0)
O = 1j*(edge(k,0,k-1)-edge(k,k-1,0))
P = edge(k,0,0)+edge(k,k-1,k-1)
effects = [(P+O)/2,(P-O)/2,np.eye(k)-P]
ps, dps = [], []
for phase in (.3,1.4):
a_mat=np.diag(np.ones(k-1),-1).astype(complex)
a_mat[-1,-2]=np.exp(1j*phase)
H=a_mat+a_mat.conj().T
U,dU=expm_frechet(-1j*strength*H/norm(H),-1j*S)
x,dx=U[:,0],dU[:,0]
ps.append([np.vdot(x,E@x).real for E in effects])
dps.append([2*np.vdot(dx,E@x).real for E in effects])
ps,dps=np.array(ps),np.array(dps)
info=mass=0.
for i in range(small_n+1):
for j in range(small_n-i+1):
c=np.array([i,j,small_n-i-j])
terms=np.exp(gammaln(small_n+1)-gammaln(c+1).sum()+(c*np.log(ps)).sum(axis=1))
marginal=terms.mean()
derivative=np.mean(terms*(c*dps/ps).sum(axis=1))
mass+=marginal
info+=derivative*derivative/marginal
b=2*strength**(k-1)/math.factorial(k-1)
lower=4*small_n*(1-strength**2)**2/(1+small_n*b*b)
assert abs(mass-1)<1e-12 and lower <= info <= 4*small_n+1e-10
return dict(design_action=a,detected_budget=n,guarantees=guarantees,
old_model_ratio=ratio,exact_mixture_CFI=float(info),mixture_lower_bound=lower,
mixture_clean_CFI=4*small_n,mixture_n=small_n)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output',type=Path,default=Path('results.json'))
args=parser.parse_args()
checks=dict(ambiguity=ambiguity_check,passive_graph=graph_check,common_factor=factor_check,
ordered_words=word_check,jordan=nilpotent_check,ordered_lattice=lattice_check,
root_spectrum=spectrum_check,ou=ou_check,sewing=sewing_check,information=fisher_check)
checks.update(projective_certificate=exact_certificate,weighted_distance=weighted_check,
elementary_geometry=geometry_check)
data={'runtime':dict(python=platform.python_version(),numpy=np.__version__,
scipy=scipy.__version__,sympy=sympy.__version__)}
for name,check in checks.items():
data[name]=check()
print(f'PASS {name}',flush=True)
args.output.write_text(json.dumps(data,indent=2,allow_nan=False)+'\n',encoding='utf-8')
if __name__=='__main__':
main()
|