"""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']