Complete Tally transcript
✓ one-tick joint corner count and conditional switched-port corner count (by cross-pairing plus and minus sides; derived)
✓ identity and full spin flip place every count in opposite parity classes (by cross-pairing plus and minus sides; derived)
✓ a single port-mixing pulse predicts its violation fraction (by cross-pairing plus and minus sides; derived)
✓ independent position-parity and port read errors preserve the balanced control (by cross-pairing plus and minus sides; derived)
✓ the zero and full pulse calibrations have complementary observed rates (by cross-pairing plus and minus sides; derived)
✓ independent measurements of a mixed rod and a mixed front register their opposite shears (by cross-pairing plus and minus sides; derived)
✓ xz shear vanishes in both reconstructions (by cross-pairing plus and minus sides; derived)
✓ yz shear vanishes in both reconstructions (by cross-pairing plus and minus sides; derived)
✓ the three diagonal rod times front entries give the same squared speed (by cross-pairing plus and minus sides; derived)
✓ the mixed rod times front entries cancel (by cross-pairing plus and minus sides; derived)
✓ held-back packet plane and displacement have separately predicted squared readings (by cross-pairing plus and minus sides; derived)
✓ two added velocities pass the six front calibrations and cross the seventh plane (by cross-pairing plus and minus sides; derived)
✓ four equilateral wedge angles give the deficit cosine (by cross-pairing plus and minus sides; derived)
✓ the scalar rotation trace agrees for axial and transverse rotations (by cross-pairing plus and minus sides; derived)
✓ moving the spin rotation to a perpendicular axis gives a finite residual (by cross-pairing plus and minus sides; derived)
✓ the squared signed-phase contrast follows from the same rod geometry (by cross-pairing plus and minus sides; derived)
✓ reversing the second quarter turn changes the retained interference sign (by cross-pairing plus and minus sides; derived)
✓ the signed contrast separates the coherent prediction from independent flips (by cross-pairing plus and minus sides; derived)
Native Tally source
# Exact rational controls for port-resolved fronts and spin transport.
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)
fn wrong(u,v)
return share(v*v,u*u+v*v)
end
let joint=fraction(1 trial,16 trial)
let same=four*joint
check same==fraction(1 trial,4 trial) and share(joint,one+flip(same))==fraction(1 trial,12 trial) "one-tick joint corner count and conditional switched-port corner count"
check wrong(one,zero)==zero and wrong(zero,one)==one "identity and full spin flip place every count in opposite parity classes"
check wrong(one,one)==half and wrong(three,four)==fraction(16 trial,25 trial) "a single port-mixing pulse predicts its violation fraction"
fn xor_rate(a,b)
return a*(one+flip(b))+b*(one+flip(a))
end
let e=xor_rate(fraction(1 trial,100 trial),fraction(1 trial,50 trial))
check e==fraction(37 trial,1250 trial) and xor_rate(e,half)==half "independent position-parity and port read errors preserve the balanced control"
check xor_rate(e,zero)==e and xor_rate(e,one)==one+flip(e) "the zero and full pulse calibrations have complementary observed rates"
fn mixed(a,b,ab)
return half*(ab+flip(a)+flip(b))
end
let gxx=one
let gyy=two
let gzz=four
let gxy=mixed(gxx,gyy,whole(5 trial))
let qxx=whole(8 trial)
let qyy=four
let qzz=one
let qxy=mixed(qxx,qyy,four)
check gxy==one and qxy==flip(four) "independent measurements of a mixed rod and a mixed front register their opposite shears"
check mixed(gxx,gzz,whole(5 trial))==zero and mixed(qxx,qzz,whole(9 trial))==zero "xz shear vanishes in both reconstructions"
check mixed(gyy,gzz,whole(6 trial))==zero and mixed(qyy,qzz,whole(5 trial))==zero "yz shear vanishes in both reconstructions"
check gxx*qxx+gxy*qxy==four and gxy*qxy+gyy*qyy==four and gzz*qzz==four "the three diagonal rod times front entries give the same squared speed"
check gxx*qxy+gxy*qyy==zero and gxy*qxx+gyy*qxy==zero "the mixed rod times front entries cancel"
let held=qxx+qyy+qzz+flip(two*qxy)
check held==whole(21 trial) and gxx+gyy+gzz+flip(two*gxy)==whole(5 trial) "held-back packet plane and displacement have separately predicted squared readings"
let alternative=power(two+two+one,2 trial)
check alternative==whole(25 trial) and alternative>held "two added velocities pass the six front calibrations and cross the seventh plane"
fn double_cos(c)
return two*c*c+flip(one)
end
let c=fraction(1 trial,3 trial)
let deficit_cos=double_cos(double_cos(c))
check deficit_cos==fraction(17 trial,81 trial) "four equilateral wedge angles give the deficit cosine"
check one+two*deficit_cos==fraction(115 trial,81 trial) "the scalar rotation trace agrees for axial and transverse rotations"
let width=one+flip(deficit_cos)
check width==fraction(64 trial,81 trial) and width>zero "moving the spin rotation to a perpendicular axis gives a finite residual"
check one+flip(deficit_cos*deficit_cos)==two*power(fraction(56 trial,81 trial),2 trial) "the squared signed-phase contrast follows from the same rod geometry"
# Each Bloch rotation supplies one mean squared cosine for the one-tick overlap.
let kappa=half*half
let base=two*half*half
let interference=two*kappa*half*half
check base+interference==fraction(5 trial,8 trial) and base+flip(interference)==fraction(3 trial,8 trial) "reversing the second quarter turn changes the retained interference sign"
check two*interference==fraction(1 trial,4 trial) and base==half "the signed contrast separates the coherent prediction from independent flips"
port.py
"""Exact joint probabilities for the six-stage walk and one inserted z rotation.
Run python3 port.py. All amplitudes in the finite calculation are Gaussian
integers with a common normalization removed. No third-party packages.
"""
from fractions import Fraction
from itertools import product
STAGES = (0, 1, 2, 2, 1, 0)
SIGNS = (-1, 1)
ZERO = (0, 0, 0, 0)
def project(v, axis, sign):
"""Apply the signed Pauli projector, times 2 for x or y, times 1 for z."""
a, b, c, d = v # spinor (a + ib, c + id) in the z basis
if axis == 2:
return (a, b, 0, 0) if sign == 1 else (0, 0, c, d)
if axis == 0:
u, w = a + sign*c, b + sign*d
return u, w, sign*u, sign*w
# The y eigenspinor is (1, i*sign)/sqrt(2).
u, w = a + sign*d, b - sign*c
return u, w, -sign*w, sign*u
def tick(state):
for axis in STAGES:
following = {}
for site, v in state.items():
for sign in SIGNS:
vout = project(v, axis, sign)
if vout == ZERO:
continue
pos = list(site)
pos[axis] += sign
pos = tuple(pos)
old = following.get(pos, ZERO)
following[pos] = tuple(a+b for a, b in zip(old, vout))
state = {p: v for p, v in following.items() if v != ZERO}
return state
def rotate_z(state, u, v):
"""Apply u*I - i*v*sigma_z, with sqrt(u²+v²) restored in probabilities."""
return {p: (u*a+v*b, u*b-v*a, u*c-v*d, u*d+v*c)
for p, (a, b, c, d) in state.items()}
def measure(state, ticks, source, denominator, verify_hull):
wrong = 0
port_masses = {}
for detector in SIGNS:
shift = (source+detector)//2
ends = (shift-ticks+1, shift+ticks-1)
extremes = set(product(ends, (-ticks, ticks), (-ticks, ticks)))
found = set()
port_mass = 0
for site, (a, b, c, d) in state.items():
# The two external normalized x spinors supply a factor 1/2.
intensity = (a+detector*c)**2 + (b+detector*d)**2
if intensity == 0:
continue
assert all(i % 2 == 0 for i in site)
x, y, z = (i//2 for i in site)
port_mass += intensity
if (1 if (ticks-x) % 2 == 0 else -1) != source*detector:
wrong += intensity
if verify_hull:
assert ends[0] <= x <= ends[1] and max(abs(y), abs(z)) <= ticks
if (x, y, z) in extremes:
found.add((x, y, z))
assert intensity * 16**ticks == denominator
if verify_hull:
assert found == extremes and len(found) == (4 if ticks == 1 else 8)
port_masses[detector] = Fraction(port_mass, denominator)
assert sum(port_masses.values()) == 1
return Fraction(wrong, denominator), port_masses
def main():
for source in SIGNS:
state = {(0, 0, 0): (1, 0, source, 0)}
for n in range(1, 7):
state = tick(state)
wrong, ports = measure(state, n, source, 4*16**(2*n), True)
assert wrong == 0
if n <= 3:
assert ports[source] == (Fraction(1, 4), Fraction(25, 32),
Fraction(55, 128))[n-1]
if source == 1:
print(f"N={n}: P(same port)={ports[source]}, wrong parity={wrong}")
for n in (2, 3, 4):
for boundary, source, (u, v) in product(range(1, n), SIGNS,
((1, 0), (1, 1), (3, 4), (0, 1))):
state = {(0, 0, 0): (1, 0, source, 0)}
for step in range(1, n+1):
state = tick(state)
if step == boundary:
state = rotate_z(state, u, v)
norm2 = u*u+v*v
wrong, _ = measure(state, n, source, 4*norm2*16**(2*n), False)
assert wrong == Fraction(v*v, norm2)
print("Both x sources passed the exact hull and parity checks through 6 ticks.")
print("One z rotation gave wrong-parity mass 0, 1/2, 16/25, or 1 at every tested boundary.")
if __name__ == "__main__":
main()
echo.py
"""Two z pulses one forward tick apart. Run with python3 echo.py."""
from fractions import Fraction
from port import SIGNS, ZERO, measure, rotate_z, tick
def initial(source):
return {(0, 0, 0): (1, 0, source, 0)}
def norm2(state):
return sum(a*a for v in state.values() for a in v)
def overlap_after_one_tick(psi):
# The common -i in both alternatives cancels from their overlap.
a = tick(rotate_z(psi, 0, 1))
b = rotate_z(tick(psi), 0, 1)
aa, bb = norm2(a), norm2(b)
if aa != bb:
raise ArithmeticError("Inconsistent branch normalization")
real_dot = sum(sum(x*y for x, y in zip(v, b.get(k, ZERO))) for k, v in a.items())
return Fraction(real_dot, aa)
def wrong_mass(n, first_boundary, source, pulse1, pulse2):
if not 0 <= first_boundary < n:
raise ValueError("The two pulses need one whole tick between them")
state = initial(source)
for boundary in range(n + 1):
if boundary:
state = tick(state)
if boundary == first_boundary:
state = rotate_z(state, *pulse1)
if boundary == first_boundary + 1:
state = rotate_z(state, *pulse2)
normalization = 4 * (16**(2*n))
for u, v in (pulse1, pulse2):
normalization *= u*u + v*v
return measure(state, n, source, normalization, False)[0]
def branch_formula(pulse1, pulse2, kappa):
c1, s1 = pulse1
c2, s2 = pulse2
norm = (c1*c1 + s1*s1) * (c2*c2 + s2*s2)
return Fraction((s1*c2)**2 + (c1*s2)**2 + 2*s1*c2*c1*s2*kappa, norm)
def main():
for source in SIGNS:
psi = initial(source)
for _ in range(4):
assert overlap_after_one_tick(psi) == Fraction(1, 4)
psi = tick(psi)
for n in range(1, 5):
for boundary in range(n):
for p1, p2 in (((1, 1), (1, 1)), ((1, 1), (1, -1)),
((3, 4), (4, -3))):
direct = wrong_mass(n, boundary, source, p1, p2)
assert direct == branch_formula(p1, p2, Fraction(1, 4))
for n, boundary in ((1, 0), (3, 1)):
for sign in (1, -1):
p2 = (1, sign)
# Independent arms implement complete dephasing between the
# parity sectors after the first half pulse.
separated = (wrong_mass(n, boundary, source, (1, 0), p2)
+ wrong_mass(n, boundary, source, (0, 1), p2)) / 2
coherent = wrong_mass(n, boundary, source, (1, 1), p2)
assert separated == Fraction(1, 2)
if source == 1:
print(f"N={n} first={boundary} second sign={sign:+d} "
f"coherent={coherent} dephased={separated}")
print("Both x sources passed. One-tick overlap and signed contrast each equal 1/4.")
if __name__ == "__main__":
main()
front.py
"""Infer a velocity ellipsoid and a rod metric from separate exact synthetic measurements."""
from fractions import Fraction as F
from itertools import product
UNIT = ((1, 0, 0), (0, 1, 0), (0, 0, 1))
PROBES = UNIT + ((1, 1, 0), (1, 0, 1), (0, 1, 1))
VALIDATION = (1, -1, 1)
def apply(matrix, v):
return tuple(sum(a*b for a, b in zip(row, v)) for row in matrix)
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def quadratic(matrix, v):
return dot(v, apply(matrix, v))
def infer(readings):
"""Polarize the three coordinate and three pairwise-sum readings."""
x, y, z, xy, xz, yz = map(F, readings)
b, c, e = (xy-x-y)/2, (xz-x-z)/2, (yz-y-z)/2
return ((x, b, c), (b, y, e), (c, e, z))
def facet(v, point):
return dot(v, point)**2
def main():
# Physical displacement A z in a Euclidean frame, with c=2 per clock unit.
# These synthetic generators are independent of the reconstruction routine.
def rod(v):
x, y, z = v
return (x+y)**2+y*y+4*z*z
def front(n):
x, y, z = n
return 4*(x*x+(y-x)**2)+z*z
rods = tuple(map(rod, PROBES))
fronts = tuple(map(front, PROBES))
assert rods == (1,2,4,5,5,6)
assert fronts == (8,4,1,4,9,5)
g, q = infer(rods), infer(fronts)
for i, j in product(range(3), repeat=2):
assert dot(g[i], q[j]) == 4*(i == j)
assert quadratic(g, VALIDATION) == rod(VALIDATION) == 5
assert quadratic(q, VALIDATION) == front(VALIDATION) == 21
# Appending two antipodal velocities changes a support function by pointwise max.
point = (2,-2,1)
assert all(facet(n, point) <= front(n) for n in PROBES)
assert facet(VALIDATION, point) == 25
print("Rod and front squared readings:", rods, fronts)
print("GQ = 4 I; seventh rod squared = 5; seventh front squared = 21.")
print("The nonellipsoidal control agrees on six front probes and yields 25 on the seventh.")
if __name__ == "__main__":
main()
fan.py
"""Independently compare rod reconstruction, face transport and a pair readout."""
from fractions import Fraction as F
from itertools import product
from math import acos, atan2, cos, exp, pi, sin, sqrt
from random import Random
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 tr(a):
return [list(row) for row in zip(*a)]
def scale(k,a):
return [[k*x for x in row] for row in a]
def add(a,b):
return [[x+y for x,y in zip(l,r)] for l,r in zip(a,b)]
def tet(h, ac, bc, ad, bd, cd):
z=(ac*ac-bc*bc+h*h)/(2*h)
zp=(ad*ad-bd*bd+h*h)/(2*h)
r=sqrt(ac*ac-z*z)
rp=sqrt(ad*ad-zp*zp)
q=(r*r+rp*rp+(z-zp)**2-cd*cd)/(2*r*rp)
if not -1<q<1:
raise ValueError("Degenerate tetrahedron")
return acos(q)
def deficit(lengths):
# Shared rods are supplied only once.
h=lengths[0]
ring=lengths[1:5]
ar=lengths[5:9]
br=lengths[9:13]
return 2*pi-sum(tet(h,ar[j],br[j],ar[(j+1)%4],br[(j+1)%4],ring[j])
for j in range(4))
def rotation(c,s):
return [[c,-s,0],[s,c,0],[0,0,1]]
def enclosure():
lo,hi=F(999,1000),F(1001,1000)
zlo=(2*lo*lo-hi*hi)/(2*hi)
zhi=(2*hi*hi-lo*lo)/(2*lo)
assert zlo>0
rlo=lo*lo-zhi*zhi
rhi=hi*hi-zlo*zlo
nlo=2*rlo-hi*hi
nhi=2*rhi+(zhi-zlo)**2-lo*lo
assert nlo>0 and rlo>0
clo,chi = nlo/(2*rhi),nhi/(2*rlo)
return 2*pi-4*acos(float(clo)),2*pi-4*acos(float(chi))
I=[[1,0],[0,1]]
pauli=([[0,1],[1,0]],[[0,-1j],[1j,0]],[[1,0],[0,-1]])
singlet=[[0,1/sqrt(2)],[-1/sqrt(2),0]]
waves=[mm(singlet,tr(s)) for s in pauli]
def variance(axis,angle,v,endpoint_phase,close):
# Build the spinor hopping matrix and normalized symmetric two-boson
# amplitude in the first-quantized position/spin product basis.
V=4; d=2*V
H=[[0j]*d for _ in range(d)]
psi=[[0j]*d for _ in range(d)]
edges=[(0,1,I),(1,2,I),(2,3,I)]
if close:
U=add(scale(cos(angle/2),I),scale(-1j*sin(angle/2),pauli[axis]))
edges.append((3,0,U))
for n,m,U in edges:
for i,j in product(range(2),repeat=2):
H[2*m+i][2*n+j]=U[i][j]
H[2*n+j][2*m+i]=U[i][j].conjugate()
for n in range(V):
phase=complex(cos(endpoint_phase),sin(endpoint_phase)) if n==0 else 1
for i,j in product(range(2),repeat=2):
psi[2*n+i][2*n+j]=((-1)**n)*phase*sum(v[k]*waves[k][i][j] for k in range(3))/sqrt(V)
out=add(mm(H,psi),mm(psi,tr(H)))
norm=sum(abs(x)**2 for row in psi for x in row)
centroid=sum(x.conjugate()*y for l,r in zip(psi,out) for x,y in zip(l,r))
assert abs(norm-1)<1e-14 and abs(centroid)<1e-14
return sum(abs(x)**2 for row in out for x in row)
def closing(axis,angle,spin,phase):
return variance(axis,angle,spin,phase,True)-variance(axis,angle,spin,phase,False)
def main():
unit=[1.0]*13
delta=deficit(unit)
co=17/81; si=56*sqrt(2)/81
assert abs(cos(delta)-co)<1e-14 and abs(sin(delta)-si)<1e-14
assert abs(2*cos(delta/2)-14/9)<1e-14
# Face transitions in the local hinge-oriented incoming-face frames use
# the actual cross-section geometry, independent of the rotation readout.
c=F(1,3)
face=rotation(float(c),-sqrt(1-float(c*c)))
W=mm(mm(face,face),mm(face,face))
assert abs(atan2(W[1][0],W[0][0])-delta)<1e-14
assert abs(sum(W[i][i] for i in range(3))-115/81)<1e-14
hinge=[0,0,1]
circular=[1/sqrt(2),1j/sqrt(2),0]
assert abs(closing(2,delta,hinge,0))<1e-14
assert abs(closing(0,delta,hinge,0)-64/81)<1e-14
for direction in (1,-1):
plus=closing(2,direction*delta,circular,pi/2)
minus=closing(2,direction*delta,circular,-pi/2)
assert abs(plus-(1+direction*si))<1e-14
assert abs(plus-minus-2*direction*si)<1e-14
assert abs(variance(2,delta,circular,pi/2,False)-1)<1e-14
# Check the covariance gradient using independent rod perturbations.
grad=[-4*sqrt(2)/3]+[-sqrt(2)]*4+[2*sqrt(2)/3]*8
for i,expected in enumerate(grad):
off=1e-6
high,low=unit.copy(),unit.copy()
high[i]=exp(off);low[i]=exp(-off)
assert abs((deficit(high)-deficit(low))/(2*off)-expected)<1e-8
assert abs(sum(grad))<1e-13
assert abs(sum(x*x for x in grad)-56/3)<1e-13
lower,upper=enclosure()
assert 1.3125<lower<delta<upper<1.4071
rng=Random(3)
for _ in range(32):
assert lower<=deficit([rng.uniform(.999,1.001) for _ in range(13)])<=upper
align=pi/90
right_max=(1-cos(upper))*sin(align)**2
wrong_min=(1-cos(lower))*cos(align)**2
assert right_max<.001021 and wrong_min>.7437
# Identity-valued connection term adds scalar transport without changing
# the normalized direction. For exact a the loop norm also returns.
for a in ((.07,-.04,.02,.08),(.10,-.05,-.02,-.03)):
P=rotation(1,0)
for edge in a:
P=mm(scale(exp(-edge),face),P)
norm=sqrt(sum(P[i][0]**2 for i in range(3)))
assert abs(norm-exp(-sum(a)))<1e-14
assert max(abs(P[i][0]/norm-W[i][0]) for i in range(3))<1e-14
print(f"Four-tetrahedron deficit {delta:.12f} rad; cosine 17/81, sine 56*sqrt(2)/81.")
print("Three competing rotations have common SO(3) trace 115/81.")
print(f"Hinge and perpendicular readouts 0, {64/81:.9f}; signed phase contrast ±{2*si:.9f}.")
print(f"Rod envelope [{lower:.9f}, {upper:.9f}] rad; axis witnesses ≤{right_max:.9f}, ≥{wrong_min:.9f}.")
print("Exact lengths, phase-referenced spinor hopping, shared-rod derivatives and affine ambiguity passed.")
if __name__=="__main__":
main()
tomography.py
"""Reconstruct a real vector rotation from coherent two-phase pair-width data."""
from math import cos, sin, sqrt
from itertools import combinations
def expectations(matrix, vector):
return sum(a.conjugate()*r*b for i,a in enumerate(vector)
for r,b in zip(matrix[i],vector))
def read_width(matrix, vector, reference):
# The reference phase is applied to the root end of the closing edge.
return 1 - (reference.conjugate()*expectations(matrix, vector)).real
def reconstruct(read):
basis = [[int(i == j) for j in range(3)] for i in range(3)]
result = [[0.0]*3 for _ in basis]
for i, vector in enumerate(basis):
result[i][i] = 1 - read(vector, 1)
for i, j in combinations(range(3), 2):
u = [(a+b)/sqrt(2) for a,b in zip(basis[i],basis[j])]
v = [(a+1j*b)/sqrt(2) for a,b in zip(basis[i],basis[j])]
symmetric = 1-read(u, 1)-(result[i][i]+result[j][j])/2
antisymmetric = 1-read(v, 1j)
result[i][j], result[j][i] = symmetric+antisymmetric,symmetric-antisymmetric
return result
def multiply(a,b):
return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]
def rotation(x,y):
# Two independent axes, to exercise all symmetric and antisymmetric probes.
rx = [[1,0,0],[0,cos(x),-sin(x)],[0,sin(x),cos(x)]]
ry = [[cos(y),0,sin(y)],[0,1,0],[-sin(y),0,cos(y)]]
return multiply(rx,ry)
def main():
for x,y in ((0,0),(.4,-1.7),(1.2,0),(.8,2.1)):
matrix = rotation(x,y)
measured = reconstruct(lambda v,ref: read_width(matrix,v,ref))
assert max(abs(a-b) for u,v in zip(matrix,measured) for a,b in zip(u,v)) < 1e-14
print("Nine normalized differential settings reconstruct each signed 3 by 3 rotation.")
if __name__ == "__main__":
main()
sugawa.py
"""Replay the forward-to-reverse split on Sugawa et al. (2021), Figs. 2a and 3a,b.
Run with Python 3.8+ and no dependencies. Data and limitations are in sugawa.md.
"""
import math
# Rows and columns run I, X, Y, Z. The printed, unparenthesized estimates
# are in hundredths. The parenthesized theoretical entries are never used.
FORWARD_REAL = (
(39, -1, -1, 1),
(-1, 29, 1, -29),
(-1, 1, 0, -1),
(1, -29, -1, 31),
)
FORWARD_IMAG = (
(0, 32, 1, -35),
(-32, 0, 0, -1),
(-1, 0, 0, 0),
(35, 1, 0, 0),
)
REVERSE_REAL = (
(33, 0, 1, 1),
(0, 29, 1, -32),
(1, 1, 3, -2),
(1, -32, -2, 36),
)
REVERSE_IMAG = (
(0, -30, -2, 34),
(30, 0, -1, 1),
(2, 1, 0, 0),
(-34, -1, 0, 0),
)
REVERSE_BLOCH = (-0.68, 0.59, 0.40)
REVERSE_SPREAD = (0.01, 0.05, 0.05)
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def normalize(a):
length = math.hypot(*a)
return tuple(x / length for x in a)
def process(real, imaginary):
chi = tuple(tuple(complex(a, b) / 100 for a, b in zip(rr, ii))
for rr, ii in zip(real, imaginary))
if any(chi[i][j] != chi[j][i].conjugate() for i in range(4) for j in range(4)):
raise ValueError("Printed process matrix fails Hermiticity")
return chi
def fit_rotation(chi):
# The pure-process amplitudes are (w, -i*x, -i*y, -i*z) for real unit q.
phases = (1, -1j, -1j, -1j)
h = [[(phases[i].conjugate() * chi[i][j] * phases[j]).real
for j in range(4)] for i in range(4)]
q = (1., 0., 0., 0.)
for _ in range(100):
q = normalize([dot(row, q) for row in h])
hq = [dot(row, q) for row in h]
value = dot(q, hq)
residual = math.hypot(*(v - value * u for v, u in zip(hq, q)))
# An eigenvalue lies within 'residual' of 'value'. Bound the absolute
# value of every other eigenvalue by the remaining Frobenius norm.
lower = value - residual
frob_sq = sum(dot(row, row) for row in h)
others = math.sqrt(max(0., frob_sq - lower ** 2))
gap_lower = lower - others
if residual > 1e-12 or gap_lower <= 0.02:
raise ArithmeticError("Insufficient convergence or eigenvalue separation")
rounding_angle = 2 * math.degrees(math.asin(0.02 / (gap_lower - 0.02)))
return q, value, rounding_angle
def rotate_z(q, reverse=False):
w, x, y, z = q
if reverse:
x, y, z = -x, -y, -z
return (2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x*x + y*y))
def line_angle(a, b):
cosine = abs(dot(normalize(a), normalize(b)))
return math.degrees(math.acos(min(1., cosine)))
def process_distance(forward, reverse, adjoint):
return math.sqrt(sum(
abs((cell.conjugate() if adjoint else cell) - reverse[i][j])**2
for i, row in enumerate(forward) for j, cell in enumerate(row)
))
def main():
forward = process(FORWARD_REAL, FORWARD_IMAG)
q, overlap, rounding = fit_rotation(forward)
reverse_prediction = rotate_z(q, reverse=True)
unchanged_prediction = rotate_z(q)
# Prediction above has no access to the reverse matrix or reverse vector.
reverse = process(REVERSE_REAL, REVERSE_IMAG)
residual = tuple(y - p for y, p in zip(REVERSE_BLOCH, reverse_prediction))
for label, vec in (("unit quaternion", q),
("predicted reverse +z", reverse_prediction),
("reported reverse +z", REVERSE_BLOCH),
("reported component spreads", REVERSE_SPREAD),
("observed minus predicted", residual)):
print(f"{label:29s}", " ".join(f"{v:+.6f}" for v in vec))
print(f"forward pure-process overlap {overlap:.6f}")
print(f"reverse vector residual norm {math.hypot(*residual):.6f}")
print(f"reverse line error (degrees) {line_angle(reverse_prediction, REVERSE_BLOCH):.6f}")
print(f"unchanged line error (degrees) {line_angle(unchanged_prediction, REVERSE_BLOCH):.6f}")
print(f"forward print bound (degrees) {rounding:.6f}")
print(f"reverse process residual {process_distance(forward, reverse, True):.6f}")
print(f"unchanged process residual {process_distance(forward, reverse, False):.6f}")
if __name__ == "__main__":
main()
gp_b.py
"""An orbit-based leading geodetic drift and the published joint GP-B comparison."""
from math import cos, pi, radians, sin, sqrt
def dot(a,b):
return sum(x*y for x,y in zip(a,b))
def cross(a,b):
return (a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0])
def main():
mu,c=3.986004418e14,299792458.
a,e=7027.4e3,.0014
i,node=radians(90.007),radians(163.26)
ra,dec=radians(343.2594),radians(16.8412)
s=(cos(dec)*cos(ra),cos(dec)*sin(ra),sin(dec))
north=(-sin(dec)*cos(ra),-sin(dec)*sin(ra),cos(dec))
normal=(sin(i)*sin(node),-sin(i)*cos(node),cos(i))
projection=dot(north,cross(normal,s))
assert abs(projection-sin(i)*cos(ra-node))<2e-15
mean_motion=sqrt(mu/a**3)
mas_per_rad=(180/pi)*3600*1000
seconds_per_year=365.25*86400
rate=1.5*mu/(c*c*a)*mean_motion*projection*mas_per_rad*seconds_per_year
angle_per_rev=3*pi*mu/(c*c*a)
revolutions=seconds_per_year*mean_motion/(2*pi)
assert abs(rate-angle_per_rev*revolutions*projection*mas_per_rad)<1e-10
ellipse=rate/(1-e*e)
assert abs(rate+6603.87627)<.0001 and abs(ellipse+6603.88922)<.0001
measured,error,mission=-6601.8,18.3,-6606.1
diff=measured-mission
assert abs(diff-4.3)<1e-10 and .2349<diff/error<.2351
print(f"North projection {projection:.11f}; circular orbit {rate:.3f} mas/yr; Kepler ellipse {ellipse:.3f}.")
print(f"One orbit {angle_per_rev*mas_per_rad:.6f} mas; Kepler period {2*pi/mean_motion/60:.5f} min.")
print(f"Published joint N–S minus mission GR {diff:+.1f} ± {error:.1f} mas/yr ({diff/error:.3f} sigma).")
if __name__=="__main__":
main()
replay.py
"""Replay the detector-port and measured-geometry 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 = "2313affcea8d1d350b825dd8c654ee5ff1985a396e7cc3c572407d347beff574"
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 ("port", "echo", "front", "fan", "tomography", "sugawa", "gp_b"):
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 / "geometry.tly", work / "geometry.tly")
result = subprocess.run([*python, str(tally / "tally.py"), "geometry.tly"], cwd=work,
stdout=subprocess.PIPE, check=True)
actual = result.stdout.decode("utf-8").splitlines()
expected = (ROOT / "geometry.out").read_text(encoding="utf-8").splitlines()
if actual != expected or sum(line.startswith("✓") for line in actual) != 18:
raise ValueError("Tally output differs from the 18 published checks")
print("All seven offline checks and the complete 18-assertion Tally transcript passed.")
if __name__ == "__main__":
main()