Complete Tally transcript
✓ the homogeneous gate clock and proposed rod scale inside the reference shell (by cross-pairing plus and minus sides; derived)
✓ the nonlinear finite-grid rest source gives the selected central scalar value (by cross-pairing plus and minus sides; derived)
✓ the empty edge and corner cells satisfy source-free force balance (by cross-pairing plus and minus sides; derived)
✓ each axial occupation sources the spring field through its own clock derivative (by cross-pairing plus and minus sides; derived)
✓ the finite probe lowers its relaxed gap through the inverse central stiffness (by cross-pairing plus and minus sides; derived)
✓ the radius and external mass are fixed by the same scalar field (by cross-pairing plus and minus sides; derived)
✓ including the compressed shell reproduces its exterior energy and Newtonian binding formula (by cross-pairing plus and minus sides; derived)
✓ the equilibrium tangential pressure per unit surface energy (by cross-pairing plus and minus sides; derived)
✓ the two equilibrium annular clocks have different coordinate rates (by cross-pairing plus and minus sides; derived)
✓ local rod surveys independently determine both circumference gradients (by cross-pairing plus and minus sides; derived)
✓ the held-back two-shell curvature and clock comparison fails the unit GR ratio (by cross-pairing plus and minus sides; derived)
✓ removing the exterior shell restores the vacuum relation (by cross-pairing plus and minus sides; derived)
✓ the two supported shells leave distinct exterior and total masses (by cross-pairing plus and minus sides; derived)
✓ dust pairs, dust with a light sheet, and two light sheets have three distinct Einstein responses (by cross-pairing plus and minus sides; derived)
✓ the attractive static response violates the positive Gram bound at the third setting (by cross-pairing plus and minus sides; derived)
✓ a constrained repulsive term repairs the static sheet coefficient (by cross-pairing plus and minus sides; derived)
✓ balanced light beams retain a shear-dependent angular response (by cross-pairing plus and minus sides; derived)
✓ a bound chain pair misses the reserved momentum response after matching size and clock (by cross-pairing plus and minus sides; derived)
✓ the two exact dimer tail distributions have distinct adjacent-bin ratios (by cross-pairing plus and minus sides; derived)
✓ an isolated canonical massive scalar can change its total spatial stress at fixed energy (by cross-pairing plus and minus sides; derived)
✓ density retardation and material pressure add in the long-wave shell radiation amplitude (by cross-pairing plus and minus sides; derived)
✓ the endpoint clock pair differs from the independently calibrated prediction by 1.162 in units of ten to the minus nineteen (by cross-pairing plus and minus sides; derived)
✓ the positive rotor curl and Cotton spectra predict distinct squared frequency ratios (by cross-pairing plus and minus sides; derived)
✓ the cubic and linear two-polarization spectra differ at the second wave number (by cross-pairing plus and minus sides; derived)
✓ the two imposed shear signals carry unit combined squared drive amplitude (by cross-pairing plus and minus sides; derived)
✓ the native squared energy changes with carrier and is constant on the flat plane (by cross-pairing plus and minus sides; derived)
✓ rotating the transverse carrier from zero to a quarter pi halves the weak displacement (by cross-pairing plus and minus sides; derived)
✓ the same pulse can leave a packet centered or reverse its displacement (by cross-pairing plus and minus sides; derived)
✓ the normalized three-site packet keeps half its two-site displacement under the transverse carrier change (by cross-pairing plus and minus sides; derived)
✓ equal-energy spinors on the flat plane can have a nonzero translation form factor (by cross-pairing plus and minus sides; derived)
✓ the first shell fixes the incident radial slope at the second shell (by cross-pairing plus and minus sides; derived)
✓ the second junction reproduces the mass measured by the outer rods (by cross-pairing plus and minus sides; derived)
✓ the two equilibrium clocks have distinct redshifts relative to infinity (by cross-pairing plus and minus sides; derived)
✓ adding proper shell energy gives the same mixed clock susceptibility in both orders (by cross-pairing plus and minus sides; derived)
✓ the explicit ordered two-link pulses cancel the intermediate mask and retain the two endpoints (by cross-pairing plus and minus sides; derived)
✓ reversing the endpoint profile reverses the commutator and equal endpoints give no displacement link (by cross-pairing plus and minus sides; derived)
✓ the finite three-dimensional envelope sets the reference clock-loop displacement (by cross-pairing plus and minus sides; derived)
✓ changing only the x carrier changes the localized packet displacement along y (by cross-pairing plus and minus sides; derived)
✓ transverse position localization lifts the zero of the sharp-momentum preparation (by cross-pairing plus and minus sides; derived)
✓ a relative packet with fixed nonzero total momentum has a nonzero signed shift before profile calibration (by cross-pairing plus and minus sides; derived)
✓ compensated nearby and remote coherences cancel in the marginal while the coincidence population is one quarter (by cross-pairing plus and minus sides; derived)
✓ opposite conditional phases reverse the interaction part of the walker coincidence count (by cross-pairing plus and minus sides; derived)
✓ doubling the mobile reference mass halves its separately addressable clock signal (by cross-pairing plus and minus sides; derived)
✓ the reflected walker loses precisely the energy gained by the finite reference (by cross-pairing plus and minus sides; derived)
✓ the reflected relative velocity reverses and the reference records eight seventeenths of recoil energy (by cross-pairing plus and minus sides; derived)
✓ the collision fraction and squared bound-energy offset independently encode the contact strength (by cross-pairing plus and minus sides; derived)
✓ the onsite mass polynomial supplies both missing fourth-order coefficients in the squared energy (by cross-pairing plus and minus sides; derived)
✓ the positive pair corner is separated from the rest pair by sixteen thirds (by cross-pairing plus and minus sides; derived)
✓ the directly squared spin Hamiltonian equals its strictly increasing axial energy polynomial (by cross-pairing plus and minus sides; derived)
✓ the exact two-cell contact equation gives the same positive-pair bound pole for both rest-spin contacts (by cross-pairing plus and minus sides; derived)
✓ the two-cell bound pair has a nonzero off-resonant corner probability even after detuning (by cross-pairing plus and minus sides; derived)
✓ moving an occupied pair together supplies a new kinetic response while every rest-state energy is preserved (by cross-pairing plus and minus sides; derived)
✓ the normalized native four-component symbol has unit self-overlap (by cross-pairing plus and minus sides; derived)
✓ equal axis transfers at a diagonal momentum select three different ordered-spin overlaps (by cross-pairing plus and minus sides; derived)
✓ the anisotropic spin weights factor from the common transfer of the two band spinors (by cross-pairing plus and minus sides; derived)
Native Tally source
# Static and finite-frequency tests of shell clocks and stress exchange.
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 half=fraction(1 trial,2 trial)
let s=fraction(1 trial,7 trial)
fn lapse(u)
return share(one+flip(u),one+u)
end
fn area_scale(u)
return power(one+u,2 trial)
end
check lapse(s)==fraction(3 trial,4 trial) and area_scale(s)==fraction(64 trial,49 trial) "the homogeneous gate clock and proposed rod scale inside the reference shell"
let load=fraction(17 trial,10 trial)*s*area_scale(s)
check load==fraction(544 trial,1715 trial) "the nonlinear finite-grid rest source gives the selected central scalar value"
let edge=share(two*s,whole(5 trial))
let corner=share(s,whole(5 trial))
check whole(6 trial)*edge==two*s+two*corner and whole(6 trial)*corner==three*edge "the empty edge and corner cells satisfy source-free force balance"
let face=whole(5 trial)*s+flip(four*edge)
check face==share(two*load,area_scale(s)) "each axial occupation sources the spring field through its own clock derivative"
let slope=share(two,area_scale(s))
let stiffness=fraction(7 trial,34 trial)
check slope*slope*stiffness==fraction(16807 trial,34816 trial) "the finite probe lowers its relaxed gap through the inverse central stiffness"
let r=fraction(49 trial,16 trial)
let R=r*area_scale(s)
let exterior=two*r*s
check R==four and exterior==fraction(7 trial,8 trial) "the radius and external mass are fixed by the same scalar field"
check lapse(s)+two*r*s*s==exterior and one+flip(share(one,two*R))==exterior "including the compressed shell reproduces its exterior energy and Newtonian binding formula"
check share(one,whole(12 trial))==share(one+flip(lapse(s)),four*lapse(s)) "the equilibrium tangential pressure per unit surface energy"
let d=fraction(1 trial,10 trial)
let a=fraction(1 trial,4 trial)
fn rod_slope(background,z)
return share(one+background+flip(z),one+background+z)
end
let n1=lapse(d+a)
let n2=lapse(d+half*a)
let s1=rod_slope(d,a)
let s2=rod_slope(d,half*a)
check n1==fraction(13 trial,27 trial) and n2==fraction(31 trial,49 trial) "the two equilibrium annular clocks have different coordinate rates"
check s1==fraction(17 trial,27 trial) and s2==fraction(39 trial,49 trial) "local rod surveys independently determine both circumference gradients"
check share(n2*s1,n1*s2)==fraction(527 trial,507 trial) and s1*n2>s2*n1 "the held-back two-shell curvature and clock comparison fails the unit GR ratio"
check share(lapse(a),rod_slope(zero,a))==one and share(lapse(half*a),rod_slope(zero,half*a))==one "removing the exterior shell restores the vacuum relation"
check fraction(11 trial,10 trial)+flip(fraction(209 trial,192 trial))==fraction(11 trial,960 trial) "the two supported shells leave distinct exterior and total masses"
fn exchange(e,t,f,p)
return e*f+e*p+t*f
end
let dd=exchange(one,zero,one,zero)
let dl=exchange(one,zero,one,one)
let ll=exchange(one,one,one,one)
check dd==one and dl==two and ll==three "dust pairs, dust with a light sheet, and two light sheets have three distinct Einstein responses"
check dd*ll+flip(dl*dl)==flip(one) and share(dl*dl,dd)>ll "the attractive static response violates the positive Gram bound at the third setting"
check (one+one)*(one+one)+flip(one*one)==ll "a constrained repulsive term repairs the static sheet coefficient"
check two*(one+fraction(9 trial,25 trial))==fraction(68 trial,25 trial) "balanced light beams retain a shear-dependent angular response"
let old_ratio=fraction(9 trial,10 trial)
let new_ratio=fraction(4 trial,5 trial)
check share(new_ratio,old_ratio)==fraction(8 trial,9 trial) "a bound chain pair misses the reserved momentum response after matching size and clock"
check fraction(1 trial,4 trial)*four==one and fraction(1 trial,9 trial)*whole(9 trial)==one "the two exact dimer tail distributions have distinct adjacent-bin ratios"
let wet=whole(3 trial)
let dry=flip(whole(3 trial))
check wet+flip(dry)==whole(6 trial) "an isolated canonical massive scalar can change its total spatial stress at fixed energy"
let low=share(one,three)
check one+low==fraction(4 trial,3 trial) and power(one+low,2 trial)==fraction(16 trial,9 trial) "density retardation and material pressure add in the long-wave shell radiation amplitude"
let obs=flip(fraction(1196 trial,100 trial))
let calc=flip(fraction(10798 trial,1000 trial))
check obs+flip(calc)==flip(fraction(1162 trial,1000 trial)) "the endpoint clock pair differs from the independently calibrated prediction by 1.162 in units of ten to the minus nineteen"
let qsq_ratio=three
check qsq_ratio*qsq_ratio==whole(9 trial) and power(qsq_ratio,3 trial)==whole(27 trial) "the positive rotor curl and Cotton spectra predict distinct squared frequency ratios"
check share(power(qsq_ratio,3 trial),qsq_ratio)==whole(9 trial) "the cubic and linear two-polarization spectra differ at the second wave number"
let polarization=fraction(3 trial,5 trial)
let cross=fraction(4 trial,5 trial)
check polarization*polarization+cross*cross==one "the two imposed shear signals carry unit combined squared drive amplitude"
# The order of two local clock-control pulses and a finite support packet.
fn squared_energy_drop(cos_x_squared,cos_y_squared)
return one+flip(cos_x_squared*cos_y_squared)
end
fn y_loop_response(cos_x_squared,cos_y_squared)
return cos_x_squared*(two*cos_y_squared+flip(one))
end
let half_band=fraction(1 trial,2 trial)
check squared_energy_drop(half_band,one)==half and squared_energy_drop(zero,half_band)==one "the native squared energy changes with carrier and is constant on the flat plane"
check y_loop_response(one,one)==one and y_loop_response(half_band,one)==half "rotating the transverse carrier from zero to a quarter pi halves the weak displacement"
check y_loop_response(zero,one)==zero and y_loop_response(one,zero)==flip(one) "the same pulse can leave a packet centered or reverse its displacement"
let envelope_power=one+four+one
let two_site_coherence=share(one,envelope_power)
check y_loop_response(half_band,one)*two_site_coherence==fraction(1 trial,12 trial) "the normalized three-site packet keeps half its two-site displacement under the transverse carrier change"
let cos_difference=fraction(3 trial,5 trial)
let spin_overlap_squared=share(one+cos_difference,two)
check spin_overlap_squared==fraction(4 trial,5 trial) "equal-energy spinors on the flat plane can have a nonzero translation form factor"
# Independent static shell benchmark. Units have G=c=1.
fn add_shell(interior_mass,proper_mass,radius,inside_slope)
return interior_mass+inside_slope*proper_mass+flip(share(proper_mass*proper_mass,two*radius))
end
let inner_radius=whole(8 trial)
let outer_radius=fraction(224 trial,15 trial)
let inner_rest=two
let outer_rest=fraction(28 trial,15 trial)
let inner_exterior=add_shell(zero,inner_rest,inner_radius,one)
let slope_before=fraction(7 trial,8 trial)
check inner_exterior==fraction(7 trial,4 trial) and slope_before*slope_before==one+flip(share(two*inner_exterior,outer_radius)) "the first shell fixes the incident radial slope at the second shell"
let slope_after=slope_before+flip(share(outer_rest,outer_radius))
let outer_exterior=add_shell(inner_exterior,outer_rest,outer_radius,slope_before)
check outer_exterior==fraction(49 trial,15 trial) and slope_after*slope_after==one+flip(share(two*outer_exterior,outer_radius)) "the second junction reproduces the mass measured by the outer rods"
let inner_rod=one+flip(share(inner_rest,inner_radius))
let exterior_clock_factor=share(slope_after,slope_before)
check inner_rod*exterior_clock_factor==fraction(9 trial,14 trial) and slope_after==fraction(3 trial,4 trial) "the two equilibrium clocks have distinct redshifts relative to infinity"
let work_derivative=flip(share(inner_rod,outer_radius*slope_before))
check work_derivative==flip(fraction(45 trial,784 trial)) "adding proper shell energy gives the same mixed clock susceptibility in both orders"
# Direct two-link commutator on a right-moving spin component.
# D=(T-T†)/2. The weighted matrix is (f D + D f)/2. Only the intervening site joins sites 0 and 2.
fn real_link_order(f_left,f_middle,f_right)
let d_right=flip(half)
let left_entry=d_right*share(f_left+f_middle,two)
let right_entry=d_right*share(f_middle+f_right,two)
return d_right*right_entry+flip(left_entry*d_right)
end
let endpoint_profile=whole(5 trial)
check real_link_order(one,flip(two),endpoint_profile)==half and real_link_order(one,whole(11 trial),endpoint_profile)==half "the explicit ordered two-link pulses cancel the intermediate mask and retain the two endpoints"
check real_link_order(endpoint_profile,flip(two),one)==flip(half) and real_link_order(two,one,two)==zero "reversing the endpoint profile reverses the commutator and equal endpoints give no displacement link"
# All three coordinates localized with the same five-site envelope 1,2,3,2,1.
let norm_five=two*one+two*four+three*three
let coherence_five=share(two*one*three+two*two,norm_five)
fn compact_echo(coherence,carrier_cosine)
return share(coherence*(one+coherence)*(one+coherence*carrier_cosine),four)
end
let drift_rest=compact_echo(coherence_five,one)
let drift_quarter=compact_echo(coherence_five,zero)
let drift_half=compact_echo(coherence_five,flip(one))
check coherence_five==fraction(10 trial,19 trial) and drift_rest==fraction(4205 trial,13718 trial) "the finite three-dimensional envelope sets the reference clock-loop displacement"
check drift_quarter==fraction(145 trial,722 trial) and drift_half==fraction(1305 trial,13718 trial) "changing only the x carrier changes the localized packet displacement along y"
check share(drift_half,drift_rest)==fraction(9 trial,29 trial) "transverse position localization lifts the zero of the sharp-momentum preparation"
# Quantum mobile reference and contact readout. Weak coefficients below
# divide out sinc(q), the independently calibrated sinusoidal profile.
let relative_coherence=fraction(10 trial,19 trial)
let opposite_carriers=share(relative_coherence*relative_coherence*(one+relative_coherence),two)
check opposite_carriers==fraction(1450 trial,6859 trial) "a relative packet with fixed nonzero total momentum has a nonzero signed shift before profile calibration"
let conditional_near=share(one,four)
let conditional_far=flip(conditional_near)
check conditional_near+conditional_far==zero and four*conditional_near==one "compensated nearby and remote coherences cancel in the marginal while the coincidence population is one quarter"
let coupling_g=half
let eight_ref=whole(8 trial)
fn walker_contrast(g,phase_sine)
return share(g*phase_sine,eight_ref)
end
fn reference_contrast(g,phase_cosine,reference_mass)
return flip(share(g*phase_cosine,eight_ref*reference_mass))
end
check walker_contrast(coupling_g,one)==fraction(1 trial,16 trial) and walker_contrast(coupling_g,flip(one))==flip(fraction(1 trial,16 trial)) "opposite conditional phases reverse the interaction part of the walker coincidence count"
check reference_contrast(coupling_g,one,four)==flip(fraction(1 trial,64 trial)) and reference_contrast(coupling_g,one,eight_ref)==flip(fraction(1 trial,128 trial)) "doubling the mobile reference mass halves its separately addressable clock signal"
let hop_J=share(one,four)
let reflected_cos=flip(fraction(15 trial,17 trial))
let reflected_sin=flip(fraction(8 trial,17 trial))
let reference_gain=hop_J*(one+flip(reflected_cos))
check reflected_cos*reflected_cos+reflected_sin*reflected_sin==one and reflected_sin+reference_gain==zero "the reflected walker loses precisely the energy gained by the finite reference"
check reflected_cos+hop_J*reflected_sin==flip(one) and reference_gain==fraction(8 trial,17 trial) "the reflected relative velocity reverses and the reference records eight seventeenths of recoil energy"
let g2=coupling_g*coupling_g
check share(g2,one+g2)==fraction(1 trial,5 trial) and one+hop_J*hop_J+g2==fraction(21 trial,16 trial) "the collision fraction and squared bound-energy offset independently encode the contact strength"
# Quartic mass correction for the doubled six-stage sine clock, m=1.
let axis_mass_coeff=fraction(2 trial,3 trial)
let mixed_mass_coeff=two
check share(axis_mass_coeff,two)==share(one,three) and share(mixed_mass_coeff,two)==one "the onsite mass polynomial supplies both missing fourth-order coefficients in the squared energy"
fn improved_axial_squared(t)
let m_prime=one+axis_mass_coeff*t*t
return two*t+flip(t*t)+m_prime*m_prime
end
let t_pi=two
check improved_axial_squared(t_pi)==fraction(121 trial,9 trial) and two*(fraction(11 trial,3 trial)+flip(one))==fraction(16 trial,3 trial) "the positive pair corner is separated from the rest pair by sixteen thirds"
let t_sample=fraction(2 trial,5 trial)
check improved_axial_squared(t_sample)==one+two*t_sample+share(t_sample*t_sample,three)+fraction(4 trial,9 trial)*power(t_sample,4 trial) "the directly squared spin Hamiltonian equals its strictly increasing axial energy polynomial"
# Two momenta on a two-cell periodic ring: p=0 and pi, total momentum zero.
# Both rest spin products have beta times beta equal to plus one.
let target_rest=fraction(19 trial,10 trial)
let local_green=share(share(one,target_rest+flip(two))+share(one,target_rest+flip(fraction(22 trial,3 trial))),two)
let small_g=flip(fraction(163 trial,830 trial))
check small_g*local_green==one "the exact two-cell contact equation gives the same positive-pair bound pole for both rest-spin contacts"
let corner_ratio=share(target_rest+flip(two),target_rest+flip(fraction(22 trial,3 trial)))
check corner_ratio==fraction(3 trial,163 trial) and share(corner_ratio*corner_ratio,one+corner_ratio*corner_ratio)==fraction(9 trial,26578 trial) "the two-cell bound pair has a nonzero off-resonant corner probability even after detuning"
let joint_hop=fraction(1 trial,10 trial)
fn strength_at_momentum(g,u,cos_k)
return g+u*(one+flip(cos_k))
end
check strength_at_momentum(small_g,joint_hop,one)==small_g and strength_at_momentum(small_g,joint_hop,flip(one))==small_g+two*joint_hop "moving an occupied pair together supplies a new kinetic response while every rest-state energy is preserved"
# Ordered native spin texture: dot the two four-component walk symbols
# after an axial momentum transfer. Energy alone is axis-permutation invariant.
fn walk_symbol_overlap(cxpair,sxpair,cypair,sypair,czpair,szpair)
return (cxpair+sxpair)*cypair*czpair+sypair*czpair+szpair
end
let cpair=fraction(9 trial,25 trial)
let spair=fraction(16 trial,25 trial)
let shifted_sines=fraction(7 trial,25 trial)
let texture_x=walk_symbol_overlap(zero,shifted_sines,cpair,spair,cpair,spair)
let texture_y=walk_symbol_overlap(cpair,spair,zero,shifted_sines,cpair,spair)
let texture_z=walk_symbol_overlap(cpair,spair,cpair,spair,zero,shifted_sines)
check walk_symbol_overlap(cpair,spair,cpair,spair,cpair,spair)==one "the normalized native four-component symbol has unit self-overlap"
check texture_x==fraction(14167 trial,15625 trial) and texture_y==fraction(463 trial,625 trial) and texture_z==shifted_sines "equal axis transfers at a diagonal momentum select three different ordered-spin overlaps"
let transfer_drop=one+flip(shifted_sines)
check one+flip(texture_x)==transfer_drop*cpair*cpair and one+flip(texture_y)==transfer_drop*cpair and one+flip(texture_z)==transfer_drop "the anisotropic spin weights factor from the common transfer of the two band spinors"
gates.py
"""Unitary two-stage axial slice of the six-stage walk in a spatially varying scalar."""
from math import acos, cos, sin, sqrt, tan, exp, pi
W0=.8
def clock(u):return (1-u)/(1+u)
def scale(u):return (1+u)**2
def width(u):return W0*clock(u)/scale(u)
def solve_material(w):
lo,hi=0.,.9
for _ in range(50):
mid=(lo+hi)/2
if width(mid)>w:lo=mid
else:hi=mid
return (lo+hi)/2
def fine_shift(a,b,base,sine,sign):
# Rotate to the local propagation axis, shift unitarily, rotate back at destination.
p=[c*x+sign*s*y for x,y,c,s in zip(a,b,base,sine)]
q=[-sign*s*x+c*y for x,y,c,s in zip(a,b,base,sine)]
p=[p[-1]]+p[:-1];q=q[1:]+[q[0]]
return ([c*x-sign*s*y for x,y,c,s in zip(p,q,base,sine)],
[sign*s*x+c*y for x,y,c,s in zip(p,q,base,sine)])
def envelope(y):
return exp(3*(cos(y-1)-1))*(cos(2*y)+1j*sin(2*y))
def run(n):
eps=.2;mean_speed=.6;h=2*pi/n
labels=[];jac=[];base=[];sine=[]
for j in range(n):
x=j*h
y=x
for _ in range(6):y-=(y+eps*sin(y)-x)/(1+eps*cos(y))
jt=1+eps*cos(y)
w=width(solve_material(mean_speed*jt))
assert abs(w-mean_speed*jt)<2e-15
t=acos(w)/2
labels.append(y);jac.append(jt);base.append(cos(t));sine.append(sin(t))
a=[envelope(y)/sqrt(d) for y,d in zip(labels,jac)];b=[0j]*n
total=sum(abs(v)**2 for v in a)
ticks=n//16
for _ in range(ticks):
a,b=fine_shift(a,b,base,sine,1)
a,b=fine_shift(a,b,base,sine,-1)
time=2*h*ticks
exact=[envelope(y-mean_speed*time)/sqrt(d) for y,d in zip(labels,jac)]
norm=sum(abs(x)**2+abs(y)**2 for x,y in zip(a,b))/total
error=sqrt(sum(abs(x-y)**2+abs(z)**2 for x,y,z in zip(a,exact,b))/total)
assert abs(norm-1)<1e-12
return error
def main():
for u in (0,1/7,.2):
N,A=clock(u),scale(u)
for m0 in (.2,.6):
m=m0*N
w=width(u)*sqrt(tan(m)/m)
assert w<1
k=.0008
observed=acos(cos(m)*(1-2*w*w*sin(k/2)**2))
expected=N*sqrt(m0*m0+(W0*k/A)**2)
assert abs(observed-expected)<1e-12
assert abs(clock(1/7)-.75)<1e-14 and abs(scale(1/7)-64/49)<1e-14
errors=[run(n) for n in (128,256,512,1024)]
print("Fixed-time packet errors:",errors)
assert all(1.75<a/b<2.25 for a,b in zip(errors,errors[1:]))
assert errors[-1]<.04
if __name__=="__main__":
main()
pulse_order.py
"""Order two finite-depth control pulses on the free six-stage walk.
At fixed x momentum and zero z momentum, the two middle y shifts combine
into a single coarse-cell shift. Spin and the added two-state control are
both retained. The localized packet stays away from the periodic seam.
"""
from cmath import exp
from math import acos, ceil, cos, pi, sin, sqrt
SIZE = 128
POSITIONS = tuple(range(-SIZE // 2, SIZE // 2))
UNIFORM = (1.0,) * SIZE
SLOPE = POSITIONS
def spin_x(spin, angle):
co, si = cos(angle), -1j * sin(angle)
return [(co * up + si * down, si * up + co * down) for up, down in spin]
def walk(spin, kx, direction):
"""Apply W = exp(-ikx X/2) shift_y exp(-ikx X/2) or its adjoint."""
tilted = spin_x(spin, direction * kx / 2)
result = []
for y in range(SIZE):
a, b = tilted[(y - direction) % SIZE]
c, d = tilted[(y + direction) % SIZE]
result.append(((a - 1j * b + c + 1j * d) / 2,
(1j * a + b - 1j * c + d) / 2))
return spin_x(result, direction * kx / 2)
def combine(a, left, b, right):
return [(a * u + b * v, a * w + b * z)
for (u, w), (v, z) in zip(left, right)]
def mask(spin, profile):
return [(m * a, m * b) for m, (a, b) in zip(profile, spin)]
def energy(spin, kx):
return combine(0.5j, walk(spin, kx, 1), -0.5j, walk(spin, kx, -1))
def weighted(spin, kx, profile):
return combine(0.5, mask(energy(spin, kx), profile),
0.5, energy(mask(spin, profile), kx))
def stencil_squared(spin, kx):
"""H squared from the independently known cosine-product trace of W."""
t = cos(kx) ** 2 / 4
return [tuple((1 - 2*t)*v - t*(spin[(i-2) % SIZE][j] + spin[(i+2) % SIZE][j])
for j, v in enumerate(pair)) for i, pair in enumerate(spin)]
def distance(a, b):
return max(abs(u-v) for pair, other in zip(a, b) for u, v in zip(pair, other))
def check_finite_profile():
spin = [(exp(0.017j*i*i)/12, exp(-0.027j*(i+3)**2)/14) for i in POSITIONS]
profile = [sin(6*pi*i/SIZE) + 0.37*cos(10*pi*i/SIZE) for i in POSITIONS]
for kx in (0.0, pi/4, 1.138):
assert distance(walk(walk(spin, kx, 1), kx, -1), spin) < 1e-14
direct = combine(1j, energy(weighted(spin, kx, profile), kx),
-1j, weighted(energy(spin, kx), kx, profile))
reference = combine(0.5j, stencil_squared(mask(spin, profile), kx),
-0.5j, mask(stencil_squared(spin, kx), profile))
assert distance(direct, reference) < 1e-13
# (controlled copy, forward or inverse native walk, pulse angle multiplier)
LAYERS = ((1, 1, -1), (0, -1, -1), (1, -1, 1), (0, 1, 1))
def pulse(copies, kx, profile, theta, inverse=False):
"""Conjugate local copy rotations with a controlled W or inverse W."""
for label, direction, weight in (reversed(LAYERS) if inverse else LAYERS):
before = list(copies)
before[label] = walk(before[label], kx, -direction)
after = [[], []]
for (up, down), (u, d), f in zip(before[0], before[1], profile):
angle = theta * weight * f * (-1 if inverse else 1) / 4
c, s = cos(angle), -1j * sin(angle)
after[0].append((c * up + s * u, c * down + s * d))
after[1].append((s * up + c * u, s * down + c * d))
after[label] = walk(after[label], kx, direction)
copies = after
return copies
def packet(carrier):
envelope = [1 + cos(pi*y/9) if abs(y) <= 8 else 0 for y in POSITIONS]
norm = sqrt(sum(a*a for a in envelope))
wave = [a * exp(1j*carrier*y)/norm for a, y in zip(envelope, POSITIONS)]
# An arbitrary coherent spin. Either initial control sector has the same bracket.
spin = [(a/sqrt(2), 1j*a/sqrt(2)) for a in wave]
return [spin, [(0, 0)] * SIZE], wave
def center(copies):
probs = [sum(abs(a)**2 + abs(b)**2 for a, b in pair)
for pair in zip(*copies)]
assert abs(sum(probs) - 1) < 3e-13
return sum(y*p for y, p in zip(POSITIONS, probs))
def closed_sequence(start, kx, theta):
state = pulse(start, kx, UNIFORM, theta, inverse=True)
state = pulse(state, kx, SLOPE, theta, inverse=True)
state = pulse(state, kx, UNIFORM, theta)
return pulse(state, kx, SLOPE, theta)
def loop_displacement(start, kx, theta):
return center(closed_sequence(start, kx, theta)) - center(start)
def echo_readouts():
print("kx/pi ky/pi analytic pulse .04 pulse .02 pulse .01")
for kx, carrier in ((0, 0), (pi/4, 0), (pi/2, 0), (0, pi/2)):
start, wave = packet(carrier)
coherence = sum((v.conjugate()*wave[(i+2) % SIZE]).real
for i, v in enumerate(wave))
predicted = cos(kx)**2 * coherence
measured = []
for t in (0.04, 0.02, 0.01):
# Average opposite signs to remove the odd powers of pulse amplitude.
measured.append((loop_displacement(start, kx, t)
+ loop_displacement(start, kx, -t)) / (2*t*t))
print(f"{kx/pi:.2f} {carrier/pi:.2f} {predicted: .8f} "
+ " ".join(f"{n: .8f}" for n in measured))
assert abs(measured[-1]-predicted) < 0.0007
assert abs(measured[-1]-predicted) <= 0.32*abs(measured[-2]-predicted) + 1e-9
def finite_experiment():
# The sign-paired loops use the actual gates, without extrapolating in angle.
outcomes = []
for kx in (0, pi/4, pi/2):
state, _ = packet(0)
for _ in range(12):
state = closed_sequence(state, kx, 0.2)
state = closed_sequence(state, kx, -0.2)
mean = center(state)
probability = [sum(abs(a)**2 + abs(b)**2 for a, b in pair)
for pair in zip(*state)]
variance = sum(p*(y-mean)**2 for y, p in zip(POSITIONS, probability))
seam_mass = sum(p for y, p in zip(POSITIONS, probability) if abs(y) >= 55)
assert seam_mass < 1e-14
print(f"Finite sequence kx/pi={kx/pi:.2f}: mean {mean:.9f}, "
f"variance {variance:.8f}, outer mass {seam_mass:.2e}")
outcomes.append((mean, variance))
(a, v), (b, w), (c, _) = outcomes
assert a > b > c and a - b > 0.1
trials = ceil(19*(v+w)/(a-b)**2)
print(f"Sufficient independent preparations per setting for a 95% "
f"one-sided sign bound: {trials}")
def clock_phase():
# Separate axial check for the tilted massless gates used in the shell model.
w = 4/5
k = pi/2
phase = acos(1 - w*w*(1-cos(k)))
velocity = w*w*sin(k)/sin(phase)
step = 1e-5
phase_at = lambda p: acos(1 - w*w*(1-cos(p)))
direct = (phase_at(k+step)**2 - phase_at(k-step)**2)/(4*step)
assert abs(phase*velocity-direct) < 1e-10
print(f"Tilted axial clock: phase times velocity {direct:.8f}, "
f"continuum {w*w*k:.8f}, fraction {direct/(w*w*k):.8f}")
if __name__ == "__main__":
check_finite_profile()
echo_readouts()
finite_experiment()
clock_phase()
packet_3d.py
"""Weak displacement of a compact 3D preparation under the six-stage walk.
Coordinates in the sparse dictionary are fine half-cells. Readouts use coarse
cells, and all dictionaries are on the infinite lattice (no numerical seam).
Run with Python 3, using only the standard library.
"""
from cmath import exp
from itertools import product
from math import cos, isclose, pi, sqrt
STAGES = (0, 1, 2, 2, 1, 0)
OFFSETS = (-2, -1, 0, 1, 2)
WEIGHTS = (1, 2, 3, 2, 1)
SPIN = (1 / sqrt(5), 2j / sqrt(5))
def scaled_sum(terms):
out = {}
for factor, state in terms:
for point, (up, down) in state.items():
a, b = out.get(point, (0j, 0j))
out[point] = (a + factor * up, b + factor * down)
return out
def half_shift(state, axis, direction):
"""The two Pauli projectors move one fine site in opposite directions."""
out = {}
for point, (a, b) in state.items():
sa, sb = ((b, a), (-1j*b, 1j*a), (a, -b))[axis]
for s in (-1, 1):
dest = list(point)
dest[axis] += s * direction
dest = tuple(dest)
u, v = out.get(dest, (0j, 0j))
out[dest] = (u + (a + s*sa)/2, v + (b + s*sb)/2)
return out
def walk(state, direction=1):
for axis in (STAGES if direction == 1 else reversed(STAGES)):
state = half_shift(state, axis, direction)
return state
def hamiltonian(state):
return scaled_sum(((0.5j, walk(state)), (-0.5j, walk(state, -1))))
def position(state, axis=1):
return {p: (p[axis]*a/2, p[axis]*b/2) for p, (a, b) in state.items()}
def inner(left, right):
value = 0j
for p, (a, b) in left.items():
u, v = right.get(p, (0j, 0j))
value += a.conjugate()*u + b.conjugate()*v
return value
def distance(left, right):
diff = scaled_sum(((1, left), (-1, right)))
return sqrt(inner(diff, diff).real)
def packet(kx, spin=SPIN):
norm = sum(w*w for w in WEIGHTS)**1.5
amplitudes = dict(zip(OFFSETS, WEIGHTS))
state = {}
for x, y, z in product(OFFSETS, repeat=3):
value = amplitudes[x]*amplitudes[y]*amplitudes[z]*exp(1j*kx*x)/norm
state[2*x, 2*y, 2*z] = tuple(value*s for s in spin)
return state
def bracket(state):
# Explicitly order H and H[Y]={Y,H}/2, retaining the two spin components.
hs = hamiltonian(state)
hys = hamiltonian(position(state))
hhs = hamiltonian(hs)
weighted = scaled_sum(((0.5, position(hs)), (0.5, hys)))
weighted_after_h = scaled_sum(((0.5, position(hhs)),
(0.5, hamiltonian(position(hs)))))
ordered = scaled_sum(((1j, hamiltonian(weighted)), (-1j, weighted_after_h)))
reduced = scaled_sum(((0.5j, hamiltonian(hys)), (-0.5j, position(hhs))))
assert distance(ordered, reduced) < 1e-12
return ordered
def checked_shift(kx, spin=SPIN):
psi = packet(kx, spin)
assert isclose(inner(psi, psi).real, 1, abs_tol=1e-14)
for axis in range(3):
moment = position(psi, axis)
assert abs(inner(psi, moment)) < 1e-14
assert isclose(inner(moment, moment).real, 16/19, abs_tol=1e-14)
stepped = walk(psi)
assert all(all(c % 2 == 0 and abs(c) <= 6 for c in point) for point in stepped)
assert abs(inner(stepped, stepped).real - 1) < 1e-13
assert distance(psi, walk(stepped, -1)) < 1e-12
bpsi = bracket(psi)
assert all(all(c % 2 == 0 and abs(c) <= 8 for c in point) for point in bpsi)
measured = 2*inner(position(psi), bpsi).imag
# Independently difference the centroids of normalized tangent states.
# Their derivatives at zero coincide with those of exp(-i t B) psi.
step = 1e-5
centroids = []
for sign in (-1, 1):
tilted = scaled_sum(((1, psi), (-1j*sign*step, bpsi)))
centroids.append(inner(tilted, position(tilted)).real / inner(tilted, tilted).real)
assert abs((centroids[1] - centroids[0])/(2*step) - measured) < 1e-9
coherence = sum(a*b for a, b in zip(WEIGHTS, WEIGHTS[2:])) / sum(w*w for w in WEIGHTS)
predicted = coherence*(1 + coherence*cos(2*kx))*(1 + coherence)/4
assert abs(measured - predicted) < 1e-12
return measured, predicted
if __name__ == '__main__':
print(f'125 coarse sites occupied; position RMS on each axis = {sqrt(16/19):.9f} coarse cells')
print('Kx direct six-shift bracket coherence prediction')
for label, carrier in (('0', 0), ('pi/4', pi/4), ('pi/2', pi/2)):
measured, predicted = checked_shift(carrier)
print(f'{label:4s} {measured: .9f} {predicted: .9f}')
assert abs(checked_shift(pi/2, (0, 1))[0] - checked_shift(pi/2, (1, 0))[0]) < 1e-12
material_bracket.py
"""Clock-rate commutator and a covariant continuum material. Standard library only."""
from cmath import exp
from math import acos, cos, isclose, pi, prod, sin, sqrt
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def phase(k):
return acos(prod(cos(a) for a in k))
def band_velocity(k):
omega = phase(k)
return [sin(k[i])*prod(cos(k[j]) for j in range(3) if j != i)/sin(omega)
for i in range(3)]
def band_checks():
y = pi/4
for q in (pi/4, .01, .0001):
a, b = (pi/2,y,0), (pi/2,y+q,0)
# Both energies are exactly pi/2 analytically; spinors are (1,exp(i*y))/sqrt(2).
assert isclose(phase(a),phase(b),abs_tol=1e-14)
overlap = (1+exp(-1j*(y+q))*exp(1j*y))/2
translation = 1j*q*(y+q/2)*overlap
assert isclose(abs(translation),q*(y+q/2)*cos(q/2))
print(f'Q={q:.6f}: equal-energy clock commutator 0; '
f'translation magnitude {abs(translation):.9f}, per Q {abs(translation)/q:.9f}')
k = (pi/4,pi/4,0)
assert isclose(phase(k)*band_velocity(k)[0]/k[0],4/(3*sqrt(3)))
for scale in (.08,.04,.02):
x,y,z = [scale*t for t in (1.,.7,-.4)]
exact = phase((x,y,z))*band_velocity((x,y,z))[0]
cubic = x*(1-(y*y+z*z)/3)
assert abs(exact-cubic) < .1*scale**5
def solve3(matrix, rhs):
a = [list(row)+[v] for row,v in zip(matrix,rhs)]
for i in range(3):
pivot = max(range(i,3), key=lambda j: abs(a[j][i]))
a[i],a[pivot] = a[pivot],a[i]
divisor = a[i][i]
if abs(divisor) < 1e-12:
raise ValueError('singular material gradients')
a[i] = [v/divisor for v in a[i]]
for j in range(3):
if j != i:
factor = a[j][i]
a[j] = [u-factor*v for u,v in zip(a[j],a[i])]
return [row[-1] for row in a]
def lagrangian(state):
# q are the three scalar material labels and the ray phase theta.
# First four entries are time derivatives, then four rows of spatial derivatives.
v = state[:4]
j = [state[4+3*a:7+3*a] for a in range(3)]
p = state[13:]
drift = solve3(j,[-x for x in v[:3]])
gamma = 1/sqrt(1-dot(drift,drift))
frequency = gamma*(v[3]+dot(drift,p))
k = [dot(row,p)-v[a]*v[3] for a,row in enumerate(j)]
strain_trace = sum(dot(row,row)-v[a]**2 for a,row in enumerate(j))
rho = (strain_trace-1)/2
y = frequency+phase(k)
return -rho+y*y # g=1/2
def shifted(state, increments):
trial = list(state)
for i, size in increments:
trial[i] += size
return lagrangian(trial)
def first(state, i, step=3e-5):
def f(m):
return shifted(state,[(i,m*step)])
return (f(-2)-8*f(-1)+8*f(1)-f(2))/(12*step)
def velocity_hessian(state, step):
result = []
for i in range(4):
row = []
for j in range(4):
mixed = sum(a*b*shifted(state,[(i,a*step),(j,b*step)])
for a in (-1,1) for b in (-1,1))
row.append(mixed/(4*step*step))
result.append(row)
return result
def cholesky_diagonal(matrix):
lower = [[0.]*4 for _ in range(4)]
for i in range(4):
for j in range(i+1):
residual = matrix[i][j]-dot(lower[i][:j],lower[j][:j])
if i==j:
assert residual > 0
lower[i][i] = sqrt(residual)
else:
lower[i][j] = residual/lower[j][j]
return [lower[i][i] for i in range(4)]
def check_material(state):
# Legendre identities h_pi = qdot; h_gradient = -L_gradient at fixed pi.
derivatives = [first(state,i) for i in range(16)]
momenta = derivatives[:4]
energy_bracket = [-sum(state[a]*derivatives[4+3*a+i] for a in range(4))
for i in range(3)]
shift_density = [sum(momenta[a]*state[4+3*a+i] for a in range(4))
for i in range(3)]
error = max(abs(a-b) for a,b in zip(energy_bracket,shift_density))
assert error < 1e-9
return momenta, shift_density, error
def material_checks():
rest = [0.,0.,0.,-pi/2-.1, 1.,0.,0., 0.,1.,0., 0.,0.,1., pi/2,pi/4,0.]
mom, shift, _ = check_material(rest)
n = .2
assert isclose(-mom[3], n, abs_tol=1e-10)
velocity = band_velocity(rest[13:])
for i in range(3):
total = n*(phase(rest[13:])+.5*n)*velocity[i]
assert abs(-shift[i]-total)<1e-10
assert abs(mom[i]-(n*rest[13+i]-total))<1e-10
print('rest physical total momentum =',tuple(round(-p,9) for p in shift))
tilted = [.04,-.08,.06,-1.34, 1.03,.04,-.02, .10,.95,.03, .02,-.04,1.02, 1.2,.3,-.4]
mom, shift, error = check_material(tilted)
chol = cholesky_diagonal(velocity_hessian(tilted,1e-4))
refined = cholesky_diagonal(velocity_hessian(tilted,5e-5))
assert max(abs(a-b) for a,b in zip(chol,refined)) < 2e-6
print('tilted phase action density =',round(-mom[3],9))
print('tilted shift-generator density =',tuple(round(p,9) for p in shift))
print(f'local deformation bracket residual {error:.2g}')
print('velocity Hessian Cholesky diagonal =',tuple(round(v,6) for v in chol))
if __name__ == '__main__':
band_checks()
material_checks()
cesium_band.py
"""Ground-band curvature for the cesium standing wave of Ben Dahan et al. (1996).
Run with python3 cesium_band.py. No dependencies or fitted parameters.
"""
from math import exp
def ground_energy(x, depth, cutoff):
"""E/E_R in the plane-wave basis exp[i k(x+2j)z], -cutoff <= j <= cutoff."""
diagonal = [(x+2*j)**2 + depth/2 for j in range(-cutoff, cutoff+1)]
coupling_sq = (depth/4)**2
low = min(diagonal)-depth/2-1
high = min(diagonal)
for _ in range(64):
mid = (low+high)/2
# Cholesky pivots of H-mid*I are positive iff mid is below the ground state.
pivot = diagonal[0]-mid
for d in diagonal[1:]:
if pivot <= 0.:
break
pivot = d-mid-coupling_sq/pivot
if pivot > 0.:
low = mid
else:
high = mid
return (low+high)/2
def band_curvature(x, depth, cutoff, h):
# Return m_Cs/m* = (1/2) d²(E/E_R)/d(q/k)².
weights = (-1, 16, -30, 16, -1)
return sum(w*ground_energy(x+(j-2)*h, depth, cutoff)
for j,w in enumerate(weights))/(24*h*h)
def broadened_mass(centre, depth, cutoff, h, gaussian_step=.10):
# The paper convolves mean velocity with a Gaussian in q. Differentiating
# commutes with convolution, so average curvature before taking the inverse.
tail = round(6/gaussian_step)
nodes = [i*gaussian_step for i in range(-tail, tail+1)]
weights = [exp(-z*z/2) for z in nodes]
curvature = sum(w*band_curvature(centre+z/18, depth, cutoff, h)
for z,w in zip(nodes,weights))/sum(weights)
return 1/curvature
def figure_readout():
# Pixel rows in Fig. 4(b), PDF page 4, embedded 1284x804 Fig. 4 bitmap.
# Tick centers for +2 and -2, measured downward from its top.
plus_two, minus_two = 76.5, 599.
pixels_per_mass = (minus_two-plus_two)/4
zero = (plus_two+minus_two)/2
print('Fig. 4(b) approximate graphic readings at U0/E_R = 5.7:')
for label, centre, top, bottom in (('q=0',101.,62.,140.), ('q=k',584.5,532.,638.)):
observed = (zero-centre)/pixels_per_mass
half_bar = (bottom-top)/(2*pixels_per_mass)
print(f'{label}: marker {observed:+.2f}, plotted vertical half-span {half_bar:.2f} m_Cs')
def main():
figure_readout()
depth = 5.7
print('q/k band mass/m_Cs Gaussian-averaged response mass/m_Cs')
for centre in (0., 1.):
mass = 1/band_curvature(centre, depth, 7, .003)
smooth = broadened_mass(centre, depth, 7, .003)
assert abs(mass-1/band_curvature(centre,depth,9,.0015)) < 1e-6
assert abs(smooth-broadened_mass(centre,depth,9,.0015,.05)) < 1e-6
print(f'{centre:.0f} {mass:+.6f} {smooth:+.6f}')
assert abs(band_curvature(0.,0.,4,.003)-1) < 1e-8
if __name__ == '__main__':
main()
cell.py
"""Solve a sourced finite scalar lattice and measure the adiabatic loading of a clock."""
from fractions import Fraction as F
from itertools import product
SITES=tuple(product((-1,0,1), repeat=3))
INDEX={x:i for i,x in enumerate(SITES)}
CENTRE=INDEX[(0,0,0)]
N=len(SITES)
NEIGHBORS=[]
for x in SITES:
row=[]
for axis,sign in product(range(3),(-1,1)):
y=list(x);y[axis]+=sign
if tuple(y) in INDEX:row.append(INDEX[tuple(y)])
NEIGHBORS.append(row)
def clock(x):return (1-x)/(1+x)
def solve(a,b):
# Positive Dirichlet stiffness makes Gaussian elimination possible without row exchanges.
m=[r.copy()+[v] for r,v in zip(a,b)]
for i in range(len(b)):
assert m[i][i]>0
for j in range(i+1,len(b)):
s=m[j][i]/m[i][i]
for k in range(i,len(b)+1):m[j][k]-=s*m[i][k]
result=[0.]*len(b)
for i in reversed(range(len(b))):
result[i]=(m[i][-1]-sum(m[i][j]*result[j] for j in range(i+1,len(b))))/m[i][i]
return result
def equilibrium(mass,probe):
mu=[mass if sum(t*t for t in x)==1 else 0 for x in SITES]
mu[CENTRE]=probe
u=[0.]*N
for _ in range(10):
lap=[6*x-sum(u[j] for j in row) for x,row in zip(u,NEIGHBORS)]
grad=[z-2*m/(1+x)**2 for z,m,x in zip(lap,mu,u)]
h=[[0.]*N for _ in u]
for i in range(N):
h[i][i]=6+4*mu[i]/(1+u[i])**3
for j in NEIGHBORS[i]:h[i][j]=-1
if max(map(abs,grad))<1e-14:break
u=[x-d for x,d in zip(u,solve(h,grad))]
else:raise ArithmeticError("Equilibrium did not converge")
energy=sum(.5*x*z+m*clock(x) for x,z,m in zip(u,lap,mu))
return u,energy,h
def main():
s=F(1,7)
mass=F(17,10)*s*(1+s)**2
assert mass==F(544,1715) and clock(s)==F(3,4)
state,base,h=equilibrium(float(mass),0)
for pos,u in zip(SITES,state):
predicted=(s,s,2*s/5,s/5)[sum(v*v for v in pos)]
assert abs(u-float(predicted))<2e-15
inv=solve(h,[int(i==CENTRE) for i in range(N)])[CENTRE]
assert abs(inv-7/34)<1e-14
eps=.0002
small=equilibrium(float(mass),eps)[1]-base
twice=equilibrium(float(mass),2*eps)[1]-base
second=(twice-2*small)/eps**2
predicted=-float(F(16807,34816))
assert abs(second-predicted)<.0003
assert abs((4*small-twice)/(2*eps)-.75)<2e-8
test=.01
loaded=equilibrium(float(mass),test)[1]-base
vacuum=equilibrium(0.,test)[1]
print("Central scalar",state[CENTRE],"weak-clock rate",clock(state[CENTRE]))
print("Inverse central stiffness",inv,"relaxed curvature",predicted)
print("Finite probe (gap 0.01 in spring units) loaded/empty frequency ratio",loaded/vacuum)
if __name__=="__main__":
main()
shell.py
"""Spherical material shell benchmark. Run with python3 shell.py (standard library)."""
from decimal import Decimal as D, getcontext
from fractions import Fraction as F
from math import isclose, sqrt
getcontext().prec = 55
# Geometrized units G=c=1, R0=1. Energies have units of length.
MU = F(1, 4)
W = F(1, 12)
ETA = F(1, 3)
def number(f):
return D(f.numerator)/D(f.denominator)
def proper_energy(area_ratio):
return (3*area_ratio + 13*area_ratio**(-D(1)/3))/64
def static_action(q, psi, chi):
radius = q*psi**2
return 2*q*(psi-1)*(chi-1) - chi/psi*proper_energy(radius**2)
def static_adm(radius):
energy = proper_energy(radius**2)
return energy-energy**2/(2*radius)
def omitted_equation(r, a, d):
"""Covariant radial and Cartesian transverse components from the metric."""
psi = 1+a/r
dp, ddp = -a/r**2, 2*a/r**3
lapse = (r+d)/(r+a)
dn, ddn = (a-d)/(r+a)**2, -2*(a-d)/(r+a)**3
ric_rad = -2*ddp/psi + 4*(dp/psi)**2
ric_tan = -2*dp/(r*psi) - 2*(dp/psi)**2
hess_rad = ddn - 2*dp*dn/psi
hess_tan = dn/r + 2*dp*dn/psi
return (psi**2*(lapse*ric_rad-hess_rad),
psi**2*(lapse*ric_tan-hess_tan))
def check_radial_energy():
radius = D(1)
step = D('0.000001')
e0 = proper_energy(radius**2)
area_pressure = -(proper_energy(1+step)-proper_energy(1-step))/(2*step)
assert abs(area_pressure/e0-number(W)) < D('1e-12')
first = (static_adm(radius+step)-static_adm(radius-step))/(2*step)
second = (static_adm(radius+step)-2*static_adm(radius)+static_adm(radius-step))/step**2
exact = (1-MU)*(4*ETA*(1+W)-2*W)-MU*(1+2*W)**2
assert exact == F(89,144)
assert abs(first) < D('1e-12') and abs(second/e0-number(exact)) < D('1e-10')
eta_crit = W*(3+8*W+8*W**2)/(2*(1+W))
assert eta_crit == F(67,468)
assert (1-MU)**2*exact == F(89,256)
print(f'radial stiffness R^2 U"/E = {exact}, numerical {second/e0:.10f}')
print(f'critical dP/dsigma = {eta_crit}; example {ETA}')
def check_junction():
for radius in (.8, 1., 1.2):
energy = float(proper_energy(D(str(radius))**2))
for velocity in (0., .1, -.23):
adm = energy*sqrt(1+velocity**2)-energy**2/(2*radius)
left = sqrt(1+velocity**2)-sqrt(1-2*adm/radius+velocity**2)
assert isclose(left, energy/radius)
# Independent static extrinsic-curvature jump, P/sigma in G=c=1 units.
mass = float(static_adm(D(1)))
lapse = sqrt(1-2*mass)
w_israel = ((1-mass)/lapse - 1)/(2*(1-lapse))
assert isclose(w_israel, float(W))
print(f'junction M/R = {mass:.8f}, interior clock rate {lapse:.8f}')
def check_statics():
p = 1/(1-MU/2)
h, q = 2-p, 1/p**2
a = q*(p-1)
assert a == F(7,64) and h/p == F(3,4)
point = list(map(number,(q,p,h)))
step = D('0.000001')
for axis in range(3):
above, below = list(point), list(point)
above[axis] += step
below[axis] -= step
assert abs((static_action(*above)-static_action(*below))/(2*step)) < D('1e-10')
assert abs(static_action(*point)+static_adm(D(1))) < D('1e-52')
for r in (1., 2.3, 5.):
for d in (-float(a), .15):
radial, transverse = omitted_equation(r,float(a),d)
residual = (float(a)+d)/r**3
assert abs(radial+2*residual) < 1e-14
assert abs(transverse-residual) < 1e-14
print(f'isotropic radius q={q}, exterior parameter a={a}, p={p}, h={h}')
def causal_limit():
lo, hi = 0., 1.
for _ in range(70):
w = (lo+hi)/2
if 8*w**3+8*w*w+w-2 < 0:
lo = w
else:
hi = w
w = (lo+hi)/2
mu = 4*w/(1+4*w)
print(f'causal radial threshold w={w:.9f}, mu={mu:.9f}, '
f'N={1-mu:.9f}, GM/(Rc^2)={mu*(1-mu/2):.9f}')
if __name__ == '__main__':
check_statics()
check_junction()
check_radial_energy()
causal_limit()
nested.py
"""Exact static scalar shell stations, their material pressure, and two annular clocks."""
from fractions import Fraction as F
from math import sqrt
def rods(u):
return (1+u)**2
def lapse(u):
return (1-u)/(1+u)
def radial_slope(offset, coefficient, r):
return (1+offset-coefficient/r)/(1+offset+coefficient/r)
def shell_material(r,u,ai,ao):
area_factor=rods(u)
proper_radius=r*area_factor
n=lapse(u)
slope=-2*(ao*ao-ai*ai)/(r*r*n*area_factor)
mu=(4*(ao-ai)+2*n*slope*r*(1+u))*area_factor/2
pressure_ratio=-proper_radius*slope/(2*mu)
return mu,proper_radius,pressure_ratio
def rest_energy(ratio,mu,w,eta):
# A two-dimensional material with dp/dsigma=eta, in units c=1.
return mu*((eta-w)*ratio+(1+w)*ratio**(-eta))/(1+eta)
def finite_hessian(f,x,h=1e-4):
def offset(changes):
v=x.copy()
for i,z in changes:v[i]+=z
return f(v)
n=len(x);m=[[0.]*n for _ in x];centre=f(x)
for i in range(n):
pos,neg=offset([(i,h)]),offset([(i,-h)])
assert abs((pos-neg)/(2*h))<2e-6
m[i][i]=(pos+neg-2*centre)/h**2
for j in range(i):
m[i][j]=m[j][i]=sum(a*b*offset([(i,a*h),(j,b*h)]) for a in (-1,1) for b in (-1,1))/(4*h*h)
return m
def pivots(m):
a=[r.copy() for r in m];out=[]
for i,row in enumerate(a):
v=row[i];out.append(v)
for j in range(i+1,len(a)):
factor=a[j][i]/v
for k in range(i+1,len(a)):a[j][k]-=factor*row[k]
return out
def pair_transfer(mu1, mu2, radius1, radius2):
"""GR branch in areal coordinates, with positive inner and outer slopes."""
def outside(mass, proper_mass, radius):
inside_slope = sqrt(1 - 2*mass/radius)
outside_slope = inside_slope - proper_mass/radius
if outside_slope <= 0:
raise ValueError("Both shells must remain on the ordinary static branch")
return mass + proper_mass*(inside_slope + outside_slope)/2, inside_slope, outside_slope
inner_mass, _, inner_slope = outside(0, mu1, radius1)
final_mass, gap_slope, outer_slope = outside(inner_mass, mu2, radius2)
inner_clock = inner_slope * outer_slope/gap_slope
return final_mass, inner_clock, outer_slope
def check_pair_transfer():
# The four one-sided slopes are inferred from the areal mass and junction.
r1, r2 = F(8), F(224, 15)
mu1, mu2 = F(2), F(28, 15)
b1, a2, b2 = F(3, 4), F(7, 8), F(3, 4)
m1, m2 = r1*(1-b1*b1)/2, r2*(1-b2*b2)/2
assert (m1, m2) == (F(7,4), F(49,15))
assert 1-2*m1/r2 == a2*a2 and (r1*(1-b1), r2*(a2-b2)) == (mu1, mu2)
n1, n2 = b1*b2/a2, b2
assert (n1, n2) == (F(9,14), F(3,4))
point = tuple(map(float, (mu1, mu2, r1, r2)))
totals = pair_transfer(*point)
assert max(abs(x-y) for x,y in zip(totals, (m2, n1, n2))) < 1e-14
# Numerically vary each physical shell input, keeping the other three fixed.
def perturb(index, step):
args = list(point)
args[index] += step
return pair_transfer(*args)
h = 1e-5
slopes = []
for i in range(4):
plus, minus = perturb(i, h), perturb(i, -h)
slopes.append(tuple((p-m)/(2*h) for p, m in zip(plus, minus)))
# Israel pressure: 8*pi*R*p = (1/b + b - 1/a - a)/2.
work1 = n1 * (1/b1 + b1 - 2)/2
work2 = n2 * (1/b2 + b2 - 1/a2 - a2)/2
assert (work1,work2) == (F(3,112), F(11,448))
assert max(abs(row[0]-expected) for row,expected in
zip(slopes, (n1,n2,work1,work2))) < 2e-9
cross = -b1/(r2*a2)
assert cross == F(-45,784)
assert max(abs(slopes[1][1]-cross), abs(slopes[0][2]-cross)) < 2e-9
print("GR shell transfer: exterior mass", m2, "inner and outer clocks", n1, n2)
print("ADM mass derivatives by input (mu1, mu2, R1, R2):", [row[0] for row in slopes])
print("Cross responses dN1/dmu2 and dN2/dmu1:", slopes[1][1], slopes[0][2],
"exact", cross)
def main():
# c=G=1. Inside a shell ai, outside ao are the 1/r coefficients of u.
m,R,w=shell_material(F(49,16),F(1,7),F(0),F(7,16))
assert (m,R,w)==(1,4,F(1,12))
assert m*lapse(F(1,7))+2*F(7,16)*F(1,7)==F(7,8)
d,a=F(1,10),F(1,4)
radii=(F(4,5),F(3));u=tuple(d+a/r for r in radii)
jumps=(a,F(11,20)-a)
mats=[shell_material(radii[0],u[0],F(0),a),
shell_material(radii[1],u[1],a,F(11,20))]
assert [t[0] for t in mats]==[F(1243,1600),F(781,1200)]
assert [t[2] for t in mats]==[F(125,517),F(96,539)]
e=sum(mat[0]*lapse(v)+2*j*v for mat,v,j in zip(mats,u,jumps))
assert e==F(209,192) and 2*sum(jumps)-e==F(11,960)
def energy(x):
r1,r2,z1,z2=x
field=2*((z1-z2)**2/(1/r1-1/r2)+r2*z2*z2)
for r,z,(mass,rad,w) in zip((r1,r2),(z1,z2),mats):
ratio=(r*rods(z)/float(rad))**2
field+=lapse(z)*rest_energy(ratio,float(mass),float(w),.8)
return field
x=list(map(float,(*radii,*u)))
assert abs(energy(x)-float(e))<1e-12
stiffness=pivots(finite_hessian(energy,x))
ratio=(lapse(d+a/2)/lapse(d+a))/(radial_slope(d,a,F(2))/radial_slope(d,a,F(1)))
assert ratio==F(527,507)
for r in (1.,1.4,2.):
# Independent local, measured derivative of areal radius per rod length.
h=1e-5
observed=((r+h)*rods(float(d+a/(r+h)))-(r-h)*rods(float(d+a/(r-h))))/(2*h*rods(float(d+a/r)))
assert abs(observed-float(radial_slope(d,a,r)))<2e-10
print("Single shell: proper mass 1, areal radius 4, pressure/energy 1/12, total and exterior mass 7/8.")
print("Two shells: total",e,"exterior",2*sum(jumps),"clock/rod ratio",ratio)
print("Reduced spherical static-energy pivots at dp/dsigma=0.8:",stiffness)
assert min(stiffness)>0
# Stable evaluation of the very small departure from unity at laboratory scale.
gc=6.67430e-11/299792458**2
outer=gc*1000/(2*1.0)
z1,z2=gc*10/(2*.2),gc*10/(2*.4)
gap=2*outer*(z1-z2)/((1+outer-z2)*(1-outer-z1))
print("Illustrative laboratory shell shift",2*outer,"nested ratio minus unity",gap)
assert 6.8e-51<gap<7.0e-51
check_pair_transfer()
if __name__=="__main__":
main()
breathing.py
"""Weak-field radiation from a spherical elastic surface; standard library."""
from math import cos, isclose, pi, sin, sqrt
def form(x):
if abs(x) < .01:
return 4/3-x*x/5+x**4/105
return sin(x)/x + (sin(x)/x-cos(x))/x**2
def integrate(function, panels=160):
"""Mean over direction cosine mu in [-1,1], composite Simpson rule."""
step = 2/panels
total = function(-1)+function(1)
for i in range(1,panels):
total += (4 if i%2 else 2)*function(-1+i*step)
return total*step/6
def retarded_source(x, amplitude, phase):
"""In M=R=c=1 units return excess above rest mass.
Use the source through first order in amplitude, evaluated on the moving
shell. Opposite-amplitude differencing extracts its linear response.
"""
def direction(mu):
# theta = Omega*t_emit is implicit even at fixed observer time.
theta = phase+mu*x
for _ in range(10):
theta = phase+mu*x*(1+amplitude*cos(theta))
speed = -amplitude*x*sin(theta)
stress = -amplitude*x*x*cos(theta)
# Subtract the static integrand before summation for numerical precision.
return (stress+mu*speed)/(1-mu*speed)
return integrate(direction)
def response(x, phase):
amplitude = 1e-5
return (retarded_source(x,amplitude,phase)-retarded_source(x,-amplitude,phase))/(2*amplitude)
def detector_check():
"""Ideal equal-arm, long-wavelength response at the GW170817 merger epoch.
Arm directions are from LALSuite 7.26, lal/LALDetectors.h (Earth-fixed).
GWOSC gives 2017-08-17 12:41:04.43 UTC. The optical position is Coulter et al.
"""
from datetime import datetime, timezone
from math import radians
arms = {
'H1': ((-.22389266154,.79983062746,.55690487831),
(-.91397818574,.02609403989,-.40492342125)),
'L1': ((-.95457412153,-.14158077340,-.26218911324),
(.29774156894,-.48791033647,-.82054461286)),
'V1': ((-.70045821479,.20848948619,.68256166277),
(-.05379255368,-.96908180549,.24080451708)),
}
def dot(u,v):
return sum(a*b for a,b in zip(u,v))
def mix(a,b,x,y):
return tuple(x*p+y*q for p,q in zip(a,b))
def patterns(arm_a,arm_b,n,p,q):
# D=(arm_a arm_a - arm_b arm_b)/2; columns correspond to
# projections onto an orthonormal triad of sky and two tangent axes.
an,ap,aq = (dot(arm_a,v) for v in (n,p,q))
bn,bp,bq = (dot(arm_b,v) for v in (n,p,q))
longitudinal = (an*an-bn*bn)/2
breathing = (ap*ap+aq*aq-bp*bp-bq*bq)/2
plus = (ap*ap-aq*aq-bp*bp+bq*bq)/2
cross = ap*aq-bp*bq
assert abs(breathing+longitudinal) < 3e-10
return breathing, sqrt(plus*plus+cross*cross)
epoch = datetime(2017,8,17,12,41,4,430000,tzinfo=timezone.utc)
jd_offset = epoch.timestamp()/86400 + (2440587.5-2451545.)
centuries = jd_offset/36525
# Mean Greenwich sidereal angle, using UTC as the UT1 approximation.
gmst = radians((280.46061837+360.98564736629*jd_offset
+.000387933*centuries**2-centuries**3/38710000)%360)
ra = radians(15*(13+9/60+48.085/3600))
dec = -radians(23+22/60+53.343/3600)
angle = ra-gmst
n = (cos(dec)*cos(angle),cos(dec)*sin(angle),sin(dec))
p = (-sin(angle),cos(angle),0)
q = (-sin(dec)*cos(angle),-sin(dec)*sin(angle),cos(dec))
for label,(a,b) in arms.items():
breathing, tensor = patterns(a,b,n,p,q)
rotated = patterns(a,b,n,mix(p,q,cos(.73),sin(.73)),mix(p,q,-sin(.73),cos(.73)))
assert all(abs(x-y)<1e-12 for x,y in zip((breathing,tensor),rotated))
print(f'{label}: D:nn={-breathing:+.6f}, F_b={breathing:+.6f}, '
f'tensor quadrature norm={tensor:.6f}')
# Unit arms at arbitrary non-right angle in a controlled laboratory setting.
n,p,q = (1,0,0),(0,1,0),(0,0,1)
for angle in (.25,pi/4,pi/2):
a,b = (1,0,0),(cos(angle),sin(angle),0)
assert abs(patterns(a,b,n,p,q)[0]+sin(angle)**2/2)<1e-14
def main():
detector_check()
for eta in (.0025,.0625,.25,1/3,1):
x = 2*sqrt(eta)
h = form(x)
angular = integrate(lambda mu: (3-mu*mu)*cos(x*mu)/2)
assert abs(angular-h) < 1e-8
measured = -response(x,0)/x**2
assert abs(measured-h) < 1e-8
assert abs(response(x,pi/2)) < 1e-12
# Independently integrate the far energy flux over a cycle by
# differentiating the retarded waveform in observer phase.
dphase, phases = 1e-4, 20
flux = 0.
for j in range(phases):
phase = 2*pi*j/phases
derivative = (response(x,phase+dphase)-response(x,phase-dphase))/(2*dphase)
flux += derivative*derivative/phases
assert isclose(flux/x**4,h*h/2,rel_tol=1e-7)
print(f'eta={eta:.6f} x={x:.6f} H={h:.9f} retarded H={measured:.9f} '
f'power coefficient={flux/x**4:.9f}')
# Local surface balance from pressure: M xi_ddot = 8 pi R deltaP.
m, c, r, a, eta = 4., 7., 2., .001, .3
sigma = m*c*c/(4*pi*r*r)
delta_p = -2*eta*sigma*a/r
omega = 2*sqrt(eta)*c/r
assert isclose(8*pi*r*delta_p/m, -omega**2*a)
assert isclose(8*pi*r*r*delta_p, -m*r*omega**2*a)
assert isclose(form(.00001),4/3,rel_tol=1e-10)
if __name__ == '__main__':
main()
rod.py
"""Calibrate a composite rod, breakup threshold and center-of-mass motion.
Run with Python 3.9+ and the standard library. The chain is analytic.
The unconfined cubic calculation integrates infinite-lattice Fourier modes.
"""
from fractions import Fraction
from math import asinh, cos, isclose, log, pi, sqrt
def check_chain():
# Dimensionless g=|U|/(4J). Units are a=J0=1 before rescaling.
lapse = Fraction(4,5)
scale = Fraction(16,9)
j0, j1 = 1, 3*lapse/8
u0, u1 = 3, 2*lapse
checks = []
for j,u,w in ((j0,u0,Fraction(5,4)),(j1,u1,Fraction(5,3))):
g = Fraction(u)/(4*j)
assert w*w == 1+g*g
delta = 4*j*(w-1)
radius2 = 1/(2*g*g)
curvature = j/w
checks.append((delta,radius2,curvature,curvature/(delta*radius2)))
q = w-g # amplitude ratio per site
at = lambda n: float(q)**abs(n)
energy = -4*j*w
# Independently apply the original relative-coordinate hopping.
for n in range(-48,49):
image = -2*j*(at(n-1)+at(n+1)) - (u*at(n) if n==0 else 0)
assert isclose(image,energy*at(n),abs_tol=1e-14)
samples = [n for n in range(-48,49)]
norm = sum(at(n)**2 for n in samples)
observed = sum(n*n*at(n)**2 for n in samples)/norm
assert isclose(observed,radius2,abs_tol=1e-13)
print(f"chain g={g}, P(1)/P(0)={q*q}, C={checks[-1][-1]}")
old,new = checks
assert new[0]/old[0] == lapse
assert new[1]/old[1] == 1/scale**2
assert new[2]/old[2]/(lapse/scale**2) == Fraction(8,9)
assert (old[3],new[3]) == (Fraction(9,10),Fraction(4,5))
assert isclose(asinh(0.75)/asinh(4/3),log(2)/log(3))
print("RMS and clock calibrations pass; scaled band curvature = 8/9.")
def transverse(grid):
c = [cos(2*pi*i/grid) for i in range(grid)]
return [12-4*(a+b) for a in c for b in c]
def cubic(delta, grid):
# Analytic inverse transform in x at fixed q_y,q_z:
# f_n = r^|n|/sqrt(A²-16), A=12+delta-4*cos(q_y)-4*cos(q_z).
t = transverse(grid)
mean, norm, moment, neighbor = 0.0,0.0,0.0,0.0
for v in t:
a = v+delta
root = sqrt(a*a-16)
f0 = 1/root
r = 4/(a+root)
s = r*r
mean += f0
norm += f0*f0*(1+s)/(1-s)
moment += 2*f0*f0*s*(1+s)/(1-s)**3
neighbor += 2*f0*f0*r/(1-s)
u=grid**2/mean
return u,sqrt(moment/norm),neighbor/norm
def cubic_fourier(delta,grid):
# Independent three-dimensional Fourier integrals. Differentiating the
# momentum wavefunction yields the imaged second moment via Parseval.
c = [cos(2*pi*i/grid) for i in range(grid)]
transverse_values = transverse(grid)
integrals = [0.0]*4
for x in c:
for v in transverse_values:
f = 1/(delta+v-4*x)
f2 = f*f
integrals[0] += f
integrals[1] += f2
integrals[2] += 16*(1-x*x)*f2*f2
integrals[3] += x*f2
near,norm,moment,corr = integrals
return grid**3/near,sqrt(moment/norm),corr/norm
def dispersion_check(delta, interaction, expected, grid=64):
# Solve the bound-state energy anew with a small dimensionless COM wavevector.
k = 0.01
span = 4*cos(k/2)
t = transverse(grid)
low,high = delta-0.01,delta+0.01
for _ in range(48):
trial = (low+high)/2
green = sum(1/sqrt((trial+v)**2-span*span) for v in t)/len(t)
if green > 1/interaction:
low = trial
else:
high = trial
fitted = 2*(delta-(low+high)/2)/(k*k)
assert isclose(fitted,expected,rel_tol=1e-5), (fitted,expected)
def main():
check_chain()
records=[]
for delta in (0.5,2.0):
values=cubic(delta,96)
for check in (cubic(delta,64),cubic_fourier(delta,64)):
assert all(isclose(a,b,abs_tol=5e-10) for a,b in zip(values,check))
u,radius,curvature=values
dispersion_check(delta,u,curvature)
invariant = curvature/(delta*radius*radius)
records.append((delta,radius,curvature,invariant))
print(f"cubic delta={delta:g}, U/J={u:.8f}, Rx/a={radius:.8f}, "
f"D/(J*a²)={curvature:.8f}, C={invariant:.8f}")
old,new=records
scale=old[1]/new[1]
observed=old[0]/new[0]*new[2]/old[2]
score=observed*scale**2
assert isclose(score,new[3]/old[3],abs_tol=1e-12)
print(f"calibrated cubic length factor={scale:.8f}; band curvature/prediction={score:.8f}")
if __name__ == "__main__":
main()
pressure.py
"""Static reciprocal response of thin light sheets and cold matter."""
from fractions import Fraction as F
def stress(energy,xx,yy,xy=0):
return ((energy,0,0,0),(0,xx,xy,0),(0,xy,yy,0),(0,0,0,0))
def residue(a,b):
# Both indices raised in the (-+++) convention. Transfer is along z.
metric=(-1,1,1,1)
trace=lambda t:sum(metric[i]*t[i][i] for i in range(4))
contraction=sum(metric[i]*metric[j]*a[i][j]*b[i][j] for i in range(4) for j in range(4))
return 2*contraction-trace(a)*trace(b)
def stable_kernel(x,y,modes):
return sum(a*b/stiffness for a,b,stiffness in zip(x,y,modes))
def main():
dust=stress(1,0,0)
light=stress(1,F(1,2),F(1,2))
beamx,beamy=stress(1,1,0),stress(1,0,1)
tilt=stress(1,F(9,25),F(16,25),F(12,25))
assert tuple(residue(a,b) for a,b in ((dust,dust),(dust,light),(light,light)))==(1,2,3)
assert residue(dust,dust)*residue(light,light)-residue(dust,light)**2==-1
assert residue(beamx,beamx)==4 and residue(beamx,beamy)==2
assert residue(beamx,tilt)==2+2*F(9,25)
for t in (dust,light,tilt):assert all(x==0 for x in t[3])
# Even extra independent attractive channels cannot lower 4 after a fit to 1,2.
for y in (F(0),F(1),F(-2,3)):
d=(F(1),0)
l=(F(2),y)
k=(F(1),F(5))
assert stable_kernel(d,l,k)==2
assert stable_kernel(l,l,k)-4==y*y/5
print("Normalized dust/dust, dust/light sheet, and light sheet/light sheet:",1,2,3)
print("After fitting the first two, stable unconstrained reciprocal scalar exchange predicts at least 4.")
print("Balanced single-axis light sheets, parallel vs perpendicular:",4,2)
if __name__=="__main__":
main()
constrained.py
"""Constrained static stress exchange. All checks use the Python standard library."""
from fractions import Fraction as F
from math import cos, isclose, pi, sin, sqrt
def add(a, b):
return [x+y for x, y in zip(a,b)]
def inner(a, b):
return sum(x*y for x,y in zip(a,b))
def gradient(phi):
return [phi[(n+1)%len(phi)]-v for n,v in enumerate(phi)]
def divergence(links):
return [v-links[n-1] for n,v in enumerate(links)]
def centre(data):
mean = sum(data)/len(data)
return [v-mean for v in data]
def constrained_flux(density):
if sum(density) != 0:
raise ValueError("Periodic Gauss law requires zero net charge")
# Integrate E_n - E_(n-1) = density_n and minimize over uniform flux.
links, current = [], 0
for value in density:
current += value
links.append(current)
return centre(links)
def poisson(density):
# -D phi is the minimum flux with divergence equal to density.
links = constrained_flux(density)
phi, value = [], 0
for e in links:
phi.append(value)
value -= e
return centre(phi)
def minimum(s, t):
source = add(s, t)
phi = poisson(source)
e = constrained_flux(t)
grad = gradient(phi)
assert divergence(e) == t
assert [-v for v in divergence(grad)] == source
scalar = inner(grad,grad)/2-inner(source,phi)
electric = inner(e,e)/2
return scalar, electric
def bilinear(a, b):
whole = minimum(add(a[0],b[0]), add(a[1],b[1]))
one, two = minimum(*a), minimum(*b)
return tuple(h-x-y for h,x,y in zip(whole,one,two))
def checks():
# An unnormalized periodic profile, per transverse cell area.
f = list(map(F,(2,-1,0,3,-4,-1,2,-1)))
zero = [F(0)]*len(f)
gram = inner(f, poisson(f))
modes = ((f,zero), (zero,f))
for a in range(2):
for b in range(2):
scalar, electric = bilinear(modes[a],modes[b])
assert -scalar/gram == 1
assert -electric/gram == -int(a==b==1)
assert -(scalar+electric)/gram == ((1,1),(1,0))[a][b]
# Compute the four-dimensional contraction afresh for two generic sources.
eta = (-1,1,1,1)
for (s1,t1),(s2,t2) in (((F(1),F(2)),(F(3),F(-1))),
((F(-2),F(1)),(F(0),F(3)))):
a, b = (s1,t1/2,t1/2,0), (s2,t2/2,t2/2,0)
residue = 2*inner(a,b)-inner(eta,a)*inner(eta,b)
assert residue == s1*s2+s1*t2+t1*s2
# Mixed source profiles, including a different lattice translation in each channel.
shifted = f[2:]+f[:2]
invf, invg = poisson(f), poisson(shifted)
scalar, electric = bilinear((f,shifted),(shifted,f))
assert scalar+electric == -inner(f,invg)-inner(f,invf)-inner(shifted,invg)
# An arbitrary circulation (the unconstrained flux degree) raises its energy.
flux = constrained_flux(f)
extra = [v+F(2,3) for v in flux]
assert divergence(extra) == f
assert (inner(extra,extra)-inner(flux,flux))/2 == len(f)*F(2,9)
# Independent exact inverse of the periodic Laplacian: distance kernel.
n = len(f)
kernel = [F(n*n-1,12*n) - F(i*(n-i),2*n) for i in range(n)]
inverse = [sum(kernel[(i-j)%n]*v for j,v in enumerate(f)) for i in range(n)]
assert inverse == poisson(f)
print(f'finite periodic test: <f,L^+f>={gram}, normalized attractive matrix [[1,1],[1,0]]')
# Three exact nonzero Fourier eigenvectors at distinct finite lattice momenta.
for pattern, lam in (((1,0,-1,0),2), ((2,-1,-1),3), ((1,-1),4)):
profile = list(map(F,pattern*4))
zeros = [F(0)]*len(profile)
predicted = inner(profile,profile)/lam
assert inner(profile,poisson(profile)) == predicted
assert bilinear((profile,zeros),(zeros,profile)) == (-predicted,0)
assert bilinear((zeros,profile),(zeros,profile)) == (-predicted,predicted)
print('Fourier lambda=2,3,4: exact matched mixed pole, exact cancellation of pressure-pressure')
def matter_checks():
# Real free KG field in a flat periodic box, c=hbar=1 and unit amplitude.
mass = 1.
for k in (.5,.1,.02):
w = sqrt(mass**2+k**2)
samples = []
dt = dz = 1e-5
def stress(z, time):
phase = k*z-w*time
field = cos(phase)
ft, fz = w*sin(phase), -k*sin(phase)
s = (ft*ft+fz*fz+mass*mass*field*field)/2
momentum = -ft*fz
pxy = (ft*ft-fz*fz-mass*mass*field*field)/2
return s, momentum, pxy+fz*fz, 2*pxy
for j in range(64):
z, time = j*2*pi/(64*k), .11
s, mom, pz, t = stress(z,time)
ahead, behind = stress(z,time+dt), stress(z,time-dt)
right, left = stress(z+dz,time), stress(z-dz,time)
deriv_t = [(a-b)/(2*dt) for a,b in zip(ahead,behind)]
deriv_z = [(a-b)/(2*dz) for a,b in zip(right,left)]
assert abs(deriv_t[0]+deriv_z[1]) < 2e-8
assert abs(deriv_t[1]+deriv_z[2]) < 2e-8
assert abs(deriv_t[3]+(w/k)*deriv_z[3]) < 2e-7
assert abs(t+mass**2*cos(2*(k*z-w*time))) < 1e-12
samples.append(t)
assert abs(sum(samples)/len(samples)) < 1e-12
print(f'KG k/m={k:.2f}: t is neutral, required |Jz/t|={w/k:.6f}')
# A homogeneous oscillator keeps its energy while the integrated pressure changes sign.
values = []
for time in (0., pi/(4*mass), pi/(2*mass)):
field, velocity = cos(mass*time), -mass*sin(mass*time)
energy = (velocity**2+mass**2*field**2)/2
transverse = velocity**2-mass**2*field**2
assert isclose(energy,mass**2/2)
values.append(round(transverse,12))
assert values == [-1.,0.,1.]
if __name__ == '__main__':
checks()
matter_checks()
pressure_wave.py
"""Conserved-source exchange, freely falling tidal readout and a causal ring burst.
Run python3 pressure_wave.py. Units c=1, metric signature -+++. The reported
tidal tensor is divided by 8*pi*G and the metric perturbation by 16*pi*G.
"""
import math
ETA = (-1, 1, 1, 1)
def tensor(rho, mean, plus, cross, ratio):
return [[rho, 0, 0, ratio*rho],
[0, mean+plus, cross, 0],
[0, cross, mean-plus, 0],
[ratio*rho, 0, 0, ratio**2*rho]]
def trace_reverse(T):
trace = sum(e*T[i][i] for i, e in enumerate(ETA))
return [[ETA[i]*ETA[j]*T[i][j] - (ETA[i]*trace/2 if i == j else 0)
for j in range(4)] for i in range(4)]
def electric(h, q):
return [[q[0]**2*h[i][j] + q[i]*q[j]*h[0][0]
- q[0]*q[i]*h[0][j] - q[0]*q[j]*h[i][0]
for j in range(1, 4)] for i in range(1, 4)]
def angular(E, theta):
return ((E[0][0]-E[1][1])*math.cos(2*theta)/2
+ E[0][1]*math.sin(2*theta))
def check_symbols():
rho, p, a, b = 0.7, 1.0, 0.6, 0.8j
s, t, e, f = 0.35, -0.2, 0.4, -0.15j
K = 1.25
print('Omega/K longitudinal in-phase plus quadrature cross')
for u in (0., .5, .95, .99, 1.01, 1.05):
om, delta = u*K, 1-u*u
D = K*K-om*om
q = [-om, 0., 0., K]
T = tensor(rho, p, a, b, u)
probe = tensor(s, t, e, f, u)
for j in range(4):
assert abs(sum(q[i]*T[i][j] for i in range(4))) < 1e-14
h = [[v/D for v in row] for row in trace_reverse(T)]
xi = (0.25, 0.45j, -0.33, 0.60)
shifted = [[h[i][j]+1j*(q[i]*xi[j]+q[j]*xi[i]) for j in range(4)] for i in range(4)]
E = electric(h, q)
diff = electric(shifted, q)
assert max(abs(E[i][j]-diff[i][j]) for i in range(3) for j in range(3)) < 1e-12
# The physical response to complex Fourier amplitudes pairs the
# source at q with the conjugated probe, corresponding to -q.
exchange = sum(probe[i][j].conjugate()*h[i][j] for i in range(4) for j in range(4))
predicted = ((delta*rho*s/2 + rho*t + s*p)/(K*K)
+ 2*(a*e.conjugate()+b*f.conjugate())/D)
assert abs(predicted-exchange) < 1e-12
assert abs(E[2][2]-(p+delta*rho/2)) < 1e-12
assert abs((E[0][0]+E[1][1])/2-u*u*rho/2) < 1e-12
assert abs(angular(E, 0)-om*om*a/D) < 1e-12
assert abs(angular(E, math.pi/4)-om*om*b/D) < 1e-12
print(f'{u:7.2f} {E[2][2]:13.6f} {angular(E,0).real:16.6f} '
f'{angular(E,math.pi/4).imag:19.6f}')
# A retarded scalar plus an unaltered static compensator matches the
# zero-frequency trace kernel, but leaves a false pure-pressure pole.
for u in (.99, 1.01):
D = K*K*(1-u*u)
T = tensor(0., 1., 0., 0., u)
h = [[v/D for v in row] for row in trace_reverse(T)]
gr = sum(T[i][j]*h[i][j] for i in range(4) for j in range(4))
naive = 2*(1/D-1/(K*K))
assert abs(gr) < 1e-12
print(f'At Omega/K={u:.2f}, K^2 pure-pressure exchange: '
f'spin two {K*K*gr:.3f}, mixed scalar-Gauss extension {K*K*naive:.3f}')
def causal_burst():
sites, period, cycles, receiver = 256, 16, 4, 20
length = cycles*period
alpha = 2*math.pi/period
# Compact real-space stress profile -Delta_z(delta_0) with unit steps.
shape = [0.]*sites
shape[0], shape[1], shape[-1] = 2., -1., -1.
cosine = [math.cos(alpha*j) for j in range(sites)]
normalization = sum(s*c for s, c in zip(shape, cosine))
def component(x):
return sum(t*c for t, c in zip(x, cosine))/normalization
old = [[0.]*sites for _ in range(3)]
cur = [[0.]*sites for _ in range(3)] # H_pressure, H_plus, H_cross
largest_pressure_error = largest_mode_error = 0.
max_after = [0., 0.]
arrival = None
factor = length*math.tan(alpha/2)
for n in range(length+period):
phase = n*alpha
drive = (math.cos(phase), 0.6*math.cos(phase), 0.8*math.sin(phase))
if n >= length:
drive = (0., 0., 0.)
new, tidal = [], []
for field in range(3):
y, previous = cur[field], old[field]
lap = [y[(j-1)%sites]-2*y[j]+y[(j+1)%sites] for j in range(sites)]
following = [2*y[j]-previous[j]+lap[j]+drive[field]*shape[j] for j in range(sites)]
dtt = [following[j]-2*y[j]+previous[j] for j in range(sites)]
# Ezz = (dtt-Delta_z)H_pressure; differential arms see -dtt H_TT.
electric_field = ([v-w for v, w in zip(dtt, lap)] if field == 0
else [-v for v in dtt])
new.append(following)
tidal.append(electric_field)
largest_pressure_error = max(largest_pressure_error,
max(abs(v-drive[0]*s) for v, s in zip(tidal[0], shape)))
if arrival is None and abs(tidal[1][receiver]) > 1e-10:
arrival = n
if n >= length:
measured = (component(tidal[1]), component(tidal[2]))
predicted = (.6*factor*math.sin(phase), -.8*factor*math.cos(phase))
for j in (0, 1):
largest_mode_error = max(largest_mode_error, abs(measured[j]-predicted[j]))
max_after[j] = max(max_after[j], abs(measured[j]))
old, cur = cur, new
assert arrival == receiver-1
assert largest_pressure_error < 1e-12 and largest_mode_error < 2e-10
print(f'First tidal signal at site {receiver}: tick {arrival} (distance from drive {receiver-1})')
print(f'Max pointwise pressure identity error {largest_pressure_error:.3e}')
print(f'Post-burst modal arm amplitudes {max_after[0]:.6f}, {max_after[1]:.6f}')
print(f'Max post-burst quadrature error {largest_mode_error:.3e}')
if __name__ == '__main__':
check_symbols()
causal_burst()
tensor_rotor.py
"""Spectra and static-charge checks for three linear tensor Hamiltonians.
Run python3 tensor_rotor.py. No dependencies. Spatial units a=1; time is
continuous. All checks use the staggered symbol K_i=2 sin(k_i/2).
"""
from itertools import product
from math import cos, pi, sin, sqrt
I = [[float(i == j) for j in range(3)] for i in range(3)]
def inner(a, b):
return sum(x*y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def add(a, b, weight=1.):
return [[x + weight*y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def outer(a, b):
return [[x*y for y in b] for x in a]
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 trace(a):
return sum(row[i] for i, row in enumerate(a))
def symbol(k):
return [2*sin(x/2) for x in k]
def generators(K):
x, y, z = K
cross = [[0., -z, y], [z, 0., -x], [-y, x, 0.]]
def magnetic(a):
return mm(mm(cross, a), list(zip(*cross)))
def cotton(a):
b = magnetic(a)
# One overall i is dropped in this real Fourier representation.
return mm(cross, add(b, I, -trace(b)/2))
return magnetic, cotton
def symmetric_basis():
for i in range(3):
for j in range(i, 3):
a = [[0.]*3 for _ in range(3)]
a[i][j] = a[j][i] = 1. if i == j else 1/sqrt(2)
yield a
def max_difference(a, b):
return max(abs(x-y) for ra, rb in zip(a,b) for x,y in zip(ra,rb))
def check_grid(n=8):
basis = list(symmetric_basis())
largest = charge_error = 0.
count = 0
for indices in product(range(-n//2, n//2), repeat=3):
if not any(indices):
continue
K = symbol([2*pi*j/n for j in indices])
K2 = sum(t*t for t in K)
b, c = generators(K)
# Check the derivative phase placements: raw forward difference,
# rephased to its half-cell midpoint, equals the staggered symbol.
for j, t in zip(indices, K):
k = 2*pi*j/n
phase = complex(cos(k/2), -sin(k/2))
assert abs((complex(cos(k), sin(k))-1)*phase-1j*t) < 1e-14
for op, scale, modes in ((b, K2**2, 3), (c, K2**3, 2)):
images = [op(a) for a in basis]
projector = [[inner(v,w)/scale for w in images] for v in images]
# Symmetric P²=P and tr P integer determine all six eigenvalues.
largest = max(largest, max_difference(mm(projector,projector), projector),
abs(trace(projector)-modes))
v = (0.27, -.48, .65)
gauge = add(outer(v,K), outer(K,v))
assert inner(b(gauge), b(gauge)) < 1e-22
assert inner(c(I), c(I)) < 1e-22
assert abs(inner(b(I),b(I))-2*K2**2) < 1e-11
# The linear comparator: B is K² on the transverse trace and
# -K² on TT; its gauge kernel drops out of both integrated energies.
P = add(I, outer(K,K), -1/K2)
scalar_charge = .8
trace_field = [[scalar_charge*x/2 for x in row] for row in P]
assert abs(trace(trace_field)-scalar_charge) < 1e-12
assert abs(inner(trace_field,trace_field)/2-scalar_charge**2/4) < 1e-12
for a in basis:
cotton_tensor = c(a)
assert max_difference(cotton_tensor, list(zip(*cotton_tensor))) < 1e-12
assert abs(trace(cotton_tensor)) < 1e-12
assert max(abs(sum(K[i]*cotton_tensor[i][j] for i in range(3)))
for j in range(3)) < 1e-12
transverse = mm(mm(P,a),P)
tt = add(transverse,P,-trace(transverse)/2)
assert max_difference(b(tt), [[-K2*x for x in row] for row in tt]) < 1e-12
assert abs(inner(transverse,transverse)-trace(transverse)**2/2-inner(tt,tt)) < 1e-12
# Static vector charge test. K·E=rho with the irrelevant i removed.
khat = [x/sqrt(K2) for x in K]
rho = (.4, -.6, .9)
longitudinal = sum(x*y for x,y in zip(rho,khat))
perp = [r-longitudinal*x for r,x in zip(rho,khat)]
base = add(add(outer(khat,perp),outer(perp,khat)),outer(khat,khat),longitudinal)
for constrained, e_coeff in ((False,1.),(True,1.5)):
e = add(base,P,-longitudinal/2 if constrained else 0.)
e = [[x/sqrt(K2) for x in row] for row in e]
assert max(abs(sum(K[i]*e[i][j] for i in range(3))-rho[j]) for j in range(3)) < 1e-12
if constrained:
assert abs(trace(e)) < 1e-12
energy2 = (2*sum(x*x for x in perp)+e_coeff*longitudinal**2)/K2
charge_error = max(charge_error,abs(inner(e,e)-energy2))
count += 1
assert largest < 1e-12 and charge_error < 1e-12
print(f'{count} nonzero modes: B has rank 3, Cotton rank 2; '
f'largest normalized projector error {largest:.3e}')
print(f'Vector-charge energy identity maximum error {charge_error:.3e}')
def main():
check_grid()
# Ratios for harmonic m=2 relative to m=1 in a periodic length-N box.
print('N ratio z=1 ratio z=2 ratio z=3')
for n in (16,32,64):
ratio = sin(2*pi/n)/sin(pi/n)
print(f'{n:2d} {ratio:10.6f} {ratio**2:11.6f} {ratio**3:11.6f}')
# An unconstrained transverse trace A=P/sqrt(2) is normalized. Its
# elastic energy is negative at small K despite a finite trace penalty.
for n in (16,32,128):
K = 2*sin(pi/n)
elastic = (-K*K+2*10*K**4)/2
print(f'N={n}: curvature-constraint-violating trace trial, '
f'elastic energy including lambda=10 penalty {elastic:+.8f}')
electric = -0.25+10*K**2/6
print(f'N={n}: Gauss-violating isotropic E trial, kinetic energy '
f'including lambda=10 penalty {electric:+.8f}')
# A local six-component wave equation restricted by hard TT initial data
# is positive even off that sector. Softening its divergence constraints
# leaves a longitudinal shear at arbitrarily low frequency.
for n in (32,64,128):
K = 2*sin(pi/n)
omega = K*sqrt((1+10*K**2/2)*(1+10/2))
print(f'N={n}: positive wave comparator, soft-constraint shear '
f'omega={omega:.6f}, omega/K={omega/K:.6f}')
print('On a torus, the uniform trace momentum has energy -1/4 and '
'satisfies both derivative constraints; fixing the global sector matters.')
if __name__ == '__main__':
main()
clocks_data.py
"""Reproduce the clock-redshift checks on Zheng et al. (2023), without dependencies."""
import csv
import hashlib
import math
from pathlib import Path
C = 299792458.0
G_LOCAL = -9.803
# All fractional frequencies and gradients quoted below use 10^-19 units.
SLOPE = G_LOCAL * 0.01 / C**2 * 1e19
SYSTEMATIC = 2.5
DATA = Path(__file__).with_name('clocks_data.csv')
CSV_LF_SHA256 = '4bd3925ca24a93ca7a0d28938c64b643dc8bfac6079d8a6feaf6273c33b1dba3'
# Corrected fractional frequency differences and total uncertainties, from
# Supplementary Table 1. Pair (2,4) shares no atoms with endpoints (1,5).
HALF_HEIGHT = (-5.78, 2.19)
ENDPOINT = (-11.96, 2.93)
def run_summary(rows):
weight = sum(1/e**2 for _, e in rows)
mean = sum(y/e**2 for y, e in rows)/weight
chi_sq = sum(((y-mean)/e)**2 for y, e in rows)
nominal = 1/math.sqrt(weight)
# The paper inflates the pooled statistical error when reduced chi² > 1.
# We show the nominal and scatter-adjusted errors separately for each split.
adjusted = nominal*max(1., math.sqrt(chi_sq/(len(rows)-1)))
return mean, nominal, adjusted, chi_sq
def main():
if hashlib.sha256(DATA.read_bytes().replace(b'\r\n', b'\n')).hexdigest() != CSV_LF_SHA256:
raise ValueError('Expected the Zenodo Fig3.csv, up to standard line endings')
with DATA.open(newline='') as fin:
table = list(csv.reader(fin))[2:] # the header is followed by a units row
if [int(r[3]) for r in table] != list(range(1, 15)):
raise ValueError('Unexpected measurement-run indices')
runs = [(float(r[4]), float(r[5])) for r in table]
print(f'Independent gradient {SLOPE:.6f} x 10^-19/cm')
for h in (0.99, 1.00):
expected = SLOPE*h
observed, sigma = ENDPOINT
height_sigma = abs(SLOPE)*0.01
total = math.hypot(sigma, height_sigma)
print(f'h={h:.2f} cm: prediction {expected:.6f}, observed {observed:.2f}, '
f'residual {observed-expected:+.6f}, conditional SD {total:.6f}, '
f'standardized residual {(observed-expected)/total:+.3f}')
print(f'Flat-clock endpoint displacement {abs(ENDPOINT[0])/ENDPOINT[1]:.3f} measurement SD')
y0, e0 = HALF_HEIGHT
y1, e1 = ENDPOINT
print(f'Disjoint clock pairs: prediction {2*y0:.2f}, residual {y1-2*y0:+.2f}; '
f'allowed SD [{abs(e1-2*e0):.2f}, {e1+2*e0:.2f}] for any correlation')
print('run subset mean nominal SD adjusted SD chi squared')
for label, rows in (('1-7', runs[:7]), ('8-14', runs[7:]), ('1-14', runs)):
m, e, a, chi = run_summary(rows)
print(f'{label:9s} {m:10.6f} {e:13.6f} {a:14.6f} {chi:16.6f}')
early, _, e_early, _ = run_summary(runs[:7])
late, _, e_late, _ = run_summary(runs[7:])
print(f'Late minus early {late-early:+.6f}, conditional statistical SD '
f'{math.hypot(e_early,e_late):.6f}')
print(f'Late minus gravimeter {late-SLOPE:+.6f}, conditional total SD '
f'{math.hypot(e_late,SYSTEMATIC):.6f}')
if __name__ == '__main__':
main()
contact_reference.py
"""Read the separation of two mobile particles after spatial clock pulses.
Every gate is onsite or joins nearest neighbours on the physical lattice.
The square array stores the two-particle wavefunction, with walker position
as its first index and reference position as its second. All momenta and
energies use one cell, one time unit and hbar=1.
"""
from cmath import exp
from math import ceil, cos, pi, sin, sqrt
LENGTH = 16
MASS = 4.0
J = 1/MASS
G = 0.5
Q = pi/4
COSINE = [cos(Q*j) for j in range(LENGTH)]
SINE = [sin(Q*j)/Q for j in range(LENGTH)]
def inner(a, b):
return sum(x.conjugate()*y for x, y in zip(a, b))
def coincident(a):
return [v if i//LENGTH == i % LENGTH else 0 for i, v in enumerate(a)]
def contact_probability(a):
return sum(abs(a[i*LENGTH+i])**2 for i in range(LENGTH))
def branch(separation, phase):
a = [0j] * LENGTH**2
for ref in range(LENGTH):
a[((ref+separation) % LENGTH)*LENGTH+ref] = 1/sqrt(2*LENGTH)
a[((ref+separation+1) % LENGTH)*LENGTH+ref] = exp(1j*phase)/sqrt(2*LENGTH)
return a
def preparation(phase):
# Equal mixing cancels the phase dependence in both one-body density matrices.
return (branch(0, phase), branch(4, phase+pi))
class ProfileHamiltonian:
def __init__(self, profile, contact, mass=MASS):
hopping = 1/mass
self.diagonal = []
self.groups = [[] for _ in range(4)]
for y in range(LENGTH):
yp = (y+1) % LENGTH
for r in range(LENGTH):
rp = (r+1) % LENGTH
i = y*LENGTH+r
d = 2*profile[y]+(mass+hopping)*profile[r]
self.diagonal.append(d + (contact*profile[r] if y == r else 0))
walker_link = 0.25j*(profile[y]+profile[yp])
ref_link = -0.25*hopping*(profile[r]+profile[rp])
self.groups[y % 2].append((i, yp*LENGTH+r, walker_link))
self.groups[2+r % 2].append((i, y*LENGTH+rp, ref_link))
def apply(self, state):
result = [d*a for d, a in zip(self.diagonal, state)]
for group in self.groups:
for i, j, h in group:
result[j] += h*state[i]
result[i] += h.conjugate()*state[j]
return result
def pulse(self, state, angle):
# A symmetric finite-depth pulse. Negative angle gives its exact inverse.
phases = [exp(-0.5j*angle*d) for d in self.diagonal]
a = [p*x for p, x in zip(phases, state)]
for group, scale in ((0,.5),(1,.5),(2,.5),(3,1),(2,.5),(1,.5),(0,.5)):
for i, j, h in self.groups[group]:
mag = abs(h)
if mag:
c, s = cos(scale*angle*mag), -1j*sin(scale*angle*mag)/mag
x, y = a[i], a[j]
a[i], a[j] = c*x+s*h.conjugate()*y, c*y+s*h*x
return [p*x for p, x in zip(phases, a)]
def generator(c, s, state):
cs = c.apply(s.apply(state))
sc = s.apply(c.apply(state))
return [1j*(a-b) for a,b in zip(cs,sc)]
def response(state, generator_state):
# d<P_contact>/da for exp(-i a B).
return 2*inner(coincident(state), generator_state).imag
def loop(c, s, state, t):
for pulse, angle in ((c,-t),(s,-t),(c,t),(s,t)):
state = pulse.pulse(state, angle)
assert abs(inner(state,state).real-1) < 1e-12
return state
def check_marginals():
for phase in (pi/2,-pi/2,0):
states = preparation(phase)
for i in range(LENGTH):
for j in range(LENGTH):
walker = sum(s[i*LENGTH+k]*s[j*LENGTH+k].conjugate()
for s in states for k in range(LENGTH))/2
ref = sum(s[k*LENGTH+i]*s[k*LENGTH+j].conjugate()
for s in states for k in range(LENGTH))/2
expected = 1/LENGTH if i == j else 0
assert max(abs(walker-expected),abs(ref-expected)) < 1e-14
relative = [sum(abs(s[((k+r) % LENGTH)*LENGTH+k])**2
for s in states for k in range(LENGTH))/2 for r in range(LENGTH)]
assert all(abs(n-(.25 if r in (0,1,4,5) else 0)) < 1e-14
for r,n in enumerate(relative))
uniform = ProfileHamiltonian([1]*LENGTH,G)
mean_energy = sum(inner(s,uniform.apply(s)).real for s in states)/2
assert abs(mean_energy-(2+MASS+J+G/4)) < 1e-13
def velocity_sum(a):
out = [0j]*len(a)
for y in range(LENGTH):
for r in range(LENGTH):
i=y*LENGTH+r
out[i] = (a[((y+1)%LENGTH)*LENGTH+r]+a[((y-1)%LENGTH)*LENGTH+r])/2
out[i] += J*(a[y*LENGTH+(r+1)%LENGTH]-a[y*LENGTH+(r-1)%LENGTH])/(2j)
return out
def contact_generator(state):
va = velocity_sum(state)
pv = coincident(va)
vp = velocity_sum(coincident(state))
return [G*sin(Q)/(2*Q)*(x+y) for x,y in zip(pv,vp)]
def verify_interaction():
free = ProfileHamiltonian(COSINE,0), ProfileHamiltonian(SINE,0)
coupled = ProfileHamiltonian(COSINE,G), ProfileHamiltonian(SINE,G)
state = [exp(0.013j*i*i)/LENGTH for i in range(LENGTH**2)]
direct = [b-a for a,b in zip(generator(*free,state),generator(*coupled,state))]
error = max(abs(a-b) for a,b in zip(direct,contact_generator(state)))
assert error < 1e-12
print(f"Native two-body commutator versus local contact formula: {error:.2e}")
for phase in (pi/2,-pi/2):
states = preparation(phase)
predicted = G*sin(Q)/Q*(sin(phase)+J*cos(phase))/8
exact = sum(response(a,contact_generator(a)) for a in states)/2
assert abs(exact-predicted) < 1e-13
def probability(hamiltonians, t):
return sum(contact_probability(loop(*hamiltonians,a,t)) for a in states)/2
estimates = []
for t in (0.12,0.06,0.03):
contrast = sum(probability(coupled,u)-probability(free,u) for u in (t,-t))/2
estimates.append(contrast/t**2)
print(f"phase/pi={phase/pi:+.1f}: exact {exact:+.9f}, finite estimates",
" ".join(f"{e:+.9f}" for e in estimates))
assert abs(estimates[-1]-exact) < .0004
assert abs(estimates[-1]-exact) < .31*abs(estimates[-2]-exact)
# Dephasing removes the signal without changing the contact population.
dephased = []
for r in (0,1,4,5):
a = [0j]*LENGTH**2
for j in range(LENGTH):a[((j+r)%LENGTH)*LENGTH+j]=1/sqrt(LENGTH)
dephased.append(a)
assert max(abs(response(a,contact_generator(a))) for a in dephased)<1e-14
def finite_counts():
# Four independent Bernoulli settings: the +/- phase at g on and g off.
# Record the entire contrast, since its sign can differ from the weak limit.
for angle, pairs, sign in ((.15,4,1),(.30,4,-1),(.24,8,-1)):
probabilities = []
for phase in (pi/2,-pi/2):
for g in (G,0):
c = ProfileHamiltonian(COSINE,g)
s = ProfileHamiltonian(SINE,g)
total = 0
for state in preparation(phase):
for _ in range(pairs):
state = loop(c,s,state,angle)
state = loop(c,s,state,-angle)
total += contact_probability(state)/2
probabilities.append(total)
a,b,c,d = probabilities
difference = (a-b)-(c-d)
assert sign*difference > .01
variance = sum(p*(1-p) for p in probabilities)
n = ceil(19*variance/difference**2)
print(f"Finite counts: angle={angle}, pairs={pairs}, "
+ " ".join(f"{p:.8f}" for p in probabilities)
+ f", contrast {difference:+.8f}, sufficient shots per setting {n}")
def localized_branches(phase, coherent_reference):
# Near and far branches have opposite phases on the same pair of sites.
# Exchanging walker and reference puts the coherence entirely on the reference.
states = []
for location, sign in ((0,1), (4,-1)):
a = [0j]*LENGTH**2
for position, amp in ((0,1), (1,sign*exp(1j*phase))):
y, r = ((location, position) if coherent_reference else (position, location))
a[y*LENGTH+r] = amp/sqrt(2)
states.append(a)
return states
def verify_localized():
for mass in (4.,8.):
free = ProfileHamiltonian(COSINE,0,mass), ProfileHamiltonian(SINE,0,mass)
coupled = ProfileHamiltonian(COSINE,G,mass), ProfileHamiltonian(SINE,G,mass)
def delta(state):
return response(state, generator(*coupled,state))-response(state,generator(*free,state))
for on_ref in (False,True):
phases = (0,pi) if on_ref else (pi/2,-pi/2)
for phase in phases:
a,b = localized_branches(phase,on_ref)
expected = G*sin(Q)/(8*Q)*(-cos(phase)/mass if on_ref else sin(phase))
mixed = (delta(a)+delta(b))/2
# Both local states have equal weights on two orthogonal basis states.
# A coherent superposition of these orthogonal product branches is entangled.
pure = [(x+1j*y)/sqrt(2) for x,y in zip(a,b)]
for i in (0,1,4):
for j in (0,1,4):
dw = sum(pure[i*LENGTH+k]*pure[j*LENGTH+k].conjugate()
for k in range(LENGTH))
dr = sum(pure[k*LENGTH+i]*pure[k*LENGTH+j].conjugate()
for k in range(LENGTH))
sw = (0,4) if on_ref else (0,1)
sr = (0,1) if on_ref else (0,4)
assert abs(dw-(.5 if i==j and i in sw else 0)) < 1e-14
assert abs(dr-(.5 if i==j and i in sr else 0)) < 1e-14
assert max(abs(mixed-expected),abs(delta(pure)-expected)) < 1e-13
t=.012
observed = sum(contact_probability(loop(*coupled,pure,u))
-contact_probability(loop(*free,pure,u))
for u in (-t,t))/(2*t*t)
assert abs(observed-expected)<.00015
label = 'reference' if on_ref else 'walker'
print(f"Localized {label}, mass {mass:.0f}, phase/pi={phase/pi:+.1f}: "
f"contact coefficient {expected:+.8f}, finite {observed:+.8f}")
if __name__ == "__main__":
check_marginals()
verify_interaction()
verify_localized()
finite_counts()
reference_scattering.py
"""Elastic recoil and signed contact spectroscopy on the K=0 two-body band.
The rest energy is removed during time propagation. In relative coordinate
the nearest-neighbour hopping is (i-J)/2 and the contact is a real onsite g.
"""
from cmath import exp
from math import atan, cos, exp as real_exp, pi, sin, sqrt
J = 0.25
G = 0.5
HOP = (1j-J)/2
BASE = 2+4+J
def action(a, interaction):
b = [HOP*x+HOP.conjugate()*y
for x,y in zip([a[-1]]+a[:-1],a[1:]+[a[0]])]
mid = len(a)//2
b[mid] += interaction*a[mid]
return b
def energy(p):
return BASE+sin(p)-J*cos(p)
def norm(a):
return sum(abs(x)**2 for x in a)
def evolve(a, interaction, steps, dt, order=17):
# Taylor propagation. The norm of the reduced Hamiltonian is at most
# sqrt(1+J^2)+|g|, so the truncation is controlled uniformly in box size.
for _ in range(steps):
result = a[:]
term = a
for n in range(1,order+1):
term = [(-1j*dt/n)*z for z in action(term,interaction)]
result = [x+y for x,y in zip(result,term)]
a = result
assert abs(norm(a)-1) < 2e-10
return a
def scattering(width, interaction=G):
length = 32*width
x = range(-length//2,length//2)
a = [real_exp(-(j+6*width)**2/(4*width**2)) for j in x]
n = sqrt(norm(a))
a = evolve([z/n for z in a],interaction,18*width,2/3)
# After 12 widths of propagation both outgoing packets separate from contact.
mid = length//2
left = a[:mid]
prob = norm(left)
cos_p = sum((x.conjugate()*y).real for x,y in zip(left,left[1:]))/prob
return prob, J*(1-cos_p)
def bound_state(interaction):
scale = sqrt(1+J**2)
energy_shift = (1 if interaction > 0 else -1)*sqrt(scale**2+interaction**2)
# Remove the hopping phase, then solve the recurrence away from contact.
t = abs(HOP)
decay = (energy_shift-interaction)/(2*t)
link_phase = HOP/t
sites = range(-96,97)
a = [link_phase**r * decay**abs(r) for r in sites]
ref = action(a,interaction)
error = max(abs(x-energy_shift*y) for x,y in zip(ref[1:-1],a[1:-1]))
assert abs(decay)<1 and error < 1e-12
return BASE+energy_shift
def main():
other = -pi + 2*atan(J)
incoming_speed = 1.0
outgoing_speed = cos(other)+J*sin(other)
assert abs(energy(other)-energy(0))<1e-14 and abs(outgoing_speed+1)<1e-14
assert abs(cos(other)+15/17)<1e-14 and abs(sin(other)+8/17)<1e-14
probability = G**2/(G**2+incoming_speed**2)
recoil = J*(1-cos(other))
print(f"Plane waves: reflection {probability:.9f}, reference energy gain {recoil:.9f}")
# As a separate direct check, impose matching at the defect for an incoming
# right-moving unit wave, reflected r*exp(i other*x), and transmitted t.
for g in (G,-G):
r = g/(1j*incoming_speed-g)
t = 1+r
left = exp(0j)+r*exp(-1j*other)
right = t
residual = HOP*left+HOP.conjugate()*right+g*t-(energy(0)-BASE)*t
assert abs(residual)<1e-14
assert abs(abs(r)**2-probability)<1e-14
assert abs(abs(t)**2+abs(r)**2-1)<1e-14
print(f"Signed bound energy, g={g:+.1f}: {bound_state(g):.9f}")
last_error = 1
for width in (6,12,24):
p, e = scattering(width)
error = abs(p-probability)+abs(e-recoil)
print(f"Packet width {width}: reflected probability {p:.8f}, "
f"conditional reference energy gain {e:.8f}")
assert error < last_error
last_error = error
assert last_error < .0005
if __name__ == "__main__":
main()
free_reference.py
"""Two free walks, periodic clock pulses, and a mobile position reference.
Run with Python 3 and the standard library. All angular momenta below are
crystal momenta in radians per coarse cell. Position is in coarse cells.
"""
from cmath import exp
from itertools import product
from math import acos, cos, isclose, pi, sin, sqrt
LENGTH = 16
STEP = 2 # the two masks carry ±2 momentum bins
MOMENTA = tuple(2*pi*j/LENGTH for j in range(LENGTH))
Q = MOMENTA[STEP]
WEIGHTS = (1, 2, 3, 2, 1)
POINTS = tuple(range(-2, 3))
SPIN = (0.5, 0.5j, -0.5j, -0.5)
FORM = cos(Q/2)**2*sin(Q)/Q
def native(k):
x, y, z = (MOMENTA[j] for j in k)
return sin(x)*cos(y)*cos(z), sin(y)*cos(z), sin(z)
def weak(k):
x, y, z = (MOMENTA[j] for j in k)
return FORM*cos(x)**2*sin(2*y)*cos(z)**2/2
def pauli_action(a, b, vec):
x, y, z = vec
return z*a + (x-1j*y)*b, (x+1j*y)*a - z*b
def on_spin(spin, which, vector):
pairs = ((0, 2), (1, 3)) if which == 0 else ((0, 1), (2, 3))
out = [0j]*4
for i, j in pairs:
out[i], out[j] = pauli_action(spin[i], spin[j], vector)
return out
def modulate(state, sine):
"""Apply the sum of the two independently weighted native Hamiltonians."""
out = {}
for pair, spin in state.items():
for which, initial in enumerate(pair):
old = native(initial)
for sign in (-1, 1):
final = (initial[0], (initial[1]+sign*STEP) % LENGTH, initial[2])
new = native(final)
vector = [(v+w)/2 for v, w in zip(old, new)]
# Fourier coefficient of sin(qy)/q or cos(qy).
factor = sign/(2j*Q) if sine else 0.5
dest = (final, pair[1]) if which == 0 else (pair[0], final)
accum = out.setdefault(dest, [0j]*4)
for j, value in enumerate(on_spin(spin, which, vector)):
accum[j] += factor*value
return out
def check_pulse_order():
# Test distinct entangled and product spin inputs and intermediate momenta.
largest = 0.
for seed, spin in product(range(35), (SPIN, (0j, 1., 0j, 0j))):
pair = tuple(tuple((a*seed+b) % LENGTH for a, b in seq)
for seq in (((3, 4), (5, 1), (1, 2)), ((2, 1), (7, 3), (3, 0))))
state = {pair: spin}
cs = modulate(modulate(state, True), False)
sc = modulate(modulate(state, False), True)
target = sum(weak(k) for k in pair)
for dest in cs.keys() | sc.keys():
left, right = cs.get(dest, (0j,)*4), sc.get(dest, (0j,)*4)
for j in range(4):
result = 1j*(left[j]-right[j])
expected = target*spin[j] if dest == pair else 0j
largest = max(largest, abs(result-expected))
assert largest < 2e-14
return largest
def fourier_profile(carrier):
norm = sqrt(LENGTH*sum(w*w for w in WEIGHTS))
return [sum(w*exp(-1j*(k-carrier)*r) for r, w in zip(POINTS, WEIGHTS))/norm
for k in MOMENTA]
def relative_centroid(total_x, carrier, t):
"""Finite-ring relative-position readout after evolution by the weak generator."""
x_weight = [abs(z)**2 for z in fourier_profile(carrier)]
z_weight = [abs(z)**2 for z in fourier_profile(0)]
y_amplitudes = fourier_profile(0)
inverse = [[exp(1j*k*r)/sqrt(LENGTH) for k in MOMENTA] for r in range(LENGTH)]
probabilities = [0.]*LENGTH
for x, z in product(range(LENGTH), repeat=2):
amplitudes = []
for y in range(LENGTH):
p = (x, y, z)
other = ((total_x-x) % LENGTH, -y % LENGTH, -z % LENGTH)
b = weak(p)+weak(other)
amplitudes.append(y_amplitudes[y]*exp(-1j*t*b))
for r, row in enumerate(inverse):
value = sum(a*v for a, v in zip(amplitudes, row))
probabilities[r] += x_weight[x]*z_weight[z]*abs(value)**2
assert abs(sum(probabilities)-1) < 3e-13
# The initial relative packet and the first-order stencil avoid the cut.
return sum((r if r < LENGTH//2 else r-LENGTH)*p for r, p in enumerate(probabilities))
def check_fibers():
coherence = sum(a*b for a, b in zip(WEIGHTS, WEIGHTS[2:])) / sum(w*w for w in WEIGHTS)
predicted = FORM*coherence**2*(1+coherence)/2
step = 1e-4
for total, carrier, target in ((0, 0., 0.), (LENGTH//4, 0., predicted),
(LENGTH//4, pi/2, -predicted)):
plus = relative_centroid(total, carrier, step)
minus = relative_centroid(total, carrier, -step)
readout = (plus-minus)/(2*step)
assert abs(readout-target) < 1e-9
print(f'P_x={MOMENTA[total]:.6f} K_x={carrier:.6f}: '
f'relative centroid derivative {readout:+.9f}, analytic {target:+.9f}')
for p in product(range(LENGTH), repeat=3):
other = tuple(-j % LENGTH for j in p)
assert abs(weak(p)+weak(other)) < 1e-15
def true_phase(x, y, z=0.):
return acos(cos(x)*cos(y)*cos(z))
def check_alternatives():
# Finite difference the relative velocity of a reference-attached actuator.
def relative_generator(p, k, mass_a, mass_r):
ea, er = sqrt(mass_a**2+p*p), sqrt(mass_r**2+k*k)
return ea*(p/ea-k/er)
for ma, mr in ((1., 1.), (1., 4.)):
d = 1e-5
read = (relative_generator(d, -d, ma, mr) -
relative_generator(-d, d, ma, mr))/(2*d)
assert abs(read - (1+ma/mr)) < 1e-9
print(f'reference-attached, m_A/m_R={ma/mr:g}: {read:.6f}')
# Regular equal-velocity counterexample on the positive tick-phase branch.
a = pi/4
d = 1e-5
gradient = (true_phase(a, a+d)-true_phase(a, a-d))/(2*d)
center_current = 2*true_phase(a, a)*gradient
assert abs(center_current-2*pi/(3*sqrt(3))) < 1e-9
print(f'co-moving packets: boost bracket {center_current:.9f}, ordinary momentum {2*a:.9f}')
# Same internal carrier and total momentum, but a different moving energy.
p, qx, qy = pi/2, pi/4, pi/4
mass = 2*true_phase(qx, qy)
free = true_phase(qx, p/2+qy) + true_phase(-qx, p/2-qy)
imposed = sqrt(p*p+mass*mass)
assert isclose(mass, 2*pi/3) and isclose(free, 3*pi/4)
assert isclose(imposed, 5*pi/6) and isclose(imposed-free, pi/12)
d = 1e-5
current = imposed*(sqrt((p+d)**2+mass**2)-sqrt((p-d)**2+mass**2))/(2*d)
assert abs(current-p) < 1e-9
print(f'pair moving energy: native {free:.9f}, imposed {imposed:.9f}, gap {imposed-free:.9f}')
if __name__ == '__main__':
print(f'periodic 16-cell torus, q=pi/4, finite-profile factor {FORM:.9f}')
print(f'largest explicit two-copy ordered-pulse error {check_pulse_order():.2g}')
check_fibers()
check_alternatives()
improved_contact.py
"""Replay the three-dimensional massive clock, contact boost and corner leakage.
Only Python's standard library is needed. Momentum is in inverse coarse cells,
energy in inverse time, and the worked examples use mass one.
"""
from itertools import product
from math import ceil, cos, isclose, pi, sin, sqrt
def symbol(k, improved=True, mass=1.):
x, y, z = k
t = [2*sin(s/2)**2 for s in k] # stable form of 1-cos(s)
diag = sum(s*s for s in t)
mixed = t[0]*t[1] + t[1]*t[2] + t[0]*t[2]
d = (2*diag/3 + 2*mixed)/mass if improved else 0.
return (sin(x)*cos(y)*cos(z), sin(y)*cos(z), sin(z), mass+d)
def velocity(k, j, improved=True, mass=1.):
x, y, z = k
sx, sy, sz = map(sin, k)
cx, cy, cz = map(cos, k)
b_derivs = ((cx*cy*cz, 0., 0.), (-sx*sy*cz, cy*cz, 0.),
(-sx*cy*sz, -sy*sz, cz))
t = [2*sin(s/2)**2 for s in k]
dd = sin(k[j])*(4*t[j]/3 + 2*sum(t[i] for i in range(3) if i != j))/mass
return (*b_derivs[j], dd if improved else 0.)
def dot(a, b):
return sum(x.conjugate()*y for x, y in zip(a, b))
def length(a):
return sqrt(dot(a, a).real)
def dirac(v, u):
x, y, z, m = v
a, b, c, d = u
return (m*a + z*c + (x-1j*y)*d, m*b + (x+1j*y)*c - z*d,
z*a + (x-1j*y)*b - m*c, (x+1j*y)*a - z*b - m*d)
def positive(v):
x, y, z, m = v
e = length(v)
u = (e+m, 0., z, x+1j*y)
return tuple(a/length(u) for a in u)
def act(spin, v, which):
out = [0j]*16
for j in range(4):
ids = range(j, 16, 4) if which == 0 else range(4*j, 4*j+4)
vals = dirac(v, [spin[i] for i in ids])
for i, a in zip(ids, vals):
out[i] = a
return out
BETA = (1, 1, -1, -1)
SIGN = tuple(a*b for a, b in product(BETA, repeat=2))
def scalar_contact(u):
return [s*a for s, a in zip(SIGN, u)]
def pair_velocity(u, k, j, improved):
v = velocity(k, j, improved)
return [a+b for a, b in zip(act(u, v, 0), act(u, v, 1))]
def bands():
for k in product((0., pi), repeat=3):
vec = symbol(k)
assert length(vec[:3]) < 3e-15
corners = sum(s != 0 for s in k)
assert isclose(length(vec), 1+8*corners/3+4*corners*(corners-1))
for scale in (.18, .09, .045):
k = tuple(scale*s for s in (1., -.7, .45))
row = []
for improved in (False, True):
v = symbol(k, improved)
en = length(v)
u = positive(v)
assert length([z-en*a for z, a in zip(dirac(v, u), u)]) < 1e-14
defect = abs(dot(v[:3], v[:3])+(v[3]-1)*(v[3]+1)-dot(k,k))
current = [dot(v, velocity(k, j, improved)) for j in range(3)]
row.extend((defect, length([a-b for a, b in zip(current, k)])))
for j in range(3):
d = 2e-6
kp, km = list(k), list(k)
kp[j] += d
km[j] -= d
finite = (length(symbol(kp, improved))**2-length(symbol(km, improved))**2)/(4*d)
assert abs(finite-current[j]) < 2e-10
print(f'k scale {scale:.3f}: bare E²/current errors {row[0]:.4g} {row[1]:.4g}; '
f'improved {row[2]:.4g} {row[3]:.4g}')
if scale != .18:
assert 58 < old[2]/row[2] < 68 and 29 < old[3]/row[3] < 35
old = row
for n in range(101):
p = pi*n/100
t = 1-cos(p)
assert isclose(length(symbol((p,0,0)))**2, 1+2*t+t*t/3+4*t**4/9)
def matrix_elements():
p = pi/4
k = (p, 0., 0.)
out = (p-pi, 0., 0.)
u = positive(symbol(k, False))
z = tuple(b*a for b, a in zip(BETA, u))
assert length([a-length(symbol(k, False))*b
for a, b in zip(dirac(symbol(out,False), z), z)]) < 1e-12
initial = [a*b for a, b in product(u, repeat=2)]
final = [a*b for a, b in product(z, repeat=2)]
vs = scalar_contact(pair_velocity(initial, k, 0, False))
sv = pair_velocity(scalar_contact(initial), out, 0, False)
anomaly = dot(final, [(a+b)/2 for a, b in zip(vs, sv)])
assert abs(dot(final, scalar_contact(initial))-1) < 1e-13
assert abs(anomaly-2*sin(p)*cos(p)/length(symbol(k,False))) < 1e-13
detuning = 2*(length(symbol(out))-length(symbol(k)))
assert abs(detuning-3.50940015100523) < 1e-12
print(f'bare resonant scalar contact in units g/L³: 1; boost anomaly {anomaly.real:.9f}')
print(f'improved positive-pair detuning at p=pi/4: {detuning:.9f}')
for p in (.2, .1, .05):
k = (p, -.7*p, .45*p)
v, vel = symbol(k), velocity(k, 0)
u = positive(v)
initial = [a*b for a, b in product(u, repeat=2)]
va = pair_velocity(initial, k, 0, True)
vs = scalar_contact(va)
sv = pair_velocity(scalar_contact(initial), k, 0, True)
diag = dot(initial, [(a+b)/2 for a, b in zip(vs, sv)]).real
dens = dot(initial, va).real
assert abs(diag - 2*v[3]*vel[3]/length(v)) < 1e-13
assert abs(dens - 2*dot(v, vel)/length(v)) < 1e-13
print(f'positive branch at scale {p:.2f}: scalar {diag:.8f}, density {dens:.8f}')
def squared_norm(blocks):
return sum(dot(u, u).real for u in blocks)
def corner_leakage():
size, g = 4, .2
configs = list(product(range(size), repeat=3))
volume = len(configs)
corners = [i for i, n in enumerate(configs) if i and all(s in (0, size//2) for s in n)]
pp = (0, 1, 4, 5)
def occupation(psi):
return sum(abs(psi[i][j])**2 for i in corners for j in pp)
for improved in (False, True):
symbols = []
for n in configs:
k = tuple(2*pi*s/size for s in n)
symbols.append((symbol(k, improved), symbol(tuple(-s for s in k), improved)))
def hamiltonian(psi):
contact = [g*s*sum(block[j] for block in psi)/volume for j, s in enumerate(SIGN)]
result = []
for block, (a, b) in zip(psi, symbols):
left, right = act(block, a, 0), act(block, b, 1)
result.append([x+y+c for x, y, c in zip(left, right, contact)])
return result
initial = [[0j]*16 for _ in configs]
initial[0][0] = 1.
rate = occupation(hamiltonian(initial))
assert abs(rate-7*(g/volume)**2) < 1e-17
end = .2
steps = ceil(end*(2*max(length(a) for a, _ in symbols)+abs(g)))
psi = initial
for _ in range(steps):
term = psi
total = [row[:] for row in psi]
for order in range(1, 17):
factor = -1j*end/(steps*order)
term = [[factor*x for x in row] for row in hamiltonian(term)]
for row, add in zip(total, term):
for j, value in enumerate(add):
row[j] += value
psi = total
assert abs(squared_norm(psi)-1) < 5e-14
prob = occupation(psi)
print(f'4³ torus, g={g}, t={end}, improved={improved}: '
f'corner probability {prob:.9g}, short-time coefficient {rate:.9g}')
if improved:
bound = (abs(g)*(1+1/sqrt(volume))/(16/3))**2
assert 0 < prob < bound
print(f'all-time improved corner probability bound {bound:.9g}')
def affine_identity():
# Open axial section of the actual improved symbol. Test the interaction
# identity by retaining the full [H,K] in a finite 2-particle position box.
size, g = 5, .61
configs = list(product(range(size), repeat=2))
basis = {pt: i for i, pt in enumerate(configs)}
rng_state = [[complex(sin(.71*(i+3*j)), cos(.31*(2*i+j))) for j in range(16)]
for i in range(len(configs))]
stencil = {0: (0,0,0,2.), 1: (.5j,0,0,-2/3), -1: (-.5j,0,0,-2/3),
2: (0,0,0,1/6), -2: (0,0,0,1/6)}
def apply(state, mode, contact=False):
result = [[0j]*16 for _ in configs]
for pt, block in zip(configs, state):
if (contact or mode == 'V') and pt[0] == pt[1]:
weight = g*pt[0] if mode == 'K' else g
result[basis[pt]] = [a+weight*b for a, b in
zip(result[basis[pt]], scalar_contact(block))]
if mode == 'V':
continue
for which, src in enumerate(pt):
for jump, coeff in stencil.items():
dst = src+jump
if not 0 <= dst < size:
continue
target = (dst, pt[1]) if which == 0 else (pt[0], dst)
out = result[basis[target]]
factor = {'H': 1., 'K': (src+dst)/2, 'v': -1j*jump}[mode]
for j, a in enumerate(act(block, coeff, which)):
out[j] += factor*a
return result
def comm(contact):
hk = apply(apply(rng_state,'K',contact),'H',contact)
kh = apply(apply(rng_state,'H',contact),'K',contact)
return [[1j*(a-b) for a,b in zip(u,v)] for u,v in zip(hk,kh)]
full, free = comm(True), comm(False)
vs = apply(apply(rng_state,'v'),'V')
sv = apply(apply(rng_state,'V'),'v')
residual = max(abs(a-b-(c+d)/2) for blocks in zip(full, free, vs, sv)
for a,b,c,d in zip(*blocks))
assert residual < 1e-12
print(f'independent full-affine interaction identity residual {residual:.2g}')
if __name__ == '__main__':
bands()
matrix_elements()
affine_identity()
corner_leakage()
virtual_contact.py
"""Exact finite-ring K=0 contact resolvent, units m=a=hbar=1. Python stdlib only."""
from math import cos, hypot, pi, sin, sqrt
def band(k):
s = sin(k)
m = 1 + (2/3)*(1-cos(k))**2
return m, s, hypot(m, s)
def loops(length, z):
"""Return contact loops for high momenta, other low bands, open low ++.
Each loop stores G00, G11=G22, G33 and G03=G12 in the sigma_x basis.
The k and -k terms cancel entries with an odd number of sigma_z factors.
"""
parts = [[0.0]*4 for _ in range(3)]
for j in range(-length//2, length//2):
k = 2*pi*j / length
m, s, e = band(k)
r, t = m/e, s/e
for a in (-1, 1):
for b in (-1, 1):
if 4*abs(j) >= length:
group = 0
elif a == b == 1:
group = 2
else:
group = 1
denominator = z-(a+b)*e
if denominator == 0:
if group != 2:
raise ValueError("closed channel at a free pole")
# At a real open free pole the reduced vertex is still
# well-defined. Flag the open loop so it cannot be used.
parts[group] = [float("nan")]*4
continue
scale = 1/(4*length*denominator)
entries = ((1+a*r)*(1+b*r), (1+a*r)*(1-b*r),
(1-a*r)*(1-b*r), -a*b*t*t)
for i, value in enumerate(entries):
parts[group][i] += scale*value
return parts
def add(*arrays):
return [sum(entries) for entries in zip(*arrays)]
def trace_weight(loop):
a, c, d, _ = loop
return (a+2*c+d)/4
def loop_matrix(loop):
a, c, d, b = loop
return [[a,0,0,b], [0,c,b,0], [0,b,c,0], [b,0,0,d]]
def solve(matrix, rhs):
a = [list(row) + [v] for row, v in zip(matrix, rhs)]
for i in range(len(a)):
p = max(range(i,len(a)), key=lambda j: abs(a[j][i]))
a[i], a[p] = a[p], a[i]
pivot = a[i][i]
if abs(pivot) < 1e-14:
raise ValueError("singular resolvent")
a[i] = [x/pivot for x in a[i]]
for j, row in enumerate(a):
if j != i:
factor = row[i]
a[j] = [x-factor*y for x,y in zip(row,a[i])]
return [row[-1] for row in a]
def minus(a,b):
return [[v-w for v,w in zip(x,y)] for x,y in zip(a,b)]
def inverse(a):
n = len(a)
return list(zip(*(solve(a,[float(i==j) for i in range(n)]) for j in range(n))))
def vertex(g, loop):
bare_inverse = [[(1 if i in (0,3) else -1)/g if i==j else 0
for j in range(4)] for i in range(4)]
return inverse(minus(bare_inverse,loop_matrix(loop)))
def pair(k):
m,s,e = band(k)
c = sqrt((1+m/e)/2)
d = s/(2*c*e)
return [c*c, -c*d, c*d, -d*d]
def matrix_element(left, matrix, right):
return sum(a.conjugate()*m*b for a,row in zip(left,matrix)
for m,b in zip(row,right))
def finite_ring_check(length=16, g=0.2):
# Compare a dense full-Hamiltonian inverse at one complex energy to both
# the contact T matrix and its two consecutive eliminations.
q = 2*pi/length
z = 2*band(q)[2] + 0.07j
high, other, low = loops(length, z)
reduced = vertex(g, add(high,other))
restored = inverse(minus(inverse(reduced),loop_matrix(low)))
full = vertex(g, add(high,other,low))
error_t = max(abs(a-b) for x,y in zip(restored,full) for a,b in zip(x,y))
n = 4*length
mat = [[0j]*n for _ in range(n)]
for j in range(length):
m,s,_ = band(2*pi*j/length)
free = ((2*m,-s,s,0),(-s,0,0,s),(s,0,0,-s),(0,s,-s,-2*m))
for a in range(4):
row = mat[4*j+a]
row[4*j+a] = z
for b in range(4):
row[4*j+b] -= free[a][b]
sign = 1 if a in (0,3) else -1
for l in range(length):
row[4*l+a] -= sign*g/length
u = pair(q)
rhs = [0j]*n
rhs[4:8] = u
dense = solve(mat,rhs)
exact = sum(x*y for x,y in zip(u,dense[4:8]))
free_pole = 1/(z-2*band(q)[2])
compressed = free_pole + free_pole**2*matrix_element(u,restored,u)/length
assert error_t < 1e-12 and abs(exact-compressed) < 1e-10
print(f"Restored contact T error {error_t:.3g}, dense resolvent error {abs(exact-compressed):.3g}")
def pair_spectrum(length, total_k, relative_offset=0.0):
"""Precompute free poles and their contact spectral weights for any K.
p=2*pi*j/L+relative_offset; k1=K/2+p, k2=K/2-p. Fixed relative_offset=0
is the smooth equal-twist family. For an untwisted finite ring at an
allowed K, use relative_offset=-K/2 (equivalent modulo 2*pi/L).
"""
if length <= 0:
raise ValueError("length must be positive")
spectrum = []
for j in range(length):
p = 2*pi*j/length + relative_offset
m1,s1,e1 = band(total_k/2+p)
m2,s2,e2 = band(total_k/2-p)
for a in (-1,1):
u,v,w = (1+a*m1/e1)/2, a*s1/(2*e1), (1-a*m1/e1)/2
for b in (-1,1):
x,y,z = (1+b*m2/e2)/2, b*s2/(2*e2), (1-b*m2/e2)/2
upper = (u*x, u*y, v*x, v*y, u*z, v*y, v*z, w*x, w*y, w*z)
spectrum.append((a*e1+b*e2, tuple(t/length for t in upper)))
return spectrum
def contact_denominator(spectrum, z, g):
"""det[I - g (sigma_x tensor sigma_x) G_K(z)] away from free poles."""
total = [0.0]*10
for pole, weights in spectrum:
if z == pole:
raise ValueError("free pole in contact denominator")
inv = 1/(z-pole)
for i in range(10):
total[i] += weights[i]*inv
mat = [[0.0]*4 for _ in range(4)]
index = 0
signs = (1,-1,-1,1)
for i in range(4):
for j in range(i,4):
value = total[index]
mat[i][j] = (i==j)-g*signs[i]*value
mat[j][i] = (i==j)-g*signs[j]*value
index += 1
det = 1.0
for i in range(4):
p = max(range(i,4), key=lambda j: abs(mat[j][i]))
if mat[p][i] == 0:
return 0.0
if p != i:
mat[i],mat[p] = mat[p],mat[i]
det = -det
pivot = mat[i][i]
det *= pivot
for j in range(i+1,4):
ratio = mat[j][i]/pivot
for k in range(i+1,4):
mat[j][k] -= ratio*mat[i][k]
return det
def bound_pair_energy(spectrum, g, lower, upper, tolerance=1e-12):
"""Bisect a real, pole-free bracket containing one simple bound root."""
if lower >= upper or tolerance <= 0 or any(lower <= e <= upper for e,_ in spectrum):
raise ValueError("ordered bracket outside the free poles and positive tolerance required")
f_lo = contact_denominator(spectrum,lower,g)
f_hi = contact_denominator(spectrum,upper,g)
if f_lo == 0:
return lower
if f_hi == 0:
return upper
if f_lo*f_hi > 0:
raise ValueError("bracket must enclose a sign-changing root")
while upper-lower > tolerance:
mid = (lower+upper)/2
if mid in (lower,upper):
break
f_mid = contact_denominator(spectrum,mid,g)
if f_mid == 0:
return mid
if (f_mid > 0) == (f_lo > 0):
lower, f_lo = mid, f_mid
else:
upper = mid
return (lower+upper)/2
def main():
g = 0.2
for length in (256,1024,4096):
high, other, _ = loops(length,2.)
closed = add(high,other)
rest = vertex(g, closed)[0][0]
print(f"L={length} high trace/4={trace_weight(high):+.9f} high rest={high[0]:+.9f}"
f" closed trace/4={trace_weight(closed):+.9f} closed rest={closed[0]:+.9f}"
f" matched g={rest:.9f}")
assert abs(rest-0.196345325) < 1e-8
for k_index in (64,32,16,8):
k = 2*pi*k_index/length
m,_,e = band(k)
high, other, _ = loops(length,2*e)
t = vertex(g,add(high,other))
forward = matrix_element(pair(k),t,pair(k))-rest*(m/e)**2
backward = matrix_element(pair(-k),t,pair(k))-rest
print(f"k={k:.7f} residual/k^2 forward={forward/k**2:+.8f}"
f" backward={backward/k**2:+.8f}")
assert abs(forward/k**2) < 0.03 and abs(backward/k**2) < 0.03
finite_ring_check()
spectrum = pair_spectrum(128,0.0)
bound = bound_pair_energy(spectrum,-0.5,1.5,1.9999)
assert abs(contact_denominator(spectrum,bound,-0.5)) < 1e-9
print(f"Attractive bound pole L=128, K=0, g=-0.5: {bound:.12f}")
if __name__ == "__main__":
main()
moving_bound.py
"""Moving bound pair in two local, rest-gap-matched spin contacts.
Integrate the relative-momentum resolvent in the Brillouin zone. In the gap
between mixed-sign bands and the positive two-particle continuum the Green
matrix is real and has no poles. Units set both constituent rest masses and
their small-momentum limiting speed to one.
"""
from math import cos, pi, sin, sqrt
I = ((1,0),(0,1))
X = ((0,1),(1,0))
Z = ((1,0),(0,-1))
def kron(a,b):
return [[a[i//2][j//2]*b[i%2][j%2] for j in range(4)] for i in range(4)]
BASIS = [kron(a,b) for a in (I,X,Z) for b in (I,X,Z)]
CONTACTS = {"density":kron(I,I), "mass":kron(X,X)}
def band(p):
t = 1-cos(p)
mass = 1+(2/3)*t*t
s = sin(p)
e = sqrt(s*s+mass*mass)
return e,mass/e,s/e
def sample(K,n):
modes=[]
for j in range(n):
p = 2*pi*j/n
a,x,z = band(K/2+p)
b,y,w = band(K/2-p)
modes.append((a+b,a-b,x,z,y,w))
return modes
def green(modes,energy):
coef=[0.0]*9
for plus,minus,x,z,y,w in modes:
pp,mm = 1/(energy-plus),1/(energy+plus)
pm,mp = 1/(energy-minus),1/(energy+minus)
c0,c1,c2,c12 = pp+mm+pm+mp, pp-mm+pm-mp, pp-mm-pm+mp, pp+mm-pm-mp
coef[0]+=c0
coef[1]+=c2*y
coef[2]+=c2*w
coef[3]+=c1*x
coef[4]+=c12*x*y
coef[5]+=c12*x*w
coef[6]+=c1*z
coef[7]+=c12*z*y
coef[8]+=c12*z*w
return [[sum(c*b[i][j] for c,b in zip(coef,BASIS))/(4*len(modes))
for j in range(4)] for i in range(4)]
def determinant(matrix):
a=[row[:] for row in matrix]
d=1.
for i in range(len(a)):
pivot=max(range(i,len(a)),key=lambda j:abs(a[j][i]))
if a[pivot][i]==0:return 0.
if pivot!=i:
a[i],a[pivot]=a[pivot],a[i]
d=-d
factor=a[i][i]
d*=factor
for j in range(i+1,len(a)):
m=a[j][i]/factor
for k in range(i+1,len(a)):
a[j][k]-=m*a[i][k]
return d
def kernel(green_matrix,contact,g):
return [[contact[i][j]/g-green_matrix[i][j] for j in range(4)] for i in range(4)]
def root(fun,lo,hi):
sign=fun(lo)
assert sign*fun(hi)<0, (lo,hi)
for _ in range(51):
mid=(lo+hi)/2
value=fun(mid)
if value==0:return mid
if sign*value<0:hi=mid
else:lo=mid
return (lo+hi)/2
def calibrate(z0,contact,n):
block=green(sample(0,n),z0)
def f(g):return determinant(kernel(block,contact,g))
prev=-.001
for i in range(1,151):
now=-i/50
if f(prev)*f(now)<0:return root(f,now,prev)
prev=now
raise ValueError("No weak attractive pole at the requested rest energy")
def moving(K,z0,contact,g,n):
modes=sample(K,n)
# Follow the shallow bound state below the positive continuum threshold.
delta=2-z0
edge=min(m[0] for m in modes)
lo,hi=edge-2.5*delta, edge-.12*delta
assert lo>max(abs(m[1]) for m in modes)
return root(lambda z:determinant(kernel(green(modes,z),contact,g)),lo,hi)
def multiply(a,v):
return [sum(x*y for x,y in zip(row,v)) for row in a]
def amplitudes(modes,z,contact,g):
k=kernel(green(modes,z),contact,g)
# A nonzero column of the adjugate supplies the null contact spinor.
candidates=[]
for i in range(4):
col=[(-1)**(i+j)*determinant([[k[r][c] for c in range(4) if c!=j]
for r in range(4) if r!=i]) for j in range(4)]
candidates.append(col)
chi=max(candidates,key=lambda v:sum(x*x for x in v))
norm=sqrt(sum(v*v for v in chi))
chi=[v/norm for v in chi]
assert max(map(abs,multiply(k,chi)))<3e-10
states=[]
for plus,minus,x,z1,y,z2 in modes:
projected=[0.]*4
for a,b,energy in ((1,1,plus),(1,-1,minus),(-1,1,-minus),(-1,-1,-plus)):
A=((1+a*z1,a*x),(a*x,1-a*z1))
B=((1+b*z2,b*y),(b*y,1-b*z2))
v=multiply(kron(A,B),chi)
for i in range(4):projected[i]+=v[i]/(4*(z-energy))
states.append(projected)
source=multiply(contact,[g*sum(v[j] for v in states)/len(states) for j in range(4)])
assert max(abs(x-y) for x,y in zip(source,chi))<3e-10
worst=0.
weights=[]
for (plus,minus,x,z1,y,z2),v in zip(modes,states):
a,b=(plus+minus)/2,(plus-minus)/2
h=[[a*(x*BASIS[3][i][j]+z1*BASIS[6][i][j])
+b*(y*BASIS[1][i][j]+z2*BASIS[2][i][j]) for j in range(4)] for i in range(4)]
hv=multiply(h,v)
worst=max(worst,max(abs(v[i]*z-hv[i]-source[i]) for i in range(4)))
weights.append(sum(t*t for t in v))
assert worst<3e-9
n=len(modes)
high=sum(w for j,w in enumerate(weights) if n//4<=j<=3*n//4)/sum(weights)
at_zero=[sum(v[j] for v in states) for j in range(4)]
on_site=sum(a*b for a,b in zip(at_zero,multiply(contact,at_zero)))/(n*sum(weights))
even=multiply(CONTACTS["mass"],chi)
assert max(abs(a-b) for a,b in zip(even,chi))<3e-9
return high,on_site
def curvature(z0,contact,g,n,pair_hop=0.):
estimates=[]
for h in (.06,.03,.015):
gh=g+pair_hop*(1-cos(h))
estimates.append(2*z0*(moving(h,z0,contact,gh,n)-z0)/h**2)
result=estimates[2]+(estimates[2]-estimates[1])/3
previous=estimates[1]+(estimates[1]-estimates[0])/3
assert abs(result-previous)<3e-5
return result
def run(z0,kind,n=384):
contact=CONTACTS[kind]
g=calibrate(z0,contact,n)
assert abs(moving(0,z0,contact,g,n)-z0)<2e-12
curv=curvature(z0,contact,g,n)
k=.3
energy=moving(k,z0,contact,g,n)
high,weight=amplitudes(sample(0,n),z0,contact,g)
print(f"rest {z0:.3f}, {kind:7s}, g={g:+.9f}, E E''={curv:.9f}, "
f"E(0.3)={energy:.9f}, metric={sqrt(z0*z0+k*k):.9f}, high weight={high:.8f}, contact={weight:.9f}")
return g,curv,energy
def contact_weight(z,kind,g,n):
# The source normalization gives the actual onsite spin expectation.
# Check its value independently by differentiating the bound energy in g.
S=CONTACTS["mass"]
# Rest parity makes the local Green matrix commute with S.
G0=green(sample(0,n),z)
assert max(abs(sum(S[i][l]*G0[l][j]-G0[i][l]*S[l][j] for l in range(4)))
for i in range(4) for j in range(4))<1e-12
vals=[]
for eps in (.001,.0005):
e1=moving(0,z,CONTACTS[kind],g+eps,n)
e2=moving(0,z,CONTACTS[kind],g-eps,n)
vals.append((e1-e2)/(2*eps))
assert abs(vals[0]-vals[1])<2e-6
derivative=(4*vals[1]-vals[0])/3
_,expectation=amplitudes(sample(0,n),z,CONTACTS[kind],g)
assert abs(derivative-expectation)<2e-8
return expectation
def finite_range_repair():
n=384
kind="mass"
contact=CONTACTS[kind]
z=1.9
g=calibrate(z,contact,n)
weight=contact_weight(z,kind,g,n)
initial=curvature(z,contact,g,n)
u=(1-initial)/(z*weight)
repaired=curvature(z,contact,g,n,u)
assert abs(repaired-1)<2e-5
print(f"Rest contact {weight:.9f}, pair hopping {u:.9f}, repaired E E'' {repaired:.9f}")
for k in (.3,.6):
actual=moving(k,z,contact,g+u*(1-cos(k)),n)
print(f"Calibration held out K={k}: energy {actual:.9f}, "
f"metric {sqrt(z*z+k*k):.9f}, difference {actual-sqrt(z*z+k*k):+.9f}")
other=1.975
g2=calibrate(other,contact,n)
test=curvature(other,contact,g2,n,u)
print(f"Held-out rest energy {other} with the same pair hopping: E E'' {test:.9f}")
assert abs(test-1)>1e-3
if __name__=="__main__":
for z in (1.9,1.975,1.99):
for kind in CONTACTS:
result=run(z,kind)
g2=calibrate(z,CONTACTS[kind],768)
e2=moving(.3,z,CONTACTS[kind],g2,768)
assert abs(result[0]-g2)<1e-10 and abs(result[2]-e2)<1e-10
finite_range_repair()
from virtual_contact import pair_spectrum, bound_pair_energy
for momentum in (0.,.04):
direct=bound_pair_energy(pair_spectrum(128,momentum),-.5,1.8,1.99)
independent=moving(momentum,1.94555,CONTACTS["mass"],-.5,128)
assert abs(independent-direct)<2e-10
print("Independent four-band pole check passed at rest and in motion.")
bound_3d.py
"""Three-dimensional bound-pair curvature on the full Brillouin torus.
Optional dependency: NumPy. Run python bound_3d.py for converged quadrature.
Use python bound_3d.py 16 for a quick check. No fitting libraries are used.
"""
import sys
import numpy as np
REST = 1.90
I2 = np.eye(2)
X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
Z = np.diag([1., -1.])
GAMMA = [np.eye(4)] + [np.kron(X, a) for a in (X, Y, Z)] + [np.kron(Z, I2)]
PAIRS = [(i, j) for i in range(4) for j in range(i+1, 4)]
BASIS = np.zeros((16, len(PAIRS)))
for col, (a, b) in enumerate(PAIRS):
BASIS[4*a+b, col] = 1/np.sqrt(2)
BASIS[4*b+a, col] = -1/np.sqrt(2)
FULL_TENSORS = np.array([np.kron(a, b) for a in GAMMA for b in GAMMA])
TENSORS = np.array([BASIS.T @ t @ BASIS for t in FULL_TENSORS])
BETA_PAIR = TENSORS[-1].real
IDENTITY = np.eye(6)
def mode(k, shape):
x, y, z = k
t = [2*np.sin(a/2)**2 for a in k]
b = [np.sin(x)*np.cos(y)*np.cos(z), np.sin(y)*np.cos(z), np.sin(z)]
m = 1+2*sum(a*a for a in t)/3+2*(t[0]*t[1]+t[0]*t[2]+t[1]*t[2])
e = np.sqrt(sum(a*a for a in b)+m*m)
basis = np.stack([np.broadcast_to(a/e, shape).ravel() for a in (*b, m)], axis=1)
return e.ravel(), basis
class Torus:
def __init__(self, size, rest=REST):
self.rest = rest
self.size = size
self.grid = tuple(np.asarray(axis) for axis in
np.ogrid[0:size:1, 0:size:1, 0:size:1])
def green(self, energy, axis=0, momentum=0., derivative=False, full=False):
# The four signed spectral projectors span all sixteen physical spin states.
# Integrate them first, then restrict the coincident source to exchange-odd.
moments = np.zeros((5, 5))
n = self.size
for lo in range(0, n, 8):
k = [self.grid[0][lo:lo+8], self.grid[1], self.grid[2]]
k = [p*(2*np.pi/n) for p in k]
shape = np.broadcast_shapes(*(p.shape for p in k))
shift = [momentum/2 if i == axis else 0. for i in range(3)]
ea, a = mode([p+s for p, s in zip(k, shift)], shape)
eb, b = mode([-p+s for p, s in zip(k, shift)], shape)
w = []
for s, t in ((1,1), (1,-1), (-1,1), (-1,-1)):
den = energy-s*ea-t*eb
w.append(-.25/den**2 if derivative else .25/den)
pp, pm, mp, mm = w
const = pp+pm+mp+mm
first = pp+pm-mp-mm
second = pp-pm+mp-mm
cross = pp-pm-mp+mm
moments[0,0] += np.sum(const)
moments[1:,0] += np.sum(first[:,None]*a, axis=0)
moments[0,1:] += np.sum(second[:,None]*b, axis=0)
moments[1:,1:] += a.T @ (cross[:,None]*b)
g = np.tensordot(moments.ravel()/n**3, FULL_TENSORS if full else TENSORS, axes=1)
assert np.max(abs(g-g.conj().T)) < 1e-12
return g
def rest_calibration(torus):
green = torus.green(torus.rest)
germ = green[np.ix_((0,5),(0,5))]
ev, vec = np.linalg.eigh(germ)
# Choose the negative pole with largest positive-mass-orbital coincidence amplitude.
root = np.argmax(abs(vec[0])**2)
lam = ev[root]
state = np.zeros(6,dtype=complex)
state[[0,5]] = vec[:,root]
assert lam < 0 and abs(state[0])**2 > .97
assert np.linalg.norm(green@state-lam*state) < 1e-12
d_energy = (state.conj() @ torus.green(torus.rest, derivative=True) @ state).real
assert d_energy < 0
return green, lam, state, d_energy
def row(torus, spacing, axis, calibrated):
plus = torus.green(torus.rest, axis, spacing)
return extract_curvature(torus.rest, spacing, plus, calibrated)
def extract_curvature(rest, spacing, plus, calibrated):
green0, lam, state, d_energy = calibrated
minus = BETA_PAIR @ plus @ BETA_PAIR # exact inversion on a symmetric torus
slope = (plus-minus)/(2*spacing)
curve = (plus+minus-2*green0)/spacing**2
results = []
for contact in (IDENTITY, BETA_PAIR):
pole_matrix = green0-lam*contact
eigenvalues, vectors = np.linalg.eigh(pole_matrix)
kept = abs(eigenvalues)>1e-9
assert np.sum(~kept) == 1
gaps = eigenvalues[kept]
overlaps = vectors[:,kept].conj().T @ slope @ state
pole_curve = (state.conj() @ curve @ state).real - 2*np.sum(abs(overlaps)**2/gaps)
results.append(-rest*pole_curve/d_energy)
return np.array(results)
def moving_root(torus, axis, momentum, contact, calibrated):
_, lam, state, _ = calibrated
energy = torus.rest
for _ in range(3):
vals, vecs = np.linalg.eigh(torus.green(energy, axis, momentum)-lam*contact)
j = np.argmax(abs(vecs.conj().T @ state)**2)
slope = (vecs[:,j].conj() @ torus.green(energy, axis, momentum, derivative=True)
@ vecs[:,j]).real
energy -= vals[j]/slope
residual = min(abs(np.linalg.eigvalsh(torus.green(energy, axis, momentum)-lam*contact)))
assert residual < 1e-12
return energy
def rotations():
# The 24 proper cubic rotations, generated by quarter-turns about x and z.
turns = [(np.array([[1,0,0],[0,0,-1],[0,1,0]]), (I2-1j*X)/np.sqrt(2)),
(np.array([[0,-1,0],[1,0,0],[0,0,1]]), (I2-1j*Z)/np.sqrt(2))]
queue = [(np.eye(3,dtype=int), I2)]
seen = set()
for r, u in queue:
key = tuple(r.ravel())
if key in seen:
continue
seen.add(key)
for t, v in turns:
queue.append((t@r, v@u))
u4 = np.kron(I2,u)
yield r, BASIS.T@np.kron(u4,u4)@BASIS
assert len(seen) == 24
ROTATIONS = list(rotations())
def average_channels(positive, axis=2):
# For K along lab axis i select U_R G(R^-1 K) U_R†.
total = np.zeros((6,6), dtype=complex)
for r, u in ROTATIONS:
direction = r[axis,:]
j = np.argmax(abs(direction))
g = positive[j]
if direction[j] < 0:
g = BETA_PAIR@g@BETA_PAIR
total += u@g@u.conj().T
return total/len(ROTATIONS)
def calculate(n, rest=REST, detailed=False):
torus = Torus(n,rest)
cal = rest_calibration(torus)
green, lam, state, d_energy = cal
weight = lam**2/(-d_energy)
full = torus.green(rest,full=True)
full_gaps = [np.sort(abs(np.linalg.eigvalsh(full-lam*contact)))[1]
for contact in (np.eye(16),FULL_TENSORS[-1])]
assert min(full_gaps) > 1e-5
print(f'E0={rest:.3f}, mesh={n}, g={1/lam:.10f}, E0*contact={rest*weight:.9f}, '
f'next full inverse-kernel gap={min(full_gaps):.7f}')
results = []
orient_rest = average_channels([green]*3)
assert np.linalg.norm(orient_rest@state-lam*state) < 1e-12
oriented_cal = (orient_rest,lam,state,d_energy)
# Richardson elimination of the leading step-squared error.
for step in (.01,.005,.0025):
plus = [torus.green(rest,j,step) for j in range(3)]
row_ = [extract_curvature(rest,step,g,cal) for g in plus]
avg = average_channels(plus)
for j in (0,1):
values = extract_curvature(rest,step,average_channels(plus,j),oriented_cal)
assert np.max(abs(values-extract_curvature(rest,step,avg,oriented_cal))) < 5e-8
row_.append(extract_curvature(rest,step,avg,oriented_cal))
results.append(np.array(row_))
coarse = (4*results[1]-results[0])/3
fine = (4*results[2]-results[1])/3
print(' refinement of extrapolated curvatures:',f'{np.max(abs(fine-coarse)):.2g}')
for name,pair in zip(('x','y','z','cubic'),fine):
print(f' {name}: R_density={pair[0]:.9f}, R_mass={pair[1]:.9f}')
if detailed:
# Locate actual moving poles independently of the curvature formula.
steps = (.012,.006)
for j,axis in enumerate('xyz'):
for i,contact in enumerate((IDENTITY,BETA_PAIR)):
energies = [moving_root(torus,j,k,contact,cal) for k in steps]
raw = [2*rest*(e-rest)/k**2 for e,k in zip(energies,steps)]
cross = (4*raw[1]-raw[0])/3
assert abs(cross-fine[j,i]) < 3e-6
print(f' {axis} contact {i}, E(.012)={energies[0]:.10f}, '
f'E(.006)={energies[1]:.10f}, independent R={cross:.8f}')
return fine,rest*weight
def independent_green():
# Invert the unrestricted 16 by 16 Hamiltonian directly on a small grid.
n = 5
torus = Torus(n)
ktotal = .117
full = np.zeros((16,16),complex)
for index in np.ndindex(n,n,n):
p = 2*np.pi*np.array(index)/n
halves = np.array((0,ktotal/2,0))
pair = []
for k in (p+halves,-p+halves):
en, basis = mode(k,())
pair.append(en[0]*sum(a*b for a,b in zip(basis[0],GAMMA[1:])))
h = np.kron(pair[0],GAMMA[0])+np.kron(GAMMA[0],pair[1])
full += np.linalg.inv(REST*np.eye(16)-h)
err = np.max(abs(full/n**3-torus.green(REST,1,ktotal,full=True)))
assert err < 1e-14
print(f'independent full Green matrix direct-inversion residual {err:.2g}')
if __name__ == '__main__':
independent_green()
sizes = [int(x) for x in sys.argv[1:]] or [16,32,48,64,80]
results = [calculate(n,detailed=(n == sizes[0])) for n in sizes]
if len(sys.argv) == 1:
assert np.max(abs(results[-1][0]-results[-2][0])) < 2e-6
held = [calculate(n,1.975) for n in (64,96,112)]
print('held-out mesh difference in R:', np.max(abs(held[-1][0]-held[-2][0])))
train, weight_train = results[-1]
test, weight_test = held[-1]
c = (1-train[-1])/weight_train
print('onsite pair-hop calibration c (density, mass):', c)
print('held-out ratios after this correction:', test[-1]+weight_test*c)
pair_shapes.py
"""Exact covering controls and relative shapes of two calculated quadratic energy sublevels."""
from fractions import Fraction
from itertools import product
from math import sqrt
def relative_shapes(density, mass):
eigenvalues = [m / d for d, m in zip(density, mass)]
return sqrt(max(eigenvalues)), 1 / sqrt(min(eigenvalues))
def main():
# The four regular-tetrahedron directions are the even sign triples / sqrt(3).
signs = [s for s in product((-1, 1), repeat=3) if s[0]*s[1]*s[2] == 1]
gram = [[Fraction(sum(x*y for x, y in zip(a, b)), 3) for b in signs] for a in signs]
assert all(gram[i][i] == 1 for i in range(4))
assert all(gram[i][j] == Fraction(-1, 3) for i in range(4) for j in range(i))
inradius = -gram[0][1]
radius_squared = 1 - inradius**2
assert radius_squared == Fraction(8, 9)
# Finest ordered-model curvatures at E0=1.900, in the same rods.
density = (1.52018924, 1.53379403, 1.43825053)
mass = (1.51829182, 1.53343829, 1.36466062)
scales = relative_shapes(density, mass)
disparity = scales[0] * scales[1]
assert abs(disparity - 1.02649) < 0.00001
print(f"Four-copy radius squared {radius_squared}; mutual shape ratio {disparity:.8f}")
for name, curvatures in (("density", density), ("mass", mass)):
print(f"{name} longest/shortest semiaxis {sqrt(max(curvatures)/min(curvatures)):.8f}")
# Recalibrating any one axis in both models preserves all relative eigenvalues.
common = (2.0, 0.7, 1.3)
adjusted = [tuple(x*s*s for x,s in zip(form,common)) for form in (density,mass)]
assert all(abs(a-b) < 1e-14 for a,b in zip(scales, relative_shapes(*adjusted)))
cubic = relative_shapes([1.52882750]*3, [1.52384400]*3)
assert abs(cubic[0]*cubic[1]-1) < 1e-14
if __name__ == "__main__":
main()
reference_data.py
"""Replay the numerical reading of Zhang et al., PRL 135, 230202, Fig. 4(b).
Run without arguments for the independent recoil calculation. With --source PATH,
also verify the original PDF and the plotted marker pixels. Python 3, stdlib only.
"""
import argparse
from hashlib import sha256
from math import exp
from pathlib import Path
import re
import zlib
PAPER_SHA = "599aab6511d8165125ecc4b88580f43d792941a56f0836cd5634e4b459f28ed9"
PIXEL_SHA = "a4cdb298beaa94192b500b8f9484793e3fc72b6c2367f519213b78a980b02e28"
RECOIL_KHZ = 3.7710
TRAP_KHZ = 36.0
# Coordinates in original pixels (x right, y down). Two central disks overlap.
# Columns are Fig. 4(b) marker centers, read to roughly +/-2 pixels.
MARKERS = ((1028, 111), (1076, 247), (1131, 292), (1142, 277),
(1172, 476), (1244, 518), (1371, 581), (1482, 719))
X_ZERO, X_FOUR = 1004.5, 1723.5
Y_POINT_TWO, Y_POINT_NINE = 809.5, 39.5
# Vertical endpoints of the coldest and hottest reported one-sigma bars.
COLD_Y_BAR = (96, 125)
HOT_Y_BAR = (696, 742)
# At the coldest point the marker obscures any horizontal bar shorter than its
# diameter. Use the full disk outline as a reading envelope for that endpoint.
COLD_X_ENVELOPE = (1017, 1038)
HOT_X_BAR = (1310, 1622)
def occupation(x):
return 4 * (x - X_ZERO) / (X_FOUR - X_ZERO)
def fringe(y):
return 0.2 + 0.7 * (Y_POINT_TWO - y) / (Y_POINT_TWO - Y_POINT_NINE)
def thermal(n, recoil_over_trap):
return exp(-2 * recoil_over_trap * (2 * n + 1))
def contrast_ratio(cold, hot):
return exp(-4 * RECOIL_KHZ * (hot - cold) / TRAP_KHZ)
def verify_source(path):
pdf = path.read_bytes()
if sha256(pdf).hexdigest() != PAPER_SHA:
raise ValueError("This extraction uses the cited byte-exact publisher PDF.")
# In this specific PDF object 64 is a FlateDecode RGB image without a
# predictor. Restrict parsing to the pinned file and verify its pixel hash.
stream = re.search(rb"(?:\r|\n)64 0 obj\s*<<[^>]*>>\s*stream(?:\r\n|\n|\r)", pdf)
if stream is None:
raise ValueError("Figure 4 stream was not found.")
pixels = zlib.decompress(pdf[stream.end():])
assert len(pixels) == 1752 * 904 * 3 and sha256(pixels).hexdigest() == PIXEL_SHA
def red(x, y):
start = 3 * (1752 * y + x)
r, g, b = pixels[start:start + 3]
return r - g > 96 and r - b > 70 and g < 150
for x, y in MARKERS:
# Some marker pixels are occluded by the drawn curve. Confirm that a
# neighborhood of each transcribed center is filled, not just a line.
assert sum(red(i, j) for i in range(x-5, x+6) for j in range(y-5, y+6)) >= 60
# Edge checks allow the antialiasing of the printed error bars.
for (x, y), y_bar, x_bar in (
(MARKERS[0], COLD_Y_BAR, COLD_X_ENVELOPE),
(MARKERS[-1], HOT_Y_BAR, HOT_X_BAR),
):
for edge_x, edge_y in [(x, v) for v in y_bar] + [(v, y) for v in x_bar]:
assert any(red(i, j) for i in range(edge_x-2, edge_x+3)
for j in range(edge_y-2, edge_y+3))
print("Verified original PRL PDF, Figure 4 RGB stream and marker/error-bar pixels.")
def report():
print("Fig 4(b) occupation measured V predicted V measured - predicted")
points = [(occupation(x), fringe(y)) for x, y in MARKERS]
eta_squared = RECOIL_KHZ / TRAP_KHZ
for i, (n, v) in enumerate(points, 1):
predicted = thermal(n, eta_squared)
print(f"{i:8d} {n:10.3f} {v:10.3f} {predicted:11.3f} {v-predicted:+.3f}")
cold, hot = points[0], points[-1]
measured = hot[1] / cold[1]
predicted = contrast_ratio(cold[0], hot[0])
measured_low = fringe(HOT_Y_BAR[1]) / fringe(COLD_Y_BAR[0])
measured_high = fringe(HOT_Y_BAR[0]) / fringe(COLD_Y_BAR[1])
predicted_low = contrast_ratio(occupation(COLD_X_ENVELOPE[0]), occupation(HOT_X_BAR[1]))
predicted_high = contrast_ratio(occupation(COLD_X_ENVELOPE[1]), occupation(HOT_X_BAR[0]))
print(f"Hot/cold measured {measured:.4f}, vertical bar envelope [{measured_low:.3f}, {measured_high:.3f}]")
print(f"Hot/cold predicted {predicted:.4f}, horizontal envelope [{predicted_low:.3f}, {predicted_high:.3f}]")
print(f"36 kHz unsqueezed zero-temperature visibility {thermal(0, eta_squared):.4f}")
eta, u_eta = 0.316, 0.001 # Cheng et al., 2026 preprint, Eq. S11
v0 = thermal(0, eta**2)
print(f"2026 calibrated eta reference {v0:.5f} +/- {4*eta*v0*u_eta:.5f}")
assert measured_low < predicted < measured_high and predicted_low < measured < predicted_high
assert 0.06 < cold[1] - thermal(cold[0], eta_squared) < 0.08
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", type=Path, help="verify the cited publisher PDF")
args = parser.parse_args()
if args.source:
verify_source(args.source)
report()
replay.py
"""Replay the shell clock and gravitational stress 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 = "61cebdbf05b33b1ebeac92de12a750940c0995986374ecbdca12ac79658b6cff"
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")
parser.add_argument("--full", action="store_true", help="also run the three-dimensional bound-pair integrals with NumPy")
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 ("gates", "pulse_order", "packet_3d", "material_bracket", "cesium_band", "cell", "shell", "nested", "breathing", "rod", "pressure", "constrained", "pressure_wave", "tensor_rotor", "clocks_data", "contact_reference", "reference_scattering", "free_reference",
"improved_contact", "virtual_contact", "moving_bound", "pair_shapes", "reference_data"):
subprocess.run([*python, str(ROOT / (script + ".py"))], check=True)
if args.full:
import os
environment = dict(os.environ, OPENBLAS_NUM_THREADS="1")
subprocess.run([sys.executable, "-B", str(ROOT / "bound_3d.py")], env=environment, 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 / "clocks.tly", work / "clocks.tly")
result = subprocess.run([*python, str(tally / "tally.py"), "clocks.tly"], cwd=work,
stdout=subprocess.PIPE, check=True)
actual = result.stdout.decode("utf-8").splitlines()
expected = (ROOT / "clocks.out").read_text(encoding="utf-8").splitlines()
if actual != expected or sum(line.startswith("✓") for line in actual) != 55:
raise ValueError("Tally output differs from the 55 published checks")
count = "twenty-four" if args.full else "twenty-three standard-library"
print(f"All {count} calculations and the complete 55-assertion Tally transcript passed.")
if __name__ == "__main__":
main()
clock_plot.py
"""Plot Zheng et al. (2023), Supplementary Table 1, with its total error bars.
Optional figure build: python3 clock_plot.py (matplotlib and Pillow).
Data checks in clocks_data.py require only the standard library.
"""
from io import BytesIO
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from PIL import Image
from clocks_data import ENDPOINT, HALF_HEIGHT, SLOPE
# Pair ordering within each set is top-to-bottom at the same nominal spacing.
# Corrected fractional frequency and total uncertainty, both in 1e-19 units.
PAIR_GROUPS = (
(0.25, ((-2.71, 1.98), (-4.68, 1.99), (-2.04, 1.96), (-2.52, 2.02))),
(0.50, ((-7.23, 2.18), HALF_HEIGHT, (-6.22, 2.19))),
(0.75, ((-7.91, 2.52), (-8.90, 2.50))),
(1.00, (ENDPOINT,)),
)
def main():
fg, secondary, teal, grid = '#1d2831', '#455664', '#006f6e', '#e3e8ea'
with plt.rc_context({'font.size': 9, 'text.color': fg, 'axes.labelcolor': fg,
'xtick.color': secondary, 'ytick.color': secondary}):
fig, ax = plt.subplots(figsize=(4.20, 3.78), dpi=100)
fig.subplots_adjust(left=.16, right=.97, top=.75, bottom=.26)
fig.text(.07, .94, 'Clock redshift over one centimetre', fontsize=13.8,
weight='bold', ha='left')
fig.text(.07, .86, 'Fractional frequency shift (×10⁻¹⁹)', fontsize=10)
ax.plot([0, 1.04], [0, SLOPE*1.04], color=fg, lw=1.6,
label='Gravimeter prediction', zorder=2)
for i, (height, values) in enumerate(PAIR_GROUPS):
for j, (v, err) in enumerate(values):
x = height + .021*(j-(len(values)-1)/2)
ax.errorbar(x, v, yerr=err, fmt='o', ms=4.2, color=teal, lw=1.2,
capsize=2, zorder=3,
label='Clock pair ±1σ' if (i, j) == (0, 0) else None)
ax.set(xlim=(0, 1.07), ylim=(-16, 2), yticks=[-15,-10,-5,0],
xticks=[0,.25,.50,.75,1.0], xticklabels=['0','0.25','0.50','0.75','1.00'],
xlabel='Nominal height difference (cm)')
ax.grid(axis='y', color=grid, lw=.8)
ax.tick_params(length=0, pad=5)
for spine in ax.spines.values():
spine.set_visible(False)
ax.legend(loc='lower left', frameon=False, handlelength=1.65,
borderpad=0, fontsize=8.3, labelspacing=.3)
fig.text(.07, .090, 'Shared clocks correlate the ten pairs. Symbols at each',
fontsize=8.4, color=secondary)
fig.text(.07, .047, 'height are spread for visibility. Zheng et al., Table S1 (2023).',
fontsize=8.4, color=secondary)
output = BytesIO()
fig.savefig(output, format='png', facecolor='white')
plt.close(fig)
output.seek(0)
with Image.open(output) as raster:
raster.convert('RGB').quantize(colors=128, dither=Image.Dither.NONE).save(
Path(__file__).with_name('clock_redshift.png'), optimize=True)
if __name__ == '__main__':
main()