Complete Tally transcript
✓ the second surveyed bond has the calibrated unit tangent (by cross-pairing plus and minus sides; derived)
✓ one shear produces different squared front speeds along the two detector normals (by cross-pairing plus and minus sides; derived)
✓ the first reciprocal squared altitude differs from the other two (by cross-pairing plus and minus sides; derived)
✓ the chosen speed fits inside all three fine shift bounds (by cross-pairing plus and minus sides; derived)
✓ rotating and splitting the spin axes cancels the mixed cone entry (by cross-pairing plus and minus sides; derived)
✓ a rational pulse gives a spin-resolved signal at fixed target probability (by cross-pairing plus and minus sides; derived)
✓ an independent transverse spin analyzer measures the signed quadrature (by cross-pairing plus and minus sides; derived)
✓ opposite canonical momentum kicks cancel in the mean but add in the variance (by cross-pairing plus and minus sides; derived)
✓ an ordinary elastic dipole changes interaction sign between axial and diagonal pairs (by cross-pairing plus and minus sides; derived)
✓ two angles null the leading elastic interaction (by cross-pairing plus and minus sides; derived)
✓ ordinary and tuned longitudinal squared resonance ratios at two measured wave numbers (by cross-pairing plus and minus sides; derived)
✓ at zero uniform modulus the two axial static susceptibilities distinguish the tuned limit (by cross-pairing plus and minus sides; derived)
✓ rest dilation charges give the candidate Newton coefficient in units c to the fourth over pi b (by cross-pairing plus and minus sides; derived)
✓ the two post-Newtonian shape factors predict a factor of two in relative light delay (by cross-pairing plus and minus sides; derived)
✓ the opposite ribbon gradients give a detector-gain-cancelling ratio (by cross-pairing plus and minus sides; derived)
✓ the measured microwave half splitting is 181.5 tenths of a MHz (by cross-pairing plus and minus sides; derived)
✓ the four ancillary rail populations are positive and normalized (by cross-pairing plus and minus sides; derived)
✓ the coherent rail state reproduces all three components of a prescribed drift (by cross-pairing plus and minus sides; derived)
✓ a unit-lapse flow of one quarter light speed supplies a squared shift of one sixteenth (by cross-pairing plus and minus sides; derived)
✓ the held shell has a self-consistent weak-branch exterior speed (by cross-pairing plus and minus sides; derived)
✓ the field and shell energy differ from the exterior mass at the rational benchmark (by cross-pairing plus and minus sides; derived)
✓ the weak branch requires a finite central clock shift even where inversion forces a zero vector (by cross-pairing plus and minus sides; derived)
Native Tally source
# Rational controls on the deforming-link study.
ratchet 32 step
import "atom"
let zero=whole(0 trial)
let one=whole(1 trial)
let two=whole(2 trial)
let three=whole(3 trial)
let four=whole(4 trial)
let half=fraction(1 trial,2 trial)
let shear=fraction(3 trial,4 trial)
let tx=fraction(3 trial,5 trial)
let ty=fraction(4 trial,5 trial)
let vxx=one+shear*tx
let vxy=shear*ty
check tx*tx+ty*ty==one and tx==shear*ty "the second surveyed bond has the calibrated unit tangent"
check vxx*vxx+vxy*vxy==fraction(197 trial,80 trial) and tx*tx+ty*ty==one "one shear produces different squared front speeds along the two detector normals"
check one+shear*shear==fraction(25 trial,16 trial) "the first reciprocal squared altitude differs from the other two"
let slow=ty
check slow*fraction(5 trial,4 trial)==one and slow*one<one "the chosen speed fits inside all three fine shift bounds"
check tx+flip(shear*ty)==zero and slow*slow+tx*tx==one "rotating and splitting the spin axes cancels the mixed cone entry"
let s2=fraction(3 trial,5 trial)
let c2=fraction(4 trial,5 trial)
let target=fraction(1 trial,16 trial)
let up=target*s2*s2
let down=target*c2*c2
check up==fraction(9 trial,400 trial) and up+down==target "a rational pulse gives a spin-resolved signal at fixed target probability"
check share(target*(one+flip(two*s2*c2)),two)==fraction(1 trial,800 trial) "an independent transverse spin analyzer measures the signed quadrature"
check two*slow+flip(two*slow)==zero and power(two*slow,2 trial)==fraction(64 trial,25 trial) "opposite canonical momentum kicks cancel in the mean but add in the variance"
fn angular(nx2)
return whole(5 trial)*nx2*nx2+flip(three*nx2)
end
check angular(one)==two and angular(half)==flip(fraction(1 trial,4 trial)) "an ordinary elastic dipole changes interaction sign between axial and diagonal pairs"
check angular(zero)==zero and angular(fraction(3 trial,5 trial))==zero "two angles null the leading elastic interaction"
let qlo=one
let qhi=three
check share(three*qhi,three*qlo)==three and share(three*qhi*qhi,three*qlo*qlo)==whole(9 trial) "ordinary and tuned longitudinal squared resonance ratios at two measured wave numbers"
check share(share(one,three*qlo),share(one,three*qhi))==three "at zero uniform modulus the two axial static susceptibilities distinguish the tuned limit"
let scalar=fraction(1 trial,3 trial)
check share(scalar*scalar,whole(12 trial))==fraction(1 trial,108 trial) "rest dilation charges give the candidate Newton coefficient in units c to the fourth over pi b"
check share(one,two)==half and share(one+one,one+zero)==two "the two post-Newtonian shape factors predict a factor of two in relative light delay"
let row=fraction(4 trial,5 trial)
let curve=row*row
check curve==fraction(16 trial,25 trial) and share(curve,share(one,curve))==fraction(256 trial,625 trial) "the opposite ribbon gradients give a detector-gain-cancelling ratio"
let left=whole(66348 trial)
let right=whole(66711 trial)
check share(right+flip(left),two)==fraction(363 trial,2 trial) "the measured microwave half splitting is 181.5 tenths of a MHz"
let vx=fraction(1 trial,4 trial)
let vy=flip(fraction(1 trial,2 trial))
let vz=fraction(1 trial,8 trial)
let a=share(one+vx+vy+vz,four)
let b=share(one+vx+flip(vy)+flip(vz),four)
let c=share(one+flip(vx)+vy+flip(vz),four)
let d=share(one+flip(vx)+flip(vy)+vz,four)
check a+b+c+d==one and a>zero and b>zero and c>zero and d>zero "the four ancillary rail populations are positive and normalized"
check a+b+flip(c)+flip(d)==vx and a+flip(b)+c+flip(d)==vy and a+flip(b)+flip(c)+d==vz "the coherent rail state reproduces all three components of a prescribed drift"
check share(one,four)*four==one and share(one,four)*share(one,four)==fraction(1 trial,16 trial) "a unit-lapse flow of one quarter light speed supplies a squared shift of one sixteenth"
let shellx=fraction(25 trial,169 trial)
let lapse=fraction(12 trial,13 trial)
let compact=shellx*lapse
check lapse*lapse+shellx==one and compact==fraction(300 trial,2197 trial) "the held shell has a self-consistent weak-branch exterior speed"
let energy=lapse+share(shellx,four*lapse)
check energy==fraction(601 trial,624 trial) and share(one,lapse)+flip(energy)==fraction(25 trial,208 trial) "the field and shell energy differ from the exterior mass at the rational benchmark"
check three*shellx<two and shellx>zero and lapse<one "the weak branch requires a finite central clock shift even where inversion forces a zero vector"
axes.py
"""Homogeneous six-gate cone in independently surveyed physical coordinates."""
from math import acos, cos, sin, sqrt
from itertools import product
UNIT = ((1.,0.,0.), (0.,1.,0.), (0.,0.,1.))
BONDS = ((1.,0.,0.), (.75,1.,0.), (0.,0.,1.)) # columns, twice one fine shift
DUAL = ((1.,-.75,0.), (0.,1.,0.), (0.,0.,1.))
def dot(a,b):
return sum(x*y for x,y in zip(a,b))
def norm(a):
return sqrt(dot(a,a))
def unit(a):
return tuple(x/norm(a) for x in a)
def matrix(left,right):
return [[sum(a[i]*b[j] for a,b in zip(left,right)) for j in range(3)] for i in range(3)]
def split(mean,perp,w):
assert abs(dot(mean,perp)) < 1e-14 and 0 <= w <= 1
s=sqrt(1-w*w)
return tuple(tuple(w*x+sign*s*y for x,y in zip(mean,perp)) for sign in (-1,1))
def spin_gate(spin,axis,angle):
x,y,z=axis
a,b=spin
sa,ca=sin(angle),cos(angle)
return (ca*a-1j*sa*(z*a+(x-1j*y)*b),
ca*b-1j*sa*((x+1j*y)*a-z*b))
def node_speed(direction, k, gates):
# Extract the traceless, anti-Hermitian part to avoid loss of accuracy near identity.
col=(1,0);order=(0,1,2,2,1,0)
for j,i in enumerate(order):
col=spin_gate(col,gates[i][int(j>=3)],.5*k*dot(direction,BONDS[i]))
return sqrt(col[0].imag**2+abs(col[1])**2)/k
def main():
for i,j in product(range(3),repeat=2):
assert abs(dot(BONDS[i],DUAL[j])-int(i==j))<1e-15
tangents=tuple(map(unit,BONDS))
frozen=matrix(BONDS,tangents)
assert abs(dot(frozen[0],frozen[0])-197/80)<1e-14
assert abs(dot(frozen[1],frozen[1])-1)<1e-14
assert tuple(map(norm,DUAL))==(1.25,1.,1.)
gates=[split(unit(r),p,.8*norm(r)) for r,p in zip(DUAL,(UNIT[2],UNIT[2],UNIT[0]))]
means=[tuple((x+y)/2 for x,y in zip(a,b)) for a,b in gates]
calibrated=matrix(BONDS,means)
for i,j in product(range(3),repeat=2):
assert abs(calibrated[i][j]-.8*int(i==j))<1e-14
probes=(*UNIT,unit((1,1,-1)),unit((2,-3,1)))
ref=[(node_speed(v,1e-5,[(a,a) for a in tangents]),node_speed(v,1e-5,gates)) for v in probes]
for v,(bare,fit) in zip(probes,ref):
expected=norm([sum(v[i]*frozen[i][j] for i in range(3)) for j in range(3)])
assert abs(bare-expected)<1e-8 and abs(fit-.8)<5e-6
finite=[node_speed(v,.4,gates) for v in probes]
assert max(finite)-min(finite)>.001
print("Rod dual lengths:",tuple(map(norm,DUAL)))
print("Tangent gate squared front support:",[dot(row,row) for row in frozen])
print("Calibrated low-k speeds:",[round(b,8) for _,b in ref])
print("Finite-k sin(eigenphase)/|k|:",[round(x,6) for x in finite])
if __name__=="__main__":
main()
interferometer.py
"""Direct six-stage spinor propagation with a material-dependent link phase."""
from cmath import exp
from math import cos, sin, pi, sqrt
ORIGIN = (0,0,0)
TARGET = (0,2,2)
def split(axis,sign,state):
a,b=state
pa,pb=[(b,a),(-1j*b,1j*a),(a,-b)][axis]
return (a+sign*pa)/2,(b+sign*pb)/2
def walk(theta):
states={ORIGIN:(1,0)}
for axis in (0,1,2,2,1,0):
following={}
for pos,spin in states.items():
for sign in (-1,1):
dest=list(pos);dest[axis]+=sign;dest=tuple(dest)
da,db=split(axis,sign,spin)
angle=theta*(dest[0]*dest[1]-pos[0]*pos[1]) if axis==0 else 0
phase=exp(1j*angle)
a,b=following.get(dest,(0,0))
following[dest]=a+phase*da,b+phase*db
states=following
return states
def validate_pointer():
# Conditional on the rare destination, the two x ports each have probability 1/2.
a,sigma,mean=1.1,.22,.35
h=.002
q=[mean+i*h for i in range(-1200,1201)]
f=[exp(-(t-mean)**2/(4*sigma**2)) for t in q]
total=sum(abs(x)**2 for x in f)
predicted=exp(4j*a*mean-8*a*a*sigma*sigma)
observed=sum(abs(g)**2*exp(4j*a*t) for t,g in zip(q,f))/total
assert abs(predicted-observed)<1e-12
kicks=[]
for sign in (-1,1):
packet=[g*exp(2j*sign*a*t) for t,g in zip(q,f)]
mom=sum((packet[i].conjugate()*(packet[i+1]-packet[i-1])/(2j*h)).real
for i in range(1,len(q)-1))/total
assert abs(mom-2*sign*a)<.0001
kicks.append(mom)
print("Gaussian fringe visibility:",round(abs(observed),8),"port-conditioned momenta:",kicks)
def main():
for theta in (0,.133,-.133,pi/8,pi/4,pi/2):
all_sites=walk(theta)
assert abs(sum(abs(a)**2+abs(b)**2 for a,b in all_sites.values())-1)<1e-14
a,b=all_sites[TARGET]
assert abs(a+sin(2*theta)/4)<1e-14 and abs(b-1j*cos(2*theta)/4)<1e-14
joint=abs(a-1j*b)**2/2
assert abs(joint-(1-sin(4*theta))/32)<1e-14
assert abs(abs(a)**2+abs(b)**2-1/16)<1e-14
validate_pointer()
print("Both spin quadratures agree with the entire six-stage unitary.")
if __name__=="__main__":
main()
elastic.py
"""Compatible central-spring lattice. Run with python3 elastic.py (standard library)."""
from math import cos, sin, pi, sqrt, isclose
AXES = ((1, 0, 0), (0, 1, 0), (0, 0, 1))
BONDS = AXES + ((1, 1, 0), (1, -1, 0), (1, 0, 1), (1, 0, -1),
(0, 1, 1), (0, 1, -1))
def bond_matrix(q):
"""Hessian from actual linearized length changes of individual bonds."""
matrix = [[0.0] * 3 for _ in AXES]
for d in BONDS:
qd = sum(x*y for x, y in zip(q, d))
factor = 4*sin(qd/2)**2 / sum(x*x for x in d)
for i in range(3):
for j in range(3):
matrix[i][j] += factor*d[i]*d[j]
return matrix
def entries(c, s):
x, y, z = c
u, v, w = s
return (2*(3-x-x*y-x*z), 2*(3-y-y*z-y*x), 2*(3-z-z*x-z*y),
2*u*v, 2*u*w, 2*v*w)
def lattice_laws():
for q in ((.8, .4, -.7), (0, .1, 0), (pi, pi, pi), (1.3, -2.6, .7)):
direct = bond_matrix(q)
pairs = ((0, 0), (1, 1), (2, 2), (0, 1), (0, 2), (1, 2))
analytic = entries(tuple(map(cos, q)), tuple(map(sin, q)))
assert all(abs(direct[i][j]-v) < 1e-13 for (i,j), v in zip(pairs, analytic))
for kappa, b in ((1, 0), (0, 1), (1, 1)):
poles, static = [], []
for q in (pi/3, 2*pi/3):
scale = 4*sin(q/2)**2
longitudinal = bond_matrix((q, 0, 0))[0][0] * (kappa+b*scale)
assert isclose(longitudinal, 3*scale*(kappa+b*scale))
poles.append(sqrt(longitudinal))
static.append(scale/longitudinal)
print(f"kappa={kappa}, b={b}: pole ratio {poles[1]/poles[0]:.9f}, "
f"static chi(q1)/chi(q2) {static[0]/static[1]:.9f}")
# Unit mass, unit stiffness, unit angular drive frequency, q1 then q2.
assert isclose((1/(3-1))/(3/(9-1)), 4/3)
def real_space(size, radii):
"""Periodic infinite-time static kernel. Mean displacement and cell are fixed.
Apply octant symmetry, then Fourier inversion. Dilation is summed only
along x, where each transverse odd Fourier coefficient integrates to zero.
"""
half = size//2
freq = [2*pi*j/size for j in range(half+1)]
c, s = list(map(cos, freq)), list(map(sin, freq))
weight = [1] + [2]*(half-1) + [1]
modes = sorted(set(radii) | {2*r for r in radii})
phase = {r: [cos(r*q) for q in freq] for r in modes}
axial = dict.fromkeys(modes, 0.0)
diagonal = dict.fromkeys(modes, 0.0)
volume = dict.fromkeys(modes, 0.0)
for i, x in enumerate(c):
for j, y in enumerate(c):
sum_bond = sum_volume = 0.0
xy = 2*s[i]*s[j]
for k, z in enumerate(c):
if i == j == k == 0:
continue
xx = 2*(3-x-x*y-x*z)
yy = 2*(3-y-y*z-y*x)
zz = 2*(3-z-z*x-z*y)
xz, yz = 2*s[i]*s[k], 2*s[j]*s[k]
gxx = yy*zz-yz*yz
gyy = zz*xx-xz*xz
gzz = xx*yy-xy*xy
gxy = xz*yz-xy*zz
gxz = xy*yz-xz*yy
gyz = xy*xz-yz*xx
det = xx*gxx + xy*gxy + xz*gxz
qx, qy, qz = 2*(1-x), 2*(1-y), 2*(1-z)
invdet = weight[k]/det
sum_bond += qx*gxx*invdet
# For v_l=exp(i k_l)-1, reflection-averaged 2 Re(v_i v_j*)
# contracted with the off-diagonal inverse keeps 2 sin(k_i)sin(k_j).
vol = qx*gxx + qy*gyy + qz*gzz + xy*gxy + xz*gxz + yz*gyz
sum_volume += vol*invdet/(qx+qy+qz)
pref = -weight[i]*weight[j]/size**3
for r in modes:
arm = pref*phase[r][i]
axial[r] += arm*sum_bond
diagonal[r] += arm*phase[r][j]*sum_bond
volume[r] += arm*sum_volume
return [(r,
(8/7)*r**3*(axial[r]-axial[2*r]),
(8/7)*(sqrt(2)*r)**3*(diagonal[r]-diagonal[2*r]),
-2*r*(volume[r]-volume[2*r])) for r in radii]
def direct_small(size, r):
"""Full Brillouin zone with complex bond vertices; independent of octant reduction."""
vals = [0.0]*3
for i in range(size):
for j in range(size):
for k in range(size):
if i == j == k == 0:
continue
q = [2*pi*t/size for t in (i, j, k)]
c, s = list(map(cos, q)), list(map(sin, q))
xx, yy, zz, xy, xz, yz = entries(c, s)
a, b, d = yy*zz-yz*yz, xx*zz-xz*xz, xx*yy-xy*xy
e, f, g = xz*yz-xy*zz, xy*yz-xz*yy, xy*xz-xx*yz
adj = ((a,e,f), (e,b,g), (f,g,d))
det = xx*a+xy*e+xz*f
v = [complex(x-1,y) for x,y in zip(c,s)]
q2 = sum(abs(t)**2 for t in v)
bond = abs(v[0])**2*a/det
volume = sum(v[l].conjugate()*adj[l][m]*v[m]
for l in range(3) for m in range(3)).real/(det*q2)
dx = cos(q[0]*r)-cos(q[0]*2*r)
dxy = cos((q[0]+q[1])*r)-cos((q[0]+q[1])*2*r)
vals[0] -= (8/7)*r**3*bond*dx/size**3
vals[1] -= (8/7)*(sqrt(2)*r)**3*bond*dxy/size**3
vals[2] += 2*r*volume*dx/size**3
return vals
if __name__ == "__main__":
lattice_laws()
assert all(abs(a-b)<1e-12 for a,b in
zip(real_space(10,(2,))[0][1:], direct_small(10,2)))
print("L r axial bond A diagonal bond A soft dilation A")
for size in (96, 160):
for r, ax, dg, vol in real_space(size, (6, 10)):
print(f"{size:3d} {r:3d} {ax:16.9f} {dg:18.9f} {vol:16.9f}")
if size == 160 and r == 10:
assert isclose(ax, 1/(2*pi), rel_tol=.06)
assert isclose(dg, -1/(16*pi), rel_tol=.12)
assert isclose(vol, 1/(12*pi), rel_tol=.05)
print("Continuum ", *(f"{v:16.9f}" for v in (1/(2*pi), -1/(16*pi), 1/(12*pi))))
charge.py
"""Rest, kinetic and passive dilation responses of a doubled six-stage unitary."""
from math import acos, cos, sin, sqrt, tan
from axes import spin_gate, split
PHOTON = 4/5
def weight(m):
return PHOTON*sqrt(tan(m)/m)
def axial_cos(k,w):
axes=split((1,0,0),(0,0,1),w)
a,b=(1,0)
for axis in axes:
a,b=spin_gate((a,b),axis,k/2)
return a.real
def omega(m,k,w):
return acos(cos(m)*axial_cos(k,w))
def lab_energy(s,m0,p):
# Laboratory time T=s², rod spacing s, hbar=T0=a0=1.
m=s*m0
return omega(m,s*p,weight(m))/s**2
def main():
for m in (.25,.7,.95):
w=weight(m)
assert w<=1
for k in (.1,.6,1.2):
assert abs(axial_cos(k,w)-(1-2*w*w*sin(k/2)**2))<1e-14
for s in (.98,1.,1.02):
h=.0005
energy=lab_energy(s,m,0)
inverse_mass=2*(lab_energy(s,m,h)-energy)/h**2
assert abs(energy-m/s)<1e-13
assert abs(inverse_mass-PHOTON**2/(s*m))<2e-5
charge=-(lab_energy(1+.00001,m,0)-lab_energy(1-.00001,m,0))/.00006
assert abs(charge-m/3)<1e-9
expected4=-PHOTON**2/(24*m)+PHOTON**4*(1-m/tan(m))/(8*m**3)
k=.012
residual=(omega(m,k,w)-sqrt(m*m+(PHOTON*k)**2))/k**4
assert abs(residual-expected4)<.00012
print(f"mass phase {m:.2f} mixing {w:.6f} P/E {charge/m:.6f} quartic difference {expected4:.6f}")
lo,hi=1.0,1.2
for _ in range(50):
mid=(lo+hi)/2
if weight(mid)>1:hi=mid
else:lo=mid
print("Maximum admissible positive mass phase for this photon speed:",round(lo,8))
assert 1<lo<1.1
if __name__=="__main__":
main()
solar.py
"""Static solar light propagation with compatible Euclidean rods; standard library."""
from math import asinh, cosh, expm1, hypot, isclose, pi, sinh
C = 299792458.0
AU = 149597870700.0
SOLAR_GM = 1.3271244e20
SOLAR_RADIUS = 6.957e8
SOLAR_M = SOLAR_GM/C**2
X1, X2 = AU, 7.43*AU
def log_factor(h):
return asinh(X1/h) + asinh(X2/h)
def optical_ray(x1, x2, epsilon, steps=800):
"""Fixed endpoints (-x1,1),(x2,1); length unit = impact parameter.
Solve Fermat's equation for n=exp(epsilon/r); return optical excess length.
"""
t0, t1 = -asinh(x1), asinh(x2)
dt = (t1-t0)/steps
def rhs(t, y, slope):
x, jac = sinh(t), cosh(t)
radius = hypot(x, y)
sec = hypot(1, slope)
bend = -epsilon*(y-slope*x)*sec**2/radius**3
excess = expm1(epsilon/radius)*sec + slope*slope/(sec+1)
return jac*slope, jac*bend, jac*excess
def shoot(initial_slope):
y, p, excess = 1.0, initial_slope, 0.0
for i in range(steps):
t = t0+i*dt
a = rhs(t, y, p)
b = rhs(t+dt/2, y+dt*a[0]/2, p+dt*a[1]/2)
d = rhs(t+dt/2, y+dt*b[0]/2, p+dt*b[1]/2)
e = rhs(t+dt, y+dt*d[0], p+dt*d[1])
y += dt*(a[0]+2*b[0]+2*d[0]+e[0])/6
p += dt*(a[1]+2*b[1]+2*d[1]+e[1])/6
excess += dt*(a[2]+2*b[2]+2*d[2]+e[2])/6
return y-1, excess
# Secant shooting varies the initial slope until the other endpoint is hit.
p0, p1 = 0.0, 3*epsilon
res0, _ = shoot(p0)
for _ in range(10):
res1, excess = shoot(p1)
if abs(res1) < 3e-13:
return excess
p0, res0, p1 = p1, res1, p1-res1*(p1-p0)/(res1-res0)
raise ArithmeticError("Optical ray missed the endpoint")
def check_source():
strength, radius = .034, 2.3
def displacement(r):
if r < radius:
return strength*(r/(2*radius)-r**3/(10*radius**3))
return strength*(.5-radius**2/(10*r**2))
for r in (.1*radius, .5*radius, radius, 2*radius, 10*radius):
h = 1e-5*radius
divergence = (displacement(r+h)-displacement(r-h))/(2*h) + 2*displacement(r)/r
expected = (strength*(3*radius**2-r*r)/(2*radius**3)
if r < radius else strength/r)
assert isclose(divergence, expected, rel_tol=2e-8)
def main():
check_source()
near, far = 1.6*SOLAR_RADIUS, 5*SOLAR_RADIUS
print("Fixed endpoint axial distances 1 au and 7.43 au.")
eps = 2e-7
for h in (near, far):
n1, n2 = X1/h, X2/h
slope = (optical_ray(n1,n2,eps)-optical_ray(n1,n2,-eps))/(2*eps)
theory = log_factor(h)
print(f"h/Rsun={h/SOLAR_RADIUS:.1f}, ray derivative {slope:.9f}, "
f"closed form {theory:.9f}")
assert isclose(slope, theory, rel_tol=2e-8)
dh = .00001*h
minus_gradient = -(log_factor(h+dh)-log_factor(h-dh))/(2*dh)
analytical = (X1/hypot(X1,h)+X2/hypot(X2,h))/h
assert isclose(minus_gradient, analytical, rel_tol=2e-9)
for gamma in (0, 1):
coeff = (1+gamma)*SOLAR_M/C
relative = coeff*(log_factor(near)-log_factor(far))
limb = 2*(1+gamma)*SOLAR_M/SOLAR_RADIUS * 180/pi*3600
print(f"gamma={gamma}: differential delay {relative*1e6:.6f} us one-way, "
f"{2*relative*1e6:.6f} us return trip; limb bending {limb:.6f} arcsec")
# Verify the exact change to diagonal Schwarzschild coordinates outside the horizon.
for r in (3., 10., 50.): # geometric units with GM=c=1
v, f = (2/r)**.5, 1-2/r
a = v/f
assert abs(-f*a+v) < 1e-13
assert isclose(1 + 2*v*a-f*a*a, 1/f)
if __name__ == "__main__":
main()
tilted.py
"""An eight-channel walk with a continuously tunable low-energy drift.
Run python3 tilted.py. The propagation is an axial invariant sector of the
full model, with the native Pauli spin in its +x eigenstate.
"""
import cmath
import math
RAILS = ((1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1))
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def weights(v):
p = [(1 + dot(d, v))/4 for d in RAILS]
if min(p) <= 0:
raise ValueError('Velocity must be in the open rail tetrahedron')
return p
def low_frequency(p, k):
phases = [dot(d, k) for d in RAILS]
lo, hi = min(phases), max(phases)
if hi-lo >= math.pi:
raise ValueError('Bisection needs the near-origin pole-free interval')
for _ in range(60):
w = (lo + hi)/2
if sum(m*math.tan((z-w)/2) for m, z in zip(p, phases)) > 0:
lo = w
else:
hi = w
return (lo + hi)/2
def direct_residual(p, k, w):
# Evaluate det[diag(exp(-i*d.k)) (2aa^T-I) - exp(-i*w) I] by
# elimination on the physical rail matrix, separately from the secular sum.
a = [math.sqrt(v) for v in p]
eigen = cmath.exp(-1j*w)
matrix = []
for i, d in enumerate(RAILS):
shift = cmath.exp(-1j*dot(d, k))
matrix.append([2*shift*a[i]*a[j] - ((shift + eigen) if i == j else 0)
for j in range(4)])
product = 1.
for i in range(4):
row = max(range(i, 4), key=lambda j: abs(matrix[j][i]))
if row != i:
matrix[i], matrix[row] = matrix[row], matrix[i]
product = -product
pivot = matrix[i][i]
product *= pivot
if pivot == 0:
return 0.
for j in range(i+1, 4):
fac = matrix[j][i]/pivot
for col in range(i+1, 4):
matrix[j][col] -= fac*matrix[i][col]
return abs(product)
def dispersion():
v = (0.25, -0.15, 0.1)
p = weights(v)
for i in range(3):
k = [0., 0., 0.]
k[i] = .37
w = low_frequency(p, k)
assert abs(w-math.asin(v[i]*math.sin(k[i]))) < 2e-15
assert direct_residual(p, k, w) < 2e-14
direction = (.7, -.2, .5)
print('oblique h abs(w-v.k) after cubic correction |det|')
for h in (.2, .1, .05, .025):
k = [h*z for z in direction]
linear = dot(v, k)
cubic = sum(w*(dot(d, k)-linear)**3 for w, d in zip(p, RAILS))/12
w = low_frequency(p, k)
res = direct_residual(p, k, w)
assert res < 2e-14
assert abs(w-linear-cubic) < 0.01*h**5
print(f'{h:9.3g} {abs(w-linear):11.4e} {abs(w-linear-cubic):20.4e} {res:.2e}')
def initial(r):
s = (r - 5.)/1.45
if abs(s) >= 1.:
return 0j
return math.exp(1 - 1/(1-s*s)) * cmath.exp(2j*(r-5.))
def speed(r):
return 1-1/math.sqrt(r)
def radial_time(r):
return r + 2*math.sqrt(r) + 2*math.log(math.sqrt(r)-1)
def transported(r, t):
# The outgoing PG null characteristic takes t = F(r) - F(r0).
target = radial_time(r)-t
lo, hi = 1 + 1e-10, r
for _ in range(60):
mid = (lo+hi)/2
if radial_time(mid) < target:
lo = mid
else:
hi = mid
r0 = (lo+hi)/2
return math.sqrt(speed(r0)/speed(r))*initial(r0)
def packet(n):
dx = 8/n
steps = n//8
rr = [2+i*dx for i in range(n)]
aa = [[math.sqrt(q) for q in weights((-1/math.sqrt(r), 0., 0.))] for r in rr]
norm = math.sqrt(dx*sum(abs(initial(r))**2 for r in rr))
psi = [[a*initial(r)/norm for a in row] for row, r in zip(aa, rr)]
max_leak = 0.
for _ in range(steps):
nxt = [[0j]*4 for _ in rr]
for i, (a, row) in enumerate(zip(aa, psi)):
overlap = dot(a, row)
for j, d in enumerate(RAILS):
# Native +x adds one site to each rail's signed axial shift.
nxt[(i + 1 + d[0]) % n][j] = 2*a[j]*overlap-row[j]
psi = nxt
low = [dot(a, row) for a, row in zip(aa, psi)]
leakage = dx*sum(abs(q-a[j]*f)**2 for row, a, f in zip(psi, aa, low)
for j, q in enumerate(row))
max_leak = max(max_leak, leakage)
total = dx*sum(abs(q)**2 for row in psi for q in row)
assert abs(total-1) < 1e-12
# No support can reach the periodic seam by t=1: range at most +2/tick.
assert max(map(abs, psi[0]+psi[-1])) == 0.
exact = [transported(r, steps*dx)/norm for r in rr]
err = math.sqrt(dx*sum(abs(f-g)**2 for f, g in zip(low, exact)))
return err, leakage, max_leak, abs(total-1)
def main():
dispersion()
print('N envelope L2 final outside mass max outside mass norm defect')
previous = None
for n in (64, 128, 256, 512):
result = packet(n)
if previous is not None:
assert result[0] < previous[0] and result[2] < previous[2]
print(f'{n:3d} {result[0]:14.6e} {result[1]:17.6e} '
f'{result[2]:17.6e} {result[3]:.1e}')
previous = result
if __name__ == '__main__':
main()
closure.py
"""Thin-shell exterior, sourced closure, and its obstruction at a symmetry center."""
from fractions import Fraction as F
from math import sqrt
def potential_shell(r, panels=40000):
"""Normalized potential of a unit spherical shell via midpoint angular quadrature."""
return sum(1/sqrt(1+r*r-2*r*(-1+(2*j+1)/panels))
for j in range(panels))/panels
def energy(x, eta):
return sqrt(1-x)+x*x/(4*eta)
def solve(eta):
lo,hi=0.,2/3
assert 0<eta<hi*sqrt(1-hi)
for _ in range(60):
m=(lo+hi)/2
if m*sqrt(1-m)<eta:lo=m
else:hi=m
return (lo+hi)/2
def main():
x=F(25,169)
root=F(12,13)
eta=x*root
stationary_energy=root+x/(4*root)
exterior_mass=1/root
assert (1-x)==root*root and eta==F(300,2197)
assert stationary_energy==F(601,624) and exterior_mass-stationary_energy==F(25,208)
assert abs(solve(float(eta))-float(x))<1e-14
eps=1e-5
assert energy(float(x)+eps,float(eta))>energy(float(x),float(eta))
assert energy(float(x)-eps,float(eta))>energy(float(x),float(eta))
# Independent angular sum over the actual spherical source.
for r in (0.,.2,.7,1.3,2.,4.):
assert abs(potential_shell(r)-1/max(1.,r))<1e-8
for eta in (.0001,.001,.02):
x=solve(eta)
assert abs(x*sqrt(1-x)-eta)<1e-14
assert abs((energy(x,eta)-1)/eta+.25)<.01
# The gradient is zero at the center, while the required velocity norm is positive.
assert potential_shell(0)==1 and x>0
print(f"compactness {eta:g}; squared shell speed {x:.9g}; exterior/rest mass {1/sqrt(1-x):.9f}")
print("Stationary shell, normalized exterior strength, and nonzero central clock potential checked.")
if __name__=="__main__":
main()
honeycomb.py
"""Planar honeycomb hopping and an exact zero-mode intensity test.
Standard-library replay. Energies are in units of the unstrained hopping.
The longitudinal 24-cell repeat is a Bloch normalization box. The primitive
honeycomb lives in the plane; no curvature is introduced by gluing a specimen.
"""
from cmath import exp as phase
from math import acos, atan2, cos, exp, hypot, isclose, log, pi, sin, sqrt
def symmetric_spectrum(matrix):
"""Jacobi diagonalization, including the independent numerical eigenstates."""
a = [row[:] for row in matrix]
size = len(a)
vectors = [[float(i == j) for j in range(size)] for i in range(size)]
for _ in range(100*size*size):
r, s = max(((i, j) for i in range(size) for j in range(i+1, size)),
key=lambda pair: abs(a[pair[0]][pair[1]]))
if abs(a[r][s]) < 2e-15:
break
angle = atan2(2*a[r][s], a[s][s]-a[r][r])/2
c, u = cos(angle), sin(angle)
rr, ss, rs = a[r][r], a[s][s], a[r][s]
a[r][r] = c*c*rr - 2*c*u*rs + u*u*ss
a[s][s] = u*u*rr + 2*c*u*rs + c*c*ss
a[r][s] = a[s][r] = 0.0
for i in range(size):
if i not in (r,s):
ir, ik = a[i][r], a[i][s]
a[i][r] = a[r][i] = c*ir-u*ik
a[i][s] = a[s][i] = u*ir+c*ik
vr, vs = vectors[i][r], vectors[i][s]
vectors[i][r], vectors[i][s] = c*vr-u*vs, u*vr+c*vs
else:
raise ArithmeticError("Jacobi iteration failed")
return sorted((a[i][i], [row[i] for row in vectors]) for i in range(size))
def real_space_check(k, gamma, middle, weights):
"""Apply the three actual bonds to the proposed Bloch eigenstate."""
columns = 24
assert abs(phase(1j*columns*k)-1) < 2e-13
# With zero B amplitudes H|psi> vanishes on A automatically.
a = {(j,n): phase(1j*k*(j+n/2))*(-1)**n*sqrt(p/columns)
for j in range(columns) for n,p in enumerate(weights)}
b_image = [a[j,n]+a[(j+1) % columns,n]
+ exp(gamma*(n+0.5-middle))*a[j,n+1]
for j in range(columns) for n in range(2*middle)]
assert max(map(abs,b_image)) < 2e-13
assert isclose(sum(abs(v)**2 for v in a.values()),1,abs_tol=1e-13)
def fixture(k, gamma, middle=3):
scale = abs(2*cos(k/2))
hop = [exp(gamma*(n+0.5-middle)) for n in range(2*middle)]
bonds = [edge for t in hop for edge in (scale,t)]
count = len(bonds)+1
matrix = [[0.0]*count for _ in range(count)]
for i, t in enumerate(bonds):
matrix[i][i+1] = matrix[i+1][i] = t
spectrum = symmetric_spectrum(matrix)
energy, state = min(spectrum,key=lambda eigenpair:abs(eigenpair[0]))
gap = min(abs(e) for e,_ in spectrum if abs(e)>1e-12)
assert abs(energy)<1e-12 and sum(abs(e)<1e-12 for e,_ in spectrum)==1
assert all(abs(state[i])<2e-13 for i in range(1,count,2))
weights = [exp(-gamma*(n-middle)**2)*scale**(2*n) for n in range(2*middle+1)]
weights = [p/sum(weights) for p in weights]
observed = [state[i]**2 for i in range(0,count,2)]
assert max(abs(p-q) for p,q in zip(observed,weights))<2e-13
ratios = [a*c/(b*b) for a,b,c in zip(observed,observed[1:],observed[2:])]
assert all(isclose(r,exp(-2*gamma),abs_tol=3e-12) for r in ratios)
real_space_check(k,gamma,middle,weights)
return observed,gap,ratios[0]
def check_rods(gamma,middle=3,beta=3):
# A_j,n = (sqrt(3)*(j+n/2), Y_n); B is halfway across the slants.
# A rows are separated by a slant's vertical projection plus vertical bond length.
heights = [0.0]
for n in range(2*middle):
length = 1-gamma*(n+0.5-middle)/beta
assert length>0
assert isclose(exp(-beta*(length-1)),exp(gamma*(n+0.5-middle)),abs_tol=1e-14)
heights.append(heights[-1]+0.5+length)
assert hypot(sqrt(3)/2,0.5)==1
assert isclose(heights[-1]-heights[-2]-0.5,length,abs_tol=1e-14)
# A frozen row has two longitudinal Dirac momenta so long as t_n<2.
nodes = [2*acos(exp(gamma*(n+0.5-middle))/2) for n in range(2*middle)]
assert all(0<k<pi for k in nodes)
return nodes
def main():
g = log(5/4)
K, q = 2*pi/3, pi/12
for gamma in (g,0,-g):
frozen=check_rods(gamma)
print(f"gamma={gamma:+.8f}, frozen positive nodes: {frozen[0]:.6f} -> {frozen[-1]:.6f} rad")
for k in (K,-K,K+q,-K+q):
p,gap,ratio=fixture(k,gamma)
if gamma==g and abs(abs(k)-K)<1e-12:
assert isclose(p[0]/p[3],(4/5)**9,abs_tol=1e-13)
assert p.index(max(p))==3
if gamma==g and k==K+q:assert p.index(max(p))==2
if gamma==g and k==-K+q:assert p.index(max(p))==4
if gamma==0 and abs(abs(k)-K)<1e-12:
assert max(abs(x-1/7) for x in p)<1e-13
print(f" k/pi={k/pi:+.6f} ratio={ratio:.8f} gap/t={gap:.8f}")
plus,_,_ = fixture(K,g)
minus,_,_ = fixture(K,-g)
gains = (0.32, 0.81, 0.47)
def measured_ratio(profile):
a,b,c = (gain*row for gain,row in zip(gains,profile[2:5]))
return a*c/(b*b)
assert isclose(measured_ratio(plus)/measured_ratio(minus),256/625,abs_tol=1e-13)
print("Reversing the gradient in fixed unequal detector channels gives 256/625.")
print("Both valleys, two gradients, uniform hopping, full real-space bonds and finite spectra passed.")
if __name__ == "__main__":
main()
measured.py
"""Replay a signed Landau-level test on Bellec et al., Fig. 2 (2020).
python3 measured.py
python3 measured.py --verify-source path/to/2001.10287v1.tar.gz
The source check also accepts its unmodified fig2.pdf member.
"""
import argparse
import csv
import hashlib
import io
import math
from pathlib import Path
import re
import tarfile
import zlib
FIGURE_HASH = 'f78f5351588ad20713b7364e34723fdc1efc3f0d9141ff1ca4cbf1d472b9f59a'
DATA = Path(__file__).with_name('measured.csv')
def extract_source(path):
if path.suffix.lower() == '.pdf':
pdf = path.read_bytes()
else:
with tarfile.open(path) as archive:
pdf = archive.extractfile('fig2.pdf').read()
if hashlib.sha256(pdf).hexdigest() != FIGURE_HASH:
raise ValueError('This extractor expects fig2.pdf from arXiv:2001.10287v1')
stream = re.search(rb'(?ms)^9 0 obj\s.*?stream\r?\n(.*?)\r?\nendstream', pdf)
page = zlib.decompress(stream[1]).decode('latin-1')
tick_positions = [float(x) for x in re.findall(
r'^([.\d]+) 28\.0584 m\n\1 24\.5584 l', page, re.MULTILINE)]
if len(tick_positions) != 4:
raise ValueError('Failed to locate four labeled frequency ticks')
def frequency(x):
return 6620 + 60*(x-tick_positions[0])/(tick_positions[-1]-tick_positions[0])
if max(abs(frequency(x)-mhz)
for x, mhz in zip(tick_positions, (6620, 6640, 6660, 6680))) > 0.0001:
raise ValueError('Interior tick calibration mismatch')
traces = []
for baseline in ('85.2144', '28.0584'):
beginning = page.index('-142.604672 ' + baseline + ' m\n')
rows = page[beginning:].splitlines()[1:4002]
trace = []
for row in rows:
x, y, operation = row.split()
f = frequency(float(x))
if operation != 'l' or abs(f - round(f, 1)) > 0.0001:
raise ValueError('Unexpected vector trace sample')
if 6610 <= round(f, 1) <= 6697:
trace.append((round(f, 1), float(y)-float(baseline)))
traces.append(trace)
buf = io.StringIO()
buf.write('frequency_MHz,beta_015_DOS_plot_units,beta_020_DOS_plot_units\n')
for (f1, h1), (f2, h2) in zip(*traces):
if f1 != f2:
raise ValueError('Frequency grids differ')
buf.write(f'{f1:.1f},{h1:.6f},{h2:.6f}\n')
return buf.getvalue()
def peak_centres(points, heights, fraction):
peaks = [i for i in range(1, len(points)-1)
if heights[i] > heights[i-1] and heights[i] > heights[i+1]]
centre = min(peaks, key=lambda i: abs(points[i]-6653))
strong = [i for i in peaks if heights[i] >= fraction*heights[centre]]
left = [points[i] for i in reversed(strong) if i < centre]
right = [points[i] for i in strong if i > centre]
return left, right
def selected(rows, fraction):
freq, low, high = zip(*rows)
neg_low, pos_low = peak_centres(freq, low, fraction)
neg_high, pos_high = peak_centres(freq, high, fraction)
return ((neg_high[0], pos_high[0]),
((0.20, -2, neg_high[1]), (0.20, 2, pos_high[1]),
(0.15, -1, neg_low[0]), (0.15, 1, pos_low[0])))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--verify-source', type=Path)
args = parser.parse_args()
if args.verify_source:
if extract_source(args.verify_source) != DATA.read_text():
raise ValueError('Bundled spectra differ from author figure')
print('Both complete plotted intervals match the pinned vector figure.')
with DATA.open(newline='') as fin:
table = csv.reader(fin)
next(table)
rows = [tuple(map(float, r)) for r in table]
if len(rows) != 871 or any(abs(row[0] - 6610 - i/10) > 1e-8
for i, row in enumerate(rows)):
raise ValueError('Incomplete plotted frequency interval')
pair, holdout = selected(rows, 0.50)
for fraction in (0.35, 0.40, 0.45, 0.55, 0.60, 0.65):
if selected(rows, fraction) != (pair, holdout):
raise ValueError('Peak assignment is threshold sensitive')
centre = sum(pair)/2
gap = (pair[1]-pair[0])/2
print(f'Calibration +/-1 at beta=0.20: {pair[0]:.1f}, {pair[1]:.1f} MHz')
print(f'Centre {centre:.2f} MHz, half-splitting {gap:.2f} MHz')
print('beta n observed sqrt(n) observed-predicted equal spacing')
errors, equal_errors = [], []
for beta, n, observed in holdout:
amplitude = math.copysign(gap*math.sqrt(beta/.2), n)
pred = centre + amplitude*math.sqrt(abs(n))
equal = centre + amplitude*abs(n)
errors.append(observed-pred)
equal_errors.append(observed-equal)
print(f'{beta:.2f} {n:+3d} {observed:10.1f} {pred:9.3f} '
f'{observed-pred:+19.3f} {equal:15.3f}')
low = [observed for beta, _, observed in holdout if beta == 0.15]
print(f'At beta=0.15 measured half-splitting {(low[1]-low[0])/2:.2f} MHz, '
f'predicted {gap*math.sqrt(.15/.20):.2f}, frozen spectrum {gap:.2f}')
nominal = 3*21.5*math.sqrt(.20/2)
print(f'Absolute continuum gap from published t0 is {nominal:.2f} MHz, '
f'measured {gap:.2f} MHz')
for label, err in (('Dirac', errors), ('Equal spacing', equal_errors)):
print(f'{label} residual RMS {math.sqrt(sum(x*x for x in err)/len(err)):.3f} MHz')
if __name__ == '__main__':
main()
replay.py
"""Replay the deforming-link and gravitational-response 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 = "89d3f42bd1417a0d26320d0231f0252c872318b82de6cb423d76a4fbcbee4500"
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 ("axes", "interferometer", "elastic", "charge", "solar", "tilted", "closure", "honeycomb", "measured"):
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 / "links.tly", work / "links.tly")
result = subprocess.run([*python, str(tally / "tally.py"), "links.tly"], cwd=work,
stdout=subprocess.PIPE, check=True)
actual = result.stdout.decode("utf-8").splitlines()
expected = (ROOT / "links.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 nine offline checks and the complete 22-assertion Tally transcript passed.")
if __name__ == "__main__":
main()
plot_measured.py
"""Plot the measured spectra. Matplotlib is optional and used only by this script."""
import csv
from io import BytesIO
from math import copysign, sqrt
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from PIL import Image, PngImagePlugin
from measured import DATA, selected
OUTPUT = Path(__file__).with_name('measured-peaks.png')
INK = '#17323A'
TRACE = '#0F5660'
FIT = '#AB500A'
PRED = '#7A3596'
def main():
with DATA.open(newline='') as source:
reader = csv.reader(source)
next(reader)
rows = [tuple(map(float, row)) for row in reader]
pair, holdout = selected(rows, .50)
centre, gap = sum(pair)/2, (pair[1]-pair[0])/2
frequencies, low, high = zip(*rows)
plt.rcParams.update({
'font.family': 'DejaVu Sans', 'font.size': 9.5, 'text.color': INK,
'axes.labelcolor': INK, 'xtick.color': INK, 'ytick.color': INK,
'axes.spines.top': False, 'axes.spines.right': False,
'axes.edgecolor': '#708489', 'axes.linewidth': .6,
'path.simplify': False,
})
fig = plt.figure(figsize=(4.3, 6.2), dpi=300, facecolor='white')
fig.text(.067, .961, 'Microwave resonance spectra',
va='center', size=15.4, weight='bold')
dashed = (0, (3, 2))
legend = [
Line2D([], [], color=TRACE, lw=1.5, label='Measured spectrum'),
Line2D([], [], marker='o', ls='', mec=TRACE, mfc='white', mew=1.5,
ms=5, label='Held-out peak'),
Line2D([], [], marker='D', ls='', color=FIT, ms=5, label='Peak used to fit'),
Line2D([], [], color=PRED, ls=dashed, lw=1.5, label='√|n| prediction'),
]
fig.legend(handles=legend, loc='upper left', bbox_to_anchor=(.063,.927),
ncol=2, frameon=False, handlelength=1.7, handletextpad=.5,
columnspacing=1.6, fontsize=9.6, borderaxespad=0, labelspacing=.56)
settings = ((.20, high, .550, 'Fit ±1 and test ±2'),
(.15, low, .208, 'Test ±1 at the second deformation'))
for beta, values, bottom, description in settings:
ax = fig.add_axes((.16, bottom, .798, .232))
fig.text(.16, bottom+.25, f'β = {beta:.2f}', fontsize=11, weight='bold')
fig.text(.37, bottom+.25, description, fontsize=9.2)
maximum = max(values)
heights = [v/maximum for v in values]
observed_height = dict(zip(frequencies, heights))
ax.fill_between(frequencies, heights, facecolor='#E5F0F1', linewidth=0)
ax.plot(frequencies, heights, color=TRACE, lw=1.18, zorder=3)
for setting, level, observed in holdout:
if setting != beta:
continue
predicted = centre + copysign(gap*sqrt(abs(level)*beta/.20), level)
ax.axvline(predicted, color=PRED, ls=dashed, lw=1.25, zorder=2)
ax.plot(observed, observed_height[observed], marker='o', mfc='white',
mec=TRACE, mew=1.55, ms=5.1, zorder=4)
if beta == .20:
ax.plot(pair, [observed_height[f] for f in pair], ls='', marker='D',
mfc=FIT, mec='white', mew=.55, ms=6.2, zorder=5)
ax.set(xlim=(frequencies[0],frequencies[-1]), ylim=(0,1.07),
xticks=(6620,6640,6660,6680), yticks=(0,.5,1),
yticklabels=('0','0.5','1'), ylabel='Relative density')
ax.ticklabel_format(axis='x', useOffset=False, style='plain')
ax.tick_params(length=2.7, width=.6, pad=3)
ax.grid(axis='y', color='#C6D1D2', lw=.55)
ax.set_axisbelow(True)
if beta == .15:
ax.set_xlabel('Resonance frequency (MHz)', labelpad=5)
fig.text(.067, .102, 'Each trace is scaled to its maximum over 6610–6697 MHz.',
size=8.35)
fig.text(.067, .069, 'Measurements from Bellec et al. (2020), Fig. 2.',
size=9.1, weight='bold')
fig.text(.067, .038, 'doi.org/10.1038/s41377-020-00351-2', size=8.6)
metadata = PngImagePlugin.PngInfo()
metadata.add_text('Title', 'Microwave resonance spectra')
metadata.add_text('Description', 'Measured curves from Bellec et al. (2020), '
'Fig. 2; new peak selection, model fit and predictions.')
metadata.add_text('Source', 'https://doi.org/10.1038/s41377-020-00351-2')
with BytesIO() as raw:
fig.savefig(raw, format='png')
raw.seek(0)
with Image.open(raw) as image:
indexed = image.convert('RGB').quantize(
colors=48, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
indexed.save(OUTPUT, optimize=True, dpi=(300,300), pnginfo=metadata)
plt.close(fig)
if __name__ == '__main__':
main()