Complete Tally transcript
✓ normalized plane waves on eight cubed have squared contact overlap two over volume squared (by cross-pairing plus and minus sides; derived)
✓ the equal-energy current-changing matrix element survives squared (by cross-pairing plus and minus sides; derived)
✓ two fixed-volume Fourier grids count the exceptional momenta in the range bound (by cross-pairing plus and minus sides; derived)
✓ Parseval bounds the correction norm from its contact amplitude (by cross-pairing plus and minus sides; derived)
✓ eight-site edge requires a correction radius of at least two (by cross-pairing plus and minus sides; derived)
✓ the contact connects principal momenta separated by two pi with known squared matrix element (by cross-pairing plus and minus sides; derived)
✓ the corner hopping amplitude survives the full time-series remainder (by cross-pairing plus and minus sides; derived)
✓ the eight-corner detection probability has a positive early-time lower bound (by cross-pairing plus and minus sides; derived)
✓ the calibrated axial carrier fixes its energy flux (by cross-pairing plus and minus sides; derived)
✓ a measured band strain slope can cancel the packet-edge recoil (by cross-pairing plus and minus sides; derived)
✓ equal unstrained bands can drive the same support in opposite directions (by cross-pairing plus and minus sides; derived)
✓ this example has stable sound and a nonresonant moving envelope (by cross-pairing plus and minus sides; derived)
✓ the curvature term changes the finite-wavevector density while preserving total energy (by cross-pairing plus and minus sides; derived)
✓ opposite deviations of the strain exponent from one violate a saturated cone on opposite strain sides (by cross-pairing plus and minus sides; derived)
✓ independent lattice and force calibrations fix both peak-to-peak swings in micrometers (by cross-pairing plus and minus sides; derived)
Native Tally source
# Rational witnesses for energy transport, mechanical strain and ray recoil.
ratchet 16 step
import "atom"
let zero=whole(0 trial)
let one=whole(1 trial)
let two=whole(2 trial)
let half=fraction(1 trial,2 trial)
let four=whole(4 trial)
let eight=whole(8 trial)
let length=eight
let volume=length*length*length
let ux=one
let uy=zero
let contact_sq=share(two,volume*volume)
check contact_sq==fraction(1 trial,131072 trial) "normalized plane waves on eight cubed have squared contact overlap two over volume squared"
check (ux+flip(uy))*(ux+flip(uy))*contact_sq==contact_sq "the equal-energy current-changing matrix element survives squared"
fn exceptional(l)
return l*l*l+(flip(l)+four)*(l+flip(two))*(l+flip(two))
end
let points=exceptional(length)
check points==whole(368 trial) and exceptional(whole(16 trial))==whole(1744 trial) "two fixed-volume Fourier grids count the exceptional momenta in the range bound"
check share(volume,points)==fraction(32 trial,23 trial) "Parseval bounds the correction norm from its contact amplitude"
check (length+flip(four))*half==two "eight-site edge requires a correction radius of at least two"
let x_in=half
let x_out=flip(half)
let fold=two*(x_in+flip(x_out))
check fold==two and share(one,volume*volume)==fraction(1 trial,262144 trial) "the contact connects principal momenta separated by two pi with known squared matrix element"
let tau=fraction(1 trial,8 trial)
let remainder=share(tau*tau,two*(one+flip(share(tau,whole(3 trial)))))
let lower=share(tau,eight)+flip(remainder)
check remainder==fraction(3 trial,368 trial) and lower==fraction(11 trial,1472 trial) "the corner hopping amplitude survives the full time-series remainder"
check eight*lower*lower>fraction(44 trial,100000 trial) "the eight-corner detection probability has a positive early-time lower bound"
let epsilon=half
let sine=fraction(3 trial,5 trial)
let cosine=fraction(4 trial,5 trial)
let energy=one+epsilon*sine
let velocity=epsilon*cosine
let current=energy*velocity
let dynamic=energy*velocity*velocity
let pressure=epsilon*sine
check sine*sine+cosine*cosine==one and current==fraction(13 trial,25 trial) "the calibrated axial carrier fixes its energy flux"
fn edge_load(slope,dynamic,pressure)
return dynamic+flip(slope*pressure)
end
let cancel=share(dynamic,pressure)
check cancel==fraction(52 trial,75 trial) and edge_load(cancel,dynamic,pressure)==zero "a measured band strain slope can cancel the packet-edge recoil"
check edge_load(zero,dynamic,pressure)==fraction(26 trial,125 trial) and edge_load(one,dynamic,pressure)==flip(fraction(23 trial,250 trial)) "equal unstrained bands can drive the same support in opposite directions"
let sound_sq=share(half,two)
check sound_sq==fraction(1 trial,4 trial) and sound_sq>velocity*velocity "this example has stable sound and a nonresonant moving envelope"
let q=whole(3 trial)
let tidal=flip(two*q*q)
check tidal==flip(whole(18 trial)) and flip(two*zero*zero)==zero "the curvature term changes the finite-wavevector density while preserving total energy"
let g_low=fraction(4 trial,5 trial)
let g_high=fraction(6 trial,5 trial)
check g_low+flip(one)<zero and g_high+flip(one)>zero "opposite deviations of the strain exponent from one violate a saturated cone on opposite strain sides"
# Measured lattice spacing 0.532 micrometers, calibrated J/h=1549 Hz.
let spacing=fraction(532 trial,1000 trial)
let tunnel=whole(1549 trial)
fn swing(f,spacing,tunnel)
return share(four*tunnel*spacing,f)
end
let weak=swing(fraction(211 trial,10 trial),spacing,tunnel)
let strong=swing(fraction(507 trial,10 trial),spacing,tunnel)
check weak>whole(156 trial) and weak<fraction(1563 trial,10 trial) and strong>whole(65 trial) and strong<fraction(651 trial,10 trial) "independent lattice and force calibrations fix both peak-to-peak swings in micrometers"
current.py
"""Two-boson energy-current obstruction for the autonomous cubic Pauli walk.
All matrices use ordered spin indices (++,+-,-+,--). This program checks the
wave witnesses, contact spin span and determinant underlying the analytic proof.
It uses only Python's standard library. The infinite-volume result is in current.md.
"""
from cmath import exp
from itertools import permutations, product
from math import cos, sin, pi, sqrt
X = ((0, 1), (1, 0))
Y = ((0, -1j), (1j, 0))
Z = ((1, 0), (0, -1))
I = ((1, 0), (0, 1))
PAULI = (X, Y, Z)
K = (pi/2, 0, 0)
A = (pi/4, 0, 0)
B = (pi/4, pi/2, 0)
V = (1, 0, 0, -1)
def tensor(a, b):
return tuple(tuple(a[r//2][s//2]*b[r%2][s%2] for s in range(4)) for r in range(4))
def apply(matrix, v):
return tuple(sum(a*b for a, b in zip(row, v)) for row in matrix)
def close(v, w, tol=4e-13):
return max(abs(a-b) for a, b in zip(v, w)) < tol
def pauli(d, shift=0):
return tuple(tuple(shift*I[r][s]+sum(d[j]*PAULI[j][r][s] for j in range(3))
for s in range(2)) for r in range(2))
def symbol(k):
x, y, z = k
return (sin(x)*cos(y)*cos(z), sin(y)*cos(z), sin(z))
def power_current_x(k, offset):
# Units epsilon=a=hbar=1. Half of the anticommutator of h and its derivative.
x, y, z = k
d = symbol(k)
derivative = cos(x)*cos(y)*cos(z)
return pauli((offset*derivative, 0, 0), shift=d[0]*derivative)
def pair(op, k):
p = tuple(t-s for t, s in zip(K, k))
left, right = tensor(op(k), I), tensor(I, op(p))
return tuple(tuple(a+b for a, b in zip(row, col)) for row, col in zip(left, right))
def frame_action(v):
# Four times the sum of projectors onto ++y, --y, ++z, --z. Exact integer arithmetic.
result = [0j]*4
for s, weight in (((1, 1j, 1j, -1), 1), ((1, -1j, -1j, -1), 1),
((1, 0, 0, 0), 4), ((0, 0, 0, 1), 4)):
dot = sum(complex(a).conjugate()*b for a, b in zip(s, v))
for i in range(4):
result[i] += weight*s[i]*dot
return tuple(result)
def determinant(matrix):
ans = 0j
for p in permutations(range(4)):
inversions = sum(p[i] > p[j] for i in range(4) for j in range(i+1, 4))
term = (-1)**inversions
for i, j in enumerate(p):
term *= matrix[i][j]
ans += term
return ans
def main():
empty = (0,)*4
for momentum in (A, B, (B[0], -B[1], B[2])):
assert close(apply(pair(lambda k: pauli(symbol(k)), momentum), V), empty)
for offset in (0, 1, 3.5):
out = apply(pair(lambda k: power_current_x(k, offset), momentum), V)
assert close(out, V if momentum == A else empty)
# Real-space contact amplitudes; the common total translation phase factors out.
def relative_waves(r):
phase = exp(1j*A[0]*r[0])
return phase, phase*cos(B[1]*r[1])
assert relative_waves((0, 0, 0)) == (1, 1)
assert abs(relative_waves((0, 2, 0))[0]-relative_waves((0, 2, 0))[1]) == 2
# These three triplet directions exhaust the contact space.
for s, eigenvalue in ((V, 8), ((1, 0, 0, 1), 4), ((0, 1, 1, 0), 4)):
assert frame_action(s) == tuple(eigenvalue*z for z in s)
# Discrete singular set of the free matrix, counted with integer modular arithmetic.
# Parseval bounds the norm of every exact correction with D(0)=-v.
for side in (8, 16, 24, 32):
singular = sum((8*x) % (2*side) == side or (4*y) % (2*side) == side
or (4*z) % (2*side) == side
for x, y, z in product(range(side), repeat=3))
assert singular == side**3-(side-4)*(side-2)**2
assert side**3/singular > side/8
print("finite box: exceptional points L³−(L−4)(L−2)²; minimum support radius L/2−2")
worst = 0
for k in product((-.87, .21, pi/4, 1.27), (-.71, .31, pi/2), (.15, 1.1)):
kx, ky, kz = k
expected = cos(2*kx)**2*cos(ky)**4*cos(kz)**4
value = determinant(pair(lambda q: pauli(symbol(q)), k))
worst = max(worst, abs(value-expected))
assert worst < 2e-15
# The simple transverse crossing gives a first-order pole at a generic point.
# This numerical ratio illustrates the analytic nonintegrability argument.
def gap(dx):
k = (pi/4+dx, .41, -.32)
p = tuple(t-s for t, s in zip(K, k))
return sqrt(sum(z*z for z in symbol(k)))-sqrt(sum(z*z for z in symbol(p)))
assert abs(gap(1e-4)/gap(5e-5)-2) < 1e-6
print("contact-dark pair: free energy relative to 2E0 = 0,0; free x currents = 1,0")
print("contact spin frame (normalized projector sum): triplet eigenvalues 2,1,1")
print(f"free relative determinant maximum spot-check error {worst:.2e}")
if __name__ == "__main__":
main()
resonance.py
"""On-shell matrix elements for a contact, using first-quantized Bose states."""
from cmath import exp
from math import cos, factorial, pi, sin, sqrt
from itertools import product
def contact_element(length, incoming, outgoing):
# At contact each summand is a scalar plane wave times its spin vector.
volume = length**3
total = 0j
for site in product(range(length), repeat=3):
def contact(state):
phase, spin = state
factor = exp(1j*sum(x*k for x,k in zip(site,phase)))/volume
return [factor*c for c in spin]
left, right = contact(outgoing), contact(incoming)
total += sum(x.conjugate()*y for x,y in zip(left,right))
return total
def main():
plus, minus = [1/sqrt(2),1/sqrt(2)], [1/sqrt(2),-1/sqrt(2)]
opposite = [(plus[i]*minus[j]+minus[i]*plus[j])/sqrt(2)
for i,j in product(range(2),repeat=2)]
v = [1/sqrt(2),0,0,-1/sqrt(2)]
for length in (8,16):
volume = length**3
k = (pi/2,0,0)
overlap = contact_element(length,(k,v),(k,[sqrt(2)*x for x in v]))
assert abs(overlap-sqrt(2)/volume) < 1e-14
wrapped = contact_element(length,((pi,0,0),opposite),((-pi,0,0),opposite))
assert abs(wrapped-1/volume)<1e-14
assert abs(2*pi*wrapped-2*pi/volume)<1e-14
free_energies = [(1.37+sin(p))+(1.37-sin(p)) for p in (pi/2,-pi/2)]
assert free_energies[0]==free_energies[1]
# Corner leading probability and rigorously positive lower bound at short time.
tau = 1/8
tail = sum(tau**m/factorial(m) for m in range(2,30))
bound = tau*tau/(2*(1-tau/3))
assert tail < bound and abs(tau/8-bound-11/1472)<1e-15
print("Verified normalized contact amplitudes sqrt(2)/V and 1/V in two cubes.")
print("At tau=1/8: any-corner probability >",(tau/8-bound)**2*8)
if __name__ == "__main__":
main()
material.py
"""Evaluate the material conservation equations on continuous three-dimensional coordinates.
No external packages. Fourth-order multivariate Taylor jets evaluate all spatial
derivatives of the two second-order site Hamiltonians at the quoted configuration.
The test uses the two-boson sector on a single bond and unsymmetrised lab q vectors.
"""
from cmath import exp
from itertools import product
from math import factorial, sqrt
DEG = 4
DIM = 6
POWERS = sorted((p for p in product(range(DEG + 1), repeat=DIM) if sum(p) <= DEG),
key=lambda p: (sum(p), p))
INDEX = {p: i for i, p in enumerate(POWERS)}
SIZE = len(POWERS)
PRODUCT = [(i, j, INDEX[tuple(a + b for a, b in zip(p, v))])
for i, p in enumerate(POWERS) for j, v in enumerate(POWERS)
if sum(p) + sum(v) <= DEG]
DIFFER = [[(i, INDEX[tuple(n - int(s == k) for s, n in enumerate(p))], p[k])
for i, p in enumerate(POWERS) if p[k]] for k in range(DIM)]
class Jet:
def __init__(self, value=0):
self.c = [0] * SIZE
self.c[0] = value
def __add__(self, rhs):
obj = Jet()
if isinstance(rhs, Jet):
obj.c = [a + b for a, b in zip(self.c, rhs.c)]
else:
obj.c = self.c.copy()
obj.c[0] += rhs
return obj
__radd__ = __add__
def __mul__(self, rhs):
obj = Jet()
if isinstance(rhs, Jet):
for i, j, k in PRODUCT:
obj.c[k] += self.c[i] * rhs.c[j]
else:
obj.c = [a * rhs for a in self.c]
return obj
__rmul__ = __mul__
def __sub__(self, rhs):
return self + (-1) * rhs
def __rsub__(self, rhs):
return (-1) * self + rhs
def d(self, k):
obj = Jet()
for i, j, n in DIFFER[k]:
obj.c[j] = n * self.c[i]
return obj
def series(self, coeff):
z = self - self.c[0]
acc = Jet()
for a in reversed(coeff):
acc = acc * z + a
return acc
def exp(self):
return self.series([exp(self.c[0]) / factorial(i) for i in range(DEG + 1)])
def square_root(self):
a = self.c[0]
b = [sqrt(a)]
for i in range(1, DEG + 1):
b.append(b[-1] * (1.5 - i) / (a * i))
return self.series(b)
def reciprocal(self):
a = self.c[0]
return self.series([(-1) ** i / a ** (i + 1) for i in range(DEG + 1)])
def coordinate(k, value):
z = Jet(value)
z.c[INDEX[tuple(int(t == k) for t in range(DIM))]] = 1
return z
R = tuple(coordinate(i, x) for i, x in enumerate((.2, -.4, .3, 1.1, .6, -.25)))
r = tuple(R[3 + i] - R[i] for i in range(3))
length = sum(a * a for a in r).square_root()
mass, spring, rest, gamma, e0, u = 1.7, .73, 1.2, .8, 1.31, .63
beta = (.3 + .4j)
g = ((1 - length * (1 / rest)) * gamma).exp()
v = .5 * spring * (length - rest) * (length - rest)
def add(a, b):
return [x + y for x, y in zip(a, b)]
def plus(A, B):
return lambda x: add(A(x), B(x))
def scale(a, A):
return lambda x: [a * t for t in A(x)]
def times(a):
return lambda x: [a * t for t in x]
def compose(A, B):
return lambda x: A(B(x))
def sym(A, B):
return plus(compose(A, B), compose(B, A))
def comm(A, B):
return plus(compose(A, B), scale(-1, compose(B, A)))
def hop(x):
# Index n counts the particles on site 0. beta multiplies a1†a0.
result = [Jet() for _ in x]
for n in range(3):
if n:
result[n - 1] = result[n - 1] + beta * sqrt(n * (3 - n)) * x[n]
if n < 2:
result[n + 1] = result[n + 1] + beta.conjugate() * sqrt((n + 1) * (2 - n)) * x[n]
return result
bond = plus(times(v), scale(g, hop))
def momentum(n, i):
return lambda x: [-1j * w.d(3 * n + i) for w in x]
def site(n):
def action(x):
halfbond = bond(x)
result = []
for j, w in enumerate(x):
count = j if n == 0 else 2 - j
onsite = e0 * count + .5 * u * count * (count - 1)
kin = sum(w.d(3 * n + i).d(3 * n + i) for i in range(3)) * (-.5 / mass)
result.append(kin + onsite * w + .5 * halfbond[j])
return result
return action
h = [site(0), site(1)]
H = plus(*h)
I = scale(1j, comm(*h))
force = [plus(times(spring * (length - rest) * a * length.reciprocal()),
scale((-gamma / rest) * g * a * length.reciprocal(), hop)) for a in r]
def trial(s):
out = []
for n in range(3):
phase = sum((.09 * (i + 1) * (n + 1) - .21 * s * (i % 3 + 1)) * z
for i, z in enumerate(R))
out.append((1j * phase).exp() * ((.3 + .2j * n) + .17 * R[n+s-1] * R[5-n]))
return out
def vals(operator, x):
return [z.c[0] for z in operator(x)]
def check(q, s):
e = [(-1j * sum(q[i] * R[3 * n + i] for i in range(3))).exp() for n in range(2)]
dot = .5 * sum(k * a for k, a in zip(q, r))
if any(q):
sinc = ((1j * dot).exp() - (-1j * dot).exp()) * dot.reciprocal() * (-.5j)
else:
sinc = Jet(1)
midpoint = (-.5j * sum(q[i] * (R[i] + R[3+i]) for i in range(3))).exp()
D = [a * midpoint * sinc for a in r]
p = lambda i: scale(.5, plus(*(sym(momentum(n, i), times(e[n])) for n in range(2))))
energy = scale(.5, plus(*(sym(times(e[n]), h[n]) for n in range(2))))
def Pi(i, j):
kinetic = plus(*(sym(momentum(n, i), sym(momentum(n, j), times(e[n]))) for n in range(2)))
return plus(scale(.25 / mass, kinetic), scale(-1, compose(times(D[j]), force[i])))
def current(j):
convection = plus(*(sym(sym(momentum(n, j), times(e[n])), h[n]) for n in range(2)))
return plus(scale(.25 / mass, convection), scale(.5, sym(times(D[j]), I)))
x = trial(s)
defects = []
sizes = []
def evaluate(lhs, flux):
a = vals(scale(1j, comm(H, lhs)), x)
currents = [vals(f, x) for f in flux]
total = [1j * sum(q[j] * currents[j][n] for j in range(3)) for n in range(3)]
defects.extend(abs(v + w) for v, w in zip(a, total))
sizes.extend(abs(w) for w in total)
for i in range(3):
evaluate(p(i), [Pi(i, j) for j in range(3)])
evaluate(energy, [current(i) for i in range(3)])
for i in range(3):
for j in range(i):
defects.extend(abs(a-b) for a,b in zip(vals(Pi(i,j),x), vals(Pi(j,i),x)))
assert max(defects) < 2e-10
if any(q):
assert max(sizes) > .1
return max(defects), max(sizes)
def loads():
from math import exp as rexp, pi, sin
# Compare spectra at fixed material k for the transverse-uniform axial mode.
eps, k, dx = 1.0, pi / 2, 1e-5
volume = 13.0
predictions = []
for slope in (0.0, 1.0):
def gap(s):
return 2 * eps * sin(k) * rexp(-slope * s)
pressure = -(gap(dx) - gap(-dx)) / (volume * ((1+dx)**3 - (1-dx)**3))
assert abs(pressure - 2 * slope * eps / (3 * volume)) < 1e-10
predictions.append(gap(.01) / gap(0))
assert abs(predictions[0] - predictions[1]) > .009
# A local coherent superposition on a bond: identical site probabilities and
# opposite hopping energies. Central difference the two states' energies.
b = abs(beta)
leg = (.36, -.48, .8)
assert abs(sum(t*t for t in leg) - 1) < 1e-13
for sign in (-1, 1):
a0, a1 = 1/sqrt(2), sign * beta/(b*sqrt(2))
meanB = 2 * (a1.conjugate() * beta * a0).real
assert abs(meanB - sign*b) < 1e-13
def pot(R0, R1):
ell = sqrt(sum((y-x)**2 for x,y in zip(R0,R1)))
return .5 * spring * (ell-rest)**2 + rexp(-gamma * (ell/rest-1)) * meanB
for n in range(2):
for i in range(3):
x = [[0.,0.,0.], [rest * z for z in leg]]
x[n][i] += dx
upper = pot(*x)
x[n][i] -= 2*dx
lower = pot(*x)
measured = (lower-upper)/(2*dx)
predicted = (2*n-1) * gamma * meanB * leg[i] / rest
assert abs(measured-predicted) < 2e-10
return predictions
if __name__ == "__main__":
for q, s in (((0.,0.,0.), 1), ((.7,-.31,.42), 1), ((-.36,.23,.79), 2)):
error, flux = check(q,s)
print(f"q={q}: largest equation defect {error:.3g}, largest contracted flux {flux:.6g}")
ratios = loads()
print(f"At 1% dilation the gap ratios for gamma 0 and 1 are {ratios[0]:.10f}, {ratios[1]:.10f}.")
print("Both coherent single-bond inputs and all 12 Cartesian site-force derivatives agree.")
ray.py
"""Independently vary a ray/material action and evolve its driven acoustic mode."""
from math import cos, sin, sqrt, exp, asin, atan, pi
E0, epsilon, a = 1.0, 0.5, 1.0
carrier = asin(3/5)
enthalpy, stiffness = 2., .5
def energy(b, k, gamma):
return E0 + epsilon * exp(-gamma * (1/b - 1)) * sin(a*k/b)
def density(metric, rod, phase, n, gamma):
"""Fixed covariant field gradients, lower-index metric (g00,g01,g11)."""
g00, g01, g11 = metric
determinant = g00*g11-g01*g01
volume = sqrt(-determinant)
inverse = (g11/determinant, -g01/determinant, g00/determinant)
ft, fx = rod
b = sqrt(inverse[0]*ft*ft + 2*inverse[1]*ft*fx + inverse[2]*fx*fx)
ut, ux = fx/(volume*b), -ft/(volume*b)
st = (inverse[0]*ft+inverse[1]*fx)/b
sx = (inverse[1]*ft+inverse[2]*fx)/b
w, k = phase
rho = enthalpy*b + stiffness*(b-1)**2/2
return -volume*(rho+n*(ut*w+ux*k+energy(b,st*w+sx*k,gamma)))
def diff(f, x):
d = 2e-5
return (f(x-2*d)-8*f(x-d)+8*f(x+d)-f(x+2*d))/(12*d)
def lorentz_frequency(V, k, gamma):
boost = 1/sqrt(1-V*V)
w = energy(1,k,gamma)
for _ in range(24):
w = k*V+energy(1,boost*(k-V*w),gamma)/boost
return w
def check_metric(k, gamma, n):
flat, rod = [-1.,0.,1.], [0.,1.]
E = energy(1,k,gamma)
v = diff(lambda kk: energy(1,kk,gamma),k)
Eb = diff(lambda b: energy(b,k,gamma),1.)
def vary(metric_index, value):
g = flat.copy()
g[metric_index] = value
return density(g,rod,(-E,k),n,gamma)
actual = [scale*diff(lambda x: vary(i,x), flat[i])
for i,scale in enumerate([2,1,2])]
expected = [enthalpy+n*E, n*E*v, n*gamma*epsilon*sin(k)]
assert max(abs(x-y) for x,y in zip(actual,expected)) < 8e-10
p_rod = -diff(lambda ft: density(flat,[ft,1.],(-E,k),n,gamma),0.)
assert abs(p_rod-n*(E*v-k)) < 1e-10
drag = diff(lambda V: lorentz_frequency(V,k,gamma),0.)
assert abs(drag-(k-E*v)) < 1e-10
assert abs(k*v+Eb-gamma*epsilon*sin(k)) < 1e-10
def wave(gamma):
"""Independent dynamic integration and closed form for a sinusoidal packet perturbation."""
E, v, q = energy(1,carrier,gamma), .4, 1.3
Ev2 = E*v*v
force = Ev2-gamma*epsilon*sin(carrier)
omega, drive = sqrt(stiffness/enthalpy)*q, q*v
# Re n = cos(qx−qvt); its gradient is Re[iq exp(iqx−iqvt)].
from cmath import exp as cexp
amplitude = 1j*q*force/enthalpy
def acceleration(t,x):
return amplitude*cexp(-1j*drive*t)-omega**2*x
t, x, velocity, dt = 0., 0j, 0j, .005
for _ in range(600):
k1 = acceleration(t,x)
k2 = acceleration(t+dt/2,x+dt*velocity/2)
k3 = acceleration(t+dt/2,x+dt*(velocity+dt*k1/2)/2)
k4 = acceleration(t+dt,x+dt*(velocity+dt*k2/2))
x += dt*(velocity + (dt/6)*(k1+k2+k3))
velocity += dt*(k1+2*k2+2*k3+k4)/6
t += dt
exact = amplitude/(omega**2-drive**2)*(cexp(-1j*drive*t)-cos(omega*t)
+1j*drive/omega*sin(omega*t))
assert abs(x-exact) < 1e-10
# Linear total momentum balance for this same moving envelope.
env = cexp(-1j*drive*t)
acc = acceleration(t,x)
momentum_dt = enthalpy*acc-1j*drive*E*v*env
pressure_dx = stiffness*q*q*x+1j*q*gamma*epsilon*sin(carrier)*env
assert abs(momentum_dt+pressure_dx)<1e-12
return force
def curvature():
# Static metric ds²=−N(x)²dt²+dx² has R=−2N''/N.
# L_curv=−2λ n N''. By metric variation δS/δN=−T⁰⁰ at N=1.
nodes, lam = 128,.37
dx = 2*pi/nodes
env = [1+.3*cos(3*i*dx) for i in range(nodes)]
probe = [cos(3*i*dx) for i in range(nodes)]
def second(values, i):
return (values[(i+1)%nodes]+values[i-1]-2*values[i])/(dx*dx)
change_in_action = -2*lam*sum(n*second(probe,i) for i,n in enumerate(env))*dx
density_shift = [2*lam*second(env,i) for i in range(nodes)]
assert abs(sum(density_shift)*dx) < 1e-12
coupling = sum(p*d for p,d in zip(probe,density_shift))*dx
assert abs(change_in_action+coupling) < 1e-11 and abs(coupling)>5.
return coupling
def main():
for k in [carrier,-.4,1.43]:
for gamma in [0.,52/75,1.]:
check_metric(k,gamma,.31)
forces = [wave(gamma) for gamma in [0.,52/75,1.]]
assert max(abs(i-j) for i,j in zip(forces,[26/125,0,-23/250])) < 2e-15
for gamma in [.8,1.,1.2]:
shape = lambda b: exp(gamma*(1-1/b))/b
assert abs(diff(shape,1.)-(gamma-1))<2e-10
assert abs(diff(shape,gamma))<2e-10
assert shape(gamma)>=1 and (gamma==1 or shape(gamma)>1)
print("Hilbert energy, energy flux, pressure, rod momentum, moving-medium drag: passed")
print("Packet-edge force coefficients:", forces)
print("Integrated tidal source against a test lapse:",curvature())
print("Driven sound, conserved total momentum and maximum ray speed: passed")
if __name__ == "__main__":
main()
experiment.py
"""Replay static optical-lattice transport against measured 7Li cloud positions.
Default uses original Figure 2 drawn marker centers (CSV, no libraries needed).
--fetch retrieves the pinned author PDF and redigitizes using optional PyMuPDF.
The table contains measurements digitized from plotted results, not raw shots.
"""
import argparse
import csv
import hashlib
import math
from pathlib import Path
from statistics import mean
from urllib.request import urlopen
URL = "https://arxiv.org/pdf/1803.02456v1"
PDF_SHA = "2372de9ff527096f3e3fcd5da60103e7af93f352e1fab92de9d4df42c4404194"
TABLE = Path(__file__).with_name("geiger-figure2.csv")
SPACING_UM = 0.532
HOPPING_HZ = 1549.0
FORCES_HZ = [21.1, 39.3, 50.7]
def extract_pdf(data):
import pymupdf
assert hashlib.sha256(data).hexdigest() == PDF_SHA
page = pymupdf.open(stream=data, filetype="pdf")[1]
shapes = page.get_drawings()
# Gridline indices and physical tick values in the pinned figure. Each
# pair gives x ticks, then y ticks. Markers are four filled cubic arcs.
specs = [
("a1", (7, 0, 8, 25), (13, 0, 14, 40), (339, 411, 52, 120), 44),
("a2", (86, 0, 87, 25), (92, 0, 93, 40), (414, 486, 52, 120), 44),
("a3", (164, 0, 165, 25), (170, 0, 171, 40), (488, 560, 52, 120), 44),
("c", (409, 20, 410, 30), (413, 0, 414, 20), (343, 437, 249, 367), 5),
("d", (453, .5, 454, 1), (456, 0, 457, 20), (467, 560, 249, 367), 7),
]
def coordinate(point, scale, dim):
i0, v0, i1, v1 = scale
start = shapes[i0]["rect"][dim]
end = shapes[i1]["rect"][dim]
return v0 + (point - start) * (v1 - v0) / (end - start)
out = []
for panel, xs, ys, (left, right, top, bottom), count in specs:
points = []
for shape in shapes:
if shape["type"] != "fs" or len(shape["items"]) != 4:
continue
if any(item[0] != "c" for item in shape["items"]):
continue
x0, y0, x1, y1 = shape["rect"]
x, y = (x0 + x1) / 2, (y0 + y1) / 2
if left < x < right and top < y < bottom:
points.append((coordinate(x, xs, 0), coordinate(y, ys, 1)))
assert len(points) == count
out.extend((panel, x, y) for x, y in sorted(points))
return out
def read_table():
with TABLE.open() as handle:
return [(r["panel"], float(r["horizontal"]), float(r["vertical_um"]))
for r in csv.DictReader(handle)]
def rmse(numbers):
return math.sqrt(mean(e * e for e in numbers))
def assess(records):
assert [sum(p == key for p, _, _ in records) for key in ("a1", "a2", "a3", "c", "d")] == [44, 44, 44, 5, 7]
for i, force in enumerate(FORCES_HZ, 1):
trace = [(x, y) for p, x, y in records if p == f"a{i}"]
t0 = min(t for t, _ in trace)
first = [(t - t0, y) for t, y in trace if t - t0 < 1000 / force]
t, y = zip(*first)
amplitude = 2 * SPACING_UM * HOPPING_HZ / force
predicted = [amplitude * math.cos(2 * math.pi * force * u / 1000) for u in t]
offset = mean(a - b for a, b in zip(y, predicted))
cosine_error = rmse([a - b - offset for a, b in zip(y, predicted)])
tbar, ybar = mean(t), mean(y)
slope = (sum((u - tbar) * (v - ybar) for u, v in first) /
sum((u - tbar) ** 2 for u in t))
affine_error = rmse([v - ybar - slope * (u - tbar) for u, v in first])
print(f"{force:.1f} Hz: {len(t)} first-cycle centers, cosine RMSE {cosine_error:.3f} um, "
f"best affine RMSE {affine_error:.3f} um")
assert cosine_error < affine_error
for p in ("c", "d"):
errors = []
print(f"Panel {p} -- horizontal axis {'tilt (Hz)' if p == 'c' else 'J/h (kHz)'}")
for panel, x, amplitude in records:
if panel != p:
continue
expected = (2 * SPACING_UM * HOPPING_HZ / x if p == "c"
else 2 * SPACING_UM * x * 1000 / 23)
errors.append(amplitude - expected)
print(f" {x:.3f}, observed {amplitude:.2f} um, predicted {expected:.2f} um")
print(f" no-fit amplitude RMSE {rmse(errors):.3f} um")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--fetch", action="store_true", help="compare CSV to vector artwork, requires PyMuPDF")
args = parser.parse_args()
saved = read_table()
if args.fetch:
with urlopen(URL, timeout=60) as response:
fresh = extract_pdf(response.read())
assert len(fresh) == len(saved)
for (pa, xa, ya), (pb, xb, yb) in zip(fresh, saved):
assert pa == pb and abs(xa-xb) < .001 and abs(ya-yb) < .001
print("Verified 144 figure markers against the pinned author PDF.")
assess(saved)
replay.py
"""Replay the material-momentum study using standard Python and a pinned Tally runtime."""
import argparse
import hashlib
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parent
RUNTIME_SHA = "1fb281c0ef55314ec68de024ac27da152ff00739607cbbdc408eeee82ab5b193"
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"
def checked(path, expected):
data = path.read_bytes()
if hashlib.sha256(data).hexdigest() != expected:
raise ValueError(f"SHA-256 mismatch for {path.name}")
return data
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="published Tally 0.3.0 runtime ZIP")
args = parser.parse_args()
checked(args.runtime, RUNTIME_SHA)
lib = ROOT / "lib/atom.tly"
if not lib.is_file():
lib = ROOT.parent / "walk-clock-recoil/tally/lib/atom.tly"
atom = checked(lib, ATOM_SHA)
python = [sys.executable, "-E", "-s", "-B", "-X", "utf8"]
for script in ("current", "resonance", "material", "ray", "experiment"):
subprocess.run([*python, str(ROOT / (script + ".py"))], check=True)
with tempfile.TemporaryDirectory() as work_path:
work = Path(work_path)
with ZipFile(args.runtime) as runtime:
runtime.extractall(work)
tally = work / "Tally-0.3.0"
(tally / "lib/atom.tly").write_bytes(atom)
shutil.copyfile(ROOT / "momentum.tly", work / "momentum.tly")
result = subprocess.run([*python, str(tally / "tally.py"), "momentum.tly"], cwd=work,
stdout=subprocess.PIPE, check=True)
actual = result.stdout.decode("utf-8").splitlines()
expected = (ROOT / "momentum.out").read_text(encoding="utf-8").splitlines()
if actual != expected or sum(line.startswith("✓") for line in actual) != 15:
raise ValueError("Tally output differs from the 15 published checks")
print("All five offline checks and the complete 15-assertion Tally transcript passed.")
if __name__ == "__main__":
main()