Complete Tally transcript
✓ the first staggered pair has the x half-turn spin intertwiner (by cross-pairing plus and minus sides; derived)
✓ the second staggered pair has the y half-turn spin intertwiner (by cross-pairing plus and minus sides; derived)
✓ the third staggered pair has the z half-turn spin intertwiner (by cross-pairing plus and minus sides; derived)
✓ the uniform four-particle preparation has a definite contact probability and energy centroid (by cross-pairing plus and minus sides; derived)
✓ the second pair broadens the energy spectrum (by cross-pairing plus and minus sides; derived)
✓ the fourth energy moment resolves native and anisotropic hopping (by cross-pairing plus and minus sides; derived)
✓ both tensors are trace free (by cross-pairing plus and minus sides; derived)
✓ source rotation and the two pair channels give the matched double difference (by cross-pairing plus and minus sides; derived)
✓ tilted tides have a fixed short-time pair variance (by cross-pairing plus and minus sides; derived)
✓ an independent imposed strain separates the two response columns (by cross-pairing plus and minus sides; derived)
✓ the finite source-mass benchmark gives a larger contrast than the point quadrupole (by cross-pairing plus and minus sides; derived)
✓ a rotationally covariant triplet and a sharp axis marker give different moments at equal mass and radius (by cross-pairing plus and minus sides; derived)
✓ pair minus twice the single half-period displacement isolates the interaction slope (by cross-pairing plus and minus sides; derived)
✓ the measured differential centroid removes a common one-particle shift (by cross-pairing plus and minus sides; derived)
✓ all 68 tabulated bins reproduce both signed sums at millieotvos precision (by cross-pairing plus and minus sides; derived)
✓ the calibrated source-mass contrast is 205.01 Eotvos (by cross-pairing plus and minus sides; derived)
✓ the revised near-minus-far estimator differs from the mass model by less than four Eotvos (by cross-pairing plus and minus sides; derived)
Native Tally source
# Tidal pair spectroscopy. Native exact calculations on ratios and measured bins.
ratchet 16 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)
let third=fraction(1 trial,3 trial)
let volume=whole(64 trial)
let u=three
fn xfactor(sx,sy,sz)
return flip(sx*sy*sz)
end
fn yfactor(sy,sz)
return flip(sy*sz)
end
check xfactor(flip(one),one,one)==one and yfactor(one,one)==flip(one) "the first staggered pair has the x half-turn spin intertwiner"
check xfactor(flip(one),flip(one),one)==flip(one) and yfactor(flip(one),one)==one "the second staggered pair has the y half-turn spin intertwiner"
check xfactor(one,flip(one),flip(one))==flip(one) and yfactor(flip(one),flip(one))==flip(one) "the third staggered pair has the z half-turn spin intertwiner"
let p4=share(two,volume+one)
let mean=(one+flip(p4))*two*u+p4*whole(6 trial)*u
let gap=four*u
let var=p4*(one+flip(p4))*gap*gap
check p4==fraction(2 trial,65 trial) and mean==fraction(414 trial,65 trial) "the uniform four-particle preparation has a definite contact probability and energy centroid"
check var==fraction(18144 trial,4225 trial) "the second pair broadens the energy spectrum"
fn fourth(sq_hop)
return (one+flip(p4))*power(two*u,4 trial)+p4*power(whole(6 trial)*u,4 trial)+share(whole(128 trial)*u*u*sq_hop,volume+one)
end
let native=volume*(fraction(1 trial,8 trial)+fraction(1 trial,4 trial)+half)
let anisotropic=volume*(fraction(4 trial,8 trial)+fraction(9 trial,4 trial)+half)
check fourth(native)==fraction(356112 trial,65 trial) and fourth(anisotropic)==fraction(531216 trial,65 trial) "the fourth energy moment resolves native and anisotropic hopping"
let qparallel=flip(two*third)
let qperp=third
let source_parallel=flip(four)
let source_perp=two
let x=qparallel*source_parallel+two*qperp*source_perp
let y=qperp*source_parallel+qparallel*source_perp+qperp*source_perp
check qparallel+two*qperp==zero and source_parallel+two*source_perp==zero "both tensors are trace free"
check x==four and y==flip(two) and two*(x+flip(y))==whole(12 trial) "source rotation and the two pair channels give the matched double difference"
check half*half+fraction(1 trial,4 trial)*fraction(1 trial,4 trial)==fraction(5 trial,16 trial) "tilted tides have a fixed short-time pair variance"
fn det2(a,b,c,d)
return a*d+flip(b*c)
end
check det2(three,two,flip(three),flip(two))==zero and det2(three,two,zero,one)==three "an independent imposed strain separates the two response columns"
let t=fraction(7 trial,24 trial)
let transverse=fraction(24 trial,25 trial)
let diff=share(one,one+flip(t*t))+flip(transverse)
let ratio=share(two*diff,three*t*t)
check transverse*transverse*(one+t*t)==one and ratio==fraction(672768 trial,645575 trial) "the finite source-mass benchmark gives a larger contrast than the point quadrupole"
let rotor=fraction(1 trial,5 trial)
check share(rotor,half)==fraction(2 trial,5 trial) "a rotationally covariant triplet and a sharp axis marker give different moments at equal mass and radius"
let e0_slope=two
let contact_slope=three
let spring=four
let pair_shift=flip(share(two*(two*e0_slope+contact_slope),spring))
let one_shift=flip(share(two*e0_slope,spring))
check pair_shift+flip(two*one_shift)==flip(fraction(3 trial,2 trial)) "pair minus twice the single half-period displacement isolates the interaction slope"
let common=whole(9 trial)
check common+four+flip(common+flip(two))==whole(6 trial) "the measured differential centroid removes a common one-particle shift"
# Source Data Fig 1c, gradients rounded to the nearest milli-Eotvos.
let near=zero
let far=zero
let near=near+whole(284308 trial)
let near=near+whole(223822 trial)
let near=near+whole(209937 trial)
let near=near+whole(124014 trial)
let far=far+whole(2751 trial)
let far=far+whole(7601 trial)
let far=far+flip(whole(16659 trial))
let far=far+whole(45334 trial)
let near=near+whole(160240 trial)
let near=near+whole(146019 trial)
let near=near+whole(81738 trial)
let near=near+whole(132319 trial)
let far=far+whole(2605 trial)
let far=far+flip(whole(37624 trial))
let far=far+flip(whole(91127 trial))
let far=far+flip(whole(16703 trial))
let near=near+whole(215545 trial)
let near=near+whole(232002 trial)
let near=near+whole(188119 trial)
let near=near+whole(196242 trial)
let far=far+flip(whole(66799 trial))
let far=far+flip(whole(2485 trial))
let far=far+whole(20055 trial)
let near=near+whole(205231 trial)
let near=near+whole(216320 trial)
let near=near+whole(309946 trial)
let near=near+whole(304794 trial)
let far=far+flip(whole(1408 trial))
let far=far+flip(whole(47705 trial))
let far=far+whole(36301 trial)
let near=near+whole(200586 trial)
let near=near+whole(209212 trial)
let near=near+whole(156815 trial)
let near=near+whole(224008 trial)
let far=far+flip(whole(5886 trial))
let far=far+flip(whole(162696 trial))
let far=far+flip(whole(79909 trial))
let near=near+whole(231889 trial)
let near=near+whole(267165 trial)
let near=near+whole(133068 trial)
let far=far+flip(whole(34767 trial))
let far=far+whole(50968 trial)
let far=far+whole(177684 trial)
let near=near+whole(108389 trial)
let near=near+whole(161885 trial)
let near=near+whole(340307 trial)
let far=far+flip(whole(11660 trial))
let far=far+flip(whole(19128 trial))
let far=far+whole(69949 trial)
let far=far+whole(130805 trial)
let near=near+whole(158922 trial)
let near=near+whole(129399 trial)
let near=near+whole(57228 trial)
let near=near+whole(165786 trial)
let far=far+flip(whole(29898 trial))
let far=far+flip(whole(27329 trial))
let far=far+flip(whole(15985 trial))
let far=far+flip(whole(75797 trial))
let near=near+whole(317671 trial)
let near=near+whole(259031 trial)
let near=near+whole(142629 trial)
let near=near+whole(222876 trial)
let far=far+whole(29996 trial)
let far=far+whole(132752 trial)
let far=far+whole(36763 trial)
let near=near+whole(346027 trial)
let near=near+whole(272471 trial)
let near=near+whole(249393 trial)
check near==whole(7585353 trial) and far==flip(one) "all 68 tabulated bins reproduce both signed sums at millieotvos precision"
let field_diff=share(near,whole(37000 trial))+flip(share(far,whole(31000 trial)))
check field_diff>fraction(205009 trial,1000 trial) and field_diff<fraction(205010 trial,1000 trial) "the calibrated source-mass contrast is 205.01 Eotvos"
check field_diff+flip(whole(202 trial))<whole(4 trial) "the revised near-minus-far estimator differs from the mass model by less than four Eotvos"
pair.py
"""Check the cubic onsite-pair classification and projective many-body energy moments."""
from collections import Counter, defaultdict
from fractions import Fraction
from itertools import product
from math import comb, factorial, prod
SPINS = ((1, 0, 0, -1), (1, 0, 0, 1), (0, 1, 1, 0))
K_AXES = ((2, 0, 0), (2, 2, 0), (0, 2, 2))
def spin_h(p, scales):
sine, cosine = (0, 1, 0, -1), (1, 0, -1, 0)
x, y, z = (j % 4 for j in p)
dx = scales[0] * sine[x] * cosine[y] * cosine[z]
dy = scales[1] * sine[y] * cosine[z]
dz = scales[2] * sine[z]
return ((dz, dx - 1j*dy), (dx + 1j*dy, -dz))
def two_h(left, right, v):
return [sum(left[i][l]*v[2*l+j]+right[j][l]*v[2*i+l] for l in range(2))
for i, j in product(range(2),repeat=2)]
def rank(matrix):
a = [list(row) for row in matrix]
pivot = 0
for j in range(len(a[0])):
idx = next((i for i in range(pivot,len(a)) if abs(a[i][j])>1e-8),None)
if idx is None:
continue
a[idx], a[pivot] = a[pivot], a[idx]
scale = a[pivot][j]
a[pivot] = [x/scale for x in a[pivot]]
for i in range(pivot+1,len(a)):
factor = a[i][j]
a[i] = [u-factor*v for u,v in zip(a[i],a[pivot])]
pivot += 1
if pivot==len(a):
break
return pivot
def classify(scales):
grid = list(product(range(4), repeat=3))
one = {k: spin_h(k, scales) for k in grid}
found = {}
for K in grid:
gram = [[0j]*3 for _ in range(3)]
for k in grid:
other = tuple((j-l)%4 for j,l in zip(K,k))
out = [two_h(one[k],one[other],v) for v in SPINS]
for i,j in product(range(3),repeat=2):
gram[i][j] += sum(x.conjugate()*y for x,y in zip(out[i],out[j]))
dim = 3-rank(gram)
if dim:
assert dim==1
nul, = [i for i in range(3) if gram[i][i]==0]
found[K]=nul
assert found=={k:i for i,k in enumerate(K_AXES)}
def compositions(total, size):
if size==1:
yield (total,)
return
for first in range(total+1):
for rest in compositions(total-first,size-1):
yield (first,)+rest
def moments(m, volume):
mean = m+Fraction(4*m*(m-1),volume+1)
var = Fraction(16*m*(m-1)*(volume-1)*(m+volume)*(m+volume+1),
(volume+1)**2*(volume+2)*(volume+3))
return mean,var
def composition_check():
for m in range(8):
for volume in range(1,8):
energies = [sum(l*(2*l-1) for l in state) for state in compositions(m,volume)]
assert len(energies)==comb(volume+m-1,m)
mean = Fraction(sum(energies),len(energies))
var = Fraction(sum(x*x for x in energies),len(energies))-mean**2
assert (mean,var)==moments(m,volume)
def parity_source(coords):
"""Polynomial amplitudes of [Σ exp(iK·x)(a↑†²−a↓†²)]² acting on vacuum."""
creators = [(2*n+s,(-1)**(x+s)) for n,(x,_,_) in enumerate(coords) for s in (0,1)]
state = defaultdict(int)
for i,(mode,phase) in enumerate(creators):
for j in range(i+1):
other,other_phase = creators[j]
key = (other,other,mode,mode)
state[key] += phase*other_phase*(1 if i==j else 2)
return state
def hop_table(coords, beta):
"""Full real-space Fourier stencil, scaled to hopping energy ε=8 on a four-cube."""
sites = {x:i for i,x in enumerate(coords)}
table = []
for p in coords:
for spin in (0,1):
terms = []
for d in product((-1,0,1), repeat=3):
x,y,z = d
if x*y*z:
target, amp = 1-spin,-1j*x*beta[0]
elif x==0 and y*z:
target, amp = 1-spin,2*y*beta[1]*(1 if spin==0 else -1)
elif x==0 and y==0 and z:
target, amp = spin,-4j*z*beta[2]*(1 if spin==0 else -1)
else:
continue
q = tuple((a+b)%4 for a,b in zip(p,d))
terms.append((2*sites[q]+target,amp))
table.append(terms)
return table
def apply_hop(state, links):
out = defaultdict(complex)
for key,c in state.items():
for p,multiplicity in Counter(key).items():
rest = list(key)
rest.remove(p)
weight = c*multiplicity
for q,v in links[p]:
out[tuple(sorted((*rest,q)))] += weight*v
return {k:v for k,v in out.items() if v}
def contact(key,u):
return u*sum(n*(n-1)//2 for n in Counter(j//2 for j in key).values())
def norm(state):
return sum(int(abs2(c))*prod(factorial(n) for n in Counter(key).values())
for key,c in state.items())
def abs2(x):
return x.real*x.real+x.imag*x.imag
def four_bosons():
coords = list(product(range(4), repeat=3))
volume, u = len(coords), 3
state = parity_source(coords)
weight = norm(state)
assert weight==64*comb(volume+1,2)
first = {k:c*contact(k,u) for k,c in state.items()}
site_four = {k:c for k,c in state.items() if len({j//2 for j in k})==1}
mean,var = moments(2,volume)
assert Fraction(norm(first),weight)==u*u*(var+mean**2)
for beta in [(1,1,1),(2,3,1)]:
links = hop_table(coords,beta)
assert not apply_hop(state,links)
# H²ψ = K Vψ + V²ψ, supported on different site-occupancy parities.
kinetic = apply_hop(first,links)
diagonal = {k:c*contact(k,u) for k,c in first.items()}
assert kinetic.keys().isdisjoint(diagonal)
sigma2 = 8*beta[0]**2+16*beta[1]**2+32*beta[2]**2
assert norm(apply_hop(site_four,links))==4*sigma2*norm(site_four)
fourth = Fraction(norm(kinetic)+norm(diagonal),weight)
predicted = Fraction((16*(volume-1)+2592)*u**4+128*u*u*sigma2,volume+1)
assert fourth==predicted
print("Four-boson fourth moment, scales", beta, ":", fourth)
def main():
classify((1,1,1))
classify((2,3,5))
composition_check()
four_bosons()
print("Three pure onsite momenta, their spin triplets and all finite-Fock checks passed.")
if __name__=="__main__":
main()
contact.py
"""Centroids, triplet curvature coupling and source-mass comparison, standard library."""
from cmath import exp
from fractions import Fraction as F
from math import cos, isclose, pi, sin, sqrt
from random import Random
def matmul(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 apply(m,v):
return [sum(x*y for x,y in zip(row,v)) for row in m]
def inner(a,b):
return sum(x.conjugate()*y for x,y in zip(a,b))
def check_spins_and_sources():
pauli = [[[0,1],[1,0]],[[0,-1j],[1j,0]],[[1,0],[0,-1]]]
identity = [[1,0],[0,1]]
singlet = [0,1/sqrt(2),-1/sqrt(2),0]
cart = [apply(kron(identity,s),singlet) for s in pauli]
spins = []
for s in pauli:
left,right = kron(identity,s),kron(s,identity)
spins.append([[(x+y)/2 for x,y in zip(a,b)] for a,b in zip(left,right)])
tide = [[-3.,.5,.25],[.5,1.,-.75],[.25,-.75,2.]]
operator = [[0j]*4 for _ in range(4)]
for i in range(3):
for j in range(3):
block = matmul(spins[i],spins[j])
for k in range(4):
for l in range(4):
operator[k][l] += tide[i][j]*block[k][l]
for i,psi in enumerate(cart):
out = apply(operator,psi)
mean = inner(psi,out).real
assert abs(mean+tide[i][i])<1e-14
assert abs(inner(out,out).real-mean*mean-sum(tide[i][j]**2 for j in range(3) if j!=i))<1e-14
for j,bra in enumerate(cart):
assert abs(inner(bra,out)+tide[j][i])<1e-14
# Compare arbitrary spatial envelopes and momentum-dependent phases, tracing
# position AND spin of the partner. The trial Hermitian matrix is fully nonlocal.
rng = Random(31)
envelope = [.5,.2j,.1+.7j,.3]
norm = sqrt(inner(envelope,envelope).real)
envelope = [x/norm for x in envelope]
sites = len(envelope)
d = 2*sites
random_matrix = [[complex(rng.random(),rng.random()) for _ in range(d)] for _ in range(d)]
field = [[(random_matrix[i][j]+random_matrix[j][i].conjugate())/2
for j in range(d)] for i in range(d)]
energies = []
for i,psi in enumerate(cart):
C = [[0j]*d for _ in range(d)]
for site,f in enumerate(envelope):
for first in range(2):
for second in range(2):
C[2*site+first][2*site+second]=f*exp(1j*site*(i+1))*psi[2*first+second]
rho = matmul(C,[[x.conjugate() for x in row] for row in zip(*C)])
for p in range(d):
for q in range(d):
expected = abs(envelope[p//2])**2/2 if p==q else 0
assert abs(rho[p][q]-expected)<1e-14
E = 2*sum(field[p][q]*rho[q][p] for p in range(d) for q in range(d))
energies.append(E)
assert max(abs(E-energies[0]) for E in energies)<1e-14
def finite_size_ratio(t):
# The ratio to the point quadrupole. Rationalize both cancellations.
x = t*t
r = sqrt(1+x)
return 2*(3-x)/(3*(1-x)*r*(r+1-x))
def hessian_phi(point,axis,R=1.,GM=1.):
out = [[0.]*3 for _ in range(3)]
for sign in (-1,1):
r = [position-(sign*R if i==axis else 0.) for i,position in enumerate(point)]
length = sqrt(sum(x*x for x in r))
for i in range(3):
for j in range(3):
out[i][j] += GM*((i==j)/length**3-3*r[i]*r[j]/length**5)
return out
def checks():
check_spins_and_sources()
GX,GY = (hessian_phi([0.,0.,0.],i) for i in (0,1))
assert -(GX[0][0]-GX[1][1])+(GY[0][0]-GY[1][1])==12.
for t in [.1,.2,7/24]:
# Direct potentials at actual probe endpoints; a common central reference cancels.
def Phi(i,j):
return -sum(1/sqrt(1+t*t-2*sign*t*(i==j)) for sign in (-1,1))
double = (Phi(0,0)-Phi(0,1))-(Phi(1,0)-Phi(1,1))
assert abs(double+6*t*t*finite_size_ratio(t))<3e-15
small = F(7,24)
exact = (1/(1-small**2)-F(24,25))*F(2,3)/small**2
assert abs(float(exact)-finite_size_ratio(float(small)))<1e-14
assert abs((finite_size_ratio(.001)-1)/1e-6-5/12)<1e-6
difference = finite_size_ratio(.1)-finite_size_ratio(.05)
assert .0031<difference<.0033
# Compare two differential settings and one controllable independent shear.
# Rotation alone co-rotates both columns and keeps the response rank one.
def det(x,y):return x[0]*y[1]-x[1]*y[0]
assert det((3,2),(-3,-2))==0 and det((3,2),(0,1))==3
mass = 86.9091805291*1.66053906892e-27
h = 6.62607015e-34
frequency = mass*1e-12*205e-9/h
phase = 2*pi*frequency
trials = 1/(phase*phase)
assert 4.45e-11<frequency<4.48e-11 and 1.25e19<trials<1.3e19
print("Three equal one-particle marginals and tensor-line means/variances passed.")
print("Exact size/point ratio at 7/24:",exact)
print("Scaled size contrast at R and 2R (ell/R=0.1):",difference)
print(f"Illustrative 205 E signal: {frequency:.5g} Hz, {phase:.5g} rad/s, {trials:.5g} ideal one-second pairs.")
if __name__ == "__main__":
checks()
embedding.py
"""Independently check local marker encoding, a positive tidal readout, and support recoil."""
from cmath import exp as cexp
from itertools import product
from math import cos, exp, factorial, pi, sqrt
def check_encoding():
# A finite onsite basis spanning local N=0,1,2,3. Other number sectors can
# use the reference configuration identically. Tuple (N,internal index).
labels = [(n,i) for n in range(4) for i in range(n+1)]
def switch(site, pointer):
n,i = site
if n!=2:
return pointer
target=i+1
return target if pointer==0 else 0 if pointer==target else pointer
def U(state):
return {(a,switch(a,p),b,switch(b,q)):v for (a,p,b,q),v in state.items()}
def bare(state):
result = {}
def add(key, val):
result[key] = result.get(key,0j)+val
for (a,p,b,q),amp in state.items():
n,i=a
m,j=b
# A Hermitian integer-valued test link, conserving total number.
add((a,p,b,q),amp*(n*(n-1)+m*(m-1)+4*(p!=0)+4*(q!=0)))
if n>0 and m<3:
for ii in range(n):
for jj in range(m+2):
v=(1+i+ii)*(1+j+jj)
add(((n-1,ii),p,(m+1,jj),q),amp*v)
if m>0 and n<3:
for ii in range(n+2):
for jj in range(m):
v=(1+i+ii)*(1+j+jj)
add(((n+1,ii),p,(m-1,jj),q),amp*v)
return result
initial = {(a,0,b,0): complex(a[0]+b[1]+1,b[0]-a[1])
for a,b in product(labels,repeat=2)}
encoded=U(initial)
assert U(encoded)==initial
physical=U(bare(U(encoded)))
assert physical==U(bare(initial))
assert all(p==switch(a,0) and q==switch(b,0) for a,p,b,q in physical)
assert any(p or q for a,p,b,q in physical)
def check_marginals():
# Construct the full normalized two-particle arrays in first quantization.
spins=((1,0,0,-1),(1,0,0,1),(0,1,1,0))
env=[1/sqrt(6),1j/sqrt(6),2/sqrt(6)]
for axis,spin in enumerate(spins):
arr=[[0j]*6 for i in range(6)]
for n,f in enumerate(env):
for i,j in product(range(2),repeat=2):
arr[2*n+i][2*n+j]=f*cexp(1j*axis*n)*spin[2*i+j]/sqrt(2)
for i,j in product(range(6),repeat=2):
val=sum(arr[i][t]*arr[j][t].conjugate() for t in range(6))
target=abs(env[i//2])**2/2 if i==j else 0.
assert abs(val-target)<1e-14
def check_tide():
E=((3,.7,-.4),(.7,-1,.3),(-.4,.3,-2))
dipole=(1.1,-.4,.9)
mass,ell=2.,.43
def quadratic(n):
return sum(n[i]*E[i][j]*n[j] for i,j in product(range(3),repeat=2))
def phi(x):
return 2+sum(a*b for a,b in zip(x,dipole))+quadratic(x)/2
for a in range(3):
x=[ell*(i==a) for i in range(3)]
shift=mass*(phi(x)/2+phi([-t for t in x])/2-phi((0,0,0)))
assert abs(shift-mass*ell**2*E[a][a]/2)<1e-14
# Positive 14-point spherical quadrature integrates all fourth powers exactly.
axes=[(tuple(sign if i==a else 0 for i in range(3)),1/15)
for a in range(3) for sign in (-1,1)]
corners=[(tuple(t/sqrt(3) for t in signs),3/40) for signs in product((-1,1),repeat=3)]
for A,B in ((3.,0.),(0.,1.5),(1.,1.),(.6,1.2)):
for i,j in product(range(3),repeat=2):
normalization=0.
element=0.
for n,w in axes+corners:
response=B*(i==j)+(A-B)*n[i]*n[j]
normalization+=w*response
element+=w*response*mass*ell**2*quadratic(n)/2
assert abs(normalization-(i==j))<1e-14
assert abs(element-mass*ell**2*(A-B)*E[i][j]/15)<1e-14
def oscillator(force):
# ℏ=1, M=2, K=2; direct oscillator-number-basis Schrödinger propagation.
mass,stiffness=2.,2.
omega=sqrt(stiffness/mass)
x0=1/sqrt(2*mass*omega)
levels=23
w=[complex(j==0) for j in range(levels)]
roots=[sqrt(j) for j in range(levels+1)]
def rhs(state):
out=[0j]*levels
for j,c in enumerate(state):
neighbors = (roots[j]*state[j-1] if j else 0j)
if j+1<levels:
neighbors+=roots[j+1]*state[j+1]
out[j]=-1j*(omega*(j+.5)*c+force*x0*neighbors)
return out
def shifted(base,dx,t):
return [v+t*d for v,d in zip(base,dx)]
dt=pi/(900*omega)
for _ in range(900):
k1=rhs(w)
k2=rhs(shifted(w,k1,dt/2))
k3=rhs(shifted(w,k2,dt/2))
k4=rhs(shifted(w,k3,dt))
w=[v+dt*(a+2*b+2*c+d)/6 for v,a,b,c,d in zip(w,k1,k2,k3,k4)]
assert abs(sum(abs(v)**2 for v in w)-1)<1e-11
q=2*x0*sum(roots[j]*w[j-1].conjugate()*w[j] for j in range(1,levels)).real
assert abs(q+2*force/stiffness)<1e-9
# Bare/zero-phonon distinction using the full Franck–Condon sum in this regime.
S=force**2/(2*stiffness*omega)
probs=[exp(-S)*S**j/factorial(j) for j in range(30)]
energies=[j*omega-force**2/(2*stiffness) for j in range(30)]
assert abs(sum(probs)-1)<1e-14
assert abs(sum(p*e for p,e in zip(probs,energies)))<1e-14
return q
def main():
check_encoding()
check_marginals()
check_tide()
eta,g=.19,-.71
vacuum,one,pair=[oscillator(f) for f in (0.,eta,2*eta+g)]
recoil=pair-2*one+vacuum
assert abs(recoil-(-2*g/2))<1e-9
print("Local conditional encoding, matched marginals, positive rotor quadrature: passed")
print("Half-period pair recoil minus two one-particle recoils:",recoil)
if __name__=="__main__":
main()
metric.py
"""Cross-check the Weyl vertex against independent linearized curvature variations."""
from fractions import Fraction as F
from itertools import product
from math import cos, pi, sin
FOUR, THREE = range(4), range(3)
ETA = (-1, 1, 1, 1)
def tensor(function, indices=FOUR):
return [[function(i, j) for j in indices] for i in indices]
def contract(a, b):
return sum(x*y for row, col in zip(a, b) for x, y in zip(row, col))
def electric(h, momenta):
"""Electric Weyl of h_ab cos(p*x), at the origin; p is a lower-index covector."""
def riemann(a, b, c, d):
p = momenta
return (-p[b]*p[c]*h[a][d] - p[d]*p[a]*h[b][c]
+ p[c]*p[a]*h[b][d] + p[d]*p[b]*h[a][c])/F(2)
ricci = tensor(lambda i, j: sum(ETA[a]*riemann(a, i, a, j) for a in FOUR))
scalar = sum(ETA[a]*ricci[a][a] for a in FOUR)
def component(x, y):
i, j = x+1, y+1
return (riemann(0, i, 0, j) + ricci[i][j]/2
- (i == j)*(ricci[0][0]/2+scalar/6))
return tensor(component, THREE), ricci
def source(A, p):
"""Analytic metric source for lambda=1, with a matching Fourier mode of nQ."""
k = p[1:]
Ak = [sum(A[i][j]*k[j] for j in THREE) for i in THREE]
kAk = sum(t*z for t,z in zip(k, Ak))
k2 = sum(t*t for t in k)
def component(mu, nu):
if mu == nu == 0:
return -kAk/F(2)
if mu == 0 or nu == 0:
return p[0]*Ak[max(mu, nu)-1]/F(2)
i,j = mu-1, nu-1
return (-(p[0]**2+k2)*A[i][j] + k[i]*Ak[j] + k[j]*Ak[i]
- (i == j)*kAk)/F(2)
return tensor(component)
def verify_metric():
A = [[F(3),F(2),F(-1)], [F(2),F(-4),F(7,3)], [F(-1),F(7,3),F(1)]]
checked = 0
for p in [(2,3,-4,5), (-1,3,7,-2), (0,1,-2,3), (2,0,0,0), (0,0,0,0)]:
T = source(A,p)
assert all(sum(p[i]*T[i][j] for i in FOUR) == 0 for j in FOUR)
assert sum(ETA[i]*T[i][i] for i in FOUR) == 0
for mu in FOUR:
for nu in range(mu,4):
probe = tensor(lambda i,j: F((i,j) in ((mu,nu),(nu,mu))))
E, _ = electric(probe,p)
# Functional derivative comparison before restricting the metric.
assert contract(T,probe)/2 == -contract(A,E)
assert sum(E[i][i] for i in THREE) == 0
checked += 1
gauge = [1,-3,4,7]
pure = tensor(lambda i,j: p[i]*gauge[j]+p[j]*gauge[i])
conformal = tensor(lambda i,j: ETA[i]*(i == j))
for probe in (pure, conformal):
E, _ = electric(probe,p)
assert all(x == 0 for row in E for x in row)
# Static Newton potential Hessian diag(-2,1,1) and a TT plus wave with omega=3.
flat_diag = tensor(lambda i,j: -2*(i == j))
result = tensor(lambda i,j: F(0), THREE)
ricci_sum = tensor(lambda i,j: F(0))
for axis, value in enumerate((-2,1,1)):
p = [0]*4
p[axis+1] = 1
E, ricci = electric(flat_diag,p)
for i,j in product(THREE,repeat=2):
result[i][j] -= value*E[i][j]
for i,j in product(FOUR,repeat=2):
ricci_sum[i][j] -= value*ricci[i][j]
assert all(v==0 for row in ricci_sum for v in row)
assert result == tensor(lambda i,j: (-2,1,1)[i]*(i==j), THREE)
wave = tensor(lambda i,j: (i==j==1)-(i==j==2))
E, ricci = electric(wave,(3,0,0,-3))
assert all(v == 0 for row in ricci for v in row)
assert E[0][0]-E[1][1] == 9
print(f"{checked} independent metric variations, all Ward, trace and gauge tests passed.")
print("Radial-minus-tangential and TT clock factors:", result[0][0]-result[1][1], E[0][0]-E[1][1])
def pauli(k):
x,y,z = k
return (sin(x)*cos(y)*cos(z), sin(y)*cos(z), sin(z))
def native_bonds():
# Test the microscopic tagging by constructing the six-stage hopping Fourier coefficients
# directly using a four-point discrete transform on each axis (maximum spatial range is one).
grid = tuple(product(range(4),repeat=3))
displacements = tuple(product((-1,0,1),repeat=3))
from cmath import exp
weights = {}
for d in displacements:
weights[d] = [sum(pauli(tuple(pi*g/2 for g in G))[i] *
exp(-.5j*pi*sum(g*r for g,r in zip(G,d))) for G in grid)/64
for i in THREE]
for axis, expect in enumerate(((1,1,1),(0,1,1),(0,0,1))):
k = tuple((pi/2 if i==axis else 0) for i in THREE)
def band_weight(d):
phase = sum(s*r for s,r in zip(k,d))
return weights[d][axis]*exp(1j*phase)
for i,j in product(THREE,repeat=2):
hessian = sum(band_weight(d)*d[i]*d[j] for d in displacements)
assert abs(hessian-((i==j)*expect[i])) < 3e-15
q = (2*pi/3,0,0)
direct = sum(band_weight(d)*(cos(sum(qi*di for qi,di in zip(q,d))/2)-1)
for d in displacements)
endpoints = [pauli([s+sign*t/2 for s,t in zip(k,q)]) for sign in (-1,1)]
vertex = (endpoints[0][axis]+endpoints[1][axis])/2-pauli(k)[axis]
assert abs(direct-vertex) < 3e-15
assert abs(vertex-(-.5 if axis==0 else 0)) < 3e-15
assert all(spin[axis]>0 and all(abs(v)<1e-14 for j,v in enumerate(spin) if j!=axis)
for spin in endpoints)
# All three off-diagonal contrasts are available at stationary positive band peaks.
for i, j in ((0,1),(0,2),(1,2)):
tensors, candidates = [], []
for sign in (-1,1):
k = tuple(pi/2 if d==i else sign*pi/2 if d==j else 0 for d in THREE)
v, spin = tuple(map(sin,k)), pauli(k)
assert abs(sum(z*z for z in spin)-1) < 1e-14
tensors.append(tensor(lambda b,c: v[b]*v[c]-(b==c)*sum(x*x for x in v)/3, THREE))
def second(b,c):
return sum(sum(x*y for x,y in zip(spin,weights[d])) *
exp(1j*sum(x*y for x,y in zip(k,d))) *
d[b]*d[c] for d in displacements)
candidates.append(tensor(second,THREE))
delta = tensor(lambda x,y: tensors[1][x][y]-tensors[0][x][y], THREE)
shear = tensor(lambda x,y: int((x,y) in ((i,j),(j,i))),THREE)
assert abs(contract(delta,shear)-4) < 1e-14
assert all(abs(candidates[1][x][y]-candidates[0][x][y])<3e-15 for x,y in product(THREE,repeat=2))
turns = [0,pi/2,3*pi/2,2*pi]
integrals = [sin(b)-sin(a) for a,b in zip(turns,turns[1:])]
assert abs(sum(integrals)) < 1e-14
assert abs(sum(z*s for z,s in zip(integrals,[1,-1,1]))-4) < 1e-14
# A hypothetical one-micron band with epsilon/h=1 kHz.
nu = 1000*(1e-6)**2*1e-6/(8*299792458**2)
assert 1.38e-33 < nu < 1.40e-33
print("Bond quadrupole diagonals (1,1,1), (0,1,1), (0,0,1); q vertex (−1/2,0,0).")
print(f"Illustrative hopping-scale tide {nu:.6g} Hz")
if __name__ == "__main__":
verify_metric()
native_bonds()
field_data.py
"""Replay the source-mass calibration in Stray et al., Nature 602 (2022), figure 1c.
The bundled CSV contains the credited article's 68 binned gradient readings.
--fetch verifies all reported columns against the publisher's workbook and
independently reconstructs them from 727 per-ellipse readings in the data deposit.
"""
import argparse
import csv
from collections import defaultdict
from hashlib import sha256
from io import BytesIO, StringIO
from itertools import groupby
from math import hypot, isclose, pi, sqrt
from pathlib import Path
from statistics import mean, pstdev, variance
import struct
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET
from zipfile import ZipFile
from zlib import crc32, decompress
ROOT = Path(__file__).resolve().parent
WORKBOOK = ("https://media.springernature.com/full/springer-static/esm/"
"art%3A10.1038%2Fs41586-021-04315-3/MediaObjects/41586_2021_4315_MOESM2_ESM.xlsx")
DEPOSIT = "https://edata.bham.ac.uk/740/2/QuantumSensingForGravityCartographyDataCode_1.zip"
MEMBER = "Data1/Data/Figure_1_Data/Figure1c_data/Figure1c_data_processed.csv"
WORKBOOK_SHA = "97821a80ec02ad9e323b9f1bd76a03c9fff2561871c9fbf5769f7a7a89ef4c64"
MEMBER_SHA = "2ea65f1fe0cdc6db6570bcd42674f3bf35235feb406e12781f6dd36b4e716175"
CSV_SHA = "518cfe472032a455c4ee0e01f2b61c41426341865b21e02a1b353544fd0b669c"
C = 299792458
def require_hash(data, wanted):
if sha256(data).hexdigest() != wanted:
raise ValueError("Source SHA-256 differs from the pinned release")
def table(data):
return [tuple(map(float, row.values())) for row in csv.DictReader(StringIO(data.decode()))]
def workbook_rows():
with urlopen(WORKBOOK, timeout=30) as reply:
data = reply.read()
require_hash(data, WORKBOOK_SHA)
ns = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
with ZipFile(BytesIO(data)) as book:
sheet = ET.fromstring(book.read("xl/worksheets/sheet2.xml"))
rows = []
for row in sheet.iter(ns + "row"):
cells = [c for c in row.findall(ns + "c") if c.find(ns + "v") is not None]
if cells and cells[0].get("t") != "s":
rows.append(tuple(float(c.findtext(ns + "v")) for c in cells))
return sorted(rows, key=lambda row: row[1])
def ellipse_readings():
# The central directory pins this member in the published 6.16 GB ZIP.
# A range request obtains just its local header, name, extra field and body.
offset, compressed_size = 544908628, 6552
request = Request(DEPOSIT, headers={"Range": f"bytes={offset}-{offset+6750-1}"})
with urlopen(request, timeout=30) as reply:
if reply.status != 206 or not reply.headers["Content-Range"].startswith(f"bytes {offset}-"):
raise ValueError("Data repository did not honor the ZIP member range")
body = reply.read(6750)
if body[:4] != b"PK\x03\x04":
raise ValueError("Missing ZIP member header")
fn_len, extra_len = struct.unpack_from("<HH", body, 26)
assert body[30:30+fn_len].decode() == MEMBER
start = 30 + fn_len + extra_len
assert start + compressed_size <= len(body)
data = decompress(body[start:start+compressed_size], -15)
assert len(data) == 18127 and crc32(data) == 884282424
require_hash(data, MEMBER_SHA)
readings = []
for r in csv.DictReader(StringIO(data.decode())):
h, m, s = map(int, r["Time"].split(":"))
readings.append((3600*h+60*m+s, float(r["Gradient (Eo)"]), int(r["Lead position (mm)"])))
assert len(readings) == 727
return readings
def reproduce_bins(readings):
# Reimplement the deposit's Figure1c_code.py. Discard its initial far visit,
# trim two records at either end of each later visit, and preserve its strict
# end-exclusive test (even a final block of exactly eight is omitted).
bins = []
for run, (_, visit) in enumerate(groupby(readings, key=lambda x: x[2])):
fit = list(visit)[2:-2]
if not run:
continue
for start in range(0, len(fit)-8, 8):
sample = fit[start:start+8]
values = [g for _, g, _ in sample]
bins.append((run, sample[0][0], mean(values), pstdev(values)/sqrt(8)))
t0 = bins[0][1]
ref = mean(row[2] for row in bins if row[0] % 2 == 0)
return [(run, t-t0, g-ref, se) for run,t,g,se in bins]
def brackets(rows):
visits = {}
for run, record in groupby(rows, key=lambda x: int(x[0])):
sample = list(record)
visits[run] = (mean(x[1] for x in sample), mean(x[2] for x in sample),
sum(x[3]**2 for x in sample)/len(sample)**2)
assert list(visits) == list(range(1,20))
weights = defaultdict(float)
for k in range(2, 19, 2):
t_left, t_mid, t_right = [visits[j][0] for j in (k-1, k, k+1)]
fraction = (t_mid-t_left)/(t_right-t_left)
weights[k-1] += (1-fraction)/9
weights[k] -= 1/9
weights[k+1] += fraction/9
assert abs(sum(weights.values())) < 1e-14
assert abs(sum(w*visits[k][0] for k,w in weights.items())) < 1e-10
value = sum(w*visits[k][1] for k,w in weights.items())
se = sqrt(sum(w*w*visits[k][2] for k,w in weights.items()))
return value,se
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--fetch", action="store_true", help="repeat both independent source extractions")
opt = parser.parse_args()
data = (ROOT / "field_bins.csv").read_bytes()
require_hash(data, CSV_SHA)
rows = table(data)
if opt.fetch:
readings = ellipse_readings()
for alternate in [workbook_rows(), reproduce_bins(readings)]:
assert len(alternate)==len(rows)
assert all(max(abs(x-y) for x,y in zip(a,b))<2e-8 for a,b in zip(alternate,rows))
full = [[g for _,g,p in readings if p==setting] for setting in (0,550)]
untrimmed = mean(full[0])-mean(full[1])
assert isclose(untrimmed,190.51982694,abs_tol=1e-8)
print(f"727 archived ellipse fits reproduce all 68 binned rows. Untrimmed contrast {untrimmed:.3f} E.")
close = [r for r in rows if int(r[0])%2]
away = [r for r in rows if int(r[0])%2==0]
assert (len(close),len(away))==(37,31)
value = mean(r[2] for r in close)-mean(r[2] for r in away)
internal = sqrt(sum(sum(r[3]**2 for r in group)/len(group)**2 for group in (close,away)))
scatter = sqrt(sum(variance(r[2] for r in group)/len(group) for group in (close,away)))
drift, drift_se = brackets(rows)
assert abs(value-205.00952377)<1e-7 and abs(internal-12.98458760)<1e-7
assert abs(drift-200.76512984)<1e-7 and abs(drift_se-13.45017776)<1e-7
phase = (4*pi/780e-9)*.085**2*1.0*(value*1e-9)
curvature = (value*1e-9)/C**2
print(f"Direct contrast {value:.3f} E. Propagated bin errors {internal:.3f} E, scatter SE {scatter:.3f} E.")
print(f"Nine drift-cancelling contrasts {drift:.3f} ± {drift_se:.3f} E (conditional independent-bin SE).")
print(f"Raman phase {1e3*phase:.3f} mrad, magnitude of averaged curvature modulation {curvature:.6g} m^-2.")
if __name__ == "__main__":
main()
replay.py
"""Replay the tidal-pair 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 ("pair", "contact", "embedding", "metric", "field_data"):
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 / "tidal.tly", work / "tidal.tly")
result = subprocess.run([*python, str(tally / "tally.py"), "tidal.tly"], cwd=work,
stdout=subprocess.PIPE, check=True)
actual = result.stdout.decode("utf-8").splitlines()
expected = (ROOT / "tidal.out").read_text(encoding="utf-8").splitlines()
if actual != expected or sum(line.startswith("✓") for line in actual) != 17:
raise ValueError("Tally output differs from the 17 published checks")
print("All five offline checks and the complete 17-assertion Tally transcript passed.")
if __name__ == "__main__":
main()
plot_gradient.py
"""Regenerate the gradient-contrast figure with Matplotlib and Pillow.
Source: Stray et al., Nature 602, 590–594 (2022), doi:10.1038/s41586-021-04315-3,
figure 1c, CC BY 4.0. This independent reduction uses the accompanying field_bins.csv.
"""
from io import BytesIO
from itertools import groupby
from math import hypot, sqrt
from pathlib import Path
from statistics import mean
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from PIL import Image
from field_data import brackets, table
def main():
directory = Path(__file__).resolve().parent
rows = table((directory/"field_bins.csv").read_bytes())
visits = {}
for run, group in groupby(rows, key=lambda x: int(x[0])):
bins = list(group)
visits[run] = (mean(r[1] for r in bins), mean(r[2] for r in bins),
sqrt(sum(r[3]**2 for r in bins))/len(bins))
estimates = []
for run in range(2, 19, 2):
left, mid, right = [visits[j] for j in (run-1, run, run+1)]
fraction = (mid[0]-left[0])/(right[0]-left[0])
value = (1-fraction)*left[1]+fraction*right[1]-mid[1]
error = hypot((1-fraction)*left[2], mid[2], fraction*right[2])
estimates.append((value,error))
pooled, pooled_error = brackets(rows)
plt.rcParams.update({"font.family":"DejaVu Sans", "font.size":11,
"axes.labelcolor":"#29333a", "xtick.color":"#404950",
"ytick.color":"#404950", "savefig.facecolor":"white"})
fig,ax=plt.subplots(figsize=(5.4,4.4))
fig.subplots_adjust(left=.18, right=.97, top=.88, bottom=.16)
levels = list(range(9,0,-1))
points, errors = zip(*estimates)
ax.set_xlim(65,345)
ax.set_ylim(-1.6,9.65)
ax.axvline(202, color="#a04d17", ls="--", lw=1.6, zorder=1)
ax.text(202,1.022,"202 E source model", transform=ax.get_xaxis_transform(),
ha="center", va="bottom", color="#874016", fontsize=10)
ax.text(-.04,1.022,"Far visit",transform=ax.transAxes,
ha="right",va="bottom",color="#404950",fontsize=10)
ax.errorbar(points, levels, xerr=errors, fmt="o", color="#16536b", ms=5,
ecolor="#46788b", elinewidth=1.6, capsize=3, capthick=1.5, zorder=3)
ax.axhline(.1, color="#d2d7d9", lw=1.0, zorder=1)
ax.errorbar(pooled,-.85,xerr=pooled_error,fmt="D",color="#15252d",
ms=6,elinewidth=2.0,capsize=4,capthick=1.7,zorder=3)
ax.text(pooled+pooled_error+8,-.85,f"{pooled:.1f} ± {pooled_error:.1f} E",
va="center",ha="left",color="#15252d",fontsize=10)
ax.set_yticks([*levels,-.85],[*map(str,range(2,19,2)),"Combined"])
ax.set_xticks(range(100,301,50))
ax.set_xlabel("Near-minus-far gravity gradient (E)",labelpad=7)
ax.grid(axis="x",color="#e8ecee",linewidth=.75)
for name in ("left","right","top"):
ax.spines[name].set_visible(False)
ax.spines["bottom"].set_color("#81898e")
ax.tick_params(axis="y",length=0,pad=7)
img=BytesIO()
fig.savefig(img,format="png",dpi=165)
plt.close(fig)
img.seek(0)
# A bounded palette retains the antialiased plot at small download size.
with Image.open(img) as im:
im.convert("RGB").quantize(colors=160).save(directory/"gradient-contrast.png",optimize=True)
if __name__=="__main__":
main()