The native Tally program records 22 completed assertions. Seven Python checks run offline, including the reconstruction from published counts. The offline study archive includes the manuscripts, programs, transcript and replay instructions.
Python checks and replay
alternative.py
"""Checks for an autonomous local Hamiltonian with a conserved contact energy."""
from fractions import Fraction as F
from itertools import product
from math import acos,cos,sin,sqrt,isclose,factorial
def bessel_bounds(n,terms=14):
# Alternating series for J_n(1) with decreasing positive term magnitudes.
def term(j):
return F((-1)**j,2**(2*j+n)*factorial(j)*factorial(n+j))
value=sum(term(j) for j in range(terms))
return sorted((value,value+term(terms)))
def interaction_current():
# Normalized ordered-particle components of (|2 at 0> + |1 at 0,1 at z>)/sqrt(2).
origin,above=(0,0,0),(0,0,1)
psi={(origin,0,origin,0):1/sqrt(2),
(origin,0,above,0):.5,(above,0,origin,0):.5}
blocks = [(d,0,1j*d[0]/8) for d in product((-1,1), repeat=3)]
blocks += [((0,y,z),1,1j*y/4) for y,z in product((-1,1),repeat=2)]
blocks += [((0,0,z),2,1j*z/2) for z in (-1,1)]
kinetic={}
for (p,s,q,t),weight in psi.items():
for axis_particle in (0,1):
pos,spin=(p,s) if axis_particle==0 else (q,t)
for d,axis,coeff in blocks:
dest=tuple(x+dx for x,dx in zip(pos,d))
out=spin if axis==2 else 1-spin
spin_phase=(1,1j*(1-2*spin),1-2*spin)[axis]
key=(dest,out,q,t) if axis_particle==0 else (p,s,dest,out)
kinetic[key]=kinetic.get(key,0j)+weight*coeff*spin_phase
potential={k:v for k,v in psi.items() if k[0]==k[2]}
keys=kinetic.keys()|potential.keys()
derivative={k:-1j*(kinetic.get(k,0)+potential.get(k,0)) for k in keys}
def rate(applied):
return 2*sum(v.conjugate()*derivative[k] for k,v in applied.items()).real
assert isclose(rate(potential),-1/sqrt(2),abs_tol=1e-14)
assert isclose(rate(kinetic),1/sqrt(2),abs_tol=1e-14)
return rate(potential),rate(kinetic)
def main():
# Keep one site-localized source along x, uniformly polarized in +x;
# uniform transverse preparation sets k_y=k_z=0.
for n in (0,1,2):
a,b=bessel_bounds(n)
assert 0<a<=b and b*b-a*a<F(1,10**24)
print(f"axial output |x|={n}: per-site probability {float(a*a):.12f}")
a,b=bessel_bounds(0)
assert F(58552749,10**8)<a*a<b*b<F(58552751,10**8)
# Trapezoidal sampling integrates these degree-two products exactly;
# rational table contains sin² and cos² at k=j*pi/2.
s=(0,1,0,1)
mean=F(sum(s[i]*(1-s[j])*(1-s[k]) for i,j,k in product(range(4),repeat=3)),64)
assert mean==F(1,8)
for k in ((.21,.34,.55),(1.2,-.3,1.94),(2.3,.61,-.77)):
def omega(q):return acos(cos(q[0])*cos(q[1])*cos(q[2]))
om=omega(k);delta=1e-6
for axis in range(3):
plus=list(k);minus=list(k)
plus[axis]+=delta;minus[axis]-=delta
vwalk=(omega(plus)-omega(minus))/(2*delta)
vh=(sin(omega(plus))-sin(omega(minus)))/(2*delta)
assert isclose(vh,cos(om)*vwalk,abs_tol=1e-9)
rates=interaction_current()
print('Cartesian ballistic variance decrement = 1/8; initial contact and hopping rates:',rates)
if __name__=="__main__":
main()
clock.py
"""Timing visibility and a positive-frequency two-channel contact model.
Python 3 standard library. The continuum error bound and the finite-ring
expressions are analytic. The continuum matrix quadratures are convergence
checks, not a rigorous spectral discretization error estimate.
"""
from cmath import exp
from math import atan, cos, pi, sin, sqrt
def simpson(function, a, b, intervals=4096):
assert intervals % 2 == 0
h = (b-a)/intervals
odd = sum(function(a + j*h) for j in range(1, intervals, 2))
even = sum(function(a + j*h) for j in range(2, intervals, 2))
return h*(function(a) + 4*odd + 2*even + function(b))/3
def cauchy_delay(delay, window, tau):
width = 2*tau
probability = (atan((window-delay)/width) + atan((window+delay)/width))/pi
density = lambda t: width/(pi*((t-delay)**2 + width**2))
assert abs(simpson(density, -window, window) - probability) < 1e-13
return probability
def apply_phase(apply_concentration, vector, theta):
"""Apply the exponential by its power series; the operators have norm <= 1."""
value = list(vector)
term = list(vector)
for n in range(1, 50):
term = [(-1j*theta/n)*v for v in apply_concentration(term)]
value = [a + b for a, b in zip(value, term)]
return value
def ring():
# L=1 and R=L/4; p-p' is zero or +/-2*pi and both photon energies are positive.
r = 0.25
diagonal = simpson(lambda x: 1.0, -r, r)
offdiag = simpson(lambda x: cos(2*pi*x), -r, r)
assert abs(diagonal - 0.5) < 1e-14 and abs(offdiag - 1/pi) < 1e-13
def c(v):
return [diagonal*v[0]+offdiag*v[1], offdiag*v[0]+diagonal*v[1]]
state = [1.0, 0.0]
out = apply_phase(c, state, pi)
assert abs(out[0] + 1j*cos(1)) < 1e-12
assert abs(out[1] + sin(1)) < 1e-12
assert abs(sum(abs(v)**2 for v in out) - 1) < 1e-12
exchanged = abs(out[1])**2
bright = (1 + (1j*out[0]).real)/2
# Compressing the discontinuous pointwise phase *after* applying it differs
# from exponentiating C. The discarded norm is a projection loss.
compressed_mask = [a - 2*b for a, b in zip(state, c(state))]
survival = sum(abs(v)**2 for v in compressed_mask)
assert abs(compressed_mask[0]) < 1e-13 and abs(survival-4/pi**2) < 1e-13
for phase in (0, pi/3, pi/2, pi):
incident = [1/sqrt(2), exp(1j*phase)/sqrt(2)]
result = apply_phase(c, incident, pi)
overlap = sum(a.conjugate()*b for a, b in zip(incident, result))
assert abs(overlap - (-1j*cos(1) - cos(phase)*sin(1))) < 1e-12
return abs(out[0]), exchanged, bright, survival
def continuum(BR, nodes):
# At B=1 use a midpoint quadrature of the sinc kernel on relative
# momentum [-1,1]. Its diagonal is the removable limit R/pi.
step = 2/nodes
p = [-1 + (j+0.5)*step for j in range(nodes)]
initial = [1-abs(x) for x in p]
norm = sqrt(sum(x*x for x in initial))
initial = [x/norm for x in initial]
kernel = [BR*step/pi]
kernel.extend(sin(BR*j*step)/(pi*j) for j in range(1, nodes))
def c(vector):
return [sum(kernel[abs(i-j)]*a for j, a in enumerate(vector))
for i in range(nodes)]
result = apply_phase(c, initial, pi)
overlap = sum(a*b for a, b in zip(initial, result))
return -overlap.real
if __name__ == "__main__":
P = cauchy_delay(0, 2, 1)
assert abs(P - 0.5) < 1e-14
P_delayed = cauchy_delay(4, 2, 1)
assert P_delayed < P
print(f"pointwise pi phase: synchronized visibility {abs(1-2*P):.9f}, "
f"delay 4*tau visibility {abs(1-2*P_delayed):.9f}")
visibility, exchange, bright, survival = ring()
print(f"positive two-mode ring: visibility {visibility:.9f}, "
f"exchange {exchange:.9f}, phase-scanned bright port {bright:.9f}; "
f"compressed-mask survival {survival:.9f}")
BR = 10
def sinc4(x):
return (sin(x)/x)**4 if x else 1.0
probability = (3/pi)*simpson(sinc4, 0, BR/2)
assert 0 < 1-probability < 8/(pi*BR**3)
certified = 1 - 4*pi/BR**3
q1 = continuum(BR, 80)
q2 = continuum(BR, 160)
assert q2 >= certified and abs(q2-q1) < 0.00005
print(f"triangle BR=10: in-window probability {probability:.9f}, "
f"certified target quadrature >= {certified:.9f}, "
f"midpoint estimates {q1:.9f}, {q2:.9f}")
dressing.py
"""Four positive-band Bose waves testing a local dressing of the sine charge.
Run python3 dressing.py. The checks use the six one-link Pauli matrices, and
construct the actual linear combination whose contact amplitude cancels.
The mathematical obstruction and its operator hypotheses are in dressing.md.
"""
from cmath import exp
from fractions import Fraction
from math import acos, atan, cos, isclose, pi, sin, sqrt, tan
PAULI = (((0, 1), (1, 0)), ((0, -1j), (1j, 0)), ((1, 0), (0, -1)))
IDENTITY = ((1, 0), (0, 1))
def multiply(a, b):
return tuple(tuple(sum(row[k] * b[k][j] for k in range(2))
for j in range(2)) for row in a)
def walk(p):
u = IDENTITY
for axis in (0, 1, 2, 2, 1, 0):
c, s = cos(p[axis] / 2), -1j * sin(p[axis] / 2)
step = tuple(tuple(c * IDENTITY[i][j] + s * PAULI[axis][i][j]
for j in range(2)) for i in range(2))
u = multiply(step, u)
return u
def norm(v):
return sqrt(sum(abs(x)**2 for x in v))
def positive_spin(p):
u = walk(p)
omega = acos(((u[0][0] + u[1][1]) / 2).real)
plus, minus = exp(-1j * omega), exp(1j * omega)
candidates = [tuple(u[i][j] - minus * IDENTITY[i][j] for i in range(2))
for j in range(2)]
v = max(candidates, key=norm)
scale = norm(v)
v = tuple(a / scale for a in v)
assert max(abs(sum(u[i][j] * v[j] for j in range(2)) - plus * v[i])
for i in range(2)) < 2e-14
return omega, v
def contact(pair):
(o1, v), (o2, w) = map(positive_spin, pair)
# Symmetric-spin coordinates at coincidence, in the standard z basis;
# all spatial wave normalizations are taken equal.
c = (sqrt(2) * v[0] * w[0], v[0] * w[1] + v[1] * w[0],
sqrt(2) * v[1] * w[1])
return o1 + o2, sin(o1) + sin(o2), c
def pair_at(k, s, h, transverse):
# k is the total axial momentum, s the pair phase, h the phase difference.
if h == k:
return ((k + s) / 2, 0, 0), ((k - s) / 2, 0, 0)
x = atan(tan(s / 2) * tan(h / 2) / tan(k / 2))
y = acos(cos(s / 2) * cos(h / 2) / (cos(k / 2) * cos(x)))
a, b = [k / 2 + x, 0, 0], [k / 2 - x, 0, 0]
a[transverse], b[transverse] = y, -y
return tuple(a), tuple(b)
def det(columns):
a, b, c = columns
return (a[0] * (b[1] * c[2] - b[2] * c[1])
- b[0] * (a[1] * c[2] - a[2] * c[1])
+ c[0] * (a[1] * b[2] - a[2] * b[1]))
def site_witness(k, s, report=False):
waves = [pair_at(k, s, h, axis) for h, axis in ((k, 1), (0, 1), (0, 2), (k / 2, 1))]
evaluated = [contact(pair) for pair in waves]
assert all(abs(phase - s) < 2e-14 for phase, _, _ in evaluated)
charges = [q for _, q, _ in evaluated]
c = [v for _, _, v in evaluated]
determinant = det(c[:3])
assert abs(determinant) > 0.1
# Express the fourth contact vector in the basis made by the first three.
coeff = []
for j in range(3):
cols = c[:3]
cols[j] = c[3]
coeff.append(-det(cols) / determinant)
coeff.append(1)
initial = [sum(a * v[i] for a, v in zip(coeff, c)) for i in range(3)]
weighted = [sum(a * q * v[i] for a, q, v in zip(coeff, charges, c)) for i in range(3)]
assert norm(initial) < 2e-14
assert norm(weighted) > 0.001
assert charges[0] < charges[3] < charges[1]
assert isclose(charges[1], charges[2], abs_tol=2e-14)
# The entire interpolation has the prescribed phase and positive band:
# q = 2 sin(s/2) cos(h/2).
for j in range(13):
h = k * j / 12
if j == 12:
h = k
phase, q, _ = contact(pair_at(k, s, h, 1))
assert abs(phase - s) < 2e-14
assert abs(q - 2 * sin(s / 2) * cos(h / 2)) < 2e-14
if report:
print(f"contact basis determinant magnitude {abs(determinant):.12f}")
print("sine charges (axial, transverse y, transverse z, intermediate)")
print(" ", tuple(round(q, 12) for q in charges))
print(f"contact-cancelled input norm {norm(initial):.3g}; "
f"after charge weighting {norm(weighted):.12f}")
def main():
# The squared reference charges are 3/2 and 2. At h=k/2 the squared
# charge is (2+sqrt(3))/2, strictly between them since 1<sqrt(3)<2.
exact_values = (sqrt(6) / 2, sqrt(2), (1 + sqrt(3)) / 2)
for h, expected in zip((pi / 3, 0, pi / 6), exact_values):
_, measured, _ = contact(pair_at(pi / 3, pi / 2, h, 1))
assert isclose(measured, expected, rel_tol=0, abs_tol=2e-14)
# det squared of the three spin vectors at K=pi/3, s=pi/2 equals
# (1-beta^2)^2 for the above unnormalized local spin convention.
_, _, ax = contact(pair_at(pi / 3, pi / 2, pi / 3, 1))
_, _, ay = contact(pair_at(pi / 3, pi / 2, 0, 1))
_, _, az = contact(pair_at(pi / 3, pi / 2, 0, 2))
assert isclose(abs(det([ax, ay, az]))**2, float((1 - Fraction(1, 3))**2),
abs_tol=2e-14)
site_witness(pi / 3, pi / 2, report=True)
for k, s in ((0.90, 1.48), (1.13, 1.64)):
site_witness(k, s)
print("Sine and absolute sine agree on all four positive-band input waves.")
# Signed sine also has an exact opposite-charge alias on the full walk.
p = (0.22, -0.75, 0.53)
u, alias = walk(p), walk((p[0], p[1], p[2] + pi))
assert max(abs(u[i][j] + alias[i][j]) for i in range(2) for j in range(2)) < 2e-14
print("The third-axis pi shift negates the one-particle tick, as required.")
if __name__ == "__main__":
main()
empirical.py
"""Reanalyse the deposited counts for Morvan et al., Nature 612, 240 (2022).
Python 3.10+ and standard library only. Default (offline): replay the reduced
integer counts embedded below. --csv PATH or --fetch: rederive and verify all
those counts against the SHA-256-pinned 17 MB public, aggregate-count CSV.
"""
import argparse
import cmath
import csv
import hashlib
import io
import math
import statistics
import urllib.request
from collections import defaultdict
from itertools import combinations
from pathlib import Path
SITES = 24
DEPTHS = (0, 3, 30, 60) # preparation plus the authors' Figure S7 checkpoints
FILE = "bound_state_trajectories_nphotons_2.csv"
URL = "https://zenodo.org/records/6981407/files/" + FILE
SHA256 = "14167d9ec4461941e45003fc199482439c6540d80e8da22de93e84e600b8daeb"
# One line per starting bitstring. At each depth the packed columns are
# total shots / shots with exactly two excitations / adjacent two-excitation shots.
REDUCED = """
3 10000/8250/8184 10000/7757/4483 10000/4588/2418 10000/3025/1319
6 10000/8181/8112 10000/7689/5182 10000/4668/2293 10000/3021/1223
12 10000/8067/7489 10000/7922/4473 10000/4876/2470 10000/3172/1358
24 10000/7989/7389 10000/7961/5445 10000/4539/2296 10000/3059/1241
48 10000/8229/8151 10000/7878/4748 10000/4601/2438 10000/3151/1307
96 10000/8182/8106 10000/7864/5609 10000/4633/2280 10000/3094/1283
192 10000/8165/8074 10000/7793/4724 10000/4694/2461 10000/3012/1299
384 10000/7961/7828 10000/7540/5003 10000/4746/2454 10000/2992/1207
768 10000/7598/6798 10000/7310/3689 10000/4704/2448 10000/2863/1141
1536 10000/7842/7072 10000/7532/4939 10000/4811/2499 10000/3076/1309
3072 10000/8272/8172 10000/7781/4200 10000/4913/2657 10000/3130/1280
6144 10000/8161/8079 10000/7912/5487 10000/5085/2723 10000/3236/1450
12288 10000/8209/8099 10000/7847/4407 10000/5013/2833 10000/2969/1330
24576 10000/8316/8241 10000/7984/5448 10000/4913/2634 10000/3167/1345
49152 10000/8244/8172 10000/7913/4714 10000/5054/2990 10000/3155/1446
98304 10000/8247/8170 10000/7825/5398 10000/5102/2847 10000/3202/1359
196608 10000/8229/8136 10000/7603/4376 10000/5140/2911 10000/3251/1441
393216 10000/8217/8136 10000/7330/5080 10000/4752/2495 10000/3078/1408
786432 10000/8248/7709 10000/7606/4110 10000/5017/2903 10000/3218/1453
1572864 10000/8326/8258 10000/7552/5146 10000/4825/2761 10000/3095/1322
3145728 10000/8183/7713 10000/7663/4518 10000/4970/2912 10000/3193/1488
6291456 10000/8257/8175 10000/7889/5343 10000/4800/2696 10000/3139/1433
8388609 10000/8336/8261 10000/7807/5213 10000/4846/2490 10000/3048/1237
12582912 10000/8189/8099 10000/7926/4398 10000/4811/2472 10000/3079/1218
"""
def adjacent(bits):
"""Call only for two-excitation 24-bit strings. Include the last/first bond."""
return bool((bits & (bits >> 1)) or (bits & 1 and bits & (1 << (SITES-1))))
def compact_counts():
summary = {}
for line in REDUCED.strip().splitlines():
start, *cells = line.split()
assert len(cells) == len(DEPTHS)
for depth, cell in zip(DEPTHS, cells):
summary[int(start), depth] = tuple(map(int, cell.split("/")))
return summary
def raw_counts(payload):
if hashlib.sha256(payload).hexdigest() != SHA256:
raise ValueError("CSV SHA-256 differs from the published analysis input")
summary = defaultdict(lambda: [0, 0, 0])
rows = csv.DictReader(io.StringIO(payload.decode("ascii")))
assert rows.fieldnames == ["input", "depth", "output", "count"]
for row in rows:
start, depth, output, count = (int(row[key]) for key in rows.fieldnames)
if depth not in DEPTHS:
continue
assert start.bit_count() == 2 and adjacent(start)
bins = summary[start, depth]
bins[0] += count
if output.bit_count() == 2:
bins[1] += count
if adjacent(output):
bins[2] += count
return {key: tuple(value) for key, value in summary.items()}
def model(phi, start):
"""Direct two-excitation fSim on the occupation basis; no fitted parameters."""
theta = math.pi/6
stay = math.cos(theta)
hop = 1j*math.sin(theta)
pair_phase = cmath.exp(1j*phi)
masks = [(1 << a) | (1 << b) for a,b in combinations(range(SITES), 2)]
index = {bits:i for i,bits in enumerate(masks)}
state = [0j]*len(masks)
state[index[start]] = 1
# Gate updates act on disjoint 2x2 subspaces and single |11> components.
layers = []
for parity in (0,1):
gates = []
for a in range(parity,SITES,2):
b = (a+1) % SITES
left, right = 1 << a, 1 << b
pair = left | right
swap_pairs = [(i, index[bits ^ pair]) for i,bits in enumerate(masks)
if bits & pair == left]
gates.append((index[pair], swap_pairs))
layers.append(gates)
result = {}
for depth in range(max(DEPTHS)+1):
if depth in DEPTHS:
assert abs(sum(abs(v)**2 for v in state)-1) < 1e-12
result[depth] = sum(abs(v)**2 for bits,v in zip(masks,state) if adjacent(bits))
if depth == max(DEPTHS):
break
for gates in layers:
for both, swap_pairs in gates:
state[both] *= pair_phase
for i,j in swap_pairs:
x,y = state[i],state[j]
state[i],state[j] = stay*x+hop*y, hop*x+stay*y
return result
def summarize(rows):
observed = [a/t for _,t,a in rows]
n = len(rows)
shot_se = math.sqrt(sum(p*(1-p)/t for p,(_,t,_) in zip(observed,rows)))/n
spread = statistics.stdev(observed)
total,two,adj = map(sum,zip(*rows))
return statistics.mean(observed), shot_se, spread, (total,two,adj)
def run():
parser = argparse.ArgumentParser(description=__doc__)
source = parser.add_mutually_exclusive_group()
source.add_argument("--csv", type=Path, help="verify the original local Zenodo CSV")
source.add_argument("--fetch", action="store_true", help="download and verify the original CSV in memory")
args = parser.parse_args()
measured = compact_counts()
if args.csv or args.fetch:
if args.csv:
data = args.csv.read_bytes()
else:
req = urllib.request.Request(URL+"?download=1", headers={"User-Agent":"collision-study/1.0"})
with urllib.request.urlopen(req,timeout=120) as response:
data = response.read()
if raw_counts(data) != measured:
raise ValueError("Counts differ from embedded reduction")
print(f"Verified {len(data)} original bytes, SHA-256 {SHA256}.")
expected_starts = {(1 << i) | (1 << ((i+1) % SITES)) for i in range(SITES)}
assert all({i for i,t in measured if t == d} == expected_starts for d in DEPTHS)
model_results = {name:[model(phi,start) for start in (3,6)]
for name,phi in (("on",2*math.pi/3),("off",0.0))}
print("depth total retained adjacent retained/all P(adj|two) shot_SE across_start_SD ideal_on ideal_off")
for d in DEPTHS:
values = [value for (start,t),value in measured.items() if t == d]
p,se,sd,(n,k,a) = summarize(values)
ranges = []
for outcomes in model_results.values():
parities = [row[d] for row in outcomes]
ranges.append(f"{statistics.mean(parities):.6f}")
print(f"{d:2d} {n} {k} {a} {k/n:.6f} {p:.6f} {se:.6f} {sd:.6f} " + " ".join(ranges))
print(f"Uniform fixed-number adjacency probability: {SITES/math.comb(SITES,2):.6f}")
if __name__ == "__main__":
run()
meter.py
"""Two-boson contact with a quantized material energy register on a 4^3 torus.
Run with Python 3 and its standard library. Energies in the firing histogram
are in units of epsilon. A battery rung in this total-momentum sector is 2 epsilon.
The outgoing momentum/spin labels are ordered slots for a symmetric input.
"""
from cmath import exp
from fractions import Fraction
from itertools import product
from math import cos, pi, sin, sqrt
from random import Random
MOMENTA = list(product(range(4), repeat=3)) # quarter-turn units
INPUT = (0, 0, 1)
DIM = len(MOMENTA)*4
S, C = (0, 1, 0, -1), (1, 0, -1, 0)
def axis(k):
x, y, z = k
return (S[x]*C[y]*C[z], S[y]*C[z], S[z])
AXES = [axis(k) for k in MOMENTA]
def sigma(spin, components, bit):
"""Apply the signed Pauli operator on tensor index 'bit' (2 or 1)."""
x, y, z = components
return [(z*spin[i] + (x-1j*y)*spin[i^bit]) if i & bit == 0
else (-z*spin[i] + (x+1j*y)*spin[i^bit]) for i in range(4)]
def split(field):
"""Orthogonal sectors j=0,1,2 represent pair sine charge -2,0,+2."""
sectors = [[0j]*DIM for _ in range(3)]
for k, direction in enumerate(AXES):
start = 4*k
u = field[start:start+4]
if not any(direction):
sectors[1][start:start+4] = u
continue
a, b = sigma(u, direction, 2), sigma(u, direction, 1)
ab = sigma(a, direction, 1)
for i in range(4):
sectors[0][start+i] = (u[i]-a[i]-b[i]+ab[i])/4
sectors[1][start+i] = (u[i]-ab[i])/2
sectors[2][start+i] = (u[i]+a[i]+b[i]+ab[i])/4
return sectors
def contact(field, phase):
# At fixed total momentum the same-site projector uniformly averages the
# relative momentum, separately for every pair of spin indices.
means = [sum(field[i::4])/64 for i in range(4)]
return [v + (phase-1)*means[i%4] for i,v in enumerate(field)]
def material_gate(state, phase=-1):
"""Conjugate the contact into complete energy shells; identity at edges."""
top = len(state)-1
shells = [[0j]*DIM for _ in range(top+3)]
for n, field in enumerate(state):
for j, piece in enumerate(split(field)):
shells[n+j] = [a+b for a,b in zip(shells[n+j],piece)]
out = [[0j]*DIM for _ in state]
for total, shell in enumerate(shells):
if 2 <= total <= top:
shell = contact(shell, phase)
for j, piece in enumerate(split(shell)):
n = total-j
if 0 <= n <= top:
out[n] = [a+b for a,b in zip(out[n],piece)]
return out
def hamiltonian(state):
result = []
for n, field in enumerate(state):
parts = split(field)
result.append([sum(2*(n+j)*x for j,x in enumerate(v)) for v in zip(*parts)])
return result
def distance(a,b):
return max(abs(v-w) for row,col in zip(a,b) for v,w in zip(row,col))
def mass(field):
return sum(v.real*v.real + v.imag*v.imag for v in field)
def input_field(k=INPUT):
state = [0j]*DIM
state[4*MOMENTA.index(k)] = 1
return state
def dressed_input(packet):
# Two vacant rungs above the support permit every downward-energy branch.
field = input_field()
return [[a*v for v in field] for a in list(packet)+[0,0]]
def spin_detector(state):
# Equatorial momenta have an x or y Pauli axis. Sum probabilities over
# both momentum orderings and all material outcomes before conditioning.
all_eq = down = 0.0
for field in state:
for i,(x,y,_) in enumerate(AXES):
if x or y:
all_eq += mass(field[4*i:4*i+4])
down += abs(field[4*i+3])**2
return all_eq, down
def overlap(packet, offset):
return sum(a.conjugate()*b for a,b in zip(packet[offset:],packet))
def exact_meter():
for k, direction in zip(MOMENTA, AXES):
x,y,z = k
partner = (-x%4, -y%4, (2-z)%4)
assert axis(partner) == direction
assert C[x]*C[y]*C[z] == -C[partner[0]]*C[partner[1]]*C[partner[2]]
assert sorted(sum(v[i] != 0 for v in AXES) for i in range(3)) == [8,16,32]
field = input_field()
for phase in (1, 1j, -1):
output = material_gate(dressed_input([1]), phase)
probabilities = [Fraction(mass(row)) for row in output]
scale = (1-Fraction(phase.real))/2
expected = [1-scale*Fraction(21,512), scale*Fraction(10,512),
scale*Fraction(11,512)]
assert probabilities == expected
# The final pair-energy and material-energy records sum to 4 epsilon
# on every occupied branch separately.
for n, row in enumerate(output):
for j, sector in enumerate(split(row)):
if n+j != 2:
assert mass(sector) == 0
if phase == -1:
mean = sum(2*n*p for n,p in enumerate(probabilities))
var = sum((2*n-mean)**2*p for n,p in enumerate(probabilities))
assert (mean,var) == (Fraction(1,8),Fraction(13,32))
eq,down = spin_detector(output)
assert eq==3/128 and down==9/1024 and down/eq==3/8
print(f"Signed sine, gains (0,2,4): {probabilities}; mean={mean}, variance={var}")
scattered = contact(field, -1)
zero_modes = sum(mass(scattered[4*i:4*i+4]) for i,d in enumerate(AXES) if not any(d))
assert zero_modes == 1/128
print("Magnitude sine, gains (0,2,4): (127/128,1/128,0); positive phase magnitude: (1,0,0).")
def unitary_controls():
rng = Random(829)
state = [[complex(rng.random()-.5,rng.random()-.5) for _ in range(DIM)] for _ in range(6)]
phase = exp(.73j)
forward = material_gate(state,phase)
assert distance(material_gate(forward,phase.conjugate()),state) < 3e-15
assert distance(hamiltonian(forward),material_gate(hamiltonian(state),phase)) < 3e-14
assert abs(sum(map(mass,forward))-sum(map(mass,state))) < 1e-10
# An empty-battery, lowest-energy pair belongs to an incomplete shell.
edge = [[0j]*DIM for _ in range(5)]
edge[0] = input_field((0,0,3))
assert distance(material_gate(edge),edge) == 0
def coherence_controls():
for m in (2,4,8,16):
theta = pi/(m+1)
for power in (1,2):
packet = [sin(j*theta)**power for j in range(1,m+1)]
norm = sqrt(mass(packet))
packet = [v/norm for v in packet]
eq,dd = spin_detector(material_gate(dressed_input(packet)))
p = dd/eq
c1,c2 = (overlap(packet,j).real for j in (1,2))
assert abs(eq-3/128)<1e-14
assert abs(p-(3-4*c1+c2)/8)<1e-14
assert p+1e-14 >= (1-cos(theta))**2/4
if power == 1:
assert abs(c1-cos(theta))<1e-14
else:
assert abs(p-m*sin(theta)**4/(3*(m+1)))<1e-14
print(f"M={m:2}: adjacent overlap={c1:.8f}, conditional double flip={p:.9f}")
random_phase = [exp(1j*q)/2 for q in (0,.4,1.3,-.6)]
eq,dd = spin_detector(material_gate(dressed_input(random_phase)))
assert abs(dd/eq-(3-4*overlap(random_phase,1).real+overlap(random_phase,2).real)/8)<1e-14
if __name__ == "__main__":
exact_meter()
unitary_controls()
coherence_controls()
range.py
"""Exact finite-torus controls for a collision-local energy correction.
Momenta in the four-cell periodic box are multiples of pi/2. All one-body
Pauli blocks then have Gaussian-integer entries. The fixed total momentum is
zero. A dictionary contains the two spin amplitudes in the ordered basis at
each of the 64 relative momenta (four components including both spin labels).
"""
from fractions import Fraction as F
from itertools import product
from math import isclose, cos, sin, acos, atan2, pi, sqrt
GRID = list(product(range(4),repeat=3))
C = (1,0,-1,0)
S = (0,1,0,-1)
Z = (0,0)
def plus(a,b):
return a[0]+b[0], a[1]+b[1]
def times(a,b):
return a[0]*b[0]-a[1]*b[1], a[0]*b[1]+a[1]*b[0]
def scale(a,x):
return a[0]*x,a[1]*x
def pauli(spin,axis):
if axis==0: return 1-spin,(1,0)
if axis==1: return 1-spin,(0,1-2*spin)
return spin,(1-2*spin,0)
def block(k):
x,y,z = k
b = (S[x]*C[y]*C[z],S[y]*C[z],S[z])
for i,sign in enumerate(b):
if sign: return i,sign
return None,0
def free(vec):
result = {}
for k,row in vec.items():
axis,_ = block(k)
if axis is None:
result[k] = row
continue
out=[Z]*4
for i,v in enumerate(row):
l,a=pauli(i//2,axis)
r,b=pauli(i%2,axis)
out[2*l+r]=times(times(a,b),v)
result[k]=out
return result
def charge(vec):
result={}
for k,row in vec.items():
axis,sign=block(k)
out=[Z]*4
if axis is not None:
for i,v in enumerate(row):
l,a=pauli(i//2,axis)
r,b=pauli(i%2,axis)
out[2*l+i%2]=plus(out[2*l+i%2],scale(times(a,v),sign))
out[2*(i//2)+r]=plus(out[2*(i//2)+r],scale(times(b,v),-sign))
result[k]=out
return result
def tick(vec,phase):
assert phase[0]**2+phase[1]**2==1
vec=free(vec)
avg=[(F(sum(row[j][0] for row in vec.values()),64),
F(sum(row[j][1] for row in vec.values()),64)) for j in range(4)]
delta=[times(plus(phase,(-1,0)),a) for a in avg]
return {k:[plus(v,d) for v,d in zip(row,delta)] for k,row in vec.items()}
def norm2(vec):
# The initial spin vector (up down + down up) has norm sqrt(2).
return sum(a*a+b*b for row in vec.values() for a,b in row)/F(128)
def diff(a,b):
return {k:[plus(v,scale(w,-1)) for v,w in zip(a[k],b[k])] for k in a}
def torus(phase):
initial={k:[Z,(1,0),(1,0),Z] for k in GRID}
original=charge(initial)
v=initial
q=original
assert norm2(initial)==1 and norm2(original)==2
for t in range(1,9):
v=tick(v,phase)
q=tick(q,phase)
gap=norm2(diff(charge(v),q))/t**2
# The bright same-site triplet gains one phase per two ticks.
# Its charged partner is a contact-dark singlet on the z-type momenta.
factor=(1,0)
for _ in range(t//2): factor=times(factor,phase)
squared=2*((factor[0]-1)**2+factor[1]**2)/F(t*t)
assert gap==squared and norm2(v)==1
if t==2:
predicted={k:[times(phase,v0) for v0 in row] for k,row in initial.items()}
assert norm2(diff(v,predicted))==0
if phase==(-1,0) and t in (1,2,3,4):
print(f"T={t}: squared change of averaged charge on this packet = {gap}")
def interpolation(m,delta):
# p1,2=(delta +/- x, +/- y, 0). Check both energies directly even
# when cos(m)<0 or vanishes, and check rank of the three onsite tests.
beta=sin(delta)*cos(m)/(cos(delta)*sin(m))
assert abs(beta)<1
for step in range(51):
t=delta*step/50
u=cos(m)*cos(t)/cos(delta)
v=sin(m)*sin(t)/sin(delta)
cy=min(1.,sqrt(u*u+v*v))
x=atan2(v,u) if abs(u)+abs(v)>1e-14 else pi/2
y=acos(cy)
w1=acos(max(-1.,min(1.,cos(delta+x)*cos(y))))
w2=acos(max(-1.,min(1.,cos(delta-x)*cos(y))))
assert isclose(w1,m+t,abs_tol=1e-10) and isclose(w2,m-t,abs_tol=1e-10)
# At equal sharing, two test triplets have independent +- combinations
# of |++> and |--> in the x-spin basis. The axial ray supplies m_x=0.
assert (1-beta*beta)/2>0
if __name__=="__main__":
torus((-1,0))
torus((F(3,5),F(4,5)))
for m in (pi/12,pi/4,pi/2,2*pi/3,11*pi/12):
interpolation(m,min(m,pi-m)/3)
print("Both exact torus phase controls and all five energy-sharing paths passed.")
reciprocity.py
"""Reciprocal gravitational quadrupole: exact 6^3 finite-cell tests.
Run with Python 3 standard library. Coordinates in sparse fields are doubled
so the same map supports vertex, link and face quantities. Sums run over one
periodic cell. No transverse projection is used in the time evolution.
"""
from collections import defaultdict
from fractions import Fraction as F
from itertools import product
N = 6
VOL = N**3
C2 = F(1, 4)
EPS = 2
CS = (F(1), F(1, 2), F(-1, 2), F(-1), F(-1, 2), F(1, 2))
ORIGIN = (0, 0, 0)
UNIT = {ORIGIN: 1}
def add(*fields):
result = {}
for field in fields:
for location, value in field.items():
result[location] = result.get(location, 0) + value
return {p: v for p, v in result.items() if v}
def times(field, factor):
return {p: factor * v for p, v in field.items() if factor * v}
def sub(first, second):
return add(first, times(second, -1))
def stencil(field, axis, terms):
"""Apply sum c*f(x+s) at all sites, pairing each field with its stagger."""
parts = []
for offset, coefficient in terms:
shifted = {}
for point, value in field.items():
dest = list(point)
dest[axis] -= offset
shifted[tuple(dest)] = coefficient * value
parts.append(shifted)
return add(*parts)
def centered(field, axis):
return stencil(field, axis, [(1, 1), (-1, -1)])
def average(field, axis, radius):
half = F(1, 2)
return stencil(field, axis, [(radius, half), (-radius, half)])
def native(field, axis):
quarter = F(1, 4)
field = stencil(field, axis, [(4, quarter), (-4, -quarter)])
for j in range(axis + 1, 3):
field = average(field, j, 4)
return field
def filters(field, axes):
for i in axes:
field = average(average(field, i, 1), i, 2)
for j in range(i + 1, 3):
field = average(field, j, 4)
return field
PAIRS = tuple((i, j) for i in range(3) for j in range(i, 3))
def component(tensor, i, j):
return tensor[min(i, j), max(i, j)]
def divergence(tensor, derivative):
return [add(*(derivative(component(tensor, i, j), j) for j in range(3)))
for i in range(3)]
def spatial_einstein(tensor, derivative):
trace = add(*(tensor[i, i] for i in range(3)))
div = divergence(tensor, derivative)
curvature = sub(add(*(derivative(div[i], i) for i in range(3))),
add(*(derivative(derivative(trace, i), i) for i in range(3))))
force = {}
for i, j in PAIRS:
lap = add(*(derivative(derivative(tensor[i, j], k), k) for k in range(3)))
ddtrace = derivative(derivative(trace, j), i)
force[i, j] = times(sub(add(derivative(div[j], i), derivative(div[i], j)),
add(lap, ddtrace, curvature if i == j else {})),
F(1, 2))
return curvature, force
def fold(field):
output = {}
for point, value in field.items():
dest = tuple(x % (2 * N) for x in point)
output[dest] = output.get(dest, 0) + value
return {p: v for p, v in output.items() if v}
def inner(left, right):
return sum((v * right.get(p, 0) for p, v in left.items()), F(0))
def tensor_inner(left, right):
return sum((1 if i == j else 2) * inner(left[i, j], right[i, j])
for i, j in PAIRS)
def empty():
return {ij: {} for ij in PAIRS}
def diagonal_metric(s, q, profile):
h = dict(s)
for i, sign in enumerate((1, -1, -1)):
h[i, i] = add(s[i, i], times(profile, sign*q/2))
return h
def norm_kinetic(p):
trace = add(*(p[i, i] for i in range(3)))
return tensor_inner(p, p) - inner(trace, trace)/2
def spectrum(use_native):
"""Eliminate only the constrained scalar for the independent spectral test."""
crit = F(0)
snap_shift = F(0)
weights = defaultdict(F)
for ks in product(range(N), repeat=3):
qsq = [2-2*CS[k] for k in ks]
fsq = [(1+CS[k])*CS[k]**2/2 for k in ks]
for i in range(3):
for j in range(i+1, 3):
fsq[i] *= CS[2*ks[j] % N]**2
dsq = [q*f for q, f in zip(qsq, fsq)] if use_native else qsq
d2 = sum(dsq)
if not d2:
continue
Q2 = EPS**2 * (fsq[1]*fsq[2])**2 if use_native else F(EPS**2)
x = dsq[0]/d2
gamma = C2*d2
crit += gamma*Q2*x**2 / (4*VOL)
mu = gamma*Q2*(1-x)**2 / (4*VOL)
if mu:
weights[gamma] += mu
snap_shift += gamma*Q2*(1-2*x) / (4*VOL)
expected = ((F(22111513, 25367150592), -F(104339, 134217728))
if use_native else (F(16301, 71280), F(1, 2)))
assert (crit, snap_shift) == expected
assert snap_shift + crit == sum(weights.values())
def inverse_chi(z, spring):
return spring - crit - z - sum(mu*z/(g-z) for g, mu in weights.items())
# Its derivative is strictly negative between poles. These signs prove
# positive normal frequencies and the unit-tick upper stability bound.
assert inverse_chi(F(0), F(1)) > 0
assert max(weights) < 4 and inverse_chi(F(4), F(1)) < 0
# With half the critical restoring spring there is a negative omega^2.
assert inverse_chi(F(0), crit/2) < 0 < inverse_chi(F(-4), crit/2)
return crit, snap_shift, sum(weights.values()), len(weights)
def run_feedback(use_native, steps=4):
# m=w=kappa=dt=1. The input is a plus wave on z with hxx-hyy=cos(k_z z).
def derivative(field, axis):
return fold((native if use_native else centered)(field, axis))
def filtered(field, factors):
return fold(filters(field, factors)) if use_native else fold(field)
profile = filtered(times(UNIT, EPS), (1, 2, 1, 2))
rho_profile = filtered({(-2, 0, 0): EPS, (2, 0, 0): EPS, ORIGIN: -2*EPS},
(0, 1, 2, 0, 1, 2))
j_profile = filtered({(-1, 0, 0): -EPS, (1, 0, 0): EPS},
(0, 1, 2, 1, 2))
# Independent variation of V at fixed material displacement: a TT wave
# traveling on x, or a cross-polarized wave traveling on z, has no drive.
def drive(force):
contrast = sub(force[0, 0], add(force[1, 1], force[2, 2]))
return C2*inner(profile, contrast)/2
positions = list(product(range(N), repeat=3))
def wave(axis):
return {tuple(2*x for x in p): CS[p[axis]] for p in positions}
axial_null = empty()
axial_null[1, 1] = times(wave(0), F(1, 2))
axial_null[2, 2] = times(wave(0), F(-1, 2))
assert drive(spatial_einstein(axial_null, derivative)[1]) == 0
cross_null = empty()
# An xy face is half-shifted along x,y only for the centered stencil.
offset = 0 if use_native else 1
cross_null[0, 1] = {(2*x+offset, 2*y+offset, 2*z): CS[z]
for x, y, z in positions}
assert drive(spatial_einstein(cross_null, derivative)[1]) == 0
# Check the mixed derivative in both directions. The plane wave is
# normalized by physical cosine amplitude, so its effective mass is V/8.
wave_shape = empty()
wave_shape[0, 0] = times(wave(2), F(1, 2))
wave_shape[1, 1] = times(wave(2), F(-1, 2))
shape_metric = diagonal_metric(empty(), F(1), profile)
_, force_in = spatial_einstein(wave_shape, derivative)
_, force_out = spatial_einstein(shape_metric, derivative)
k_in = drive(force_in)
k_out = C2*tensor_inner(wave_shape, force_out)
expected_k = F(9, 8192) if use_native else F(1, 8)
assert k_in == k_out == expected_k
mode_mass = F(VOL, 8)
expected_transmitter_acceleration = -F(1, 24576) if use_native else -F(1, 216)
assert -k_out/mode_mass == expected_transmitter_acceleration
s = wave_shape
p = empty()
q, P = F(0), F(0)
initial = C2*tensor_inner(s, force_in)/2
assert initial == (F(81, 128) if use_native else F(27, 8))
previous_pp = p
history = []
for step in range(steps):
h = diagonal_metric(s, q, profile)
curvature, force = spatial_einstein(h, derivative)
assert not any(divergence(force, derivative))
assert curvature == times(rho_profile, q)
# Reconstruct the physical momentum on the incoming half slice.
pp = dict(p)
pp[0, 0] = add(p[0, 0], times(profile, P/2))
assert [times(v, -2) for v in divergence(pp, derivative)] == [
times(j_profile, P), {}, {}]
if step:
for ij in PAIRS:
assert pp[ij] == previous_pp[ij]
next_p = {ij: sub(p[ij], times(force[ij], C2)) for ij in PAIRS}
next_P = P - q - drive(force)
# Check the physical momentum equation with the mechanical acceleration.
previous_pp = {ij: sub(pp[ij], times(force[ij], C2)) for ij in PAIRS}
previous_pp[0, 0] = add(previous_pp[0, 0],
times(profile, (next_P-P)/2))
trace = add(*(next_p[i, i] for i in range(3)))
next_s = {(i, j): sub(add(s[i, j], times(next_p[i, j], 2)),
trace if i == j else {}) for i, j in PAIRS}
next_q = q + next_P
h_after = diagonal_metric(next_s, next_q, profile)
mechanic = (next_P**2 + q*next_q)/2
field = norm_kinetic(next_p) + C2*tensor_inner(h_after, force)/2
assert mechanic + field == initial
if not step:
assert next_P == -expected_k
assert mechanic == expected_k**2/2 and initial-field == mechanic
history.append((next_q, mechanic))
s, p, q, P = next_s, next_p, next_q, next_P
return k_in, initial, history
if __name__ == "__main__":
for use_native in (False, True):
label = "native" if use_native else "centered"
crit, snap, total_mu, count = spectrum(use_native)
coupling, initial, history = run_feedback(use_native)
print(f"{label}: critical spring {crit}, sudden shift {snap}, "
f"radiative weight {total_mu}, {count} bright frequencies")
print(f" reciprocal cross coefficient {coupling}, initial energy {initial}, "
f"first material energy {history[0][1]}")
print(f" four-step displacement {history[-1][0]}, "
f"total energy and both Gauss laws exact")
replay.py
"""Replay the collision-energy 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 ("range", "dressing", "alternative", "meter", "clock", "reciprocity", "empirical"):
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 / "energy.tly", work / "energy.tly")
result = subprocess.run([*python, str(tally / "tally.py"), "energy.tly"], cwd=work,
stdout=subprocess.PIPE, check=True)
actual = result.stdout.decode("utf-8").splitlines()
expected = (ROOT / "energy.out").read_text(encoding="utf-8").splitlines()
if actual != expected or sum(line.startswith("✓") for line in actual) != 22:
raise ValueError("Tally output differs from the 22 published checks")
print("All seven offline checks and the complete 22-assertion Tally transcript passed.")
if __name__ == "__main__":
main()