Python checks and replay
aperture.py
"""Certified weak-limit counts in two antipodal circular detector apertures.
The source is either incoherent or an in-phase/antiphase superposition at
coarse sites +/-e_z, with the same spinor at both sites. Antipodal acceptance
eliminates the spin dependence. Each aperture includes all nonzero radii.
The half-angle is atan(1/4). Run with Python 3 and its standard library.
"""
from fractions import Fraction
from math import isqrt
SCALE = 10**32
class Interval:
"""An outward-rounded interval with integer endpoints in units of 1/SCALE."""
def __init__(self, lo, hi):
self.lo, self.hi = lo, hi
@classmethod
def exact(cls, x):
x = Fraction(x) * SCALE
return cls(x.numerator // x.denominator, -(-x.numerator // x.denominator))
def __add__(a, b):
return Interval(a.lo + b.lo, a.hi + b.hi)
def __sub__(a, b):
return Interval(a.lo - b.hi, a.hi - b.lo)
def __mul__(a, b):
vals = (a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi)
return Interval(min(vals) // SCALE, -(-max(vals) // SCALE))
def __truediv__(a, b):
assert b.lo > 0
reciprocal = Interval(SCALE**2 // b.hi, -(-SCALE**2 // b.lo))
return a * reciprocal
def sqrt(a):
assert a.lo >= 0
return Interval(isqrt(a.lo * SCALE), isqrt(a.hi * SCALE) + 1)
def hull(a, b):
return Interval(min(a.lo, b.lo), max(a.hi, b.hi))
num = Interval.exact
ZERO, ONE, TWO = num(0), num(1), num(2)
QUARTER = num(Fraction(1, 4))
ROOT2, ROOT3, ROOT6 = (num(n).sqrt() for n in (2, 3, 6))
def atan_inverse(q):
"""Alternating arctangent series at 1/q."""
partial = sum(Fraction((-1)**j, (2 * j + 1) * q**(2 * j + 1)) for j in range(24))
following = Fraction(1, 49 * q**49)
return num(partial).hull(num(partial + following))
PI = num(16) * atan_inverse(5) - num(4) * atan_inverse(239)
def sin_cos(x):
"""Enclose both values for 0 <= x <= pi/2 with alternating Taylor series."""
out = []
neg_x2 = ZERO - x * x
for degree, start in ((1, x), (0, ONE)):
total = term = start
for j in range(1, 25):
k = degree + 2 * j
term = term * neg_x2 / num(k * (k - 1))
total = total + term
k = degree + 50
following = term * neg_x2 / num(k * (k - 1))
out.append(total.hull(total + following))
return out
def gauss_nodes(length, panels):
"""Positive 4-point Gauss-Legendre rule on each equal panel."""
offset = TWO * num(Fraction(6, 5)).sqrt()
nodes = [((num(3) + offset) / num(7)).sqrt(),
((num(3) - offset) / num(7)).sqrt()]
weights = [(num(18) - num(30).sqrt()) / num(36),
(num(18) + num(30).sqrt()) / num(36)]
half_width = length / num(2 * panels)
for i in range(panels):
center = half_width * num(2 * i + 1)
for node, weight in zip(nodes, weights):
delta = half_width * node
yield center - delta, weight * half_width
yield center + delta, weight * half_width
def cap_pair(orientation, radial_panels=24, angular_panels=120):
"""Average angular law and signed interference correction, integrated."""
face = orientation == 'face'
repeats = 8 if face else 12 # wedge symmetries and diametrically opposite cap
angle = PI / num(2 if face else 3)
angular = []
for phi, weight in gauss_nodes(angle, angular_panels):
s, c = sin_cos(phi)
if face:
angular.append((c / ROOT2, ZERO - c / ROOT2, s, weight))
else:
p, q = c / ROOT6, s / ROOT2
angular.append((TWO * p, q - p, ZERO - p - q, weight))
neutral = correction = ZERO
base = ONE / (ROOT2 if face else ROOT3)
for t, radial_weight in gauss_nodes(QUARTER, radial_panels):
left = radial_weight * t
for dx, dy, dz, angular_weight in angular:
# w = n_center + t e_phi. Its normalization cancels between
# the spherical area and the degree -3 directional density.
a, b = base + t * dx, base + t * dy
d = t * dz if face else base + t * dz
ad, bd = a + d, b + d
point = left * angular_weight / ((a + b) * ad * bd)
neutral = neutral + point
if face:
g = ONE - d / ad - d / bd
correction = correction + point * g
factor = num(repeats) / (TWO * PI * PI)
neutral, correction = factor * neutral, factor * correction
# In a body-diagonal cone, coordinate permutations preserve the aperture.
# Since g_x + g_y + g_z = 0 identically, its correction is exactly zero.
results = [neutral, neutral + correction, neutral - correction]
# Analytic quadrature bound for each of the three complete integrands.
# For real t,phi in a wedge, each pair sum in the denominator exceeds
# 1/2. Vary one variable in a complex disk of radius 1/8. A pair sum
# moves by at most sqrt(2)/8 in t, or sqrt(2)*cosh(1/8)/32 in phi.
# Each denominator then has modulus >0.32, |d|<1.4 and |1 +/- g|<11.
# Including t/(2*pi^2), the modulus of the integrand is <8. Cauchy's
# estimate bounds its eighth derivative by 8! * 8 / (1/8)^8.
# The 4-point Gauss remainder after this cancellation has coefficient
# 1/[(2*4+1)*binom(8,4)^2] = 1/44100. Positive weights sum to interval
# length, so the two one-dimensional composite error bounds add.
max_angle = Fraction(11, 7) if face else Fraction(22, 21)
radius = Fraction(1, 8)
width_t = Fraction(1, 4 * radial_panels)
width_phi = max_angle / angular_panels
error = (repeats * Fraction(1, 4) * max_angle * Fraction(8, 44100)
* ((width_t / radius)**8 + (width_phi / radius)**8))
pad = num(error).hi
return [Interval(v.lo - pad, v.hi + pad) for v in results]
def decimal_bounds(v, digits=11):
unit = SCALE // 10**digits
lo, hi = v.lo // unit, -(-v.hi // unit)
def render(x):
return f"{x // 10**digits}.{x % 10**digits:0{digits}d}"
return f"[{render(lo)}, {render(hi)}]"
def main():
face = cap_pair('face')
body = cap_pair('body')
print("Antipodal circular-aperture probabilities, half-angle atan(1/4)")
print("preparation face-diagonal pair body-diagonal pair"
" face / body")
for name, f, b in zip(("incoherent", "in-phase", "antiphase"), face, body):
assert f.hi - f.lo < SCALE // 10**10
assert b.hi - b.lo < SCALE // 10**10
print(f"{name:12} {decimal_bounds(f)} {decimal_bounds(b)} {decimal_bounds(f/b, 8)}")
assert face[1].lo > face[0].hi > face[2].hi
assert face[1].lo > body[1].hi and face[2].hi < body[2].lo
# Point-aperture controls follow by setting d=0 (face) or a=b=d (body).
for a, b, d, expected in ((1, 1, 0, 1), (1, 1, 1, 0)):
assert 1 - Fraction(d, a + d) - Fraction(d, b + d) == expected
print("Point-aperture factors (in-phase, antiphase): face (2,0), body (1,1).")
if __name__ == "__main__":
main()
charge.py
"""Check the bare sine-of-eigenphase charge in the one- and two-boson walk."""
from fractions import Fraction
from contact import Z, add, mul, norm, kernel
def conjugate(value):
return value[0], -value[1]
def blocks():
# Denominator 32 for F=(W^dagger-W)/(2i). K below gives 16 W.
k = {(r,out,spin):amp for spin,col in kernel().items() for r,out,amp in col}
sites = {r for r,out,spin in k}
f = {}
for r in sites:
back = tuple(-x for x in r)
for out in (0,1):
for spin in (0,1):
a = k.get((r,out,spin),Z)
b = conjugate(k.get((back,spin,out),Z))
f[r,out,spin] = mul((0,1),(a[0]-b[0],a[1]-b[1]))
return sites,f
def main():
sites,f = blocks()
assert f[(0,0,1),0,0] == (0,16)
assert (0,0,0) not in sites
for spin in (0,1):
diagonal = sum(norm(f[r,out,spin]) for r in sites for out in (0,1))
assert Fraction(diagonal,32**2) == Fraction(7,8)
# P Q² P acts on a pair at the same site. Evaluate the K=(0,pi,0)
# center-momentum symbol on triplet |up down>+|down up> (unnormalized).
for i in (0,1):
for j in (0,1):
acc = (0,0)
for r in sites:
sign = 1 if r[1]%2==0 else -1
val = add(mul(f[r,i,0],f[r,j,1]),mul(f[r,i,1],f[r,j,0]))
acc = add(acc,(2*sign*val[0],2*sign*val[1]))
assert acc[1]==0
spin = int(i!=j)
diag = Fraction(7,4)*spin + Fraction(acc[0],32**2)
assert diag == Fraction(7,2)*spin
print("Sine charge: nearest z-up hop modulus 1/2, onsite squared moment 7/8.")
print("The projected Q² center-momentum symbol attains 7/2 on the symmetric triplet.")
if __name__ == "__main__":
main()
contact.py
"""Exact two-tick scattering complement to the one-particle aperture measurements.
The two walkers start at (0,0,-1) and (0,0,1) with identical +z spin.
At each complete tick a contact phase multiplies every bunched position
configuration. A final diagonal phase leaves position probabilities invariant.
All amplitudes are pairs of integers for their real and imaginary parts.
"""
from fractions import Fraction
from math import comb
from counts import ORIGIN, STAGES, step, in_pair
Z = (0,0)
def add(a,b):
return a[0]+b[0], a[1]+b[1]
def mul(a,b):
return a[0]*b[0]-a[1]*b[1], a[0]*b[1]+a[1]*b[0]
def norm(a):
return a[0]**2+a[1]**2
def kernel():
table = {}
for spin in (0,1):
col = {ORIGIN:(1,0,0,0) if spin==0 else (0,0,1,0)}
for axis in STAGES:
col = step(col,axis)
for site,values in col.items():
pos = tuple(v//2 for v in site)
for out in (0,1):
value = tuple(values[2*out:2*out+2])
if value != Z:
table.setdefault(spin,[]).append((pos,out,value))
return table
def propagate(state,table,which):
out = {}
for (p,s,q,t),weight in state.items():
old,spin = (p,s) if which==0 else (q,t)
for delta,sp,amplitude in table[spin]:
dest = tuple(x+y for x,y in zip(old,delta))
key = (dest,sp,q,t) if which==0 else (p,s,dest,sp)
out[key] = add(out.get(key,Z),mul(weight,amplitude))
return {key:v for key,v in out.items() if v != Z}
def two_ticks(table,phase,exchange,keep=None):
left,right = (0,0,-1),(0,0,1)
state = {(left,0,right,0):(1,0)}
if exchange:
state[right,0,left,0] = (1,0)
for tick in range(2):
for which in (0,1):
state = propagate(state,table,which)
if tick==0:
if keep is not None:
state = {key:v for key,v in state.items() if (key[0]==key[2])==keep}
real,imag,scale = phase
assert real*real+imag*imag==scale*scale
state = {key:mul((real,imag) if key[0]==key[2] else (scale,0),v) for key,v in state.items()}
denominator = (2 if exchange else 1)*16**8*phase[2]**2
if keep is None:
assert sum(map(norm,state.values())) == denominator
if exchange:
assert all(state.get((q,t,p,s))==v for (p,s,q,t),v in state.items())
return state,denominator
def history_gram(table):
off,den = two_ticks(table,(1,0,1),True,False)
on,_ = two_ticks(table,(1,0,1),True,True)
result = {}
for name in ("body","same"):
values = [0]*4
for key in off.keys()|on.keys():
p,s,q,t = key
if name=="body":
if not (in_pair(p,(1,1,1)) and in_pair(q,(1,1,1))):
continue
elif p!=q:
continue
a,b = off.get(key,Z),on.get(key,Z)
cross = mul((a[0],-a[1]),b)
for i,term in enumerate((norm(a),norm(b),*cross)):
values[i] += term
result[name] = tuple(Fraction(v,den) for v in values)
return result
def lower_tail(p,n,cut):
a,d = p.numerator,p.denominator
return Fraction(sum(comb(n,k)*a**k*(d-a)**(n-k) for k in range(cut)),d**n)
def main():
table = kernel()
print('Postselected free-path and contact-path Gram matrices:', history_gram(table))
errors = lower_tail(Fraction(159,4096),1000,22),1-lower_tail(Fraction(11,1024),1000,22)
assert all(v < Fraction(1,500) for v in errors)
print('Ideal same-site test errors:', *(float(v) for v in errors))
configs = (("distinguishable",(1,0,1),False),("free bosons",(1,0,1),True),("pi",(-1,0,1),True),("pi/2",(0,1,1),True),("minus pi/2",(0,-1,1),True),("3+4i over 5",(3,4,5),True))
for label,sign,exchange in configs:
state,denom = two_ticks(table,sign,exchange)
both = {"body":0,"face":0,"same site":0,"z=1":0}
for (p,s,q,t),v in state.items():
weight = norm(v)
for name,d in (("face",(1,1,0)),("body",(1,1,1))):
if in_pair(p,d) and in_pair(q,d):
both[name] += weight
both["same site"] += weight*(p==q)
both["z=1"] += weight*(p[2]==q[2]==1)
probs = {k:Fraction(v,denom) for k,v in both.items()}
if exchange:
cosine = Fraction(sign[0],sign[2])
assert probs["body"] == (401-320*cosine)/262144
assert probs["same site"] == (203+115*cosine)/8192
assert probs["z=1"] == (13-cosine)/128
else:
assert probs["body"] == Fraction(81,262144)
assert probs["same site"] == Fraction(159,8192)
print(label,probs)
if __name__ == "__main__":
main()
counts.py
"""Exact finite detector probabilities for two coherent sources in the six-stage walk."""
import argparse
from fractions import Fraction
from pathlib import Path
import sys
# In the download, walk.py is the previously published integer-amplitude replay.
ROOT = Path(__file__).resolve().parent
walk_dir = ROOT / "prior"
if not (walk_dir / "walk.py").is_file():
walk_dir = ROOT.parent / "convex-fronts"
sys.path.insert(0, str(walk_dir))
from walk import ORIGIN, STAGES, ZERO, step
def in_pair(r, direction):
"""Two antipodal cones of half-angle arctan(1/4), excluding the origin."""
radius2 = sum(v*v for v in r)
dot = sum(v*w for v, w in zip(r, direction))
return radius2 != 0 and 17*dot*dot >= 16*radius2*sum(w*w for w in direction)
def inner(a, b):
"""Real and imaginary parts of the complex inner product of integer spinors."""
return (sum(x*y for x,y in zip(a,b)),
sum(a[i]*b[i+1]-a[i+1]*b[i] for i in (0,2)))
def shifted(state, dz):
return {(x//2,y//2,z//2+dz):value for (x,y,z),value in state.items()}
def detector(n, a, b, sites):
# a and b are the two translated source kernels, each with both spin inputs.
norm = 16**(2*n)
aa, bb, ab = [[0]*8 for _ in range(3)]
for site in sites:
av = [col.get(site, ZERO) for col in a]
bv = [col.get(site, ZERO) for col in b]
for matrix, left, right in ((aa,av,av),(bb,bv,bv),(ab,av,bv)):
for i in (0,1):
for j in (0,1):
re,im = inner(left[i], right[j])
idx = 4*i+2*j
matrix[idx] += re
matrix[idx+1] += im
# Inversion-paired aperture: total direct response and cross response are scalar in spin.
total = [x+y for x,y in zip(aa,bb)]
for matrix in (total,ab):
assert matrix[:2] == matrix[6:] and matrix[2:6] == [0]*4
pa,pb,qr,qi = [Fraction(v,norm) for v in (aa[0],bb[0],ab[0],ab[1])]
incoherent = (pa+pb)/2
exchange = qr**2+qi**2
return dict(a=pa,b=pb,mix=incoherent,plus=incoherent+qr,minus=incoherent-qr,
cross_im=qi,delayed=pa*pb,overlap=pa*pb+exchange)
def measure(n, up, down):
a,b = [[shifted(col,dz) for col in (up,down)] for dz in (-1,1)]
sites = set().union(*(c.keys() for c in a+b))
full = detector(n,a,b,sites)
assert all(full[k] == 1 for k in ("a","b","mix","plus","minus","delayed","overlap"))
assert full["cross_im"] == 0
rows = {}
for name,direction in (("face",(1,1,0)),("body",(1,1,1))):
rows[name] = detector(n,a,b,[r for r in sites if in_pair(r,direction)])
return rows
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("ticks",type=int,nargs="*",default=[3,4,8,12])
times = set(parser.parse_args().ticks)
if not times or min(times)<1:
parser.error("tick counts must be positive")
up,down = {ORIGIN:(1,0,0,0)}, {ORIGIN:(0,0,1,0)}
for n in range(1,max(times)+1):
for axis in STAGES:
up,down = step(up,axis),step(down,axis)
if n in times:
for name,row in measure(n,up,down).items():
if n==3 and name=="face":
assert (row["plus"],row["minus"],row["overlap"]) == (Fraction(17,128),Fraction(1,256),Fraction(1157,131072))
print(n,name," ".join(f"{key}={float(value):.9f}" for key,value in row.items()))
if n<=4:
print(" exact", ", ".join(f"{k}={v}" for k,v in row.items()))
if __name__ == "__main__":
main()
gravity.py
"""Finite-support transport of a coupled scalar and vector Gauss source.
Python 3 standard library. Coordinates are twice the fine-site coordinates.
Sparse maps omit zero coefficients; all stencils use integer or rational arithmetic.
"""
from fractions import Fraction
from itertools import product
PERIOD = (0, 0, 0, 1, 1, 0)
ENERGY = 2
ORIGIN = (0, 0, 0)
UNIT = {ORIGIN: 1}
def add(*fields):
result = {}
for field in fields:
for location, value in field.items():
result[location] = result.get(location, 0) + value
return {p: v for p, v in result.items() if v}
def times(field, factor):
return {p: factor * v for p, v in field.items() if factor * v}
def sub(first, second):
return add(first, times(second, -1))
def stencil(field, axis, terms):
"""Apply sum c*f(x+s) at all sites, pairing each field with its stagger."""
parts = []
for offset, coefficient in terms:
shifted = {}
for point, value in field.items():
dest = list(point)
dest[axis] -= offset
shifted[tuple(dest)] = coefficient * value
parts.append(shifted)
return add(*parts)
def centered(field, axis):
return stencil(field, axis, [(1, 1), (-1, -1)])
def average(field, axis, radius):
half = Fraction(1, 2)
return stencil(field, axis, [(radius, half), (-radius, half)])
def native(field, axis):
quarter = Fraction(1, 4)
field = stencil(field, axis, [(4, quarter), (-4, -quarter)])
for j in range(axis + 1, 3):
field = average(field, j, 4)
return field
def filters(field, axes):
for i in axes:
field = average(average(field, i, 1), i, 2)
for j in range(i + 1, 3):
field = average(field, j, 4)
return field
def diagonal_curvature(diagonal, derivative):
trace = add(*diagonal)
return add(*(derivative(derivative(sub(diagonal[i], trace), i), i)
for i in range(3)))
def phase_values(branch, stage):
def f(t):
return branch * PERIOD[t % len(PERIOD)]
return f(stage), f(stage + 1) - f(stage), f(stage) - f(stage - 1)
def ledger(radius, use_native):
derivative = native if use_native else centered
def smooth(field, factors):
return filters(field, factors) if use_native else field
# Start with directly assigned densities and directed fluxes. The triangle
# solves D_x^2 Q = rho_separated - rho_center, including radius 2.
center = times(UNIT, 2 * ENERGY)
ends = {(s * 2 * radius, 0, 0): ENERGY for s in (-1, 1)}
flux = {(s * (2 * x + 1), 0, 0): s * ENERGY
for x in range(radius) for s in (-1, 1)}
triangle = {(2*x, 0, 0): ENERGY * (radius - abs(x))
for x in range(1-radius, radius)}
center = smooth(center, (0, 1, 2, 0, 1, 2)) # L0^2
ends = smooth(ends, (0, 1, 2, 0, 1, 2))
flux = smooth(flux, (0, 1, 2, 1, 2)) # L0 Lx
triangle = smooth(triangle, (1, 2, 1, 2)) # Lx^2
half = Fraction(1, 2)
change = sub(ends, center)
assert sum(ends.values()) == sum(center.values()) == 2 * ENERGY
assert min(ends.values()) > 0 and min(center.values()) > 0
# A finite scalar dressing carries zero energy dipole. This uncompensated
# hop has the same nonzero dipole even after native finite averaging.
single = sub({(2 * radius, 0, 0): ENERGY}, times(UNIT, ENERGY))
single = smooth(single, (0, 1, 2, 0, 1, 2))
assert sum(Fraction(p[0], 2) * v for p, v in single.items()) == radius * ENERGY
assert all(sum(p[i] * v for p, v in change.items()) == 0 for i in range(3))
# Opposite axial momenta give zero total and angular momentum.
assert sum(flux.values()) == 0
assert all(sum(p[i] * v for p, v in flux.items()) == 0 for i in (1, 2))
# Axial transfer k=(0,0,pi/3) has real cosines on every h/TT site.
cosines = (1, half, -half, -1, -half, half)
def axial_component(field):
assert all(p[2] % 2 == 0 for p in field)
return sum(v * cosines[(p[2] // 2) % 6] for p, v in field.items())
for branch in (0, 1):
for stage in range(len(PERIOD)):
f, u, prev_u = phase_values(branch, stage)
h = [times(triangle, sign * f * half) for sign in (1, -1, -1)]
pxx = times(triangle, u * half)
stress = times(triangle, u - prev_u)
assert diagonal_curvature(h, derivative) == times(change, f)
assert times(derivative(pxx, 0), -2) == times(flux, u)
assert not add(times(change, u), derivative(times(flux, u), 0))
assert not add(times(flux, u - prev_u), derivative(stress, 0))
next_f, _, _ = phase_values(branch, stage + 1)
prev_f, _, _ = phase_values(branch, stage - 1)
for i, sign in enumerate((1, -1, -1)):
next_h = times(triangle, sign * next_f * half)
kinetic = sub(times(pxx, 2) if i == 0 else {}, pxx)
assert sub(next_h, h[i]) == kinetic
# At k parallel to z, H=hxx-hyy is the unnormalized plus mode.
# Evaluate (delta_t^2 - D_i D_i) H - (tau_xx-tau_yy).
hplus = sub(h[0], h[1])
ddh = times(triangle, next_f - 2*f + prev_f)
laplacian = add(*(derivative(derivative(hplus, i), i) for i in range(3)))
residual = axial_component(sub(sub(ddh, laplacian), stress))
predicted = radius**2 * (Fraction(9, 512) if use_native else 2) * f
assert residual == predicted
return len(change), len(flux), radius**2 * (Fraction(9, 512) if use_native else 2)
# Exhaustive quantum test for the radius-one block. Only the three diagonal
# metric qudits at its center are shifted. Constraint factors on every other
# qudit commute with the block and cancel from its commutator. Each amplitude
# is a single seventh root of unity; store its exponent exactly.
K = 7
def dressing(branch, stage):
f, u, _ = phase_values(branch, stage)
return (f, -f, -f), (u, 0, 0) # ENERGY/2 = 1
def tick(state):
branch, stage, coordinates, phase = state
a, b = dressing(branch, stage)
target = (stage + 1) % len(PERIOD)
new_a, new_b = dressing(branch, target)
common = tuple(x - k for x, k in zip(coordinates, a))
coords = tuple((x + k) % K for x, k in zip(common, new_a))
# W_target W_stage^dagger for W = X^a Z^b, with Z acting first.
phase += sum((t - s) * x for s, t, x in zip(b, new_b, common))
return branch, target, coords, phase % K
def energy_check(state, position, coefficients):
branch, stage, coordinates, phase = state
f, _, _ = phase_values(branch, stage)
rho_change = {(0, 0, 0): -2 * ENERGY, (2, 0, 0): ENERGY,
(-2, 0, 0): ENERGY}.get(position, 0)
exponent = sum(c * x for c, x in zip(coefficients, coordinates)) - f * rho_change
return branch, stage, coordinates, (phase + exponent) % K
def momentum_check(state, axis, sign):
branch, stage, coordinates, phase = state
_, u, _ = phase_values(branch, stage)
# At +/- half a site M_i includes +/-2*pi_ii(0). Its exponential
# translates h_ii(0) by the negative coefficient.
coords = list(coordinates)
coords[axis] = (coords[axis] - 2 * sign) % K
j = sign * ENERGY * u if axis == 0 else 0
return branch, stage, tuple(coords), (phase - j) % K
def quantum():
columns = []
for i in range(3):
diagonal = [UNIT if j == i else {} for j in range(3)]
columns.append(diagonal_curvature(diagonal, centered))
sites = set().union(*columns)
constraints = [(site, tuple(column.get(site, 0) for column in columns))
for site in sorted(sites)]
count = 0
for branch, stage, coords in product((0, 1), range(len(PERIOD)),
product(range(K), repeat=3)):
state = (branch, stage, coords, 0)
after = tick(state)
for site, coeff in constraints:
assert tick(energy_check(state, site, coeff)) == energy_check(after, site, coeff)
for axis, sign in product(range(3), (-1, 1)):
assert tick(momentum_check(state, axis, sign)) == momentum_check(after, axis, sign)
full = state
for _ in PERIOD:
full = tick(full)
assert full == state # no residual phase from the noncommuting dressings
count += 1
assert count == 2 * len(PERIOD) * K**3
branches = [(b, 0, (0, 0, 0), 0) for b in (0, 1)]
for _ in range(3):
branches = [tick(state) for state in branches]
assert branches[0][2] == (0, 0, 0)
assert branches[1][2] == (1, K - 1, K - 1)
return count, len(constraints) + 6
# Unprojected retarded evolution. Symmetric tensors store six independent
# components; contractions below still count both off-diagonal entries.
PAIRS = tuple((i, j) for i in range(3) for j in range(i, 3))
def component(tensor, i, j):
return tensor[min(i, j), max(i, j)]
def divergence(tensor, derivative):
return [add(*(derivative(component(tensor, i, j), j) for j in range(3)))
for i in range(3)]
def spatial_einstein(tensor, derivative):
trace = add(*(tensor[i, i] for i in range(3)))
div = divergence(tensor, derivative)
curvature = sub(add(*(derivative(div[i], i) for i in range(3))),
add(*(derivative(derivative(trace, i), i) for i in range(3))))
force = {}
for i, j in PAIRS:
lap = add(*(derivative(derivative(tensor[i, j], k), k) for k in range(3)))
ddtrace = derivative(derivative(trace, j), i)
force[i, j] = times(sub(add(derivative(div[j], i), derivative(div[i], j)),
add(lap, ddtrace, curvature if i == j else {})),
Fraction(1, 2))
return curvature, force
def tidal_contrast(h, derivative):
"""Twice (R_xzxz - R_yzyz) in the spatial metric on a flat background."""
def twice_riemann(i):
shear = times(derivative(derivative(h[i, 2], 2), i), 2)
return sub(shear, add(derivative(derivative(h[i, i], 2), 2),
derivative(derivative(h[2, 2], i), i)))
return sub(twice_riemann(0), twice_riemann(1))
def evolve(use_native):
half = Fraction(1, 2)
speed_sq = Fraction(1, 4)
# Native verification uses a six-site torus (216 vertices), chosen to
# include k_z=pi/3. Centered verification uses the infinite sparse lattice.
def fold(field):
if not use_native:
return field
folded = {}
for point, value in field.items():
dest = tuple(x % 12 for x in point)
folded[dest] = folded.get(dest, 0) + value
return {p: v for p, v in folded.items() if v}
def derivative(field, i):
return fold(native(field, i)) if use_native else centered(field, i)
def smooth(field, factors):
return fold(filters(field, factors)) if use_native else field
triangle = smooth(times(UNIT, ENERGY), (1, 2, 1, 2))
delta = smooth({(-2, 0, 0): ENERGY, (2, 0, 0): ENERGY,
ORIGIN: -2 * ENERGY}, (0, 1, 2, 0, 1, 2))
flux = smooth({(-1, 0, 0): -ENERGY, (1, 0, 0): ENERGY},
(0, 1, 2, 1, 2))
cosines = (1, half, -half, -1, -half, half)
def axial_fourier(field, axis):
assert all(p[axis] % 2 == 0 for p in field)
# Exact sine divided by sin(pi/3); the histories are reflection-symmetric.
sines = (0, 1, 1, 0, -1, -1)
assert sum(v * sines[(p[axis] // 2) % 6] for p, v in field.items()) == 0
return sum(v * cosines[(p[axis] // 2) % 6] for p, v in field.items())
def f(n):
return int(n in (3, 4)) # one pulse, then permanently idle
h = {ij: {} for ij in PAIRS}
pi = {ij: {} for ij in PAIRS}
plus = []
detector = []
central = []
for n in range(10):
curvature, force = spatial_einstein(h, derivative)
assert not any(divergence(force, derivative)) # exact spatial Bianchi
assert curvature == times(delta, f(n))
expected_j = times(flux, f(n) - f(n-1))
assert [times(v, -2) for v in divergence(pi, derivative)] == [expected_j, {}, {}]
central.append(curvature.get(ORIGIN, 0))
plus.append(axial_fourier(sub(h[0, 0], h[1, 1]), 2))
# Two transverse polarizations both vanish on the source axis.
assert axial_fourier(sub(h[1, 1], h[2, 2]), 0) == 0
# The yz shear is a half-grid in y,z, but integer-valued in x.
assert axial_fourier(h[1, 2], 0) == 0
if not use_native:
detector.append(tidal_contrast(h, derivative).get((0, 0, 6), 0))
stress = times(triangle, f(n+1) - 2*f(n) + f(n-1))
if n == 2:
# At the first launch, doubling just the stress coupling from
# w=1 to beta=2 produces exactly one extra copy of the flux.
wrong_pxx = add(pi[0, 0], times(force[0, 0], -speed_sq), stress)
wrong_pi = {**pi, (0, 0): wrong_pxx}
assert times(divergence(wrong_pi, derivative)[0], -2) == times(flux, 2)
for ij in PAIRS:
pi[ij] = add(pi[ij], times(force[ij], -speed_sq),
times(stress, half) if ij == (0, 0) else {})
trace_pi = add(*(pi[i, i] for i in range(3)))
for i, j in PAIRS:
h[i, j] = sub(add(h[i, j], times(pi[i, j], 2)),
trace_pi if i == j else {})
g = Fraction(3, 64) if use_native else Fraction(1, 4)
B = Fraction(3, 32) if use_native else 2
invariant = B**2 * g**2 * (4-g) / 2
for n in range(5, len(plus)-1):
a, b = plus[n], plus[n+1]
assert ((b-a)**2 + g*a*b)/2 == invariant
assert plus[5] == B*(g**2-3*g) and plus[6] == -B*g*(g**2-5*g+5)
assert all(v == 0 for v in central[5:])
if use_native:
assert central[3] == -Fraction(33, 4096)
else:
assert central[3] == -4
assert detector[:5] == [0] * 5
assert detector[5] == -Fraction(1, 8) and detector[7] == Fraction(21, 64)
return plus[5:7], invariant, central[3], detector
if __name__ == "__main__":
for r, use_native in product((1, 2), (False, True)):
nr, nj, residual = ledger(r, use_native)
print(f"radius={r}, {'native' if use_native else 'centered'}, "
f"12 branch/stage pairs verified, {nr} density and {nj} flux entries, "
f"split-state TT residual {residual}")
states, stabilizers = quantum()
print(f"{states} basis states x {stabilizers} stabilizers commute with U; "
"U^6 = I including phases; neutral-coin branches distinguishable")
for use_native in (False, True):
trace, invariant, center, detector = evolve(use_native)
print(f"retarded {'native torus' if use_native else 'centered open lattice'}: "
f"H5,H6={[str(x) for x in trace]}, free invariant={invariant}, "
f"central split curvature={center}")
if detector:
print("spatial curvature at z=3 for n=0..9:", [str(x) for x in detector])
photon_wedges.py
"""Read the mixed-input 2D optical-walk chart from Jeong et al., Fig. 6.
Example: python photon_wedges.py --download, or --archive <arXiv source tar>.
This recovers normalized *plotted* measurements. The original photon time
tags, per-site integer counts and their statistical errors are unavailable
in this source. No figure from the article is redistributed by this script.
"""
import argparse
from collections import defaultdict
import hashlib
import io
from math import atan2, hypot, sqrt
from pathlib import Path
import re
import tarfile
from urllib.request import urlopen
SOURCE = "https://arxiv.org/src/1309.6837v1"
FIGURE = "fig5_mixed.eps"
SHA256 = "a21c6290e6f66dadc498e705890497c4e96e8a2163a6186ef0430ef379f7d753"
SIDE_COLORS = {"0 .362646 .277745 0 cmyk", ".582971 .616968 .083497 0 cmyk"}
POINT = re.compile(r"([.\d-]+) ([.\d-]+) (mo|li)")
def components(edges):
neighbors = defaultdict(set)
for a, b in edges:
neighbors[a].add(b)
neighbors[b].add(a)
while neighbors:
todo = [next(iter(neighbors))]
group = set()
while todo:
point = todo.pop()
if point in neighbors:
group.add(point)
todo.extend(neighbors.pop(point))
yield group
def bars_from_chart(data):
eps = data.decode("latin1")
lines = eps[eps.index("%%Page:"):eps.index("%%PageTrailer")].splitlines()
edges = set()
for i, line in enumerate(lines):
if line not in SIDE_COLORS:
continue
points = []
for command in reversed(lines[i-15:i]):
hit = POINT.fullmatch(command)
if hit:
points.append((float(hit[1]), float(hit[2])))
if hit[3] == "mo":
break
points = list(dict.fromkeys(points))
assert len(points) == 4
for a, b in zip(points, points[1:]+points[:1]):
edges.add(tuple(sorted((a, b))))
for group in components(edges):
uprights = [(a, b) for a, b in edges if a in group
and abs(b[1]-a[1]) > 5*abs(b[0]-a[0])]
# In this EPS the graphic's ground plane has the higher y coordinate.
cols = [(min(g, key=lambda p:p[1]), max(g, key=lambda p:p[1]))
for g in components(uprights)]
assert len(cols) == 4
yield cols
def vanishing_point(lines):
# Least squares intersection of the unit-normal lines a*x+b*y+c=0.
aa = ab = bb = ac = bc = 0.0
for p, q in lines:
dx, dy = q[0]-p[0], q[1]-p[1]
a, b = -dy/hypot(dx, dy), dx/hypot(dx, dy)
c = -a*p[0]-b*p[1]
aa += a*a
ab += a*b
bb += b*b
ac += a*c
bc += b*c
det = aa*bb-ab*ab
return (ab*bc-bb*ac)/det, (ab*ac-aa*bc)/det
def grid_levels(slopes):
# Five rows fan out from each horizontal vanishing point. Split the four
# large inter-row gaps, tolerating the measured cell with zero bar height.
ranks = sorted(enumerate(slopes), key=lambda row:row[1])
gaps = [b[1]-a[1] for a, b in zip(ranks, ranks[1:])]
breaks = set(sorted(range(len(gaps)), key=gaps.__getitem__, reverse=True)[:4])
labels = [0]*len(slopes)
level = -4
for i, (site, _) in enumerate(ranks):
labels[site] = level
if i in breaks:
level += 2
return labels
def read_panel(bars):
horizon_edges = [[], []]
centers = []
vertical_edges = []
for cols in bars:
bases = [b for _, b in cols]
cx, cy = (sum(p[i] for p in bases)/4 for i in (0, 1))
centers.append((cx, cy))
bases.sort(key=lambda p:atan2(p[1]-cy, p[0]-cx))
for p, q in zip(bases, bases[1:]+bases[:1]):
family = int((p[0]-q[0])*(p[1]-q[1]) > 0)
horizon_edges[family].append((p, q))
vertical_edges.extend((t, b) for t, b in cols if b[1]-t[1] > 5)
v1, v2 = map(vanishing_point, horizon_edges)
vz = vanishing_point(vertical_edges)
# Plane horizon is the line through the two infinite ground directions.
a, b = v1[1]-v2[1], v2[0]-v1[0]
c = v1[0]*v2[1]-v1[1]*v2[0]
axes = [grid_levels([(y-vy)/(x-vx) for x, y in centers]) for vx, vy in (v1, v2)]
heights = {}
for x, y, cols in zip(*axes, bars):
assert (x, y) not in heights
values = []
for top, foot in cols:
# Homogeneous camera depth of the ground, times vertical cross ratio.
depth = 1/(a*foot[0]+b*foot[1]+c)
values.append(abs(depth*(top[1]-foot[1])/(vz[1]-top[1])))
heights[x, y] = values
return heights
def normalized(heights):
values = {point:sum(edges)/len(edges) for point, edges in heights.items()}
norm = sum(values.values())
return {point:h/norm for point, h in values.items()}
def in_wedges(point):
x, y = map(abs, point)
return x+y > 0 and 4*min(x, y) <= max(x, y)
def ideal_four_steps():
distribution = defaultdict(float)
for basis in ((1, 0), (0, 1)):
state = {(0, 0):basis}
for axis in (0, 1)*4:
new = defaultdict(lambda:[0, 0])
for point, (up, down) in state.items():
for sign in (-1, 1):
target = list(point)
target[axis] += sign
new[tuple(target)][int(sign<0)] += up+sign*down
state = new
for point, (up, down) in state.items():
distribution[point] += (up**2+down**2)/(2*2**8)
return distribution
def analyze(archive):
with tarfile.open(fileobj=archive) as source:
eps = source.extractfile(FIGURE).read()
assert hashlib.sha256(eps).hexdigest() == SHA256
panels = [[], []]
for bar in bars_from_chart(eps):
region = int(sum(b[0] for _, b in bar)/4 > 195)
panels[region].append(bar)
assert [len(p) for p in panels] == [25, 24]
control, measured = map(read_panel, panels)
exact = ideal_four_steps()
digitized, observed = normalized(control), normalized(measured)
error = max(abs(digitized[p]-v) for p, v in exact.items())
assert error < 4e-6
fraction = lambda data: sum(v for p, v in data.items() if in_wedges(p))
assert fraction(exact) == 19/32
# Spread obtained by taking the extreme of four reconstructed edges per
# bar. This probes digitization consistency, not photon sampling error.
groups = [[edges for p, edges in measured.items() if in_wedges(p) == flag]
for flag in (True, False)]
low, high = [(sum(map(min, group)), sum(map(max, group))) for group in groups]
interval = low[0]/(low[0]+high[1]), low[1]/(low[1]+high[0])
similarity = sum(sqrt(v*observed.get(p, 0)) for p,v in exact.items())**2
print(f"maximum single-site error in known theory panel: {error:.8f}")
print(f"four wedges, exact={fraction(exact):.8f}, theory chart={fraction(digitized):.8f}")
print(f"four wedges, experiment={fraction(observed):.8f}, edge spread={interval}")
print(f"origin={observed[0,0]:.8f}, full-distribution similarity={similarity:.8f}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--archive", type=Path)
source.add_argument("--download", action="store_true")
args = parser.parse_args()
if args.archive:
with args.archive.open("rb") as stream:
analyze(stream)
else:
with urlopen(SOURCE, timeout=60) as response:
analyze(io.BytesIO(response.read()))
if __name__ == "__main__":
main()
raw_atom_wedges.py
"""Score four axial wedges in the Young et al. 2D strontium fluorescence shots.
Python standard library. Pass the original tunnel.zip or --download to retrieve
the 392.5 MB Zenodo file in a temporary directory. The angular gate uses
lattice-site coordinates. An unmoved atom contributes to the denominator only.
The interval describes counting noise conditional on two valid detections.
"""
import argparse
import ast
import cmath
from collections import Counter
import hashlib
from math import cos, pi, sin, sqrt
from pathlib import Path
import shutil
import struct
import tempfile
from urllib.request import urlopen
import zipfile
URL = "https://zenodo.org/api/records/6519158/files/tunnel.zip/content"
MD5 = "8fc916b8f123ab74f602c738d06ebf80"
GROUPS = {"5.0 ms": (68, 69, 70, 72), "6.5 ms": (63, 65)}
THRESHOLDS = (4.0, 4.5, 5.0)
def peak_sites(archive, frame, run):
name = f"tunnel/roisums{frame}_{run}.npy"
with archive.open(name) as stream:
assert stream.read(8) == b"\x93NUMPY\x01\x00"
header_length = int.from_bytes(stream.read(2), "little")
description = ast.literal_eval(stream.read(header_length).decode("ascii"))
variations, repeats, regions, sites = description["shape"]
assert (variations, regions, sites) == (1, 1, 29**2)
assert description["descr"] == "<f8" and not description["fortran_order"]
row = struct.Struct(f"<{sites}d")
for _ in range(repeats):
values = row.unpack(stream.read(row.size))
signal = max(values)
yield divmod(values.index(signal), 29), signal/70
assert not stream.read(1)
def count_run(archive, run):
counts = {cut: Counter() for cut in THRESHOLDS}
for (p0, first), (p1, last) in zip(peak_sites(archive, 0, run),
peak_sites(archive, 1, run)):
x, y = (abs(a-b) for a, b in zip(p0, p1))
for cut, count in counts.items():
count["shots"] += 1
if first <= cut:
continue
count["loaded"] += 1
if last <= cut:
continue
count["retained"] += 1
count["origin"] += (x == y == 0)
count["edge"] += (0 in p1 or 28 in p1)
count["axial"] += (x+y > 0 and 4*min(x, y) <= max(x, y))
return counts
def wilson(success, total):
z = 1.959963984540054
p = success/total
denominator = 1 + z*z/total
center = (p + z*z/(2*total))/denominator
half = z*sqrt((p*(1-p)+z*z/(4*total))/total)/denominator
return center-half, center+half
def effective(t, settings):
"""Servo-settling fit used in cell 38 of the authors’ QRW_calculations.ipynb."""
a, tau, t0 = settings
return sqrt(a + (t/tau-t0)**2) - sqrt(a)
def lattice_probabilities(t, size):
center = size // 2
momenta = [pi*p/(size+1) for p in range(1, size+1)]
coeffs = [2/(size+1)*sin(k*(center+1))*cmath.exp(-2j*t*cos(k))
for k in momenta]
return [abs(sum(c*sin(k*(site+1)) for c,k in zip(coeffs, momenta)))**2
for site in range(size)]
def atomic_model(t, size=29):
# The two tuples are the fit coefficients printed in notebook cell 39.
# This comparator omits the independently modeled loss of fringe contrast.
tx = effective(t, (3.47157536, 0.80615786, 0.72188183))
ty = effective(t, (2.19631653, 0.95412269, 0.56254985))
px, py = (lattice_probabilities(q, size) for q in (tx, ty))
assert abs(sum(px)*sum(py)-1)<1e-12
center = size // 2
return sum(a*b for ix, a in enumerate(px) for iy,b in enumerate(py)
if (ix!=center or iy!=center) and
4*min(abs(ix-center),abs(iy-center))<=max(abs(ix-center),abs(iy-center)))
def analyze(path):
digest = hashlib.md5()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024*1024), b""):
digest.update(chunk)
assert digest.hexdigest() == MD5, "unexpected Zenodo archive"
with zipfile.ZipFile(path) as archive:
for time, runs in GROUPS.items():
clock_ms = float(time.split()[0])
print(f"{time}: flat coherent 29-site model per axis, wedge={atomic_model(clock_ms):.6f}")
totals = {cut: Counter() for cut in THRESHOLDS}
for run in runs:
rows = count_run(archive, run)
for cut in THRESHOLDS:
totals[cut].update(rows[cut])
print(f" run {run} at 4.5 photons: {dict(rows[4.5])}")
for cut, count in totals.items():
a, n = count["axial"], count["retained"]
lo, hi = wilson(a, n)
print(f"{time}, cut {cut}: axial {a}/{n}={a/n:.6f}; "
f"95% Wilson [{lo:.6f}, {hi:.6f}]; "
f"origin={count['origin']}, field edge={count['edge']}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--archive", type=Path)
source.add_argument("--download", action="store_true")
args = parser.parse_args()
if args.archive:
analyze(args.archive)
else:
with tempfile.TemporaryDirectory() as work:
path = Path(work)/"tunnel.zip"
with urlopen(URL, timeout=180) as incoming, path.open("wb") as target:
shutil.copyfileobj(incoming, target)
analyze(path)
if __name__ == "__main__":
main()
replay.py
"""Replay the pair-detector study with the pinned Tally runtime and Python."""
import argparse
import hashlib
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parent
RUNTIME_SHA = "1fb281c0ef55314ec68de024ac27da152ff00739607cbbdc408eeee82ab5b193"
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"
WALK_SHA = "6f72200b7e30d71d04149373cae8bd55bc6683c9487c8ae2632ae4acb66d23e5"
def checked(path, expected):
data = path.read_bytes()
if hashlib.sha256(data).hexdigest() != expected:
raise ValueError(f"SHA-256 mismatch for {path.name}")
return data
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="released Tally 0.3.0 runtime ZIP")
args = parser.parse_args()
checked(args.runtime, RUNTIME_SHA)
lib = ROOT / "lib/atom.tly"
if not lib.is_file():
lib = ROOT.parent / "walk-clock-recoil/tally/lib/atom.tly"
atom = checked(lib, ATOM_SHA)
walk = ROOT / "prior/walk.py"
if not walk.is_file():
walk = ROOT.parent / "convex-fronts/walk.py"
checked(walk, WALK_SHA)
python = [sys.executable, "-E", "-s", "-B", "-X", "utf8"]
for script in ("aperture", "counts", "contact", "charge", "synthetic_slice", "gravity"):
subprocess.run([*python, str(ROOT / (script + ".py"))], check=True)
with tempfile.TemporaryDirectory() as work_path:
work = Path(work_path)
with ZipFile(args.runtime) as runtime:
runtime.extractall(work)
tally = work / "Tally-0.3.0"
(tally / "lib/atom.tly").write_bytes(atom)
shutil.copyfile(ROOT / "detectors.tly", work / "detectors.tly")
result = subprocess.run([*python, str(tally / "tally.py"), "detectors.tly"],
cwd=work, stdout=subprocess.PIPE, check=True)
actual = result.stdout.decode("utf-8").splitlines()
expected = (ROOT / "detectors.out").read_text(encoding="utf-8").splitlines()
if actual != expected or sum(row.startswith("✓") for row in actual) != 16:
raise ValueError("Native transcript differs from the 16 published checks")
print("All six offline calculations and the complete native Tally transcript passed.")
if __name__ == "__main__":
main()
synthetic_slice.py
"""Test phase-resolved reconstruction of a three-dimensional one-particle walk.
A full tick has single fine x,y shifts, the paired z shift (one coarse cell),
then single fine y,x shifts. The ideal optical retarder at kappa replaces only
the paired z shift; x and y remain spatial throughout. Python standard library.
"""
from collections import defaultdict
import cmath
from math import pi, sqrt
STAGES = "xyzyx"
def polarized(a, b, axis, sign):
if axis == "x":
return (a+sign*b)/2, (b+sign*a)/2
if axis == "y":
return (a-1j*sign*b)/2, (b+1j*sign*a)/2
return (a, 0) if sign == 1 else (0, b)
def evolve(state, ticks, kappa=None):
"""With a real-space z register, kappa=None; with only x,y, supply kappa."""
for _ in range(ticks):
for axis in STAGES:
if axis == "z" and kappa is not None:
phase = cmath.exp(-1j*kappa)
state = {r:(phase*a, phase.conjugate()*b) for r,(a,b) in state.items()}
continue
following = defaultdict(lambda:[0j, 0j])
component = "xyz".index(axis)
for site, (a, b) in state.items():
for sign in (-1, 1):
u, v = polarized(a, b, axis, sign)
if u == v == 0:
continue
target = list(site)
target[component] += sign
field = following[tuple(target)]
field[0] += u
field[1] += v
state = {r:val for r,val in following.items() if any(val)}
return state
def check(ticks, source, spin, parity_grid):
direct = {(0,0,z):(weight*spin[0], weight*spin[1]) for z,weight in source}
direct = evolve(direct, ticks)
zmin = min(z for z,_ in source) - ticks
zmax = max(z for z,_ in source) + ticks
if parity_grid:
levels = range(zmin, zmax+1, 2)
phases = [pi*i/len(levels) for i in range(len(levels))]
else:
levels = range(zmin, zmax+1)
phases = [2*pi*i/len(levels) for i in range(len(levels))]
slices = []
for kappa in phases:
initial = sum(weight*cmath.exp(-1j*kappa*z) for z,weight in source)
slices.append(evolve({(0,0):(initial*spin[0], initial*spin[1])}, ticks, kappa))
sites = set().union(*(s.keys() for s in slices), (r[:2] for r in direct))
error = 0.0
total = 0.0
for xy in sites:
fields = [s.get(xy,(0,0)) for s in slices]
projected = sum(abs(v)**2 for pair in fields for v in pair)/len(phases)
expected = 0.0
for z in levels:
factors = [cmath.exp(1j*kappa*z)/len(phases) for kappa in phases]
reference = direct.get((*xy,z), (0,0))
reconstructed = [sum(w*pair[i] for w,pair in zip(factors,fields)) for i in (0,1)]
error = max(error, *(abs(a-b) for a,b in zip(reference,reconstructed)))
expected += sum(abs(v)**2 for v in reference)
assert abs(projected-expected) < 1e-13
total += expected
assert abs(total-1) < 1e-13 and error < 1e-13
return len(phases), error
def main():
point = [(0,1)]
balanced = [(-1,1/sqrt(2)),(1,1/sqrt(2))]
antisymmetric = [(-1,1/sqrt(2)),(1,-1/sqrt(2))]
for n in (1, 2, 3, 4):
worst = 0.0
for spin in ((1,0),(0,1)):
for source in (point, balanced, antisymmetric):
for parity_grid in (False, True):
count, err = check(n, source, spin, parity_grid)
if parity_grid:
assert count == n+len(source)
worst = max(worst, err)
print(f"N={n}: point {n+1} and two-site {n+2} parity-resolved settings; "
f"max amplitude error across all controls {worst:.2e}")
# An onsite interaction on an eight-site ring couples |0,0> momentum to
# |1,-1>. Independent one-particle retarder settings preserve each momentum.
sites = 8
phase = -1
matrix_element = sum((phase-1)/sites**2 *
cmath.exp(-2j*pi*(1-1)*z/sites) for z in range(sites))
assert abs(matrix_element + 0.25) < 1e-14
print("Two-particle contact at phase pi: momentum (0,0) to (1,-1) amplitude = -1/4.")
if __name__ == "__main__":
main()