Complete Tally transcript
✓ a pi flux cancels the shortest free amplitude at the selected detector (by cross-pairing plus and minus sides; derived)
✓ one mobile spectator activates the cubic-time joint amplitude (by cross-pairing plus and minus sides; derived)
✓ the first probability coefficient for the contact-assisted coincidence (by cross-pairing plus and minus sides; derived)
✓ the uniform lower bound on contact exposure exceeds 98.21 percent (by cross-pairing plus and minus sides; derived)
✓ common scaling of hopping and contact gives no Hubbard dimer dissociation amplitude (by cross-pairing plus and minus sides; derived)
✓ an incoherent breakup scan loses the entire exact protected line at Z equal one (by cross-pairing plus and minus sides; derived)
✓ a uniform harmonic tide shifts both pair levels equally at first order (by cross-pairing plus and minus sides; derived)
✓ quartic and sextic moments in the recoil doublet (by cross-pairing plus and minus sides; derived)
✓ equal recoil gaps admit opposite slopes when a separate curvature is applied (by cross-pairing plus and minus sides; derived)
✓ relative pair-correlation contrast has a finite-wavevector null at q ell equal two (by cross-pairing plus and minus sides; derived)
✓ the common one-body form-factor doublet first differs at fourth order in q (by cross-pairing plus and minus sides; derived)
✓ compensating center-of-mass and relative widths preserve the whole mass moment (by cross-pairing plus and minus sides; derived)
✓ two pulse durations remove the cubic spectral bias (by cross-pairing plus and minus sides; derived)
✓ eight-to-one shot allocation minimizes the upper bound on Ramsey sampling variance (by cross-pairing plus and minus sides; derived)
✓ shallow and deep rubidium breakup centers lie on opposite sides of the plotted contact curve (by cross-pairing plus and minus sides; derived)
✓ at the common zero crossing two deeper traps have independently measured smaller gaps (by cross-pairing plus and minus sides; derived)
✓ two calibrated loops give different widths to transverse and parallel triplets (by cross-pairing plus and minus sides; derived)
✓ three Cartesian input widths determine the cosine of an isolated right-angle loop (by cross-pairing plus and minus sides; derived)
✓ the rational matrix bracket resolves a positive minimum over all prepared onsite textures (by cross-pairing plus and minus sides; derived)
✓ the two native geodesic loops rotate about independent axes (by cross-pairing plus and minus sides; derived)
Native Tally source
# Native Tally checks on the measured operator, exact dark routes and pair clocks.
ratchet 32 step
import "atom"
let zero=whole(0 trial)
let one=whole(1 trial)
let two=whole(2 trial)
let three=whole(3 trial)
let four=whole(4 trial)
let eight=whole(8 trial)
let half=fraction(1 trial,2 trial)
# Two two-hop paths to (1,2,2), in units epsilon/8. Only the first has an intermediate contact.
let first=one*two
let second=flip(two)*one
let contact=eight
check first+second==zero and first*second<zero "a pi flux cancels the shortest free amplitude at the selected detector"
let cubic=first*contact
check cubic==whole(16 trial) and share(cubic,whole(6 trial)*power(eight,3 trial))==fraction(1 trial,192 trial) "one mobile spectator activates the cubic-time joint amplitude"
check power(fraction(1 trial,192 trial),2 trial)==fraction(1 trial,36864 trial) "the first probability coefficient for the contact-assisted coincidence"
# Variance bound for a localized pair; free support |T| <= 2 epsilon and u=20 epsilon.
let u=whole(20 trial)
let band=two
let r2=fraction(7 trial,4 trial)
let coeff=share(r2*(u*u+band*band),power(u*u+flip(band*band),2 trial))
let exposure=one+flip(share(four*coeff,power(one+coeff,2 trial)))
check coeff>zero and coeff<one and exposure>fraction(9821276 trial,10000000 trial) and exposure<fraction(9821277 trial,10000000 trial) "the uniform lower bound on contact exposure exceeds 98.21 percent"
let reservoir=whole(5 trial)
let scale=fraction(3 trial,7 trial)
let mismatch=scale*reservoir+flip(scale*reservoir)
check mismatch==zero "common scaling of hopping and contact gives no Hubbard dimer dissociation amplitude"
let Z=fraction(3 trial,5 trial)
check Z*(one+flip(Z))==fraction(6 trial,25 trial) and one*(one+flip(one))==zero "an incoherent breakup scan loses the entire exact protected line at Z equal one"
# One and two body form factors on harmonic occupations zero, one and two.
let c0=half
let c1=fraction(3 trial,2 trial)
let c2=fraction(5 trial,2 trial)
check two*c1==c0+c2 "a uniform harmonic tide shifts both pair levels equally at first order"
let fourth=two*fraction(15 trial,4 trial)+flip(fraction(3 trial,4 trial))+flip(fraction(39 trial,4 trial))
let sixth=two*fraction(105 trial,8 trial)+flip(fraction(15 trial,8 trial))+flip(fraction(375 trial,8 trial))
check fourth==flip(three) and sixth==flip(fraction(45 trial,2 trial)) "quartic and sextic moments in the recoil doublet"
let b0=flip(fraction(1 trial,3 trial))
let b1=flip(fraction(5 trial,3 trial))
let sextic=fraction(8 trial,45 trial)
let delta0=fourth*b0
let delta1=fourth*b1+sixth*sextic
let slope1=flip(fourth*b1)+flip(fraction(3 trial,2 trial)*sixth*sextic)
check delta0==one and delta1==one and slope1==one and flip(delta0)==flip(one) "equal recoil gaps admit opposite slopes when a separate curvature is applied"
fn corr(z)
return four*z+flip(z*z)
end
check corr(one)==three and corr(four)==zero "relative pair-correlation contrast has a finite-wavevector null at q ell equal two"
let z=one
let formA=two+flip(z)
let formB=two+flip(z)+share(z*z,eight)
check formB+flip(formA)==fraction(1 trial,8 trial) "the common one-body form-factor doublet first differs at fourth order in q"
check fraction(5 trial,2 trial)+half==three and half+fraction(5 trial,2 trial)==three "compensating center-of-mass and relative widths preserve the whole mass moment"
# The five-point derivative has the nonnegative exact kernel 2(1-cos x)^2/3.
let cosx=fraction(3 trial,5 trial)
let cos2=two*cosx*cosx+flip(one)
let derivative=one+flip(share(eight*cosx+flip(two*cos2),whole(6 trial)))
check derivative==fraction(2 trial,3 trial)*power(one+flip(cosx),2 trial) "two pulse durations remove the cubic spectral bias"
let shot=share(share(whole(64 trial),eight)+one,whole(36 trial))*whole(9 trial)
check shot==fraction(9 trial,4 trial) "eight-to-one shot allocation minimizes the upper bound on Ramsey sampling variance"
# Independently digitized resonance controls, in millionths of a kilohertz.
let first_peak=whole(1462247 trial)
let first_u=whole(1332736 trial)
let last_peak=whole(1844482 trial)
let last_u=whole(2085238 trial)
check first_peak+flip(first_u)==whole(129511 trial) and last_peak+flip(last_u)==flip(whole(240756 trial)) "shallow and deep rubidium breakup centers lie on opposite sides of the plotted contact curve"
# Published potassium workbook, equal magnetic field, values in 10^-7 Hz.
let low=whole(1407615409 trial)
let mid=whole(1383045826 trial)
let high=whole(1373784238 trial)
check low+flip(mid)==whole(24569583 trial) and low+flip(high)==whole(33831171 trial) "at the common zero crossing two deeper traps have independently measured smaller gaps"
# Two orthogonal closed paths, each inducing a quarter turn on a Cartesian triplet.
let sites=whole(6 trial)
let mismatch_sq=two
let one_loop=share(two*mismatch_sq,sites)
check one_loop==fraction(2 trial,3 trial) and two*one_loop==fraction(4 trial,3 trial) "two calibrated loops give different widths to transverse and parallel triplets"
let sum_width=zero+one_loop+one_loop
check sum_width==share(eight,sites) "three Cartesian input widths determine the cosine of an isolated right-angle loop"
let min_l=fraction(673 trial,4096 trial)
let min_h=fraction(1347 trial,8192 trial)
check min_h+flip(min_l)==fraction(1 trial,8192 trial) and min_l>fraction(16 trial,100 trial) "the rational matrix bracket resolves a positive minimum over all prepared onsite textures"
# Native primitive loops have tangent-area normals (0,-1,1) and (1,0,0).
let dot_axes=zero*one+flip(one)*zero+one*zero
check dot_axes==zero and zero*zero+flip(one)*flip(one)+one*one==two "the two native geodesic loops rotate about independent axes"
probe.py
"""Check the patterned spin charges, finite packet moments and phase exposure."""
from itertools import product
from math import cos, exp, pi, sin, sqrt
I = [[1,0],[0,1]]
S = ([[0,1],[1,0]], [[0,-1j],[1j,0]], [[1,0],[0,-1]])
Q = ((1,0,1), (1,1,1), (0,1,0))
K = ((1,0,0), (1,1,0), (0,1,1))
def mm(a,b):
return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]
def kron(a,b):
return [[a[i][k]*b[j][l] for k in range(len(a)) for l in range(len(b))]
for i in range(len(a)) for j in range(len(b))]
def scale(x,a):
return [[x*q for q in row] for row in a]
def add(a,b):
return [[x+y for x,y in zip(l,r)] for l,r in zip(a,b)]
def mv(a,v):
return [sum(x*y for x,y in zip(row,v)) for row in a]
def inner(a,b):
return sum(x.conjugate()*y for x,y in zip(a,b))
def adj(a):
return [[v.conjugate() for v in col] for col in zip(*a)]
def maxdiff(a,b):
return max(abs(x-y) for ra,rb in zip(a,b) for x,y in zip(ra,rb))
def signs(n):
return [(-1)**sum(x*y for x,y in zip(n,q)) for q in Q]
def gauge(n):
gx = scale(1j,S[0]) if n[1]%2 else I
gz = scale(1j,S[2]) if (n[0]+n[2])%2 else I
return mm(gx,gz)
def hopping(k):
x,y,z = k
dx,dy,dz = sin(x)*cos(y)*cos(z), sin(y)*cos(z), sin(z)
return [[dz,complex(dx,-dy)],[complex(dx,dy),-dz]]
def test_charges():
for n in product(range(2),repeat=3):
g = gauge(n)
chi = signs(n)
assert chi[0]*chi[1] == chi[2]
for j in range(3):
assert maxdiff(mm(mm(g,S[j]),adj(g)),scale(chi[j],S[j])) == 0
assert tuple((q+k)%2 for q,k in zip(Q[j],K[j])) == (0,0,1)
for delta in product((-1,0,1),repeat=3):
x,y,z=delta
if z==0 or (x!=0 and y==0):
continue
j = 0 if x else (1 if y else 2)
step = tuple(r+d for r,d in zip(n,delta))
link = mm(mm(adj(gauge(step)),S[j]),g)
assert link[0][1] == link[1][0] == 0 and link[0][0] == link[1][1]
loop=mm(mm(S[2],S[1]),mm(S[2],S[1]))
assert maxdiff(loop,scale(-1,I))==0
for k in ((.21,.43,-.35),(1.2,-2.14,.912),(-1.3,-.88,2.77)):
for j in range(3):
shifted=tuple(v+pi*q for v,q in zip(k,Q[j]))
assert maxdiff(hopping(shifted),mm(mm(S[j],hopping(k)),S[j]))<1e-14
class Fiber:
"""Distinguishable-coordinate representation restricted by the symmetric input."""
def __init__(self,total,L=4):
self.L = L
self.grid = list(product(range(L),repeat=3))
self.index = {k:i for i,k in enumerate(self.grid)}
self.total = tuple(t%L for t in total)
self.dim = len(self.grid)
self.blocks = []
for k in self.grid:
p = [2*pi*x/L for x in k]
pp = [2*pi*(t-x)/L for t,x in zip(total,k)]
self.blocks.append(add(kron(hopping(p),I),kron(I,hopping(pp))))
def start(self,a):
v = mv(kron(I,S[a]),[0,1/sqrt(2),-1/sqrt(2),0])
return [[z/sqrt(self.dim) for z in v] for k in self.grid]
def contact_vec(self,state):
return [s/self.dim for s in map(sum,zip(*state))]
def probability(self,state):
v = self.contact_vec(state)
return self.dim*inner(v,v).real
def H(self,state,u):
center = [u*x for x in self.contact_vec(state)]
return [[x+y for x,y in zip(mv(block,v),center)]
for block,v in zip(self.blocks,state)]
def step(self,state,u,dt):
result = [v.copy() for v in state]
term = state
for n in range(1,13):
term = [[(-1j*dt/n)*z for z in row] for row in self.H(term,u)]
result = [[a+b for a,b in zip(l,r)] for l,r in zip(result,term)]
return result
def charge_z(self,state):
shift = [q*self.L//2 for q in Q[2]]
Lz,Rz = kron(S[2],I),kron(I,S[2])
out = []
for i,k in enumerate(self.grid):
ki = self.index[tuple((x-q)%self.L for x,q in zip(k,shift))]
out.append([(a+b)/2 for a,b in zip(mv(Lz,state[ki]),mv(Rz,state[i]))])
return out
def overlap(a,b):
return sum(inner(x,y) for x,y in zip(a,b))
def energy_variance(p):
x,y,z = p
return 1-cos(z)+(1-cos(y)*cos(z))/2+(1-cos(x)*cos(y)*cos(z))/4
def test_finite_packets():
L=4
for a in range(3):
for p in [(0,0,0),(0,1,0),(1,2,-1)]:
k = [p0+L*q//2 for p0,q in zip(p,K[a])]
fiber = Fiber(k,L)
start = fiber.start(a)
action = fiber.H(start,0.)
answer = energy_variance([2*pi*j/L for j in p])
assert abs(overlap(action,action).real-answer)<2e-14
mean_square = sum(energy_variance([2*pi*j/L for j in k])
for k in product(range(L),repeat=3))/L**3
assert abs(mean_square-7/4)<1e-14
bound = 1-((2+sqrt(7)/2)/20)**2
assert .9723<bound<.9725
return bound
def test_phase():
# A finite wavepacket component is deliberately off the protected point, so
# its common spatial state develops a substantial non-contact amplitude.
L,p = 4,(0,1,0)
fibers = [Fiber([L*q//2+n for q,n in zip(K[a],p)],L) for a in (0,1)]
dt,steps,u = .04,20,1.3
def propagate(delta):
a,b = (f.start(j) for j,f in enumerate(fibers))
probabilities = [fibers[0].probability(a)]
for _ in range(steps):
a = fibers[0].step(a,u+delta/2,dt)
b = fibers[1].step(b,u-delta/2,dt)
probabilities.append(fibers[0].probability(a))
# J_z connects total momenta differing by pi e_y. Cross term of the
# normalized equal superposition is the signed staggered magnetization.
coherence = overlap(b,fibers[0].charge_z(a))
assert abs(overlap(a,a).real-1)<1e-12
return coherence,probabilities
flat,probs = propagate(0)
assert abs(flat-1j)<1e-12 and min(probs)<.8
integral = dt/3*(probs[0]+probs[-1]+4*sum(probs[1:-1:2])+2*sum(probs[2:-1:2]))
change = .0002
sample,_ = propagate(change)
opposite,_ = propagate(-change)
slope = (sample.real-opposite.real)/(2*change)
assert abs(slope-integral)<2e-7
return integral,slope,min(probs)
def test_dissociation():
# Evaluate the one-dimensional contact resolvent discontinuity using
# E=W cos(theta), avoiding both endpoint singularities.
for u,W in ((3.,4.),(-2.,1.5),(1.,2.)):
Eb = sqrt(u*u+W*W)
Z = abs(u)/Eb
n=2000
weights,energies = [],[]
for j in range(n):
angle = pi*(j+.5)/n
s = (W*sin(angle))**2
weights.append(s/((u*u+s)*n))
energies.append(W*cos(angle))
assert abs(sum(weights)-(1-Z))<2e-14
assert abs(sum(g*(Eb-E) for E,g in zip(energies,weights))/sum(weights)-Eb)<3e-14
alpha,du = .13,-.27
# Infinite-chain exact normalized bound state, truncated only after
# the endpoints are exponentially small. Direct variation and projection.
U = abs(u)
ratio = (U-Eb)/W * (1 if u>0 else -1)
bound=[sqrt(Z)*ratio**abs(j) for j in range(-200,201)]
bound_E = Eb*(1 if u>0 else -1)
out=[]
for i,z in enumerate(bound):
hop = -W/2*((bound[i-1] if i else 0)+(bound[i+1] if i+1<len(bound) else 0))
contact=z if i==200 else 0
assert abs(hop+u*contact-bound_E*z)<1e-14
out.append(alpha*hop+du*contact)
assert abs(inner(out,out)-abs(inner(bound,out))**2-(du-alpha*u)**2*Z*(1-Z))<1e-14
def test_isolated_weight():
B,u = 2.,20.
def c_of(r2):
return r2*(u*u+B*B)/(u*u-B*B)**2
def escape(c):
return 4*c/(1+c)**2
for p in [(0,0,0),(0,1,0),(0,0,2),(1,1,1)]:
a,L = 0,4
f = Fiber([L*q//2+n for q,n in zip(K[a],p)],L)
v = f.start(a)
term = v
moments=[]
for n in range(25):
moment=overlap(v,term)
assert abs(moment.imag)<1e-12*2**n
moments.append(moment.real)
if n%2:
assert abs(moment)<1e-13*2**n
term=f.H(term,0.)
# Neumann expansion at E>=20 has geometric remainder <=(1/10)^25/18.
def resolvent(E):
return sum(mu/E**(j+1) for j,mu in enumerate(moments))
lo,hi=u,u+B
for _ in range(55):
mid=(lo+hi)/2
if u*resolvent(mid)>1:lo=mid
else:hi=mid
E=(lo+hi)/2
norm=sum((j+1)*mu/E**(j+2) for j,mu in enumerate(moments))
Z=1/(u*u*norm)
assert abs(u*resolvent(E)-1)<1e-13
assert 1/Z-1<=c_of(moments[2])+1e-13
assert 4*Z*(1-Z)<=escape(c_of(moments[2]))+1e-13
answer=1-escape(c_of(7/4))
assert .98212<answer<.98214
return answer
def test_one_particle_rejection():
# A two-site, two-spin symmetric spatial pair with a zero-dipole triplet.
# Choose a common pulse with genuinely spin-dependent nonlocal matrix elements.
from random import Random
rng=Random(139)
random=[[complex(rng.uniform(-1,1),rng.uniform(-1,1)) for _ in range(4)] for _ in range(4)]
b=scale(.5,add(random,adj(random)))
id4=kron(I,I)
drive=add(kron(b,id4),kron(id4,b))
j=scale(.5,kron(I,S[2]))
total_j=add(kron(j,id4),kron(id4,j))
mot=kron([[.1,.5],[.5,-.4]],I)
H0=add(kron(mot,id4),kron(id4,mot))
for k in range(16):
if (k//4)//2==(k%4)//2:
H0[k][k]+=1.7
cart=[mv(kron(I,s),[0,1/sqrt(2),-1/sqrt(2),0]) for s in S]
spin=[(a+c)/sqrt(2) for a,c in zip(cart[0],cart[1])]
spatial=[[1,complex(.2,.3)],[complex(.2,.3),-.4]]
norm=sqrt(sum(abs(z)**2 for row in spatial for z in row))
start=[spatial[i//2][j//2]*spin[2*(i%2)+j%2]/norm for i,j in product(range(4),repeat=2)]
def readout(eta):
H=add(H0,scale(eta,drive))
out=start.copy()
term=start.copy()
for k in range(1,45):
term=[-.7j*v/k for v in mv(H,term)]
out=[x+y for x,y in zip(out,term)]
assert abs(inner(out,out)-1)<1e-13
return inner(out,mv(total_j,out)).real
eta=.001
flat,plus,minus=readout(0),readout(eta),readout(-eta)
first=(plus-minus)/(2*eta)
curvature=(plus+minus-2*flat)/eta**2
# Second-order contamination is deliberately nonzero for the chosen drive.
assert abs(flat)<1e-14 and abs(first)<1e-6 and abs(curvature)>.005
return first,curvature
if __name__ == "__main__":
test_charges()
bound=test_finite_packets()
gate,phase,minimum=test_phase()
test_dissociation()
print("Three exact spin charges, scalar hopping links and pi-flux loop: passed")
print("Finite packet variance and scalar Hubbard oscillator strengths: passed")
print(f"Flat staggered-spin visibility 1, minimum contact {minimum:.7f}")
print(f"Weak phase slope {phase:.9f}, integrated flat coincidence {gate:.9f} in a 0.8 exposure")
print(f"Uniform localized-pair exposure bound for |u|/epsilon=20: {bound:.8f}")
print(f"Rank-one bound from the even spectral measure: {test_isolated_weight():.8f}")
slope2,curv = test_one_particle_rejection()
print(f"Common one-body drive test: finite-difference slope {slope2:.3g}, second derivative {curv:.6f}")
flux.py
"""Exact signed graph and two-particle Taylor moments for the native hopping."""
from collections import defaultdict
from fractions import Fraction as F
from itertools import product
from math import factorial, sqrt
I=((1,0),(0,1))
X=((0,1),(1,0))
Y=((0,-1j),(1j,0))
Z=((1,0),(0,-1))
def mm(A,B):return tuple(tuple(sum(x*y for x,y in zip(row,col)) for col in zip(*B)) for row in A)
def scale(s,A):return tuple(tuple(s*x for x in row) for row in A)
def adj(A):return tuple(tuple(x.conjugate() for x in col) for col in zip(*A))
def gauge(pos):
x,y,z=pos
return mm(scale(1j,X) if y%2 else I,scale(1j,Z) if (x+z)%2 else I)
def graph(L):
sites=list(product(range(L),repeat=3))
lookup={p:i for i,p in enumerate(sites)}
bonds=[]
for sx,sy,sz in product((1,-1),repeat=3):bonds.append(((sx,sy,sz),scale(1j*sx,X)))
for sy,sz in product((1,-1),repeat=2):bonds.append(((0,sy,sz),scale(2j*sy,Y)))
for sz in (1,-1):bonds.append(((0,0,sz),scale(4j*sz,Z)))
links=[]
for p in sites:
out={}
for d,mat in bonds:
target=tuple((a+b)%L for a,b in zip(p,d))
turn=mm(adj(gauge(target)),mm(mat,gauge(p)))
weight=int(turn[0][0].real)
assert turn==scale(weight,I) and abs(weight) in (1,2,4)
out[lookup[target]]=weight
links.append(out)
assert all(links[y][x]==v for x,row in enumerate(links) for y,v in row.items())
return sites,lookup,links
def flux_test():
sites,idx,links=graph(6)
zero=idx[(0,0,0)]
moves=[(1,1,1),(0,1,1),(0,0,1)]
for i,b in enumerate(moves):
for d in moves[:i]:
along_b,along_d=idx[b],idx[d]
both=idx[tuple(u+v for u,v in zip(b,d))]
assert links[zero][along_b]*links[along_b][both]==-links[zero][along_d]*links[along_d][both]
norm=lambda p: tuple(x%2 for x in p)
sectors={(0,0,0),(1,1,1),(0,1,1),(0,0,1)}
state={zero:1}
for t in range(1,13):
new=defaultdict(int)
for i,v in state.items():
for j,h in links[i].items():new[j]+=h*v
state={i:v for i,v in new.items() if v}
assert all(norm(sites[i]) in sectors for i in state)
if t%2==0:assert all(norm(sites[i])==(0,0,0) for i in state)
return sites,idx,links
def two_particle_moments(idx,links,N=20):
# Hidden spin distinguishes the two components. H is stored in integer units epsilon/8.
V=len(links)
p=idx[(0,0,0)];b=idx[(1,1,1)];d=idx[(1,2,2)]
def step(state):
new=defaultdict(int)
for i,v in state.items():
x,y=divmod(i,V)
for nx,h in links[x].items():new[nx*V+y]+=h*v
for ny,h in links[y].items():new[x*V+ny]+=h*v
if x==y:new[i]+=8*v
return {i:v for i,v in new.items() if v}
def overlap(a,b):
if len(a)>len(b):a,b=b,a
return sum(v*b.get(i,0) for i,v in a.items())
initial,final={p*V+b:1},{d*V+b:1}
m=[overlap(final,initial)]
for _ in range((N+1)//2):
initial=step(initial)
m.append(overlap(final,initial))
final=step(final)
m.append(overlap(final,initial))
assert m[:3]==[0,0,0] and abs(m[3])==16
return m[:N+1]
def bounds(m,t):
# Entire tail bounded in norm by the exponential tail, ||H/epsilon||<=3.
real,imag=F(0),F(0)
for n,value in enumerate(m):
a=F(value)*F(t,8)**n/factorial(n)
if n%4==0:real+=a
if n%4==1:imag-=a
if n%4==2:real-=a
if n%4==3:imag+=a
begin=len(m)
tail=F(3*t)**begin/factorial(begin)/(1-F(3*t,begin+1))
# Integer-safe check on each conservative probability range printed below.
amp=sqrt(float(real*real+imag*imag))
return max(0,amp-float(tail))**2,(amp+float(tail))**2
def main():
sites,idx,links=flux_test()
m=two_particle_moments(idx,links)
print("Three pi-flux plaquettes and four excluded parity classes verified.")
print("Scaled contact-assisted matrix element of H cubed:",m[3])
for t in (1,2):
lo,hi=bounds(m,t)
assert lo>0 and hi-lo<.001
print(f"tau={t}, one specified joint output probability in [{lo:.10g}, {hi:.10g}]")
print("First integer matrix moments:",m[:8])
if __name__=="__main__":
main()
echo.py
"""Two-time spectral centroid bound and an exact nonuniqueness witness."""
from cmath import exp
from math import cos, pi, sin, sqrt
def correlation(x,w,t):
return sum(a*exp(-1j*e*t) for e,a in zip(x,w))/sum(w)
def main():
a=(sqrt(3)-1)/2
energies=[pi/6,-pi/3,pi/2]
weights=[1.,1.,a]
reflected=[-x for x in energies]
for t in (1,2):
assert abs(correlation(energies,weights,t)-correlation(reflected,weights,t))<5e-16
gap=2*sum(x*w for x,w in zip(energies,weights))/sum(weights)
assert .043<gap<.045
for i in range(-400,401):
x=i/60
f=(8*sin(x)-sin(2*x))/6
assert abs(f-x)<=abs(x)**5/30+2e-15
assert abs(1-(8*cos(x)-2*cos(2*x))/6-2*(1-cos(x))**2/3)<1e-14
values=[-1.6,-.35,.8,1.9]
prob=[.14,.28,.48,.10]
mean=sum(x*w for x,w in zip(values,prob))
for t in [.1,.2,.4]:
answer=(-8*correlation(values,prob,t).imag+correlation(values,prob,2*t).imag)/(6*t)
assert abs(answer-mean)<=max(map(abs,values))**5*t**4/30
print("Indistinguishable correlations at two times, centroid difference:",gap)
print("Bounded estimator, pointwise derivative and finite-distribution checks passed.")
if __name__=="__main__":
main()
curvature.py
"""Pair density, finite-q correlations and fixed-trap curvature calibration."""
from math import exp, pi, sqrt
def anharmonic_gap(B, C, g, cells):
# Energies in hbar*omega, length in the zero-field oscillator length.
# Dirichlet walls at ±7 are identical in both calibrated wells.
boundary = 7.
dx = 2*boundary/cells
hop = -.5/dx**2
sites = [-boundary+j*dx for j in range(1,cells)]
diagonal = [-2*hop+.5*(1+g)*y*y+B*y**4+C*y**6 for y in sites]
def count(energy):
pivot, below = diagonal[0]-energy,0
below += pivot < 0
for v in diagonal[1:]:
if abs(pivot)<1e-20:
pivot = -1e-20
pivot = v-energy-hop*hop/pivot
below += pivot<0
return below
def eigen(n):
low, high = -.5,4.
assert count(low)==0 and count(high)>n
for _ in range(47):
mid = (low+high)/2
if count(mid)>n:
high=mid
else:
low=mid
return (low+high)/2
return 2*eigen(1)-eigen(0)-eigen(2)
def matched_well(C,cells,delta=.003):
lo,hi = -.018,.002
# Stay on the central-well branch for C=0 (no remote minima inside the walls).
if C==0:lo=-.003
assert anharmonic_gap(lo,C,0,cells)>delta>anharmonic_gap(hi,C,0,cells)
for _ in range(30):
mid = (lo+hi)/2
if anharmonic_gap(mid,C,0,cells)>delta:lo=mid
else:hi=mid
B=(lo+hi)/2
step=.001
gap=anharmonic_gap(B,C,0,cells)
slope=(anharmonic_gap(B,C,step,cells)-anharmonic_gap(B,C,-step,cells))/(2*step)
return B,gap,slope
def moments():
# Dimensionless powers of x/ell obtained directly with oscillator ladder operators.
def moment(n,power):
vector={n:1.}
for _ in range(power):
out={}
for level,c in vector.items():
out[level+1]=out.get(level+1,0.)+c*sqrt((level+1)/2)
if level:
out[level-1]=out.get(level-1,0.)+c*sqrt(level/2)
vector=out
return vector.get(n,0.)
for p,want in [(2,0),(4,-3),(6,-45/2)]:
got=2*moment(1,p)-moment(0,p)-moment(2,p)
assert abs(got-want)<1e-12
# Normalized COM and relative pair states in the single-particle oscillator basis.
A={(1,1):1.}
B={(2,0):1/sqrt(2),(0,2):1/sqrt(2)}
states=[{(i,j):(A.get((i,j),0)+sign*B.get((i,j),0))/sqrt(2)
for i in range(3) for j in range(3)} for sign in (-1,1)]
def reduced(s):
return [sum(s[i,j]*s[k,j] for j in range(3)) for i in range(3) for k in range(3)]
assert reduced(states[0])==reduced(states[1])
# Relative-coordinate intensity and one-body diagonal/off-diagonal responses.
def diff_correlation(z):return 2*exp(-z/2)*(2*z-z*z/2)
assert diff_correlation(4)==0 and diff_correlation(1)>1.81
z=1.
F_B=exp(-z/4)*(2-z+z*z/8)
F_A=exp(-z/4)*(2-z)
assert abs(F_B-F_A-exp(-z/4)*z*z/8)<1e-15
def main():
moments()
delta=.003
results=[]
for cells in (420,840):
pair=[matched_well(C,cells,delta) for C in (0.,8*delta/45)]
assert all(abs(gap-delta)<2e-9 for B,gap,slope in pair)
assert pair[0][2]<-.002 and pair[1][2]>.001
results.append(pair)
# The leading central-difference grid error is quadratic in the spacing.
extrap=[(4*results[1][i][2]-results[0][i][2])/3 for i in range(2)]
assert max(abs(extrap[i]-results[1][i][2]) for i in range(2))<.00015
fz,fr,G=25090.,140.76,205e-9
shift=-fr*G/(2*pi*fz)**2
assert -1.17e-15<shift<-1.15e-15
print("Both fitted gaps on 840-cell grid:",[round(x[1],10) for x in results[1]])
print("Fitted quartic coefficients:",[round(x[0],8) for x in results[1]])
print("Curvature slopes, 420 / 840 cells:",[[round(x[2],8) for x in p] for p in results])
print("Leading ideal recoil-clock change at an illustrative 205 E:",shift,"Hz")
if __name__=="__main__":
main()
winkler.py
"""Read the authors' EPS plotting coordinates and replay their spectroscopic controls."""
import argparse
import csv
from io import BytesIO, StringIO
from hashlib import sha256
from pathlib import Path
from statistics import mean
from math import cos, exp, log, pi, sqrt
from tarfile import open as open_tar
from urllib.request import urlopen
HERE = Path(__file__).resolve().parent
DATA = HERE / 'winkler-figure4.csv'
SOURCE = 'https://arxiv.org/src/cond-mat/0605196v1'
SOURCE_SHA = '3e17a2e477200480360e08a7a8dfe51a6cd5f14af40eeda45dce6c223a36802f'
EPS_SHA = 'ecc88c55d4e363f64a6a0ce3e104881680ee11f3ac79e02c3d28b0563b1e2e19'
NAMES = ['series', 'x', 'y', 'lower_kHz', 'upper_kHz', 'published_U_over_h_kHz']
def checked(data, digest):
if sha256(data).hexdigest() != digest:
raise ValueError('Source file checksum mismatch')
return data
def interpolate(xs, x):
for (x1,y1),(x2,y2) in zip(xs,xs[1:]):
if x1 <= x <= x2:
return y1+(y2-y1)*(x-x1)/(x2-x1)
raise ValueError('Coordinate outside the interpolated range')
def extract(eps):
page = checked(eps, EPS_SHA).decode('latin1').split('%%EndPageSetup',1)[1]
objects = page.split('@rax')[1:]
def vertices(i):
return [(float(t[-3]),float(t[-2])) for line in objects[i].splitlines()
if (t:=line.split()) and t[-1] in ('m','C','l','L','c')]
def circle(i):
assert '0.00 0.99 0.95 0.00 k' in objects[i] and objects[i].count(' C')==4
x1,y1,x2,y2 = map(float,next(l for l in objects[i].splitlines()
if l.endswith(' @E')).split()[:4])
return (x1+x2)/2,(y1+y2)/2
def axis(ticks, idx, labels):
xs = [vertices(i)[0][idx] for i in ticks]
xavg,yavg = mean(xs),mean(labels)
slope = sum((x-xavg)*(y-yavg) for x,y in zip(xs,labels))/sum((x-xavg)**2 for x in xs)
f = lambda x: yavg+slope*(x-xavg)
assert max(abs(f(x)-y) for x,y in zip(xs,labels)) < .007
return f
ax=axis((69,71,73,75),0,(0,1,2,3))
ay=axis((77,79,82,85,88,91),1,(0,.2,.4,.6,.8,1))
bx=axis((3,5,7,9),0,(0,5,10,15))
by=axis((11,13,16,18,21,23),1,(0,.5,1,1.5,2,2.5))
rows=[]
def add(series,*numbers):
rows.append([series]+[f'{x:.6f}' for x in numbers]+['']*(5-len(numbers)))
for i in range(94,112):
x,y=circle(i)
add('survival',ax(x),ay(y))
drawn=[(ax(x),ay(y)) for x,y in vertices(112)]
_,center,sigma,_,_=gaussian_fit(drawn)
assert abs(center-1.59287)<.00002
assert abs(2*sqrt(2*log(2))*sigma-1.39127)<.00002
curve=sorted((bx(x),by(y)) for x,y in vertices(38))
bars=vertices(27)
assert len(bars)==60
errorbars=[]
for i in range(0,len(bars),6):
x,y=bars[i+4]
ex,ey=bars[i+5]
assert abs(bx(x)-bx(ex))<.001
errorbars.append((bx(x),min(by(y),by(ey)),max(by(y),by(ey))))
for x,y in sorted(circle(i) for i in range(40,50)):
depth,freq=bx(x),by(y)
xb,lo,hi=min(errorbars,key=lambda b:abs(b[0]-depth))
assert abs(xb-depth)<.025 and abs(freq-(lo+hi)/2)<.004
add('resonance',depth,freq,lo,hi,interpolate(curve,depth))
f=StringIO()
w=csv.writer(f,lineterminator='\n');w.writerow(NAMES);w.writerows(rows)
return f.getvalue().encode()
def gaussian_fit(points):
"""Least squares over center and log width; baseline and amplitude solved linearly."""
x,y=zip(*points)
def fit(mu,sigma):
p=[exp(-.5*((t-mu)/sigma)**2) for t in x]
p0,y0=mean(p),mean(y)
amp=sum((v-p0)*(d-y0) for v,d in zip(p,y))/sum((v-p0)**2 for v in p)
b=y0-amp*p0
residual=sum((b+amp*z-w)**2 for z,w in zip(p,y))
return residual,mu,sigma,b,amp
mu,ls,step_mu,step_ls=1.6,log(.6),.2,.2
for _ in range(9):
r=min(fit(mu+i*step_mu,exp(ls+j*step_ls)) for i in range(-3,4) for j in range(-3,4))
_,mu,sigma,_,_=r;ls=log(sigma);step_mu/=3;step_ls/=3
return r
def energy(q,depth,cut=9):
"""Lowest eigenvalue of the sinusoidal-lattice plane-wave tridiagonal (recoil units)."""
diag=[(q+2*i)**2+depth/2 for i in range(-cut,cut+1)]
off2=(depth/4)**2
lo,hi=0.,min(diag)+1e-8
for _ in range(54):
mid=(lo+hi)/2
d=diag[0]-mid
count=int(d<0)
for t in diag[1:]:
if abs(d)<1e-20:d=-1e-20
d=t-mid-off2/d
count+=int(d<0)
if count:hi=mid
else:lo=mid
return (lo+hi)/2
def wannier_overlap(depth, mesh=21, cut=6):
"""Integral |w|^4 in the dimensionless coordinate kL*x; positive Bloch gauge."""
# Odd symmetric q mesh, localized at the potential minimum. Fourier convolution
# integrates the quartic exactly on the finite periodic mesh.
coeff=[0.0]*((2*cut+1)*mesh)
off=-depth/4
for j in range(-(mesh//2),mesh//2+1):
q=2*j/mesh
e=energy(q,depth,cut)
diag=[(q+2*n)**2+depth/2-e+.02 for n in range(-cut,cut+1)]
dl=diag[:]
for k in range(1,len(dl)):
dl[k]-=off**2/dl[k-1]
v=[float(n==cut) for n in range(len(dl))]
for _ in range(7):
for k in range(1,len(dl)):
v[k]-=off*v[k-1]/dl[k-1]
v[-1]/=dl[-1]
for k in range(len(dl)-2,-1,-1):
v[k]=(v[k]-off*v[k+1])/dl[k]
norm=sqrt(sum(x*x for x in v));v=[x/norm for x in v]
resid=max(abs((diag[k]-.02)*x+off*((v[k-1] if k else 0)+(v[k+1] if k+1<len(v) else 0))) for k,x in enumerate(v))
assert resid<2e-10
for n,x in enumerate(v):
coeff[n*mesh+j+mesh//2]=x/(mesh*sqrt(pi))
assert abs(mesh*pi*sum(x*x for x in coeff)-1)<1e-12
conv=[0.]*(2*len(coeff)-1)
for i,x in enumerate(coeff):
for j,y in enumerate(coeff):
conv[i+j]+=x*y
return mesh*pi*sum(x*x for x in conv)
def compare(rows):
dip=[(float(r['x']),float(r['y'])) for r in rows if r['series']=='survival']
_,center,sigma,b,amp=gaussian_fit(dip)
h=6.62607015e-34
m=86.9091805291*1.66053906892e-27
a=415.22e-9
recoil_kHz=h/(8*m*a*a)/1000
data=[]
for r in rows:
if r['series']!='resonance':continue
depth,obs,lo,hi,u=map(float,[r[k] for k in NAMES[1:]])
j=recoil_kHz*(energy(1,depth)-energy(0,depth))/4
def center_model(n):
return mean(sqrt(u*u+(4*j*cos(pi*(i+.5)/(2*n)))**2) for i in range(n))
model=center_model(64)
assert abs(model-center_model(128))<1e-12
data.append((depth,obs,lo,hi,u,j,model))
assert len(dip)==18 and len(data)==10
rms=lambda vals:sqrt(mean(v*v for v in vals))
print(f'Dip fit from 18 points: center {center:.5f} kHz, FWHM {2*sqrt(2*log(2))*sigma:.5f} kHz, survival floor {b+amp:.4f}.')
print('depth observed lower95 upper95 U/h J/h uniform-K (frequencies kHz)')
for row in data:print(' '.join(f'{z:8.4f}' for z in row))
for nm,ds in [('all',data),('shallow',data[:4]),('deep',data[-4:])]:
er_u=rms([z[1]-z[4] for z in ds]);er_k=rms([z[1]-z[6] for z in ds])
print(nm, 'RMS vs U/h and uniform-K gap (kHz):',f'{er_u:.6f}, {er_k:.6f}')
comparisons = scale_controls(data,recoil_kHz,a)
assert abs(center-1.59229)<.00005 and abs(2*sqrt(2*log(2))*sigma-1.39462)<.0001
assert rms([r[1]-r[4] for r in data])>.12
return data,comparisons
def midpoint(u,j):
return mean(sqrt(u*u+(4*j*cos(pi*(k+.5)/128))**2) for k in range(64))
def scale_controls(data,recoil_kHz,a):
# as=100 Bohr, 87Rb. Bare single-band contact, no fit to spectral positions.
prefactor=8*pi*(pi/a)*(100*5.29177210544e-11)*recoil_kHz
alpha=sum(r[4]*r[1] for r in data[-3:])/sum(r[4]**2 for r in data[-3:])
assert abs(alpha-.9100268)<.00001
print(f'Three-deepest-point contact scale: {alpha:.6f}')
reference=(.101021,.061742),(.177843,.193349),(.146552,.051468)
overlaps=[wannier_overlap(r[0]) for r in data]
assert abs(overlaps[0]-wannier_overlap(data[0][0],31,8))<1e-6
assert abs(wannier_overlap(35)-wannier_overlap(35,31,8))<1e-6
outputs={}
for index,key in enumerate(('30 Er transverse','35 Er transverse','deep-calibrated')):
use=data if index<2 else data[:-3]
transverse=wannier_overlap(30 if index==0 else 35) if index<2 else 0
predictions=[]
for i,row in enumerate(use):
u=(prefactor*transverse**2*overlaps[i] if index<2 else alpha*row[4])
predictions.append((row[0],row[1],u,midpoint(u,row[5])))
errors=tuple(sqrt(mean((p[1]-p[j])**2 for p in predictions)) for j in (2,3))
assert all(abs(p-q)<.000005 for p,q in zip(errors,reference[index]))
print(key, f'RMS against U/h and uniform-K gap (kHz): {errors[0]:.6f}, {errors[1]:.6f}')
outputs[key]=predictions
return outputs
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fetch',action='store_true',help='check original arXiv source and extract Fig. 4')
args=parser.parse_args()
if args.fetch:
with urlopen(SOURCE,timeout=60) as f:raw=checked(f.read(),SOURCE_SHA)
with open_tar(fileobj=BytesIO(raw),mode='r:gz') as f:
eps=f.extractfile('figure4.eps').read()
if extract(eps)!=DATA.read_bytes():raise ValueError('Extracted table changed')
with DATA.open(newline='') as f:compare(list(csv.DictReader(f)))
if __name__=='__main__':
main()
calibration.py
"""Refit Hartke et al. source data and test a fixed-period optical-well calibration."""
import argparse
import csv
from hashlib import sha256
from io import BytesIO, StringIO
from math import cos, pi, sin, sqrt
from pathlib import Path
from statistics import mean
from urllib.request import urlopen
import xml.etree.ElementTree as ET
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parent
DATA = ROOT / "pair_clock.csv"
MEDIA = ("https://media.springernature.com/full/springer-static/esm/"
"art%3A10.1038%2Fs41586-021-04205-8/MediaObjects/41586_2021_4205_MOESM")
HASHES = [
"ed84ec255ab0568d013bc608fcb3671bf755e867d17586a08736e909dfc73c44",
"5fd8adb4c55b806a3ab6c2a7d828624c9b37826560b4485653d46483a2bf58e0",
]
TAG = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
SETS = [
("drive_Hz", 0, 3), ("slow_ms", 1, 1), ("fast_us", 1, 3),
("25.09kHz", 1, 7), ("38.50kHz", 1, 9), ("51.80kHz", 1, 11),
]
def extract(inputs):
output = StringIO()
writer = csv.writer(output, lineterminator="\n")
writer.writerow(["series","x","y","spread","drive_mG"])
for label, book, sheet in SETS:
with ZipFile(BytesIO(inputs[book])) as archive:
root = ET.fromstring(archive.read(f"xl/worksheets/sheet{sheet}.xml"))
for row in root.iter(TAG+"row"):
# Column A is the source dataframe index. Columns B-E contain data.
cells = {c.get("r").rstrip("0123456789"): c.findtext(TAG+"v")
for c in row.findall(TAG+"c") if c.get("t") != "s"}
if cells.get("B") is not None:
writer.writerow([label, cells["B"], cells["C"], cells["D"], cells.get("E","")])
return output.getvalue().encode()
def fetch():
inputs = []
for i, expected in enumerate(HASHES,1):
with urlopen(f"{MEDIA}{i}_ESM.xlsx",timeout=40) as response:
data = response.read()
if sha256(data).hexdigest() != expected:
raise ValueError(f"Source Data Fig. {i+1} fingerprint changed")
inputs.append(data)
# Independently identify the frequency of the *plotted fit curve*. Its densely
# sampled points differ from the 33 observations passed to our estimator.
with ZipFile(BytesIO(inputs[1])) as archive:
root = ET.fromstring(archive.read("xl/worksheets/sheet4.xml"))
curve = []
for row in root.iter(TAG+"row"):
vals = {c.get("r").rstrip("0123456789"): c.findtext(TAG+"v")
for c in row.findall(TAG+"c") if c.get("t") != "s"}
if vals.get("B") is not None:
curve.append((float(vals["B"]),float(vals["C"])))
peaks=[t for i,(t,y) in enumerate(curve[1:-1],1)
if curve[i-1][1] < y > curve[i+1][1]]
rate=(len(peaks)-1)*1e6/(peaks[-1]-peaks[0])
assert len(peaks)==4 and 35950<rate<36050
print(f"Publisher fast-fit curve: {rate:.2f} Hz from peak spacings")
if extract(inputs) != DATA.read_bytes():
raise ValueError("Offline data do not reproduce the source workbook cells")
def golden(objective, low, high, loops=32):
ratio = (sqrt(5)-1)/2
left, right = high-ratio*(high-low), low+ratio*(high-low)
lv, rv = objective(left), objective(right)
for _ in range(loops):
if lv < rv:
high, right, rv = right, left, lv
left = high-ratio*(high-low)
lv = objective(left)
else:
low, left, lv = left, right, rv
right = low+ratio*(high-low)
rv = objective(right)
return (low+high)/2
def fit_fringe(data, slow):
# Compare like phases in all three windows, allowing offset and contrast to drift.
windows = {}
for x,y,_ in data:
t = x * (1e-3 if slow else 1e-6)
windows.setdefault(int(t>0.1)+int(t>0.3),[]).append((t,y))
def profile(frequency):
stats = []
for window in windows.values():
y0 = mean(y for _,y in window)
c = [cos(2*pi*frequency*t) for t,_ in window]
s = [sin(2*pi*frequency*t) for t,_ in window]
c0,s0=mean(c),mean(s)
c=[v-c0 for v in c];s=[v-s0 for v in s]
y=[v-y0 for _,v in window]
stats.append((sum(v*v for v in y),sum(v*v for v in c),sum(v*v for v in s),
sum(a*b for a,b in zip(s,c)),sum(a*b for a,b in zip(y,c)),
sum(a*b for a,b in zip(y,s))))
def phase_error(phase):
co,si=cos(phase),sin(phase)
score=0.
for yy,cc,ss,cs,yc,ys in stats:
xy=yc*co+ys*si
xx=cc*co*co+ss*si*si+2*cs*co*si
score+=yy-max(0.,xy)**2/max(1e-16,xx)
return score
d=2*pi/24
seed=min((j*d for j in range(24)),key=phase_error)
return phase_error(golden(phase_error, seed-d, seed+d,18))
low,step,count = (115.,.12,418) if slow else (2000.,100.,980)
guesses=[low+i*step for i in range(count)]
seed=min(guesses,key=profile)
frequency=golden(profile,seed-step,seed+step)
return frequency,sqrt(profile(frequency)/len(data))
def recoil_gap(r, axial_hz, cutoff=60):
# q=0 Fourier modes exp(2 i n y) for -d²/dy² + V sin²(y).
# Implied V uses measured harmonic frequency 2 r sqrt(V). All energies in ER.
depth=(axial_hz/(2*r))**2
diagonal=[4*n*n+depth/2 for n in range(-cutoff,cutoff+1)]
off2=(depth/4)**2
def sturm_count(x):
pivot=diagonal[0]-x;count=int(pivot<0)
for val in diagonal[1:]:
if abs(pivot)<1e-18:pivot=-1e-18
pivot=val-x-off2/pivot
count+=int(pivot<0)
return count
def level(k):
a,b=0.,(2*k+3)*sqrt(depth)
for _ in range(52):
mid=(a+b)/2
if sturm_count(mid)<=k:a=mid
else:b=mid
return (a+b)/2
e0,e1,e2=[level(k) for k in range(3)]
return r*(2*e1-e2-e0)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("--fetch",action="store_true",help="verify the original two source workbooks")
if parser.parse_args().fetch:fetch()
rows={}
with DATA.open() as f:
for record in csv.DictReader(f):
rows.setdefault(record["series"],[]).append(tuple(float(record[k]) for k in ("x","y","spread")))
assert [len(rows[t]) for t,_,_ in SETS]==[6,58,33,8,5,5]
for label,slow in [("slow_ms",True),("fast_us",False)]:
freq,rmse=fit_fringe(rows[label],slow)
print(f"{label} common-phase fit: {freq:.6f} Hz, RMS {rmse:.3f} bright sites")
assert (140.5<freq<141.0) if slow else (34e3<freq<38e3)
drive=rows["drive_Hz"]
slope=sum(x*y for x,y,_ in drive)/sum(x*x for x,_,_ in drive)
ratios=[y/x for x,y,_ in drive]
print(f"Drive slope through origin {slope:.6f}; measured/predicted range {min(ratios):.4f} to {max(ratios):.4f}")
assert .93<slope<.96
zero=209.0937721
gaps=[next((y,err) for x,y,err in rows[key] if abs(x-zero)<1e-6)
for key in ["25.09kHz","38.50kHz","51.80kHz"]]
axial=[25090,38500,51800]
bare=golden(lambda r:(recoil_gap(r,axial[0])-gaps[0][0])**2,130,145)
predicted=[recoil_gap(bare,v) for v in axial]
assert max(abs(recoil_gap(bare,v,76)-p) for v,p in zip(axial,predicted))<1e-7
predicted_pert=[bare*(1+9*bare/(4*v)) for v in axial]
assert max(abs(a-b) for a,b in zip(predicted,predicted_pert))<.08
assert abs(predicted[0]-gaps[0][0])<.0001 and predicted[-1]-gaps[-1][0]>2.4
for v,(y,s),p in zip(axial,gaps,predicted):
print(f"Axial {v/1000:g} kHz: measured {y:.5f} +/- {s:.5f} Hz, calibrated single-sinusoid {p:.5f} Hz")
print(f"Single-depth inferred recoil frequency {bare:.6f} Hz.")
if __name__=="__main__":
main()
transport.py
"""Onsite pairs and spin transport on a bipartite graph, with exact rank checks."""
from fractions import Fraction as F
from math import sqrt,pi,sin,cos
from random import Random
ID = [[1,0],[0,1]]
PAULI = ([[0,1],[1,0]],[[0,-1j],[1j,0]],[[1,0],[0,-1]])
ROOT = 1
V = 6
TREE = [(0,1),(1,2),(0,3),(1,4),(2,5)]
CLOSE = [(3,4),(4,5)]
def mm(a,b):
return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]
def T(a):
return [list(row) for row in zip(*a)]
def adj(a):
return [[z.conjugate() for z in col] for col in zip(*a)]
def dot(a,b):
return sum(x.conjugate()*y for l,r in zip(a,b) for x,y in zip(l,r))
def plus(a,b):
return [[x+y for x,y in zip(l,r)] for l,r in zip(a,b)]
def times(k,a):
return [[k*x for x in l] for l in a]
def turn(axis,angle):
return plus(times(cos(angle/2),ID),times(-1j*sin(angle/2),PAULI[axis]))
def congruence(U,x):
return mm(mm(U,x),T(U))
# Normalized Cartesian spin-one tensors (I x sigma_a)|singlet>.
singlet = [[0,1/sqrt(2)],[-1/sqrt(2),0]]
BASIS = [mm(singlet,T(s)) for s in PAULI]
def projected(U):
vals=[[dot(a,congruence(U,b)) for b in BASIS] for a in BASIS]
assert max(abs(x.imag) for r in vals for x in r)<1e-14
return [[x.real for x in r] for r in vals]
def edge_list(which):
X,Z=turn(0,pi/2),turn(2,pi/2)
if which==3:
closes=(times(-1,ID),ID)
elif which==1:
closes=(Z,times(-1,Z))
elif which==0:
closes=(Z,X)
else:
raise ValueError(which)
return [(v,w,ID) for v,w in TREE]+[(v,w,U) for (v,w),U in zip(CLOSE,closes)]
def sign(n):
return (-1)**(n%3+n//3)
def ferr(rows):
return max(abs(v-round(v)) for row in rows for v in row)
def kinetic_second_moment(links):
# This is the exact Gram matrix of the separated-pair amplitudes in
# staggered Cartesian coordinates. Edges are oriented from v to w.
rows=[]
for v,w,U in links:
R=projected(U)
assert ferr(R)<1e-14
for a in range(3):
r=[0]*(3*V)
r[3*w+a]=1
for b in range(3):
r[3*v+b]=-round(R[a][b])
rows.append(r)
return times(2,mm(T(rows),rows))
def rank(A):
a=[[F(x) for x in r] for r in A];m=len(a);i=0
for j in range(len(a[0])):
pivot=next((k for k in range(i,m) if a[k][j]),None)
if pivot is None:continue
a[i],a[pivot]=a[pivot],a[i]
for k in range(i+1,m):
factor=a[k][j]/a[i][j]
for l in range(j,len(a[0])):
a[k][l]-=factor*a[i][l]
i+=1
return i
def positive_above(A,cut):
# Positive exact LDL pivots prove all eigenvalues exceed the cut.
a=[[F(x)-(cut if i==j else 0) for j,x in enumerate(row)] for i,row in enumerate(A)]
for i in range(len(a)):
if a[i][i]<=0:return False
for k in range(i+1,len(a)):
q=a[k][i]/a[i][i]
for j in range(i+1,len(a)):
a[k][j]-=q*a[i][j]
return True
def independent_fock(links):
# Sum all first-coordinate and second-coordinate spinor hopping paths in the
# ordered 12 x 12 one-particle product basis, including both particle orders.
rng=Random(72);vectors=[[complex(rng.random()-.5,rng.random()-.5) for j in range(3)]
for v in range(V)]
norm=sqrt(sum(abs(z)**2 for v in vectors for z in v))
vectors=[[z/norm for z in v] for v in vectors]
dim=2*V
H=[[0j]*dim for _ in range(dim)]
state=[[0j]*dim for _ in range(dim)]
weights=[1.0,1.3,-.67,1.2,.71,-1.,.88]
direct=0
for (n,m,U),t in zip(links,weights):
for a in range(2):
for b in range(2):
H[2*m+a][2*n+b]=t*U[a][b]
H[2*n+b][2*m+a]=t*U[a][b].conjugate()
R=projected(U)
direct+=2*t*t*sum(abs(vectors[m][j]-sum(x*y for x,y in zip(R[j],vectors[n])))**2
for j in range(3))
for n,v in enumerate(vectors):
for a in range(2):
for b in range(2):
state[2*n+a][2*n+b]=sign(n)*sum(v[j]*BASIS[j][a][b] for j in range(3))
hopped=plus(mm(H,state),mm(state,T(H)))
assert abs(dot(state,state)-1)<1e-14 and abs(dot(state,hopped))<1e-14
assert abs(dot(hopped,hopped).real-direct)<1e-13
def main():
for dim in [3,1,0]:
links=edge_list(dim)
A=kinetic_second_moment(links)
assert 3*V-rank(A)==dim
independent_fock(links)
if dim==0:
lo,hi=F(0),F(2)
for _ in range(14):
middle=(lo+hi)/2
if positive_above(A,middle):lo=middle
else:hi=middle
assert lo>0
print(f"Two orthogonal quarter-turn loops: minimum variance in [{lo}, {hi}] hopping²")
variances=[sum(A[3*r+j][3*s+j] for r in range(V) for s in range(V))/V for j in range(3)]
assert all(abs(a-b)<1e-14 for a,b in zip(variances,(2/3,4/3,2/3)))
# Commuting SO(3) rotations can nevertheless have no common fixed vector:
# distinct orthogonal half-turns, unlike rotations around one shared axis.
X,Z=projected(turn(0,pi)),projected(turn(2,pi))
assert max(abs(a-b) for ra,rb in zip(mm(X,Z),mm(Z,X)) for a,b in zip(ra,rb))<1e-14
constraints=[[round(a)-(i==j) for j,a in enumerate(row)] for W in (X,Z) for i,row in enumerate(W)]
assert rank(constraints)==3
print("Triplet kernel dimensions 3, 1, 0; exact ranks and independent spinor hopping checks passed.")
if __name__=="__main__":
main()
sphere.py
"""Exact great-circle transport on the unit three-sphere for two native loops."""
from math import acos, atan2, cos, pi, sin, sqrt
def dot(a,b):return sum(u*v for u,v in zip(a,b))
def plus(a,b):return tuple(u+v for u,v in zip(a,b))
def times(a,s):return tuple(s*u for u in a)
def unit(a):return times(a,1/sqrt(dot(a,a)))
def embed(w):
theta=sqrt(dot(w,w))
return (cos(theta),*(times(w,sin(theta)/theta) if theta else w))
def parallel(p,q,v):
"""Levi-Civita transport of a tangent vector along the short great-circle arc."""
assert abs(dot(p,v))<2e-14
return plus(v,times(plus(p,q),-dot(q,v)/(1+dot(p,q))))
def area(a,b,c):
x,y,z=dot(a,b),dot(b,c),dot(c,a)
gram=1+2*x*y*z-x*x-y*y-z*z
return 2*atan2(sqrt(max(0,gram)),1+x+y+z)
def loop(b,d,angle):
seq=[embed(times(v,angle)) for v in [(0,0,0),b,plus(b,d),d,(0,0,0)]]
columns=[]
for i in range(3):
v=(0.,*(float(j==i) for j in range(3)))
for p,q in zip(seq,seq[1:]):v=parallel(p,q,v)
columns.append(v[1:])
normal=unit((b[1]*d[2]-b[2]*d[1],b[2]*d[0]-b[0]*d[2],b[0]*d[1]-b[1]*d[0]))
def rotate(v):
return tuple(sum(v[i]*columns[i][j] for i in range(3)) for j in range(3))
assert max(abs(u-v) for u,v in zip(rotate(normal),normal))<1e-14
for i in range(3):
for j in range(3):
assert abs(dot(columns[i],columns[j])-(i==j))<1e-14
theta=acos(max(-1,min(1,(sum(columns[i][i] for i in range(3))-1)/2)))
expected=area(*seq[:3])+area(seq[0],seq[2],seq[3])
assert abs(theta-expected)<1e-10
return theta,normal
def main():
a,b,c=(1,1,1),(0,1,1),(0,0,1)
for step in (.1,.2):
t1,n1=loop(a,b,step);t2,n2=loop(b,c,step)
assert abs(dot(n1,n2))<1e-14 and min(t1,t2)>0
print(f"a/R={step}: two angles {t1:.9g}, {t2:.9g} rad; orthogonal fixed axes")
# At small arcs the angles approach the flat tangent areas / R squared.
x=loop(a,b,.05)[0]
assert abs(x/(.05**2)-sqrt(2))<.003
print("Both geodesic loops agree with their oriented spherical area magnitudes.")
if __name__=="__main__":
main()
replay.py
"""Replay the pair spectroscopy study using standard Python and a pinned Tally runtime."""
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"
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="published 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)
python = [sys.executable, "-E", "-s", "-B", "-X", "utf8"]
for script in ("probe", "flux", "echo", "curvature", "winkler", "calibration", "transport", "sphere"):
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 / "spectroscopy.tly", work / "spectroscopy.tly")
result = subprocess.run([*python, str(tally / "tally.py"), "spectroscopy.tly"], cwd=work,
stdout=subprocess.PIPE, check=True)
actual = result.stdout.decode("utf-8").splitlines()
expected = (ROOT / "spectroscopy.out").read_text(encoding="utf-8").splitlines()
if actual != expected or sum(line.startswith("✓") for line in actual) != 20:
raise ValueError("Tally output differs from the 20 published checks")
print("All eight offline checks and the complete 20-assertion Tally transcript passed.")
if __name__ == "__main__":
main()
plot_winkler.py
"""Rebuild the figure for Winkler spectroscopy with Matplotlib and Pillow."""
import contextlib
import csv
from io import BytesIO, StringIO
from math import exp
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from PIL import Image
import winkler
def main():
root=Path(__file__).resolve().parent
with winkler.DATA.open(newline='') as f:rows=list(csv.DictReader(f))
points=[(float(r['x']),float(r['y'])) for r in rows if r['series']=='survival']
with contextlib.redirect_stdout(StringIO()):
data,models=winkler.compare(rows)
_,mu,sigma,b,amp=winkler.gaussian_fit(points)
fig,axes=plt.subplots(2,1,figsize=(6,6.4),dpi=160)
fig.subplots_adjust(left=.155,right=.965,top=.949,bottom=.092,hspace=.62)
plt.rcParams.update({'font.family':'DejaVu Sans'})
blue,orange,slate='#195a80','#a44614','#53656b'
for ax in axes:
ax.spines[['right','top']].set_visible(False)
ax.tick_params(labelsize=10)
ax.grid(axis='y',color='#d9dfdf',linewidth=.6)
ax.set_axisbelow(True)
ax=axes[0]
ax.set_title('Pair survival at fixed lattice depth',loc='left',size=13,weight='semibold',pad=8)
grid=[i*3.55/300 for i in range(301)]
ax.plot(grid,[b+amp*exp(-.5*((t-mu)/sigma)**2) for t in grid],color=blue,lw=1.6,label='Gaussian fit')
ax.scatter(*zip(*points),s=25,facecolor='white',edgecolor=blue,lw=1,zorder=3,label='Measured')
ax.set(xlim=(0,3.55),ylim=(.15,1.1))
ax.set_xlabel('Drive frequency (kHz)',size=11);ax.set_ylabel('Normalized pair count',size=11)
h,l=ax.get_legend_handles_labels()
ax.legend([h[1],h[0]],[l[1],l[0]],frameon=False,ncol=2,loc='lower center',fontsize=9,bbox_to_anchor=(.50,-.04),handlelength=1.4,columnspacing=1.2)
ax=axes[1]
ax.set_title('Resonances at the seven reserved depths',loc='left',size=13,weight='semibold',pad=8)
held=models['deep-calibrated']
depths=[r[0] for r in held];obs=[r[1] for r in held]
err=[[r[1]-r[2] for r in data[:-3]],[r[3]-r[1] for r in data[:-3]]]
ax.errorbar(depths,obs,yerr=err,fmt='o',ms=4.8,elinewidth=1.1,capsize=2.5,color='#263538',
label='Measured, 95% fit interval',zorder=3)
ax.plot(depths,[r[2] for r in held],lw=1.5,color=slate,ls='--',label='Contact only')
ax.plot(depths,[r[3] for r in held],lw=1.8,color=orange,label='With pair dispersion')
ax.set(xlim=(3.7,10.3),ylim=(1.04,1.85),xticks=[4,5,6,7,8,9,10])
ax.set_xlabel('Axial lattice depth (recoil energies)',size=11);ax.set_ylabel('Center frequency (kHz)',size=11)
ax.legend(loc='lower right',frameon=False,fontsize=8.5,handlelength=1.9,labelspacing=.3)
stream=BytesIO();fig.savefig(stream,format='png',facecolor='white');plt.close(fig)
stream.seek(0)
with Image.open(stream) as im:
assert im.size==(960,1024)
im.convert('RGB').quantize(colors=128,method=Image.Quantize.MEDIANCUT).save(root/'winkler-resonances.png',optimize=True)
if __name__=='__main__':main()