Complete native Tally transcript
✓ preserving either mass eigenspace gives unit normalized curvature (by cross-pairing plus and minus sides; derived)
✓ exchanging the two onsite masses gives opposite kinetic shifts with identical rest dynamics (by cross-pairing plus and minus sides; derived)
✓ the two resolved current-line intensities exhaust the normalized local hopping strength (by cross-pairing plus and minus sides; derived)
✓ the light branch response is recovered from both current lines (by cross-pairing plus and minus sides; derived)
✓ the heavy branch response is recovered from the same two transition strengths (by cross-pairing plus and minus sides; derived)
✓ the aligned branch at the zone edge satisfies the full nearest-neighbour mass shell (by cross-pairing plus and minus sides; derived)
✓ rest spectroscopy fixes the bare detuning of a converted molecule (by cross-pairing plus and minus sides; derived)
✓ the molecular fraction equals the detuning derivative in the finite control (by cross-pairing plus and minus sides; derived)
✓ normalization and virtual transitions determine the dressed curvature (by cross-pairing plus and minus sides; derived)
✓ the direct and open responses independently sum to the same value (by cross-pairing plus and minus sides; derived)
✓ two independently calibrated rest-energy poles solve the dimer equation (by cross-pairing plus and minus sides; derived)
✓ the same interaction-dependent local rule returns its two fixed hopping coefficients (by cross-pairing plus and minus sides; derived)
✓ one functional rule restores both leading dimer curvatures (by cross-pairing plus and minus sides; derived)
✓ reusing the first numerical hopping constant overshoots the second inertia (by cross-pairing plus and minus sides; derived)
✓ the inverse interaction realizes a nonzero-momentum point of the full mass shell (by cross-pairing plus and minus sides; derived)
✓ the two isotope trap comparisons reproduce the printed mass differences (by cross-pairing plus and minus sides; derived)
✓ isotope subtraction cancels the deuterium mass input exactly (by cross-pairing plus and minus sides; derived)
✓ squaring the moving inverse scattering length transfers its sign to the shallow-pole curvature (by cross-pairing plus and minus sides; derived)
✓ the leading normalized response coefficient is four times the threshold range (by cross-pairing plus and minus sides; derived)
✓ cancelling the threshold range removes the entire term linear in inverse pair size in this truncation (by cross-pairing plus and minus sides; derived)
✓ the same static lapse gives identical fractional redshifts for both rest frequencies (by cross-pairing plus and minus sides; derived)
✓ equal constant-force curvatures lead to unequal acceleration in a gradient that couples to energy (by cross-pairing plus and minus sides; derived)
✓ the slow differential acceleration of the two crossed rest levels is minus one half (by cross-pairing plus and minus sides; derived)
✓ a common shift of the gravity energy origin preserves the crossed levels' absolute acceleration difference (by cross-pairing plus and minus sides; derived)
✓ the interbranch switch-on contribution gives unit instantaneous response for both crossed rest packets (by cross-pairing plus and minus sides; derived)
✓ equal rest energies make the differential response independent of a common gravity calibration (by cross-pairing plus and minus sides; derived)
✓ the four Hamming shells have zero weighted mean on the periodic eight-site cell (by cross-pairing plus and minus sides; derived)
✓ the zero-mode-subtracted Green function has the correct unit source (by cross-pairing plus and minus sides; derived)
✓ the six directed links give the compensating background on shell one (by cross-pairing plus and minus sides; derived)
✓ the six directed links give the compensating background on shell two (by cross-pairing plus and minus sides; derived)
✓ the far corner has the same compensating background (by cross-pairing plus and minus sides; derived)
✓ exchanging unequal source charges preserves the finite-cell interaction work (by cross-pairing plus and minus sides; derived)
✓ equal force magnitudes can give a nonzero differential acceleration (by cross-pairing plus and minus sides; derived)
✓ the discrete radial Coulomb pole has exact binding one seventy-second (by cross-pairing plus and minus sides; derived)
✓ a fixed cell leaves a finite conformal charge residual (by cross-pairing plus and minus sides; derived)
✓ the two source prescriptions differ by twice the regulated kinetic energy (by cross-pairing plus and minus sides; derived)
✓ the wave alone passes energy continuity with its own energy flux but fails with symmetric momentum (by cross-pairing plus and minus sides; derived)
✓ the material clock has a forced particular response at the beat frequency (by cross-pairing plus and minus sides; derived)
✓ the material adds unequal energy density and momentum to the beat (by cross-pairing plus and minus sides; derived)
✓ the combined symmetric tensor obeys both longitudinal conservation equations (by cross-pairing plus and minus sides; derived)
✓ two translated spherical templates balance the major endpoint and the equatorial rim (by cross-pairing plus and minus sides; derived)
✓ the equatorial rim is exactly tangent in the two-template certificate (by cross-pairing plus and minus sides; derived)
✓ the positive largest-axis coefficient repels equal anisotropic sources (by cross-pairing plus and minus sides; derived)
✓ the same positive rest sources attract along the smallest axis (by cross-pairing plus and minus sides; derived)
✓ isotropic elastic sources have only a contact term in infinite isotropic material (by cross-pairing plus and minus sides; derived)
✓ doubling the separation divides the leading radial elastic force by sixteen (by cross-pairing plus and minus sides; derived)
✓ the signs persist throughout the stated component intervals in squared centi-units (by cross-pairing plus and minus sides; derived)
✓ static force range and the relaxed sound speed satisfy the same stiffness relation (by cross-pairing plus and minus sides; derived)
✓ free bulk stability bounds the squared range multiplier at equal Lame constants (by cross-pairing plus and minus sides; derived)
✓ tuning the longitudinal plane-wave stiffness to zero makes the free bulk modulus negative at finite shear (by cross-pairing plus and minus sides; derived)
✓ the two material-ring frequencies have an exact unit squared-frequency gap (by cross-pairing plus and minus sides; derived)
✓ a ring at fixed winding density has positive material pressure (by cross-pairing plus and minus sides; derived)
✓ the coefficient four times the average sine-squared cosine-squared is one half in units of pi (by cross-pairing plus and minus sides; derived)
✓ the trapped wave's local pressure reduces to one half sech to the fourth (by cross-pairing plus and minus sides; derived)
✓ the host deformation cancels the localized guest pressure pointwise to quadratic order (by cross-pairing plus and minus sides; derived)
✓ the mass-weighted internal dipole vanishes for the mobile host and impurity (by cross-pairing plus and minus sides; derived)
✓ mass-proportional forcing leaves the relative-motion sector undriven (by cross-pairing plus and minus sides; derived)
✓ the membrane optical force path returns 0.2296 of the specified modulated force (by cross-pairing plus and minus sides; derived)
✓ clock calibration and a local echo slope recover the spherical compactness M over r (by cross-pairing plus and minus sides; derived)
✓ the same clock in flat spatial geometry gives a different echo and zero inferred mass (by cross-pairing plus and minus sides; derived)
Native Tally source
# Finite local mass channels, dressing and a bound-pair boost.
ratchet 32 step
import "atom"
let zero=whole(0 trial)
let one=whole(1 trial)
let two=whole(2 trial)
let four=whole(4 trial)
let lo=fraction(3 trial,2 trial)
let hi=fraction(5 trial,2 trial)
fn line_weight(m,b)
return share(two*m,m+b)
end
check line_weight(lo,lo)==one and line_weight(hi,hi)==one "preserving either mass eigenspace gives unit normalized curvature"
check line_weight(lo,hi)==fraction(3 trial,4 trial) and line_weight(hi,lo)==fraction(5 trial,4 trial) "exchanging the two onsite masses gives opposite kinetic shifts with identical rest dynamics"
let same=power(fraction(3 trial,5 trial),2 trial)
let other=power(fraction(4 trial,5 trial),2 trial)
check same+other==one "the two resolved current-line intensities exhaust the normalized local hopping strength"
check same*line_weight(lo,lo)+other*line_weight(lo,hi)==fraction(21 trial,25 trial) "the light branch response is recovered from both current lines"
check same*line_weight(hi,hi)+other*line_weight(hi,lo)==fraction(29 trial,25 trial) "the heavy branch response is recovered from the same two transition strengths"
check hi*hi==lo*lo+four and hi+flip(lo)==share(four,hi+lo) "the aligned branch at the zone edge satisfies the full nearest-neighbour mass shell"
# A single open level at energy 2 with curvature 1/2, coupled to a molecule.
let h=fraction(1 trial,2 trial)
let hsq=h*h
let G=share(one,lo+flip(two))
let Gz=flip(G*G)
let Gkk=G*G*h
let bare=lo+flip(hsq*G)
let Z=share(one,one+flip(hsq*Gz))
check bare==two and lo+flip(bare)+flip(hsq*G)==zero "rest spectroscopy fixes the bare detuning of a converted molecule"
check Z==h and Z*(one+flip(hsq*Gz))==one "the molecular fraction equals the detuning derivative in the finite control"
let mixR=lo*Z*(share(two,lo+bare)+hsq*Gkk)
check mixR==fraction(45 trial,56 trial) "normalization and virtual transitions determine the dressed curvature"
check mixR==Z*line_weight(lo,bare)+(one+flip(Z))*lo*h "the direct and open responses independently sum to the same value"
# Tight-binding dimer with onsite attraction -u and joint hop c(1-cos K).
fn boost(z,u,chi)
return share(two*u,z*(chi+two))
end
fn dimer_response(z,u,chi,c)
return share(z*(one+u*c),chi)
end
let z2=fraction(11 trial,6 trial)
let chi2=fraction(13 trial,6 trial)
let u2=fraction(5 trial,6 trial)
let c1=boost(lo,lo,hi)
let c2=boost(z2,u2,chi2)
check hi*hi==lo*lo+four and chi2*chi2==u2*u2+four "two independently calibrated rest-energy poles solve the dimer equation"
check c1==fraction(4 trial,9 trial) and c2==fraction(12 trial,55 trial) "the same interaction-dependent local rule returns its two fixed hopping coefficients"
check dimer_response(lo,lo,hi,c1)==one and dimer_response(z2,u2,chi2,c2)==one "one functional rule restores both leading dimer curvatures"
check dimer_response(z2,u2,chi2,c1)==fraction(407 trial,351 trial) "reusing the first numerical hopping constant overshoots the second inertia"
let s=share(whole(7 trial),four)
let energy=two
let potential_sq=two*power(energy+flip(two),2 trial)+four+flip(lo*lo)
check lo*lo+s==energy*energy and potential_sq+four+flip(s)==power(four+flip(energy),2 trial) "the inverse interaction realizes a nonzero-momentum point of the full mass shell"
# Reported neutral mass differences in units of 10^-11 atomic mass units.
let silicon=whole(825690198 trial)
let sulfur=whole(843729682 trial)
let common=flip(whole(154828629 trial))
check silicon+common==whole(670861569 trial) and sulfur+common==whole(688901053 trial) "the two isotope trap comparisons reproduce the printed mass differences"
check sulfur+common+flip(silicon+common)==sulfur+flip(silicon) and sulfur+flip(silicon)==whole(18039484 trial) "isotope subtraction cancels the deuterium mass input exactly"
# Leading threshold law: Eth(K)=2+K²/4, inverse scattering length
# a(K)^-1=kappa-Rs*K²/2. Keep coefficients through K² in the binding gap.
let kappa=fraction(1 trial,16 trial)
let Rs=fraction(1 trial,4 trial)
let bound_z=two+flip(kappa*kappa)
let edge_curve=fraction(1 trial,2 trial)
let bound_curve=edge_curve+two*kappa*Rs
let threshold_Q=bound_z*bound_curve
check threshold_Q==fraction(8687 trial,8192 trial) "squaring the moving inverse scattering length transfers its sign to the shallow-pole curvature"
check threshold_Q==one+four*kappa*Rs+flip(kappa*kappa*edge_curve)+flip(two*Rs*kappa*kappa*kappa) "the leading normalized response coefficient is four times the threshold range"
check bound_z*edge_curve==one+flip(kappa*kappa*edge_curve) "cancelling the threshold range removes the entire term linear in inverse pair size in this truncation"
# A static lapse rescales all frequencies. A uniform gradient probes their inertia.
let lapse_factor=fraction(3 trial,4 trial)
check share(lapse_factor*lo,lo)==share(lapse_factor*hi,hi) "the same static lapse gives identical fractional redshifts for both rest frequencies"
let crossed_inertia=share(two,lo+hi)
let light_fall=lo*crossed_inertia
let heavy_fall=hi*crossed_inertia
check crossed_inertia==fraction(1 trial,2 trial) and light_fall==fraction(3 trial,4 trial) and heavy_fall==fraction(5 trial,4 trial) "equal constant-force curvatures lead to unequal acceleration in a gradient that couples to energy"
fn differential_response(a,b)
return share(two*(a+flip(b)),a+b)
end
check differential_response(light_fall,heavy_fall)==flip(fraction(1 trial,2 trial)) "the slow differential acceleration of the two crossed rest levels is minus one half"
let offset=fraction(2 trial,5 trial)
check (hi+offset)*crossed_inertia+flip((lo+offset)*crossed_inertia)==fraction(1 trial,2 trial) "a common shift of the gravity energy origin preserves the crossed levels' absolute acceleration difference"
check light_fall+share(hi+flip(lo),hi+lo)==one and heavy_fall+share(lo+flip(hi),hi+lo)==one "the interbranch switch-on contribution gives unit instantaneous response for both crossed rest packets"
let trial_density=fraction(36 trial,25 trial)
let trial_mass=fraction(34 trial,25 trial)
let common_factor=fraction(26 trial,19 trial)
check differential_response(common_factor*trial_density,common_factor*trial_mass)==differential_response(trial_density,trial_mass) and differential_response(trial_density,trial_mass)==fraction(2 trial,35 trial) "equal rest energies make the differential response independent of a common gravity calibration"
# The periodic inverse lattice Laplacian with its uniform mode removed.
let six=whole(6 trial)
let three=whole(3 trial)
let eighth=fraction(1 trial,8 trial)
let green0=fraction(29 trial,192 trial)
let green1=fraction(1 trial,192 trial)
let green2=flip(fraction(7 trial,192 trial))
let green3=flip(fraction(11 trial,192 trial))
check green0+three*green1+three*green2+green3==zero "the four Hamming shells have zero weighted mean on the periodic eight-site cell"
check six*(green0+flip(green1))==one+flip(eighth) "the zero-mode-subtracted Green function has the correct unit source"
check six*green1+flip(two*(green0+two*green2))==flip(eighth) "the six directed links give the compensating background on shell one"
check six*green2+flip(two*(two*green1+green3))==flip(eighth) "the six directed links give the compensating background on shell two"
check six*(green3+flip(green2))==flip(eighth) "the far corner has the same compensating background"
let mutual_work=lo*hi*(green1+flip(green2))
check mutual_work==fraction(5 trial,32 trial) and mutual_work==hi*lo*(green1+flip(green2)) "exchanging unequal source charges preserves the finite-cell interaction work"
check differential_response(trial_density*mutual_work,trial_mass*mutual_work)==fraction(2 trial,35 trial) "equal force magnitudes can give a nonzero differential acceleration"
# A regulated Coulomb bound pair at mu*alpha*a=3/4.
let invcell=fraction(3 trial,4 trial)
let radical=fraction(5 trial,4 trial)
let reg_B=share(fraction(1 trial,32 trial),one+radical)
let reg_T=share(reg_B,radical)
check radical*radical==one+invcell*invcell and reg_B==fraction(1 trial,72 trial) "the discrete radial Coulomb pole has exact binding one seventy-second"
check reg_T==fraction(1 trial,90 trial) and reg_B+flip(reg_T)==fraction(1 trial,360 trial) "a fixed cell leaves a finite conformal charge residual"
check two*reg_T==fraction(1 trial,45 trial) "the two source prescriptions differ by twice the regulated kinetic energy"
# The material-clock contribution to the symmetric stress of an on-shell beat.
let beat_q=fraction(1 trial,2 trial)
let beat_w=fraction(1 trial,4 trial)
let beat_rho=fraction(9 trial,8 trial)
let beat_p=fraction(1 trial,4 trial)
let beat_t=fraction(1 trial,8 trial)
let beat_s=fraction(9 trial,4 trial)
let matter_residual=beat_q*beat_p+flip(beat_w*beat_rho)
check matter_residual==flip(fraction(5 trial,32 trial)) and beat_q*beat_s*beat_p==beat_w*beat_rho "the wave alone passes energy continuity with its own energy flux but fails with symmetric momentum"
let material_D=share((one+flip(beat_s))*beat_q*beat_p,beat_q*beat_q+flip(beat_w*beat_w))
check material_D==flip(fraction(5 trial,6 trial)) "the material clock has a forced particular response at the beat frequency"
let supported_rho=beat_rho+flip(beat_w*material_D)
let supported_p=beat_p+flip(beat_q*material_D)
let supported_t=beat_t+flip(beat_w*material_D)
check supported_rho==fraction(4 trial,3 trial) and supported_p==fraction(2 trial,3 trial) and supported_t==fraction(1 trial,3 trial) "the material adds unequal energy density and momentum to the beat"
check beat_q*supported_p==beat_w*supported_rho and beat_q*supported_t==beat_w*supported_p "the combined symmetric tensor obeys both longitudinal conservation equations"
# Two aligned ellipsoids in the coordinates of a fixed detector template.
let axis_a=fraction(33 trial,32 trial)
let axis_b=one
let two_radius=share(axis_a*axis_a+axis_b*axis_b,two*axis_a)
let center_shift=axis_a+flip(two_radius)
check two_radius==fraction(2113 trial,2112 trial) and center_shift==fraction(65 trial,2112 trial) "two translated spherical templates balance the major endpoint and the equatorial rim"
check two_radius*two_radius==axis_b*axis_b+center_shift*center_shift "the equatorial rim is exactly tangent in the two-template certificate"
# The axial Kelvin force for two equal diagonal rest tensors at lambda=mu=1.
# Six pi times r^3 U on axis x = x(x-y+x-z)+(x-y)(x-z).
fn axial_kernel(x,y,z)
let dy=x+flip(y)
let dz=x+flip(z)
return x*(dy+dz)+dy*dz
end
let sample_x=fraction(11 trial,2 trial)
let sample_y=whole(5 trial)
let sample_z=four
check axial_kernel(sample_x,sample_y,sample_z)==fraction(47 trial,4 trial) "the positive largest-axis coefficient repels equal anisotropic sources"
check axial_kernel(sample_z,sample_x,sample_y)==flip(fraction(17 trial,2 trial)) "the same positive rest sources attract along the smallest axis"
check axial_kernel(sample_z,sample_z,sample_z)==zero "isotropic elastic sources have only a contact term in infinite isotropic material"
check share(three,power(two,4 trial))==fraction(3 trial,16 trial) "doubling the separation divides the leading radial elastic force by sixteen"
# Sampled unit-slope pair tensor lies in x=[4.40,4.42], y=[4.28,4.29], z=[3.95,3.96].
let maxaxis_min=whole(440 trial)*(whole(11 trial)+whole(44 trial))+whole(11 trial)*whole(44 trial)
let minaxis_max=flip(whole(395 trial)*(whole(44 trial)+whole(32 trial)))+whole(47 trial)*whole(34 trial)
check maxaxis_min==whole(24684 trial) and minaxis_max==flip(whole(28422 trial)) "the signs persist throughout the stated component intervals in squared centi-units"
# Free bulk stability limits the maximum range obtained from optical mixing.
let bulk=fraction(5 trial,3 trial)
let long_stiff=three
let ell_sq=share(one,one+flip(share(one,long_stiff)))
check ell_sq==fraction(3 trial,2 trial) and ell_sq*(long_stiff+flip(one))==long_stiff "static force range and the relaxed sound speed satisfy the same stiffness relation"
check share(long_stiff,long_stiff+flip(bulk))==fraction(9 trial,4 trial) "free bulk stability bounds the squared range multiplier at equal Lame constants"
check bulk+flip(long_stiff)==flip(fraction(4 trial,3 trial)) "tuning the longitudinal plane-wave stiffness to zero makes the free bulk modulus negative at finite shear"
# The two analytic band-edge waves of the periodic material.
let modulus=fraction(4 trial,5 trial)
let invmod=share(one,modulus*modulus)
let wc2=one+invmod
let ws2=wc2+one
check wc2==fraction(41 trial,16 trial) and ws2==fraction(57 trial,16 trial) "the two material-ring frequencies have an exact unit squared-frequency gap"
check two*(invmod+flip(one))==fraction(9 trial,8 trial) "a ring at fixed winding density has positive material pressure"
check share(two*four,whole(16 trial))==h "the coefficient four times the average sine-squared cosine-squared is one half in units of pi"
# For the stationary isolated excitation with s=sech(x)^2, rho and stress at order A^2.
let local_s=fraction(9 trial,25 trial)
let gradpart=local_s*(one+flip(local_s))
let presspart=share(gradpart+local_s*(two*local_s+flip(one)),two)
check presspart==share(local_s*local_s,two) "the trapped wave's local pressure reduces to one half sech to the fourth"
check presspart+flip(share(local_s*local_s,two))==zero "the host deformation cancels the localized guest pressure pointwise to quadratic order"
# Galilean mass density compensates the internal dipole for uniform common forcing.
let impurity=one
let hostmass=four
let total_mass=impurity+hostmass
let reduced=share(impurity*hostmass,total_mass)
check share(hostmass,total_mass)*impurity+flip(share(impurity,total_mass)*hostmass)==zero "the mass-weighted internal dipole vanishes for the mobile host and impurity"
check reduced*(share(two*impurity,impurity)+flip(share(two*hostmass,hostmass)))==zero "mass-proportional forcing leaves the relative-motion sector undriven"
# Measured optical reflectivity and return transmission, scaled from the printed central values.
let reflectivity=fraction(7 trial,25 trial)
let transmission=fraction(41 trial,50 trial)
check reflectivity*transmission==fraction(287 trial,1250 trial) "the membrane optical force path returns 0.2296 of the specified modulated force"
# Areal radius and two neighboring radial echoes separate spatial length from clock rate.
let radar_clock=fraction(3 trial,4 trial)
let radar_rod=fraction(5 trial,4 trial)
let radar_echo=share(two*radar_rod,radar_clock)
let inv_rod=share(two,radar_clock*radar_echo)
check radar_echo==fraction(10 trial,3 trial) and share(one+flip(inv_rod*inv_rod),two)==fraction(9 trial,50 trial) "clock calibration and a local echo slope recover the spherical compactness M over r"
let flat_echo=share(two,radar_clock)
check flat_echo==fraction(8 trial,3 trial) and share(two,radar_clock*flat_echo)==one "the same clock in flat spatial geometry gives a different echo and zero inferred mass"
scattering.py
"""Threshold spectroscopy and out-of-sample pair curvatures. Python 3, stdlib.
The matrix order is ++ singlet, -- singlet, antisymmetric mixed orbital times
the longitudinal spin triplet. Six packed entries are (00,01,02,11,12,22).
Use --order 20 for a higher-order quadrature and --full for every held-out row.
"""
from argparse import ArgumentParser
from itertools import product
from math import cos, fsum, hypot, pi, sin, sqrt
BINDINGS = (0., .1, .01, 1/40**2, 1/80**2, 1/320**2, 1/640**2)
TWISTS = (.012, .006)
def gauss(n):
"""Gauss-Legendre nodes and weights mapped onto [0,1]."""
nodes = []
for i in range(1, n+1):
x = cos(pi*(i-.25)/(n+.5))
for _ in range(30):
p, prev = 1., 0.
for k in range(1, n+1):
p, prev = ((2*k-1)*x*p-(k-1)*prev)/k, p
slope = n*(x*p-prev)/(x*x-1)
change = p/slope
x -= change
if abs(change) < 3e-16:
break
nodes.append(((1+x)/2, 1/((1-x*x)*slope*slope)))
return nodes
def octant_nodes(n):
nodes = gauss(n)
edges = (0., .012, .06, .24, .8, pi)
for i in range(3):
for lo,hi in zip(edges,edges[1:]):
for (r,wr),(u,wu),(v,wv) in product(nodes,repeat=3):
r = lo+(hi-lo)*r
p = (r,r*u,r*v)
yield p[i:]+p[:i], wr*wu*wv*(hi-lo)*r*r/pi**3
def fields(x,y,z):
tx,ty,tz = 2*sin(x/2)**2,2*sin(y/2)**2,2*sin(z/2)**2
shift = (2/3)*(tx*tx+ty*ty+tz*tz)+2*(tx*ty+tx*tz+ty*tz)
bz,cz,cy = sin(z),cos(z),cos(y)
bx,by = sin(x)*cy*cz,sin(y)*cz
delta = bx*bx+by*by+bz*bz+shift*(2+shift) # stable e^2-1
energy = sqrt(1+delta)
return energy,delta,(1+shift)/energy,(bx/energy,by/energy,bz/energy)
def loops(nodes, k, axis):
"""Octant-integrated free contact Green matrix and its energy derivative."""
disp = [0.,0.,0.]
disp[axis] = k/2
eh,delta_h,_,_ = fields(*disp)
result = [[0.]*6 for _ in BINDINGS]
derivative = [[0.]*6 for _ in BINDINGS]
for p,w in nodes:
e1,d1,m1,b1 = fields(p[0]+disp[0],p[1]+disp[1],p[2]+disp[2])
e2,d2,m2,b2 = fields(disp[0]-p[0],disp[1]-p[1],disp[2]-p[2])
# Exact difference 2e(K/2)-e1-e2, rationalized near the integrable
# threshold singularity. Direct subtraction loses digits at tiny p.
positive_gap = (-2*(d1+d2-2*delta_h)+((d1-d2)/(e1+e2))**2)/(2*eh+e1+e2)
dot = b1[0]*b2[0]+b1[1]*b2[1]+b1[2]*b2[2]
for a,b in ((1,1),(1,-1),(-1,1),(-1,-1)):
u1,u2,dn1,dn2 = 1+a*m1,1+b*m2,1-a*m1,1-b*m2
q1,q2 = a*b1[axis],b*b2[axis]
weights = (u1*u2,-a*b*dot,-(u1*q2+u2*q1)/sqrt(2),
dn1*dn2,(dn2*q1+dn1*q2)/sqrt(2),
(u1*dn2+dn1*u2)/2-a*b*dot+2*q1*q2)
gap = positive_gap if a==b==1 else 2*eh-a*e1-b*e2
for i,binding in enumerate(BINDINGS):
inv = 1/(gap-binding)
scale = w*inv/4
row = result[i]
for h,num in enumerate(weights):
row[h] += scale*num
if k==0. and binding:
drow = derivative[i]
for h,num in enumerate(weights):
drow[h] -= scale*inv*num
return result,derivative
def mean_matrices(values):
return [tuple(map(lambda column: fsum(column)/len(values),zip(*mats)))
for mats in zip(*values)]
def rest_coupling(green):
a,b,_,d,_,_ = green
return 2/(a+d-hypot(a-d,2*b))
def inverse_contact(green, g, sign, external=(1.,0.,0.)):
"""Return Schur complement, its null direction and inverse external T."""
a,b,c,d,e,f = green
a,b,c,d,e,f = 1/g-a,-b,-c,1/g-d,-e,sign/g-f
determinant = d*f-e*e
v1,v2 = (e*c-f*b)/determinant,(e*b-d*c)/determinant
schur = a+b*v1+c*v2
w0,w1,w2 = external
regular = (f*w1*w1-2*e*w1*w2+d*w2*w2)/determinant
inverse_t = schur/((w0+v1*w1+v2*w2)**2+schur*regular)
return schur,(1.,v1,v2),inverse_t
def external_and_flux(k):
q = k/2
t = 2*sin(q/2)**2
m = 1+(2/3)*t*t
e = hypot(m,sin(q))
c = sqrt((1+m/e)/2)
d = sin(q)/(2*e*c)
# Hessian of e at K/2 along and transverse to the selected axis.
f1 = 2+2*t/3+16*t**3/9
f2 = 2/3+16*t*t/3
longitudinal = (f2*sin(q)**2+f1*cos(q))/(2*e)-(f1*sin(q))**2/(4*e**3)
transverse = (cos(q)**2+2*m*t)/e
return (c*c,-d*d,-sqrt(2)*c*d),transverse*sqrt(longitudinal)
def quadratic(packed,v):
a,b,c,d,e,f = packed
x,y,z = v
return a*x*x+d*y*y+f*z*z+2*(b*x*y+c*x*z+e*y*z)
def slope(samples,baseline):
# Steps h and h/2. Remove the first even finite-difference truncation term.
a,b = [(v-baseline)/h**2 for v,h in zip(samples,TWISTS)]
return (4*b-a)/3
def study(rest, derivatives, scans, sign):
gstar = rest_coupling(rest[0])
f0,v0,_ = inverse_contact(rest[0],gstar,sign)
inverse_lengths = []
for k,data in zip(TWISTS,scans):
w,dos = external_and_flux(k)
_,_,inverse_t = inverse_contact(data[0],gstar,sign,w)
inverse_lengths.append(4*pi*dos*inverse_t)
moving_range = -2*slope(inverse_lengths,4*pi*f0)
# Independently solve the critical threshold determinant at finite K.
# Near the critical coupling use Schur's derivative dF/dg=-v^T A v/g^2.
critical = []
for data in scans:
g = gstar
for _ in range(5):
f,v,_ = inverse_contact(data[0],g,sign)
norm = v[0]**2+v[1]**2+sign*v[2]**2
g += f*g*g/norm
critical.append(g)
hopping = slope(critical,gstar)
conversion = -gstar*gstar*moving_range/(8*pi*sum(x*x for x in v0))
assert abs(hopping-conversion)<2e-6
rows = []
for i,binding in enumerate(BINDINGS[1:],1):
g = rest_coupling(rest[i])
f,v,_ = inverse_contact(rest[i],g,sign)
c = slope([inverse_contact(d[i],g,sign)[0] for d in scans],f)
fz = -quadratic(derivatives[i],v)
assert fz>0
norm = v[0]**2+v[1]**2+sign*v[2]**2
q = (2-binding)*(.5-2*c/fz)
fixed = (2-binding)*(.5-2*(c-hopping*norm/g**2)/fz)
inv_a = 4*pi*inverse_contact(rest[0],g,sign)[2]
predicted = 1+4*moving_range*sqrt(binding)
rows.append((binding,q,predicted,fixed,inv_a))
return gstar,moving_range,hopping,rows
def run(n, full):
nodes = list(octant_nodes(n))
scans = [[],[],[]]
rests, derivs = [],[]
for axis in range(3):
r,d = loops(nodes,0.,axis)
rests.append(r)
derivs.append(d)
scans[axis] = [loops(nodes,k,axis)[0] for k in TWISTS]
# Cubic orientation channel: rotate to its common longitudinal spin basis
# then average the free Green matrices before the single contact inverse.
rests.append(mean_matrices(rests))
derivs.append(mean_matrices(derivs))
scans.append([mean_matrices([d[i] for d in scans]) for i in range(len(TWISTS))])
print("orbit contact g* R_moving fixed hop B Q(pole) Q(threshold) Q(fixed)")
for name,r,d,s in zip(("x","y","z","cubic"),rests,derivs,scans):
for label,sign in (("mass",-1),("density",1)):
gc,rr,u,rows = study(r,d,s,sign)
for B,q,pred,fixed,inv_a in rows:
if full or B in (1/40**2,1/640**2):
print(f"{name:5} {label:7} {gc:.7f} {rr:.7f} {u:.7f} {B:.8g} {q:.8f} {pred:.8f} {fixed:.8f}")
if name=="cubic" and label=="mass" and full:
print(f" Rest inverse scattering length {inv_a:.9f}")
gamma = sqrt(rows[-1][0])
measured_slope = (rows[-1][1]-1)/gamma
print(f" 1/640: threshold 4R={4*rr:.6f}, held-out (Q-1)/sqrt(B)={measured_slope:.6f}")
if n>=16 and name != "cubic":
held_out = {"x": (1.20170,1.22834), "y": (1.25777,1.27246),
"z": (0.98145,1.14822)}
assert abs(measured_slope-held_out[name][sign>0]) < 4e-5
assert abs(rows[-1][1]-rows[-1][2]) < 1e-5
assert abs(rows[-1][3]-1) < 1e-5
if __name__=="__main__":
parser=ArgumentParser(description=__doc__)
parser.add_argument("--order",type=int,default=12)
parser.add_argument("--full",action="store_true")
args=parser.parse_args()
if args.order<6:
parser.error("Use a quadrature order of at least six.")
run(args.order,args.full)
alignment.py
"""Finite-momentum and current-spectrum tests of a local multichannel mass law."""
from fractions import Fraction
from math import cos, sin, sqrt
def current_response(masses, mixing):
return [sum(2*m*mixing[a][i]**2/(m+b) for a,b in enumerate(masses))
for i,m in enumerate(masses)]
def secular(energy, momentum, masses, mixing):
strength = 4*sin(momentum/2)**2
kernel = [[(energy-masses[i] if i == j else 0)
-strength*sum(mixing[a][i]*mixing[a][j]/(energy+masses[a])
for a in range(2))
for j in range(2)] for i in range(2)]
return kernel[0][0]*kernel[1][1]-kernel[0][1]*kernel[1][0]
def root(mass_index, k, masses, mixing):
mass = masses[mass_index]
lo, hi = mass-.12, mass+.12
value = secular(lo,k,masses,mixing)
assert value*secular(hi,k,masses,mixing) < 0
for _ in range(65):
mid = (lo+hi)/2
if value*secular(mid,k,masses,mixing) <= 0:
hi = mid
else:
lo = mid
return (lo+hi)/2
def main():
m = [Fraction(3,2),Fraction(5,2)]
aligned, crossed = ((1,0),(0,1)), ((0,1),(1,0))
mixed = ((Fraction(3,5),-Fraction(4,5)),(Fraction(4,5),Fraction(3,5)))
assert current_response(m,aligned) == [1,1]
assert current_response(m,crossed) == [Fraction(3,4),Fraction(5,4)]
assert current_response(m,mixed) == [Fraction(21,25),Fraction(29,25)]
mf = list(map(float,m))
for name,v in (("aligned",aligned),("crossed",crossed),("mixed",mixed)):
for i,expected in enumerate(current_response(m,v)):
values = [2*mf[i]*(root(i,k,mf,v)-mf[i])/k**2 for k in (.02,.01)]
observed = (4*values[1]-values[0])/3
assert abs(observed-expected) < 1e-8
print(f"{name} mass {mf[i]}: current lines {float(expected):.8f}, moving pole {observed:.8f}")
# Singlet-preserving conversion gives the exact lattice mass shell even at finite momentum.
for mass in (0.25,1.5,2.5):
e = sqrt(mass**2 + sum(4*sin(k/2)**2 for k in (0.8,-1.2,0.5)))
assert abs(e-mass-sum(2*(1-cos(k))/(e+mass) for k in (0.8,-1.2,0.5))) < 1e-14
if __name__ == "__main__":
main()
current.py
"""Read the curvature of an interacting walker pair from its zero-momentum spectrum."""
import itertools
from pathlib import Path
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
if not (HERE / "bound_3d.py").is_file():
sys.path.insert(0,str(HERE.parent/"shell-clocks"))
from bound_3d import Torus, GAMMA, BETA_PAIR, IDENTITY, rest_calibration, moving_root
def symbols(p, axis):
sine, cosine = np.sin(p), np.cos(p)
t = 1-cosine
b, first, second = [], [], []
for i in range(3):
value = sine[i]*np.prod(cosine[i+1:])
b.append(value)
if axis < i:
first.append(0.)
elif axis == i:
first.append(np.prod(cosine[i:]))
else:
others = [cosine[k] for k in range(i+1,3) if k != axis]
first.append(-sine[i]*sine[axis]*np.prod(others))
second.append(-value if axis >= i else 0.)
mass = 1 + 2*np.dot(t,t)/3 + 2*sum(t[i]*t[j] for i,j in itertools.combinations(range(3),2))
factor = 4*t[axis]/3 + 2*sum(t[j] for j in range(3) if j != axis)
b.append(mass)
first.append(factor*sine[axis])
second.append(factor*cosine[axis]+4*sine[axis]**2/3)
return [sum(x*g for x,g in zip(row,GAMMA[1:])) for row in (b,first,second)]
def audit(n=3):
rest = 1.90
torus = Torus(n,rest)
calibrated = rest_calibration(torus)
coupling = 1/calibrated[1]
eye = np.eye(4)
for axis in range(3):
blocks = []
for index in itertools.product(range(n),repeat=3):
p = 2*np.pi*np.array(index)/n
a, b = symbols(p,axis), symbols(-p,axis)
blocks.append([(np.kron(aa,eye)+np.kron(eye,bb))/(2**order)
for order,(aa,bb) in enumerate(zip(a,b))])
kinetic,current,stress = np.moveaxis(np.asarray(blocks),1,0)
for label,contact,source in (("density",np.eye(16),IDENTITY),
("mass",np.kron(GAMMA[-1],GAMMA[-1]),BETA_PAIR)):
hamiltonian = np.tile(coupling*contact/n**3,(n**3,n**3))
hamiltonian = hamiltonian.astype(complex)
for i,h in enumerate(kinetic):
sub = slice(16*i,16*i+16)
hamiltonian[sub,sub] += h
levels, vectors = np.linalg.eigh(hamiltonian)
bound = np.argmin(abs(levels-rest))
assert abs(levels[bound]-rest) < 1e-12
selected = np.arange(len(levels)) != bound
gaps = rest-levels[selected]
assert min(abs(gaps)) > 1e-8
psi = vectors[:,bound].reshape(-1,16)
driven = np.einsum("bij,bj->bi",current,psi).ravel()
direct = rest*np.einsum("bi,bij,bj->",psi.conj(),stress,psi).real
amplitudes = vectors[:,selected].conj().T@driven
lines = 2*rest*abs(amplitudes)**2/gaps
lower = sum(lines[gaps>0])
higher = sum(lines[gaps<0])
response = direct+lower+higher
energies = [moving_root(torus,axis,k,source,calibrated) for k in (.01,.005)]
finite = [2*rest*(e-rest)/k**2 for e,k in zip(energies,(.01,.005))]
reference = (4*finite[1]-finite[0])/3
assert abs(response-reference) < 4e-6
print(f"{label} {('x','y','z')[axis]} bare {direct:.7f} lower {lower:.7f} "
f"higher {higher:.7f} total {response:.7f} moving {reference:.7f}")
if __name__ == "__main__":
audit()
fall.py
"""Unitary free fall of a scalar/link packet under a prescribed lapse gradient.
Run with Python and NumPy. Position refers to the same cell coordinate on the
two orbitals. Use OPENBLAS_NUM_THREADS=1 for quick small matrix eigensolves.
"""
import numpy as np
LENGTH = 320
SIGMA = .045
TIMES = np.array([.50, 1., 4., 16., 32.])
SLOPE = .0002
def model(m, n, offset=0.):
x = np.arange(LENGTH)-LENGTH//2
k = 2*np.pi*np.fft.fftfreq(LENGTH)
d = np.exp(1j*k)-1
e = np.sqrt(((m+n)/2)**2+abs(d)**2)
energy = (m-n)/2+e
spin = np.stack((np.ones_like(k),d/(energy+n)),axis=1)
spin /= np.linalg.norm(spin,axis=1)[:,None]
envelope = np.exp(-k*k/(4*SIGMA**2))
envelope /= np.linalg.norm(envelope)
psi = np.fft.fftshift(np.fft.ifft(envelope[:,None]*spin,axis=0,norm='ortho'),axes=0).ravel()
pos = np.repeat(x,2)
scalar = np.arange(0,2*LENGTH,2)
link = scalar+1
h = np.diag(np.tile([m+offset,-n+offset],LENGTH))
h[scalar,link] = h[link,scalar] = -1
h[link[:-1],scalar[1:]] = h[scalar[1:],link[:-1]] = 1
velocity = np.sin(k)/e
curvature = np.cos(k)/e-np.sin(k)**2/e**3
return h, pos, psi, envelope**2, energy+offset, velocity, curvature, 2*e
def evolve(h, pos, psi, slope, force):
matrix = h+slope*np.diag(pos) if force else h*(1+slope*(pos[:,None]+pos[None,:])/2)
vals, vecs = np.linalg.eigh(matrix)
states = vecs @ ((vecs.conj().T@psi)[:,None]*np.exp(-1j*vals[:,None]*TIMES))
prob = abs(states)**2
assert np.max(abs(prob.sum(axis=0)-1)) < 2e-13
assert np.max(np.sum(prob[abs(pos)>LENGTH//2-20],axis=0)) < 2e-18
return pos@prob
def check(m,n,force=False,offset=0.):
h,pos,psi,w,energy,v,curv,gap = model(m,n,offset)
base = curv if force else energy*curv-v*v
# In the band basis |X_-+|²=(1-v²)/gap² and the lapse's off-diagonal
# weight is (E_++E_-)/2; for an ordinary external force it is one.
coupling = 1. if force else (m-n)/2+offset
sincos = 2*np.sin(gap[:,None]*TIMES/2)**2
predicted = w@(base[:,None]-4*coupling*(1-v*v)[:,None]*sincos /
(gap[:,None]**3*TIMES**2))
finite = []
for a in (SLOPE,SLOPE/2):
plus,minus = [evolve(h,pos,psi,s*a,force) for s in (1,-1)]
finite.append(-(plus-minus)/(a*TIMES**2))
extrapolated = (4*finite[1]-finite[0])/3
assert np.max(abs(extrapolated-predicted)) < 2e-7
tag = 'force' if force else 'lapse'
print(f'{tag} m={m}, link mass={n}, C={offset:g}, width={np.sqrt(np.dot(abs(psi)**2,(pos-np.dot(abs(psi)**2,pos))**2)):.4f}')
print(' finite a:',np.round(finite[0],8))
print(' first order:',np.round(predicted,8),
'slow limit:',round(w@base,8),
'error after slope extrapolation:',f'{np.max(abs(extrapolated-predicted)):.2g}')
return predicted, finite[0], w@base
if __name__ == '__main__':
print('times:',TIMES)
for m,n in ((1.5,1.5),(2.5,2.5),(1.5,2.5),(2.5,1.5)):
check(m,n)
for m,n in ((1.5,2.5),(2.5,1.5)):
check(m,n,force=True)
check(m,n,offset=.4)
pair_fall.py
"""Adiabatic lapse-gradient response from the actual three-dimensional bound-pair branches."""
from pathlib import Path
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
if not (HERE/"bound_3d.py").is_file():
sys.path.insert(0,str(HERE.parent/"shell-clocks"))
from bound_3d import Torus, rest_calibration, IDENTITY, BETA_PAIR, calculate
def differential(responses):
density, mass = responses
return 2*(density-mass)/(density+mass)
def packet(n, step):
# A Gaussian in longitudinal momentum and a transverse plane wave.
torus = Torus(n,1.90)
cal = rest_calibration(torus)
width = 0.035
extent = int(np.ceil(5*width/step))
position = np.arange(-extent,extent+1)
weights = np.exp(-0.5*(position*step/width)**2)
weights /= weights.sum()
result = []
for source in (IDENTITY,BETA_PAIR):
positive = [torus.rest]
previous = cal[2]
for j in range(1,extent+3):
k = j*step
pole = positive[-1]
for _ in range(10):
inverse = torus.green(pole,2,k)-cal[1]*source
values,vectors = np.linalg.eigh(inverse)
overlaps = abs(vectors.conj().T@previous)
branch = np.argmax(overlaps)
assert overlaps[branch] > .85
state = vectors[:,branch]
if abs(values[branch]) < 3e-15:
break
derivative = (state.conj()@torus.green(pole,2,k,derivative=True)@state).real
pole -= values[branch]/derivative
else:
raise ArithmeticError("bound branch failed to converge")
positive.append(pole)
previous = state
def energy(j):
return positive[abs(j)]
rates = []
for j in position:
values = [energy(j+k) for k in (-2,-1,0,1,2)]
a,b,e,d,f = values
speed = (a-8*b+8*d-f)/(12*step)
curvature = (-a+16*b-30*e+16*d-f)/(12*step**2)
rates.append(e*curvature-speed**2)
result.append(float(weights@rates))
return np.array(result)
def main():
before = None
for n in (48,64):
curvatures,_ = calculate(n,1.9)
result = np.array([differential(pair) for pair in curvatures])
if before is not None:
assert max(abs(result-before)) < 3e-6
before = result
print("rest differential acceleration x,y,z,cubic:",result)
assert .0524 < result[2] < .0526
# Matched energies make the unknown common energy offset a common scale at rest.
factor = (1.90+.7)/1.90
assert abs(differential(factor*curvatures[2])-result[2]) < 1e-14
coarse = packet(32,.024)
fine = packet(48,.012)
print("wave packet sigma_K=0.035, ordered z:",fine,"eta",differential(fine))
print("joint mesh/derivative refinement:",np.max(abs(fine-coarse)))
assert np.max(abs(fine-coarse)) < .002
if __name__ == "__main__":
main()
binding.py
"""Compute the matched cubic pair's Ward coefficient using the published 3D kernel."""
import sys
from pathlib import Path
import numpy as np
# Works beside the archived kernel or in the site tree's neighboring study.
if not (Path(__file__).parent/'bound_3d.py').exists():
sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'shell-clocks'))
from bound_3d import Torus, rest_calibration, average_channels, extract_curvature
def ward(mesh, energy):
torus = Torus(mesh, energy)
gmat, lam, u, le = rest_calibration(torus)
# Choose the sign of the ++-orbital spin singlet once.
u = u*np.sign(u[0].real)
assert np.max(abs(u.imag)) < 1e-10
s0,s1 = u[[0,5]].real
cal = (average_channels([gmat]*3), lam, u, le)
step = min(0.005, np.sqrt(2-energy)*0.02)
vals = []
for h in (step, step/2):
gp = average_channels([torus.green(energy,j,h) for j in range(3)])
vals.append(extract_curvature(energy,h,gp,cal))
ratios = (4*vals[1]-vals[0])/3
zw = energy*lam**2/(-le)
c = (1-ratios)/zw
d = -c*lam**2
return dict(E=energy,L=mesh,g=1/lam,zw=zw,R=ratios.tolist(),c=c.tolist(),
d=d.tolist(),singlet_theta=float(np.arctan2(s1,s0)),
spin=[s0*s0,2*s0*s1,s1*s1])
TRAIN = (1.30,1.50,1.70,1.85,1.975)
TEST = (1.425,1.675,1.875,1.940,1.965)
OUTSIDE = (1.25,1.985)
WITNESS = (1.15,1.50,1.80,1.975)
def mesh_for(energy, refined):
if energy > 1.98:
return 160 if refined else 144
if energy >= 1.95:
return 128 if refined else 112
return 80 if refined else (64 if energy >= 1.85 else 48)
def chebyshev_fit(data, key):
nodes = np.array([data[e][key] for e in TRAIN])
mid = (nodes.min()+nodes.max())/2
halfspan = (nodes.max()-nodes.min())/2
def features(x):
return np.polynomial.chebyshev.chebvander((x-mid)/halfspan,4)
coeff = np.linalg.solve(features(nodes),[data[e]['c'][0] for e in TRAIN])
return lambda x: float((features(x)@coeff).item()), coeff
def obstruction(data):
# For 4 energies, the residuals of any constant real-symmetric 2x2 hopping
# lie in a 3D affine plane. The unit-l1 normal gives its exact minimax distance.
design = np.array([data[z]['zw']*np.array(data[z]['spin']) for z in WITNESS])
target = np.array([data[z]['zw']*np.array(data[z]['c']) for z in WITNESS])
left, sing, _ = np.linalg.svd(design, full_matrices=True)
assert sing[-1] > 1e-6
v = left[:,-1]
v /= sum(abs(v))
assert np.max(abs(v@design)) < 1e-13
unavoidable = abs(v@target)
for i, err in enumerate(unavoidable):
# Construct a matrix attaining the bound on these four rows.
yy = target[:,i]-np.sign(v@target[:,i])*err*np.sign(v)
coeff = np.linalg.lstsq(design,yy,rcond=None)[0]
assert abs(np.max(abs(design@coeff-target[:,i]))-err)<2e-10
print('four-depth l1-normal:',np.round(v,8))
print('spin-matrix minimax |R-1| (density,mass):',np.round(unavoidable,8))
def operator_check(coeff):
# Actually act with the fourth-degree Hamiltonian polynomial on a 4^3
# rest state. At rest the two allowed coincident singlets are rotation
# invariant and have S=+; each rotated copy gives the same expectation.
from bound_3d import BASIS, GAMMA, FULL_TENSORS, mode
size, z = 4, 1.675
t = Torus(size,z)
_, lam, u, le = rest_calibration(t)
h0 = []
for index in np.ndindex(size,size,size):
pp = 2*np.pi*np.array(index)/size
mats = []
for k in (pp,-pp):
en,b = mode(k,())
mats.append(en.item()*sum(x*y for x,y in zip(b[0],GAMMA[1:])))
h0.append(np.kron(mats[0],GAMMA[0])+np.kron(GAMMA[0],mats[1]))
h0 = np.array(h0)
src = BASIS@u
psi = np.stack([np.linalg.solve(z*np.eye(16)-h,src) for h in h0])
psi /= np.linalg.norm(psi)
def contact(y):
return np.broadcast_to(np.mean(y,axis=0), y.shape)
low = contact(psi)
weight = lam**2/(-le)
assert abs(np.vdot(low,low).real-weight)<1e-12
mid, half = (max(TRAIN)+min(TRAIN))/2, (max(TRAIN)-min(TRAIN))/2
for spin in (np.eye(16),FULL_TENSORS[-1]):
def normalized_h(y):
hy = np.einsum('pij,pj->pi',h0,y)+(contact(y)@spin.T)/lam
return (hy-mid*y)/half
assert np.linalg.norm(normalized_h(psi)-(z-mid)*psi/half)<1e-12
a, b = low, normalized_h(low)
total = coeff[0]*a+coeff[1]*b
for c in coeff[2:]:
a,b = b,2*normalized_h(b)-a
total += c*b
direct = np.vdot(psi,total).real
expected = weight*np.polynomial.chebyshev.chebval((z-mid)/half,coeff)
assert abs(direct-expected)<1e-9
print('finite-volume Hamiltonian polynomial: direct expectation verified')
def main():
refined = '--refine' in sys.argv
energies = sorted(set(TRAIN+TEST+OUTSIDE+WITNESS+(1.90,)))
data = {e:ward(mesh_for(e,refined),e) for e in energies}
for e in (1.30,1.50,1.80,1.90,1.975):
v = data[e]
print(f"E={e:.3f}: g={v['g']:.7f}, Ward c={np.round(v['c'],6)}, "
f"inverse-kernel d={np.round(v['d'],7)}")
obstruction(data)
for key in ('E','g'):
law, coeff = chebyshev_fit(data,key)
print(f'density-only fit in {key}, Chebyshev coefficients:',np.round(coeff,9))
for e in TEST+OUTSIDE:
v = data[e]
improved = np.array(v['R'])+v['zw']*law(v[key])
print(f' {e:.3f}: {improved[0]:.7f} {improved[1]:.7f}')
assert abs(np.diff(improved).item()-np.diff(v['R']).item())<1e-12
if key == 'E':
print('same filter on high spectral values: f(24) and f(66)', law(24.), law(66.))
operator_check(coeff)
if __name__ == '__main__':
main()
molecule.py
"""A local converting molecular channel coupled to two freely propagating massive walkers.
The archive contains bound_3d.py from the companion study. In the repository
the same unmodified source is kept in the shell-clocks directory.
"""
import argparse
from pathlib import Path
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
if not (HERE / "bound_3d.py").is_file():
sys.path.insert(0, str(HERE.parent / "shell-clocks"))
from bound_3d import Torus
def local_green(torus, energy, k=0.0, derivative=False):
"""Cubic singlet injection. The 24 rotated channels reduce to three axes."""
if k == 0:
return torus.green(energy, derivative=derivative)[0, 0].real
values = [torus.green(energy, j, k, derivative=derivative)[0, 0].real for j in range(3)]
return float(np.mean(values))
def derivatives(torus, energy):
value = local_green(torus, energy)
slope = local_green(torus, energy, derivative=True)
steps = (0.012, 0.006, 0.003)
raw = [2*(local_green(torus, energy, step)-value)/step**2 for step in steps]
coarse, fine = [(4*b-a)/3 for a, b in zip(raw, raw[1:])]
assert abs(coarse-fine) < 3e-5
return value, slope, fine
def predict(rest, coupling, derivatives):
green, slope, curve = derivatives
bare = rest - coupling**2*green
molecular_weight = 1/(1-coupling**2*slope)
molecular_response = 2*rest/(rest+bare)
open_response = -rest*curve/slope
response = molecular_weight*molecular_response+(1-molecular_weight)*open_response
implicit = rest*(2/(rest+bare)+coupling**2*curve)/(1-coupling**2*slope)
assert abs(implicit-response) < 1e-12
return bare, molecular_weight, response, open_response
def pole(torus, bare, coupling, k, guess):
"""Locate a real below-threshold zero of the full moving-channel equation."""
energy = guess
kinetic = 4*np.sin(k/2)**2
for _ in range(12):
green = local_green(torus, energy, k)
residual = energy-bare-kinetic/(energy+bare)-coupling**2*green
if abs(residual) < 2e-14:
return energy
slope = (1+kinetic/(energy+bare)**2
-coupling**2*local_green(torus, energy, k, derivative=True))
energy -= residual/slope
raise ArithmeticError("unconverged moving pole")
def direct_check():
# A finite-volume control independently locates poles at finite K and mass.
grid = Torus(9)
rest, coupling = 1.85, 2.0
bare, weight, response, _ = predict(rest,coupling,derivatives(grid,rest))
diff = 0.0001
mass_slope = (pole(grid,bare+diff,coupling,0,rest)-pole(grid,bare-diff,coupling,0,rest))/(2*diff)
assert abs(mass_slope-weight) < 1e-7
estimates = []
for k in (0.024,0.012):
e = pole(grid,bare,coupling,k,rest)
estimates.append(2*rest*(e-rest)/k**2)
assert abs((4*estimates[1]-estimates[0])/3-response) < 1e-6
print(f"direct moving-pole and detuning-slope checks: R={response:.8f}, Z={weight:.8f}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--quick", action="store_true", help="use smaller quadratures")
args = parser.parse_args()
direct_check()
grids = (32,48) if args.quick else (64,96)
last = []
for n in grids:
records = []
for rest in (1.60,1.80,1.90,1.975):
moments = derivatives(Torus(n),rest)
for coupling in (0.0,1.0,2.0,4.0):
bare, weight, response, open_response = predict(rest,coupling,moments)
records.append((weight,response))
if n == grids[-1]:
print(f"E={rest:5.3f} h={coupling:.0f} bare={bare:.8f} "
f"Z={weight:.8f} R={response:.8f} R_open={open_response:.8f}")
if last:
difference = np.max(abs(np.asarray(records)-np.asarray(last)))
print(f"mesh change {grids[0]} to {grids[1]}: {difference:.8g}")
if not args.quick:
assert difference < 2e-4
last = records
if __name__ == "__main__":
main()
dimer.py
"""A soluble one-dimensional dimer with the prescribed lattice mass shell."""
from math import cos, sin, sqrt, pi
def target(rest, k):
return sqrt(rest**2+4*sin(k/2)**2)
def contact(rest,k):
energy = target(rest,k)
return -sqrt(2*(energy-2)**2 + 4-rest**2)
def dimer(k, potential):
return 4-sqrt(potential**2 + 4*cos(k/2)**2)
def hop(rest):
chi = 4-rest
attraction = sqrt(chi**2-4)
return 2*attraction/(rest*(chi+2))
def finite_relative_residual(k, energy, potential):
# A finite-torus independent pole check using the free two-particle resolvent.
sites = 512
green = sum(1/(energy-4+2*cos(k/2)*cos(2*pi*p/sites)) for p in range(sites))/sites
return abs(1-potential*green)
def main():
for rest in (1.25,1.50,11/6,1.975):
base = contact(rest,0)
exact_error, line_error = 0., 0.
for i in range(129):
k = pi*i/128
exact_error = max(exact_error, abs(dimer(k,contact(rest,k))-target(rest,k)))
line_error = max(line_error, abs(dimer(k,base+hop(rest)*(1-cos(k)))-target(rest,k)))
assert exact_error < 2e-15
for k in (0.03,0.5,1.2,pi):
assert finite_relative_residual(k,target(rest,k),contact(rest,k)) < 2e-13
near = [2*rest*(dimer(k,base+hop(rest)*(1-cos(k)))-rest)/k**2 for k in (.02,.01)]
assert abs((4*near[1]-near[0])/3-1) < 1e-8
print(f"E={rest:.6f}: required pair hop {hop(rest):.8f}, largest sampled "
f"nearest-neighbour energy error {line_error:.7f}; exact-kernel error {exact_error:.2g}")
# Reuse a single constant calibrated at 1.5 for the second rest energy.
z = 11/6
wrong = z/(4-z)*(1+abs(contact(z,0))*hop(1.5))
assert abs(wrong-407/351)<1e-14
if __name__ == "__main__":
main()
mass_data.py
"""Reconstruct the 2005 Rainville neutron-capture comparison using the paper's inputs.
All reported standard errors are on the final quoted digits. Wavelengths below
are effective wavelengths for full capture energies, in picometres.
"""
from math import hypot
C = 299792458
MOLAR_H, SIGMA_MOLAR_H = 3.990312716e-10, 0.000000027e-10
DEUTERIUM = (0.557341007, 0.000000098)
DEUTERIUM_MINUS_TWO_H = (-0.00154828629, 0.00000000040)
# isotope, effective capture wavelength/sigma, M(parent)+M(H)-M(product)/sigma (u)
ROWS = [
("Si-29",0.146318275,0.000000086,0.00825690198,0.00000000024),
("S-33",0.143472991,0.000000054,0.00843729682,0.00000000030),
]
def reconstruct():
# Report-era conversion 1 u = 10^-3 kg / N_A. Keep the historical molar h.
factor = 1e15*MOLAR_H/C
wavelength_d, sigma_d = DEUTERIUM
common_mass, sigma_common_mass = DEUTERIUM_MINUS_TWO_H
masses, energies, residuals = [], [], []
for name,wavelength,sigma_wavelength,measured_mass,sigma_mass in ROWS:
dm = measured_mass+common_mass
gamma = factor*(1/wavelength-1/wavelength_d)
residual = 1-dm/gamma
sigma_e = hypot(factor*sigma_wavelength/wavelength**2, factor*sigma_d/wavelength_d**2,
gamma*SIGMA_MOLAR_H/MOLAR_H)
uncertainty = hypot(hypot(sigma_mass,sigma_common_mass)/gamma,dm*sigma_e/gamma**2)
print(f"{name}: trap {dm:.11f} u, gamma {gamma:.11f} u, "
f"1-dm/E {(1e7*residual):.4f}e-7, diagonal sigma {(1e7*uncertainty):.4f}e-7")
masses.append(dm)
energies.append(gamma)
residuals.append(residual)
assert abs(residuals[0]*1e7 - (-9.7)) < .3
assert abs(residuals[1]*1e7 - 2.1) < .2
# Subtract silicon from sulfur BEFORE taking any ratio. The deuterium terms cancel.
dm = ROWS[1][3]-ROWS[0][3]
gamma = factor*(1/ROWS[1][1]-1/ROWS[0][1])
assert abs(dm-(masses[1]-masses[0])) < 1e-17
assert abs(gamma-(energies[1]-energies[0])) < 1e-17
residual = 1-dm/gamma
components = [dm/gamma**2*factor*r[2]/r[1]**2 for r in ROWS]
components += [r[4]/gamma for r in ROWS]
components += [dm/gamma*SIGMA_MOLAR_H/MOLAR_H]
lower = max(0,2*max(components)-sum(components))
upper = sum(components)
print(f"isotope difference: trap {dm:.11f} u, gamma {gamma:.11f} u, "
f"residual {residual*1e6:.3f} ppm; diagonal sigma {hypot(*components)*1e6:.3f} ppm; "
f"arbitrary covariance sigma envelope {lower*1e6:.3f} to {upper*1e6:.3f} ppm")
# Cross-check the authors' reported combination to precision of their rounded errors.
reported = [(-9.7,8.0),(2.1,5.2)]
weight = sum(1/s**2 for _,s in reported)
mean = sum(y/s**2 for y,s in reported)/weight
assert abs(mean+1.4)<.05 and abs(weight**-.5-4.4)<.05
print(f"weighted published summaries {mean:.3f} ± {weight**-.5:.3f} (1e-7)")
if __name__ == "__main__":
reconstruct()
source.py
"""Reciprocal motion of two band packets and their dynamical scalar field.
The 3D periodic field is represented by conjugate Fourier modes with a fixed
mean. The centers move along z. A smooth source profile regularizes each
particle's self field. This is a long-wavelength effective Hamiltonian.
"""
import numpy as np
REST = 1.90
R = np.array([1.438250542,1.364660640])
G = .02
class FieldPair:
def __init__(self,n=25,length=56.,width=2.2):
self.length = length
self.volume = length**3
self.stiffness = 1/(4*np.pi*G)
grid = 2*np.pi*np.fft.fftfreq(n,length/n)
x,y,z = np.meshgrid(grid,grid,grid,indexing="ij")
k2 = (x*x+y*y+z*z).ravel()
mask = k2>0
self.kz = z.ravel()[mask]
self.shape = np.exp(-width**2*k2[mask]/2)
# Standard local spatial field energy on cells of width L/n.
self.khat2 = sum((2*np.sin(t*length/(2*n))/(length/n))**2 for t in (x,y,z)).ravel()[mask]
self.nmodes = len(self.kz)
def coordinates(self,x):
return np.exp(1j*x[:,None]*self.kz)*self.shape
def rates(self,state):
x,p,field,velocity = state
e = REST+R*p**2/(2*REST)
phase = self.coordinates(x.real)
potential = (phase@field).real
gradient = (phase@(1j*self.kz*field)).real
source = e.real@phase.conj()/self.volume
return [((1+potential)*R*p/REST).real,-e*gradient,
velocity,-self.khat2*field-source/self.stiffness]
def equilibrium(self,x):
rho = REST*self.coordinates(x).conj().sum(axis=0)/self.volume
return -rho/(self.stiffness*self.khat2)
def conserved(self,state):
x,p,field,velocity = state
e = REST+R*p**2/(2*REST)
matter_energy = e@(1+(self.coordinates(x)@field).real)
field_energy = self.stiffness*self.volume/2*(
np.vdot(velocity,velocity).real+np.vdot(field,self.khat2*field).real)
field_momentum = -self.stiffness*self.volume*np.vdot(velocity,1j*self.kz*field).real
return np.array([matter_energy+field_energy,p.sum()+field_momentum,
matter_energy,field_energy,field_momentum])
def initial(self,pulse):
x = np.array([-6.,6.])
field = self.equilibrium(x)
velocity = np.zeros_like(field)
if pulse:
# Add a smooth axially moving wave, with its momentum included.
spectrum = self.shape**2*np.exp(1j*5*self.kz)
wave = .004*spectrum/self.shape.dot(self.shape)
field = field+wave
velocity = -1j*self.kz*wave
return [x,np.zeros(2),field,velocity]
def step(self,state,dt):
def shifted(base,slope,t):
return [a+t*b for a,b in zip(base,slope)]
a = self.rates(state)
b = self.rates(shifted(state,a,dt/2))
c = self.rates(shifted(state,b,dt/2))
d = self.rates(shifted(state,c,dt))
return [x+dt*(ka+2*kb+2*kc+kd)/6 for x,ka,kb,kc,kd in zip(state,a,b,c,d)]
def static_force(length=56.,n=25):
pair = FieldPair(n,length)
state = pair.initial(False)
force = pair.rates(state)[1]
potential = (pair.coordinates(state[0])@state[2]).real
accel = (1+potential)*R*force/REST
eta = 2*(abs(accel[0])-abs(accel[1]))/sum(abs(accel))
# Differentiate the *relaxed* total energy, including the field half.
def energy(x0):
x=np.array([x0,6.])
return pair.conserved([x,np.zeros(2),pair.equilibrium(x),np.zeros(pair.nmodes,complex)])[0]
h=.005
from_energy = -(energy(-6+h)-energy(-6-h))/(2*h)
assert abs(force.sum()) < 2e-15
assert abs(from_energy/force[0]-1)<2e-6
assert abs(eta-2*(R[0]-R[1])/sum(R))<1e-10
print(f"L={length:g}, N={n}: equal opposite force {force[0]:.10g}, "
f"relaxed-energy slope {from_energy:.10g}, accelerations {accel}, eta={eta:.8f}")
return force[0]
def run(pair,pulse,dt):
state = pair.initial(pulse)
initial = pair.conserved(state)
max_drift = np.zeros(2)
for i in range(round(16/dt)):
state = pair.step(state,dt)
if (i+1)%10 == 0:
max_drift=np.maximum(max_drift,abs(pair.conserved(state)[:2]-initial[:2]))
change = pair.conserved(state)-initial
assert max_drift[0]<2e-8 and max_drift[1]<2e-8
assert max(abs(state[1]))<.03
print(f"pulse {pulse}, dt={dt:g}: p={state[1]}, net field momentum change "
f"{change[4]:+.9g}, field energy change {change[3]:+.9g}, drifts {max_drift}")
return np.r_[state[0],state[1],change[3:]]
def main():
static_force()
# Double box with same physical field spacing to check periodic images.
static_force(112.,51)
model = FieldPair(19)
for pulse in (False,True):
coarse = run(model,pulse,.20)
fine = run(model,pulse,.10)
assert np.max(abs(fine-coarse))<2e-6
if pulse:assert abs(fine[2]+fine[3])>1e-5
print("Both exchange runs conserve the field-plus-matter totals.")
if __name__=="__main__":
main()
covering_source.py
"""Cross-covering thresholds for the two ordered quadratic momentum sublevels.
Standard library only. Exact rational comparisons conditional on the published
numerical curvature inputs. A sampling check supplements the analytic proof.
"""
from fractions import Fraction as F
from itertools import product
from math import cos, pi, sin, sqrt
DENSITY = tuple(map(F, ('1.520189244','1.533794028','1.438250527')))
MASS = tuple(map(F, ('1.518291819','1.533438288','1.364660625')))
def main():
# Coordinates are density-template units; the equal excess-energy scale
# cancels. Reflection symmetry makes these generalized axes diagonal.
axes = sorted(((u/v,j) for j,(u,v) in enumerate(zip(DENSITY,MASS))),reverse=True)
(aa,major),(bb,middle),(cc,minor) = axes
assert (major,middle,minor) == (2,0,1)
two_sq=(aa+bb)**2/(4*aa)
tetra_upper_sq=8*aa/9
assert F(1)<cc and tetra_upper_sq < F(99,100)**2 < cc
assert two_sq < F(101,100)**2 < aa
third_scale=F(10007,10000)
shift=F(26,1000)
interior_limit=bb+(1-bb/aa)*shift**2/4
assert aa<(third_scale+shift)**2 and interior_limit<third_scale**2<two_sq
# Sub-percent feature: 0.007% error in each quadratic form is sufficient.
tiny=F(7,100000)
uncertainty=(1+tiny)/(1-tiny)
assert aa<(third_scale+shift)**2 and interior_limit*uncertainty<third_scale**2<two_sq/uncertainty
assert (aa+shift**2-third_scale**2/uncertainty)**2 < 4*aa*shift**2
assert 1/cc < F(1) < F(101,100)**2
# Independent forward and reverse one-copy thresholds fix major/minor;
# the two-copy threshold adds the middle generalized axis.
assert 4*aa*two_sq == (aa+bb)**2
a,b,c=map(lambda x:sqrt(float(x)),(aa,bb,cc))
r2=sqrt(float(two_sq))
d=(a*a-b*b)/(2*a)
print(f'axes along z,x,y: {a:.9f} {b:.9f} {c:.9f}')
print(f'one {a:.9f}, two {r2:.9f}, optimal center offsets ±{d:.9f}')
print(f'tetrahedral upper {sqrt(float(tetra_upper_sq)):.9f}; '
f'lower exclusion for three below {c:.9f}')
print(f'three collinear placements sufficient at {max(a-float(shift),sqrt(float(interior_limit))):.9f}')
print(f'middle / major {sqrt(2*r2/a-1):.9f}')
# Verify constructive two-center and tetrahedral placements directly on
# the ellipsoid boundary; the proof also covers every interior point.
tetra=[(i/3/sqrt(3)*a,j/3/sqrt(3)*a,k/3/sqrt(3)*a)
for i,j,k in product((-1,1),repeat=3) if i*j*k==1]
maximum=[0.,0.]
for j in range(101):
t=pi*j/100
for k in range(200):
p=2*pi*k/200
point=(a*cos(t),b*sin(t)*cos(p),c*sin(t)*sin(p))
two=(abs(point[0])-d)**2+point[1]**2+point[2]**2
four=min(sum((x-y)**2 for x,y in zip(point,u)) for u in tetra)
maximum[0]=max(maximum[0],two)
maximum[1]=max(maximum[1],four)
assert abs(maximum[0]-float(two_sq)) < 1e-12
assert maximum[1] <= float(tetra_upper_sq)+1e-12
eps=F(1,200)
factor=(1+eps)/(1-eps)
two_lo=sqrt(float(two_sq*factor))
two_hi=sqrt(float(aa/factor))
four_lo=sqrt(float(tetra_upper_sq*factor))
four_hi=sqrt(float(cc/factor))
assert two_sq*factor<F(101,100)**2<aa/factor
assert tetra_upper_sq*factor<F(99,100)**2<cc/factor
assert factor/cc<F(101,100)**2
print(f'with 0.5% separate form errors: two on [{two_lo:.6f},{two_hi:.6f}), '
f'four on [{four_lo:.6f},{four_hi:.6f})')
print(f'unit-scale four-copy lower margin: {100*float((cc-1)/(cc+1)):.6f}%')
def finite_energy(mesh):
"""Solve actual ordered-pair poles at fixed excess energy on four rays."""
import sys
from pathlib import Path
import numpy as np
if not (Path(__file__).parent/'bound_3d.py').exists():
sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'shell-clocks'))
from bound_3d import Torus, rest_calibration, IDENTITY, BETA_PAIR, TENSORS, mode
torus=Torus(mesh)
_,lam,source,_=rest_calibration(torus)
forms=np.array([[float(v) for v in DENSITY],[float(v) for v in MASS]])
def kernel(energy,unit,magnitude):
# The previous kernel takes an axis index. Integrate the same four
# signed bands at p+K/2 and -p+K/2 for an arbitrary vector K.
moments=np.zeros((5,5))
half=unit*magnitude/2
for lo in range(0,mesh,8):
grid=(torus.grid[0][lo:lo+8],torus.grid[1],torus.grid[2])
p=[a*(2*np.pi/mesh) for a in grid]
shape=np.broadcast_shapes(*(a.shape for a in p))
a,A=mode([s+h for s,h in zip(p,half)],shape)
b,B=mode([-s+h for s,h in zip(p,half)],shape)
pp,pm,mp,mm=[.25/(energy-sa*a-sb*b) for sa,sb in
((1,1),(1,-1),(-1,1),(-1,-1))]
moments[0,0]+=np.sum(pp+pm+mp+mm)
moments[1:,0]+=np.sum((pp+pm-mp-mm)[:,None]*A,axis=0)
moments[0,1:]+=np.sum((pp-pm+mp-mm)[:,None]*B,axis=0)
moments[1:,1:]+=A.T@((pp-pm-mp+mm)[:,None]*B)
return np.tensordot(moments.ravel()/mesh**3,TENSORS,axes=1)
verify=kernel(1.9001,np.array([0.,1.,0.]),.043)
assert np.max(abs(verify-torus.green(1.9001,1,.043)))<1e-13
worst=0.
for de in (.00001,.00005,.0005,.005,.01):
for label,vec in (('x',(1,0,0)),('y',(0,1,0)),('z',(0,0,1)),('xy',(1,1,0))):
if de==.01 and label=='xy':
continue
unit=np.array(vec)/np.linalg.norm(vec)
quadratic=forms@(unit**2)
roots=[]
for j,contact in enumerate((IDENTITY,BETA_PAIR)):
def residual(k2):
vals,vectors=np.linalg.eigh(kernel(1.9+de,unit,np.sqrt(k2))-lam*contact)
return vals[np.argmax(abs(vectors.conj().T@source))]
old=0.
now=2*1.9*de/quadratic[j]
f_old,f_now=residual(old),residual(now)
for _ in range(7):
if abs(f_now)<1e-14:
break
new=now-f_now*(now-old)/(f_now-f_old)
old,now,f_old=now,new,f_now
f_now=residual(now)
assert abs(f_now)<1e-13
# |partial_j E|<=sqrt(1+(32/3)^2): the signed mixed continua
# cannot reach the levels tested on these rays. The ++ edge >= 2.
assert 10.8*sum(abs(unit))*np.sqrt(now)<1.9+de<2
worst=max(worst,abs(f_now))
roots.append(now)
drift=100*(2*1.9*de/np.array(roots)/quadratic-1)
print(f'excess {de:.5f} {label}: mass/density radius {sqrt(roots[1]/roots[0]):.8f}, '
f'effective-form drift percent {drift[0]:.6f} {drift[1]:.6f}')
print(f'maximum inverse-kernel pole residual {worst:.2g}')
if __name__=='__main__':
import argparse
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--finite',action='store_true',help='also solve the pair poles with NumPy')
parser.add_argument('--mesh',type=int,default=48,help='periodic quadrature size for --finite')
args=parser.parse_args()
main()
if args.finite:
finite_energy(args.mesh)
form_factor.py
"""Energy-density form factor of the ordered 3D pair in a symmetric moving frame.
NumPy is optional outside this replay. The smooth Brillouin torus is integrated
by periodic cubature; its mesh is not a finite apparatus limiting q.
"""
from pathlib import Path
import sys
import numpy as np
if not (Path(__file__).parent/'bound_3d.py').exists():
sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'shell-clocks'))
from bound_3d import Torus, rest_calibration, BASIS, BETA_PAIR, GAMMA, IDENTITY
Z0 = 1.90
G = np.array(GAMMA[1:])
def block(k):
x,y,z = k
t = [2*np.sin(p/2)**2 for p in (x,y,z)]
m = 1+2*sum(s*s for s in t)/3+2*(t[0]*t[1]+t[1]*t[2]+t[2]*t[0])
coeff = np.stack(np.broadcast_arrays(np.sin(x)*np.cos(y)*np.cos(z),
np.sin(y)*np.cos(z),np.sin(z),m),axis=-1).reshape(-1,4)
e = np.sqrt(np.sum(coeff*coeff,axis=1))
return (coeff@G.reshape(4,16)).reshape(-1,4,4), e
def wave(source,z,ha,a,hb,b):
# Closed-form resolvent in the four signed-energy sectors, acting on 4x4 spins.
wpp = .25/(z-a-b)
wpm = .25/(z-a+b)
wmp = .25/(z+a-b)
wmm = .25/(z+a+b)
ma = ha@source
bt = hb.swapaxes(1,2)
mb = source@bt
def times(s,u):
return s[:,None,None]*u
return (times(wpp+wpm+wmp+wmm,source)
+times((wpp+wpm-wmp-wmm)/a,ma)
+times((wpp-wpm+wmp-wmm)/b,mb)
+times((wpp-wpm-wmp+wmm)/(a*b),ma@bt))
def bound(torus, cal, axis, k, contact):
_,lam,u0,_ = cal
energy = Z0
for _ in range(8):
g = torus.green(energy,axis,k)
vals,u = np.linalg.eigh(g-lam*contact)
j = np.argmax(abs(u.conj().T@u0))
v = u[:,j]
ge = torus.green(energy,axis,k,derivative=True)
nz = -(v.conj()@ge@v).real
step = vals[j]/nz
if abs(step)<2e-13:
break
energy += step
assert abs(step) < 2e-11
v = v*np.exp(-1j*np.angle(u0.conj()@v))
return energy,v/np.sqrt(nz)
def run_axis(torus,cal,axis,q,contact):
n = torus.size
energy,src_f = bound(torus,cal,axis,q/2,contact)
src_i = BETA_PAIR @ src_f # inversion on the chosen rest-even simple pole
u_f,u_i = [(BASIS@v).reshape(4,4) for v in (src_f,src_i)]
_,lam,_,_ = cal
interaction = lam*(src_f.conj()@contact@src_i)
one = mid = num = spincheck = 0j
no_i = no_f = 0.
grid = np.ogrid[0:n,0:n,0:n]
for lo in range(0,n,3):
k = [p*2*np.pi/n for p in (grid[0][lo:lo+3],grid[1],grid[2])]
half = [q/2 if j==axis else 0 for j in range(3)]
ha0,a0 = block([p-s for p,s in zip(k,half)])
ha1,a1 = block([p+s for p,s in zip(k,half)])
hb,b = block([-p for p in k])
wi = wave(u_i,energy,ha0,a0,hb,b)
wf = wave(u_f,energy,ha1,a1,hb,b)
# Exchange-odd identical propagators imply equal contributions from the
# two labelled copies, so their sum uses (ha0+ha1) without 1/2 here.
one += np.vdot(wf,(ha0+ha1)@wi)
center_h,_ = block(k)
mid += 2*np.vdot(wf,center_h@wi)
num += np.vdot(wf,wi)
spincheck += np.vdot(wf,wi@hb.swapaxes(1,2))
no_i += np.vdot(wi,wi).real
no_f += np.vdot(wf,wf).real
one /= n**3
mid /= n**3
num /= n**3
spincheck /= n**3
assert max(abs(no_i/n**3-1),abs(no_f/n**3-1)) < (4e-4 if n<=32 else 2e-5)
total = one+interaction
# Binding equation for each leg, using the spectator energy insertion twice.
residual = abs(total-(2*energy*num-2*spincheck-interaction))
assert residual < (1e-4 if n<=32 else 2e-5)
assert abs(total.imag) < 1e-10
return np.array([total.real,one.real,interaction.real,(mid+interaction).real,num.real])
def local_vertex_check():
# Recover the nonzero real-space hopping matrices by an exact-length DFT
# (all symbol frequencies fit from -2 to +2). Rebuild both density vertices
# by assigning every individual bond to its ends or to its midpoint.
n=5
axes=np.ogrid[0:n,0:n,0:n]
h,_=block([p*(2*np.pi/n) for p in axes])
hops=np.fft.ifftn(h.reshape(n,n,n,4,4),axes=(0,1,2))
k=np.array([.31,-.23,.19])
q=np.array([.11,.07,-.12])
end=np.zeros((4,4),complex)
middle=end.copy()
for pos in np.ndindex(n,n,n):
delta=np.array([j if j<=2 else j-n for j in pos])
bare=hops[pos]*np.exp(-1j*(k@delta))
end+=bare*(1+np.exp(-1j*(q@delta)))/2
middle+=bare*np.exp(-.5j*(q@delta))
a,ea=block(k)
b,eb=block(k+q)
c,_=block(k+q/2)
assert np.max(abs(end-(a[0]+b[0])/2)) < 1e-13
assert np.max(abs(middle-c[0])) < 1e-13
spin=np.arange(16).reshape(4,4)+1j
z=1.83
explicit=np.linalg.solve(z*np.eye(16)-np.kron(a[0],np.eye(4))-
np.kron(np.eye(4),b[0]),spin.ravel())
assert np.max(abs(wave(spin,z,a,ea,b,eb).ravel()-explicit)) < 2e-12
def main():
n = int(sys.argv[1]) if len(sys.argv)>1 else 48
axes = sys.argv[2] if len(sys.argv)>2 else 'z'
qs = [float(q) for q in sys.argv[3:]] or [.2,.05,.025]
torus = Torus(n)
cal=rest_calibration(torus)
# First four columns use F(0)=Z0; the normalized number form factor uses 1.
normalizers = np.array([Z0,Z0,Z0,Z0,1.])
print('columns: endpoint F, free contribution, contact contribution, midpoint F, number')
for axis in ('xyz'.index(name) for name in axes):
slopes = []
for label,contact in (('density',IDENTITY),('mass',BETA_PAIR)):
base=run_axis(torus,cal,axis,0.,contact)
assert abs(base[0]-Z0) < 1e-11 and abs(base[3]-Z0) < 1e-11
print(f'axis {"xyz"[axis]}, {label}, q=0: '+str(np.round(base,10)),flush=True)
radii=[]
for q in qs:
value=run_axis(torus,cal,axis,q,contact)
radius=-2*(value-base)/(normalizers*q*q)
radii.append(radius)
print(f' q={q:.5f}: {np.round(value,9)}',flush=True)
if len(qs)>=2 and abs(qs[-2]-2*qs[-1])<1e-12:
slope=(4*radii[-1]-radii[-2])/3
slopes.append(slope)
print(' directional second moments:',np.round(slope,8),flush=True)
if len(slopes) == 2:
delta=slopes[1]-slopes[0]
print(' mass minus density:',np.round(delta,8),flush=True)
assert abs(delta[0]-delta[3]) < 2e-6
if __name__=='__main__':
local_vertex_check()
main()
tensor_source.py
"""Check the symmetric-source Ward identity on actual two-particle poles."""
import argparse
from pathlib import Path
import sys
import numpy as np
HERE = Path(__file__).resolve().parent
if not (HERE / "bound_3d.py").is_file():
sys.path.insert(0,str(HERE.parent / "shell-clocks"))
from bound_3d import Torus, rest_calibration, average_channels, BETA_PAIR, IDENTITY
def averaged_green(torus,z,k,cubic,derivative=False):
if cubic:
return average_channels([torus.green(z,j,k,derivative=derivative) for j in range(3)])
return torus.green(z,2,k,derivative=derivative)
def pole(torus,cal,k,contact,cubic):
_,lam,reference,_ = cal
z = torus.rest + .4*k*k
for _ in range(12):
green = averaged_green(torus,z,k,cubic)
residues,basis = np.linalg.eigh(green-lam*contact)
scores = abs(basis.conj().T@reference)
which = int(np.argmax(scores))
assert scores[which] > .85
r = residues[which]
if abs(r)<8e-15:
return z
u = basis[:,which]
dgreen = averaged_green(torus,z,k,cubic,derivative=True)
slope = (u.conj()@dgreen@u).real
assert slope<0
z -= r/slope
raise ArithmeticError("singlet pole did not converge")
def run(size):
torus = Torus(size,1.90)
cal = rest_calibration(torus)
values = {}
for cubic,name in ((False,"native z"),(True,"cubic")):
for contact,label in ((BETA_PAIR,"mass"),(IDENTITY,"density")):
ks = (.025,.05,.10)
energies = [pole(torus,cal,k,contact,cubic) for k in ks]
sec = [(z-torus.rest)/k**2 for z,k in zip(energies,ks)]
quartic1 = 24*(sec[1]-sec[0])/(ks[1]**2-ks[0]**2)
quartic2 = 24*(sec[2]-sec[1])/(ks[2]**2-ks[1]**2)
values[(name,label)] = sec
print(f"L={size:2} {name:8} {label:7} poles " + " ".join(f"{e:.11f}" for e in energies))
print(" secants " + " ".join(f"{v:.9f}" for v in sec) +
f" E'''' estimates {quartic1:.6f}, {quartic2:.6f}")
# Any additive energy shift with positive rest energy obeys the
# same lower bound on variation of its inferred speed squared.
change = sec[-1]/sec[0]-1
print(f" offset-independent lower bound on fractional speed-squared change {change:.8f}")
assert min(np.diff(sec)) > 1e-4
if cubic:
assert change > .012
return values
if __name__=="__main__":
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("--size",type=int,default=32)
parser.add_argument("--refine",type=int,help="compare to a second torus size")
args=parser.parse_args()
coarse=run(args.size)
if args.refine:
fine=run(args.refine)
shift=max(abs(a-b) for key in coarse for a,b in zip(coarse[key],fine[key]))
print(f"Maximum secant change on mesh refinement {shift:.3g}")
if args.size>=48 and args.refine>=64:
assert shift < 5e-7
support.py
"""Conserved symmetric source of a matter wave and its dynamical supporting medium."""
from math import sqrt,sin,cos
from cmath import exp
def wave(m,s2,transverse,lower,q):
e0 = sqrt(m*m+s2*(transverse**2+lower**2))
e1 = sqrt(m*m+s2*(transverse**2+(lower+q)**2))
w = e1-e0
dot = transverse**2+lower*(lower+q)
rho = (e1*e0+s2*dot+m*m)/2
pressure = (e1*e0-s2*dot-m*m)/2
px,pz = (e1+e0)*transverse/2,(e1*lower+e0*(lower+q))/2
txz = s2*transverse*(lower+q/2)
tzz = s2*lower*(lower+q)+pressure
return w,rho,pressure,px,pz,txz,tzz
def solve(m,s2,transverse,lower,q):
w,rho,p,px,pz,txz,tzz = wave(m,s2,transverse,lower,q)
assert abs(w*rho-q*s2*pz)<1e-14 and abs(w*px-q*txz)<1e-14
assert abs(w*pz-q*tzz)<1e-14 and abs(w)<q
D = (1-s2)*q*pz/(q*q-w*w)
total = rho-w*D, pz-q*D, tzz-w*D
bare = q*pz-w*rho
assert abs(q*total[1]-w*total[0])<1e-13
assert abs(q*total[2]-w*total[1])<1e-13
print(f"m={m:g} s²={s2:g}: beat omega={w:.8f} q={q:g}, unsupported energy residual "
f"{bare:.9f}; supported density, flux and axial stress {total}")
print(f" transverse shear source (Txx-Tyy)/2={s2*transverse**2/2:.8f}")
# Causal solution for newly evolving support with the beat already present.
def drive(t):
return -1j*(1-s2)*q*pz*exp(-1j*w*t)
def derivative(t,y,v):
return v,-q*q*y+drive(t)
y=v=0j
dt=.025
max_error=max_div=0.
for n in range(1200):
t=n*dt
# y = K_s chi, v = K_s chi_dot, per unit product of the two wave amplitudes.
a,b = derivative(t,y,v)
c,d = derivative(t+dt/2,y+dt*a/2,v+dt*b/2)
e,f = derivative(t+dt/2,y+dt*c/2,v+dt*d/2)
g,h = derivative(t+dt,y+dt*e,v+dt*f)
y += dt*(a+2*c+2*e+g)/6
v += dt*(b+2*d+2*f+h)/6
t += dt
phase=exp(-1j*w*t)
exact=-1j*D*(phase-cos(q*t)+1j*w/q*sin(q*t))
max_error=max(max_error,abs(exact-y))
acceleration=drive(t)-q*q*y
energy_div=-1j*w*rho*phase+acceleration+1j*q*(pz*phase-1j*q*y)
momentum_div=-1j*w*pz*phase-1j*q*v+1j*q*(tzz*phase+v)
max_div=max(max_div,abs(energy_div),abs(momentum_div))
assert max_error<1e-8 and max_div<1e-13
print(f" initial-value evolution max error {max_error:.2g}, divergence {max_div:.2g}")
return total
def bilinear(a, matrix, b):
return sum(a[i]*matrix[i][j]*b[j] for i in range(2) for j in range(2))
Z = 1.90
GAP2 = .25
C_UPPER = 1.52384402
IDENTITY2 = ((1.,0.),(0.,1.))
MASS2 = ((Z*Z-GAP2,0.),(0.,Z*Z))
def mixing(fit_k=.05, secant=.402219349):
t = fit_k**2
# (E^2-z^2)/k^2 avoids precision loss in the fit at small k.
slope = 2*Z*secant+secant**2*t
b = sqrt((GAP2/t+slope-1)*(slope-C_UPPER))
return ((1.,b),(b,C_UPPER))
def upper_mode(k, C):
t = sum(v*v for v in k)
gap = GAP2+(C_UPPER-1)*t
b = C[0][1]
# Rationalized shift above the upper diagonal of M^2+t*C.
lift = 2*(b*t)**2/(sqrt(gap**2+4*(b*t)**2)+gap)
energy = sqrt(Z*Z+C_UPPER*t+lift)
ratio = b*t/(gap+lift)
norm = sqrt(1+ratio*ratio)
spin = (ratio/norm,1/norm)
for i in range(2):
residual = sum((MASS2[i][j]+t*C[i][j])*spin[j] for j in range(2))
assert abs(residual-energy**2*spin[i])<2e-14
return energy,spin
def mixed_beat(C,lower,upper):
e0,v0 = upper_mode(lower,C)
e1,v1 = upper_mode(upper,C)
gram = bilinear(v1,IDENTITY2,v0)
elastic = bilinear(v1,C,v0)
mass = bilinear(v1,MASS2,v0)
grad = sum(k*p for k,p in zip(upper,lower))
rho = (e1*e0*gram+grad*elastic+mass)/2
lag = (e1*e0*gram-grad*elastic-mass)/2
common = [(e1*x+e0*y)/2 for x,y in zip(lower,upper)]
momentum = [gram*x for x in common]
energy_current = [elastic*x for x in common]
stress = [[elastic*(upper[i]*lower[j]+lower[i]*upper[j])/2+(i==j)*lag
for j in range(3)] for i in range(3)]
return e1-e0,rho,momentum,energy_current,stress
def two_mode_demo():
C = mixing()
gap = sqrt((C_UPPER-1)**2+4*C[0][1]**2)
eigen = ((1+C_UPPER-gap)/2,(1+C_UPPER+gap)/2)
assert eigen[0]>0 and Z*Z-GAP2>0
print(f"Two-field fit b={C[0][1]:.11f}; gradient eigenvalues={eigen}")
rest_secant = C_UPPER/(2*Z)
fourth = 24*(C[0][1]**2/(2*Z*GAP2)-C_UPPER**2/(8*Z**3))
print(f"Rest secant={rest_secant:.9f}; fourth derivative={fourth:.7f}")
for k,target in ((.025,.401308395),(.05,.402219349),(.10,.406214726)):
energy,_ = upper_mode((0.,0.,k),C)
sec = (energy-Z)/k**2
print(f" k={k:.3f}: S={sec:.9f}; target={target:.9f}; residual={sec-target:+.9f}")
assert abs(sec-target)<(.00047 if k==.10 else .000007)
lower = (.07,.04,.03)
q = .08
upper = (*lower[:2],lower[2]+q)
w,rho,p,j,stress = mixed_beat(C,lower,upper)
assert abs(w*rho-q*j[2])<2e-14
assert max(abs(w*p[i]-q*stress[2][i]) for i in range(3))<2e-14
bare = q*p[2]-w*rho
assert abs(bare)>.001 and 0<w<q
delta = p[2]-j[2]
amp = q*delta/(q*q-w*w)
full_rho = rho-w*amp
full_p = [p[0],p[1],p[2]-q*amp]
full_stress = [[stress[i][j]-(i==j)*w*amp for j in range(3)] for i in range(3)]
tensor = [[full_rho]+full_p]+[[full_p[i]]+full_stress[i] for i in range(3)]
divergences = [q*tensor[3][nu]-w*tensor[0][nu] for nu in range(4)]
assert max(map(abs,divergences))<1e-13
assert max(abs(tensor[i][j]-tensor[j][i]) for i in range(4) for j in range(4))<1e-15
plus = (tensor[1][1]-tensor[2][2])/2
cross = tensor[1][2]
assert min(abs(plus),abs(cross))>1e-3
print(f" beat omega={w:.9f} q={q:.3f}, bare q*p_z-omega*rho={bare:+.9f}")
print(f" rho={rho:.9f}, p_z={p[2]:.9f}, J_z={j[2]:.9f}, D={amp:.9f}")
print(f" complete source rho={full_rho:.9f}, flux_z={full_p[2]:.9f}, stress_zz={tensor[3][3]:.9f}")
print(f" TT plus={plus:.9f}, cross={cross:.9f}, max Ward residual={max(map(abs,divergences)):.3g}")
# Start with an unperturbed material clock and an already prepared beat.
# This retarded analytic solution contains both the driven and free waves.
worst = 0.
for t in (0.,.7,3.,13.,30.):
f = exp(-1j*w*t)
y = -1j*amp*(f-cos(q*t)+1j*w*sin(q*t)/q)
dy = -1j*amp*(-1j*w*f+q*sin(q*t)+1j*w*cos(q*t))
ddy = -1j*amp*(-w*w*f+q*q*cos(q*t)-1j*w*q*sin(q*t))
if t==0:
assert abs(y)+abs(dy)<1e-14
assert abs(ddy+q*q*y+1j*q*delta*f)<1e-14
residuals = [-1j*w*rho*f+ddy+1j*q*(p[2]*f-1j*q*y)]
for i in range(3):
residuals.append(-1j*w*p[i]*f-(i==2)*1j*q*dy
+1j*q*(stress[2][i]*f+(i==2)*dy))
worst = max(worst,*map(abs,residuals))
print(f" zero-initial-support beat max four-divergence={worst:.3g}")
assert worst<1e-13
if __name__=="__main__":
exact=solve(1.,9/4,0.,0.,.5)
assert max(abs(a-b) for a,b in zip(exact,(4/3,2/3,1/3)))<1e-14
solve(1.90,1.52384402,.07,.03,.08)
solve(1.90,1.52882751,.07,.03,.08)
two_mode_demo()
binding_charge.py
"""Active charge of a weakly self-bound pair in a uniform scalar background."""
from math import hypot, sqrt, fsum
M0 = 2.
MU = .5
ALPHA = .2
def binding(mu,a):
return mu*ALPHA**2/(1+hypot(1,mu*ALPHA*a))
def numerical(A,a,lapse,pinned_step=True):
# Dirichlet radial half-line; fixed distant boundary well outside the pair.
if not pinned_step:
a = a/A
mu = MU/A if lapse else A*MU
count = round(280/a)
t = 1/(2*mu*a*a)
diagonal = [2*t-ALPHA/(i*a) for i in range(1,count+1)]
lo,hi = -ALPHA/a,0.
# Sturm count for the smallest eigenvalue of the actual tridiagonal matrix.
for _ in range(66):
center = (lo+hi)/2
pivot = 1.
below = 0
for i,v in enumerate(diagonal):
pivot = v-center-(t*t/pivot if i else 0.)
if abs(pivot)<1e-28:
pivot = -1e-28
below += pivot<0.
if below:
hi = center
else:
lo = center
return A*M0+(lo+hi)/2
def main():
for a in (2.,1.,.5):
x=MU*ALPHA*a
B=binding(MU,a)
H=M0-B
falloff=1/(hypot(1,x)+x)
samples=[i*falloff**i for i in range(650)]
norm=fsum(x*x for x in samples)
kinetic=fsum((y-x)**2 for x,y in zip(samples,samples[1:]))/(2*MU*a*a*norm)
assert abs(kinetic-B/hypot(1,x))<2e-13
results=[]
for lapse,fixed in ((True,True),(False,True),(False,False)):
h=.0002
q=(numerical(1+h,a,lapse,fixed)-numerical(1-h,a,lapse,fixed))/(2*h)
predicted = M0+kinetic if lapse else (M0-kinetic if fixed else H)
assert abs(q-predicted) < 3e-9
assert abs(numerical(1,a,lapse,fixed)-H) < 1e-12
results.append(q)
print(f"a={a:g}: rest energy {H:.9f}; charge lapse {results[0]:.9f}, "
f"conformal, fixed cells {results[1]:.9f}, conformal, rescaled cells {results[2]:.9f}")
print("Continuum leading charges",M0+MU*ALPHA**2/2,M0-MU*ALPHA**2/2)
if __name__=='__main__':
main()
dipole.py
"""Far-zone scalar radiation of a circular pair with measured cubic band curvatures."""
from math import cos, sin, sqrt, pi
Z = 1.90
CUBIC = (1.52882750,1.52384400)
def orbit(curvatures, speed):
# r=c_phi=1. Choose G from the leading two-body circular-orbit law.
inertias = [Z/r for r in curvatures]
mass = sum(inertias)
mu = inertias[0]*inertias[1]/mass
positions = [inertias[1]/mass,-inertias[0]/mass]
gravity = speed**2*mu/Z**2
dipole = Z*sum(positions)
quadrupole = Z*sum(x*x for x in positions)
return positions, gravity, dipole, quadrupole
def spectrum(speed,curvatures=CUBIC):
positions,g,dipole,quadrupole = orbit(curvatures,speed)
expected = [g*dipole**2*speed**4/3,16*g*quadrupole**2*speed**6/15]
harmonics = [0.,0.]
angles, samples = 32,96
for j in range(angles+1):
cosine = -1+2*j/angles
transverse = sqrt(max(0,1-cosine**2))
sums = [[0.,0.],[0.,0.]]
for k in range(samples):
t = 2*pi*k/samples
value = 0.
for x in positions:
tau = t
for _ in range(5):
tau -= (tau-speed*transverse*x*cos(tau)-t)/(1+speed*transverse*x*sin(tau))
gamma = 1+speed*transverse*x*sin(tau)
value -= Z*speed**2*transverse*x*cos(tau)/gamma**3
for l,pair in enumerate(sums,1):
pair[0] += 2*value*cos(l*t)/samples
pair[1] += 2*value*sin(l*t)/samples
weight = 1 if j in (0,angles) else (4 if j%2 else 2)
for i,(a,b) in enumerate(sums):
harmonics[i] += g*weight*(a*a+b*b)/(6*angles)
return expected,harmonics
def main():
for v in (.03,.01,.003,.001):
expected, measured = spectrum(v)
ratio = measured[0]/measured[1]
print(f"v/c_phi={v:.3f}: dipole/quadrupole {expected[0]/expected[1]:.8f}, "
f"retarded first/second {ratio:.8f}, multipole checks "
f"{measured[0]/expected[0]:.8f}, {measured[1]/expected[1]:.8f}")
assert max(abs(1-a/b) for a,b in zip(measured,expected)) < .003
expected, measured = spectrum(.03,(CUBIC[0],CUBIC[0]))
assert expected[0]==0 and measured[0]/measured[1] < 1e-22
assert measured[1]>0
print("Identical charge-to-inertia ratios with equal charges cancel every odd orbital harmonic.")
if __name__=="__main__":
main()
mediating_field.py
"""Two fixed two-path sources and a quantized scalar field initially in its vacuum.
Run with NumPy and the adjacent source.py. Time and distance use its lattice units.
"""
from itertools import product
import numpy as np
from source import FieldPair, REST
BRANCHES = tuple(product(range(2),repeat=2))
# Positions in the native 25-cell box, kept fixed in physical units on refinement.
ARMS = np.array([[-6.,-2.],[2.,6.]]) * (56./25)
def field_couplings(n=25):
field = FieldPair(n=n,length=56.,width=2.2)
omega = np.sqrt(field.khat2)
norm = np.sqrt(2*field.stiffness*field.volume*omega)
# Each nonzero k has one annihilator. The Hermitian field also contains a_k†.
c = REST * np.exp(-1j*ARMS[:,:,None]*field.kz) * field.shape/norm
return field,omega,c
def evolve(omega,c,segments):
alpha = np.zeros((4,len(omega)),dtype=complex)
phase = np.zeros(4)
for duration,on_a,on_b in segments:
angle = omega*duration
rotate = np.exp(-1j*angle)
for z,(a,b) in enumerate(BRANCHES):
force = on_a*c[0,a]+on_b*c[1,b]
free = alpha[z]*rotate
delta = force*np.expm1(-1j*angle)/omega
phase[z] += np.sum(abs(force/omega)**2*(angle-np.sin(angle)))
phase[z] += np.vdot(free,delta).imag
alpha[z] = free+delta
rho = np.empty((4,4),dtype=complex)
for s,t in product(range(4),repeat=2):
damp = -.5*np.vdot(alpha[s]-alpha[t],alpha[s]-alpha[t]).real
angle = phase[s]-phase[t]+np.vdot(alpha[t],alpha[s]).imag
rho[s,t] = .25*np.exp(damp+1j*angle)
assert np.max(abs(rho-rho.conj().T))<1e-12
assert np.linalg.eigvalsh(rho)[0]>-1e-12
return rho
def observables(rho):
tensor = rho.reshape(2,2,2,2)
marginal_a = np.trace(tensor,axis1=1,axis2=3)
# Directly measurable phases of A (or B) conditioned on either remote arm.
a_from_b = np.angle(rho[0,2]*rho[1,3].conjugate())
b_from_a = np.angle(rho[0,1]*rho[2,3].conjugate())
# Trace norm of the partial transpose gives two-qubit negativity.
eigen = np.linalg.eigvalsh(tensor.transpose(0,3,2,1).reshape(4,4))
negativity = sum(max(0.,-v) for v in eigen)
return (a_from_b,b_from_a,4*abs(rho[0,2]),2*abs(marginal_a[0,1]),negativity)
def bell_readout(rho):
tensor = rho.reshape(2,2,2,2)
a = np.angle(np.trace(tensor,axis1=1,axis2=3)[0,1])
b = np.angle(np.trace(tensor,axis1=0,axis2=2)[0,1])
phases = np.exp(1j*np.array([0.,b,a,a+b]))
aligned = phases[:,None]*rho*phases.conj()
x = np.array([[0,1],[1,0]])
y = np.array([[0,-1j],[1j,0]])
z = np.diag([1,-1])
xx,yz,zy = [np.trace(aligned@np.kron(a,b)).real for a,b in ((x,x),(y,z),(z,y))]
return xx,yz,zy,(1+xx+abs(yz+zy))/4
def expectation_density(omega,c,t):
# The same field equation with commuting expectation-value sources.
# The path populations stay one half because the sources are pinned.
drives = np.array([c[0,a]+c[1,b] for a,b in BRANCHES])
mean = drives.mean(axis=0)
kernel = (omega*t-np.sin(omega*t))/omega**2
phases = 2*np.real(np.sum(drives.conj()*mean*kernel,axis=1))
state = np.exp(1j*phases)/2
return np.outer(state,state.conj())
def retarded_square(omega,c,t):
geometry = 2*np.real(np.conjugate(c[0,0]-c[0,1])*(c[1,0]-c[1,1]))
static = np.sum(geometry*t/omega)
# Analytic double time integral of the retarded commutator.
phase = np.sum(geometry*(omega*t-np.sin(omega*t))/omega**2)
return phase,static
def graph_check(n=25):
# Point sources: m-th power of the nearest-neighbour positive graph
# Laplacian cannot connect sites more than m edges apart.
ar = np.zeros((n,n,n))
br = np.zeros_like(ar)
ar[0,0,-6],ar[0,0,-2] = 1,-1
br[0,0,2],br[0,0,6] = 1,-1
sequence=[]
for _ in range(5):
sequence.append(np.vdot(ar,br).real)
br = 6*br-sum(np.roll(br,step,axis=i) for i in range(3) for step in (-1,1))
assert sequence==[0.,0.,0.,0.,-1.]
return sequence
def main():
for n in (25,35):
_,omega,c = field_couplings(n)
for t in (1.,28.,40.):
rho = evolve(omega,c,[(t,1,1)])
aphase,bphase,conditional,visibility,neg = observables(rho)
phase,static = retarded_square(omega,c,t)
assert abs(phase-aphase)<1e-12 and abs(phase-bphase)<1e-12
assert abs(visibility-conditional*abs(np.cos(phase/2)))<1e-12
print(f"n={n} t={t:4.0f} phase={phase:+.9f} static={static:+.9f} "
f"conditional_V={conditional:.8f} local_V={visibility:.8f} negativity={neg:.8f}")
if n==25 and t==40:
assert neg>.005 and abs(phase+.125366430)<1e-8
xx,yz,zy,F = bell_readout(rho)
classical = expectation_density(omega,c,t)
_,_,_,local_v,classical_neg = observables(classical)
F_classical = bell_readout(classical)[3]
print(f"Joint readout XX={xx:.8f} YZ={yz:.8f} ZY={zy:.8f} Bell fidelity={F:.8f}")
print(f"Expectation density local_V={local_v:.8f} negativity={classical_neg:.8f} F={F_classical:.8f}")
assert F>.51 and abs(F_classical-.5)<1e-12 and classical_neg<1e-13
twice=evolve(omega,c,[(t/2,1,1),(t/2,1,1)])
assert np.max(abs(twice-rho))<2e-14
if n==25:
# Once A is decoupled, any later unitary acting on B and the field
# leaves A's previous marginal (and its offdiagonal phase) intact.
stopped=evolve(omega,c,[(20.,1,0)])
later=evolve(omega,c,[(20.,1,0),(20.,0,1)])
def marginal(r):
return np.trace(r.reshape(2,2,2,2),axis1=1,axis2=3)
assert np.max(abs(marginal(later)-marginal(stopped)))<1e-13
a,b,_,_,neg=observables(later)
assert abs(a)<1e-12 and abs(b)>.001
print(f"A then B: A conditioned on B={a:+.10f}, B conditioned on A={b:+.10f}, "
f"negativity={neg:.8f}")
print("Point-source Laplacian powers 0 through 4:",graph_check())
if __name__=="__main__":
main()
measured_source.py
"""Replay Figure 3a of An et al., Nature Communications 17, 11425 (2026).
Default: Python 3 standard library, no network or data downloads.
Optional verification: --pdf <published PDF> (PyMuPDF) or
--png <official full-resolution Fig. 3 PNG> (Pillow).
Only the small set of numerical coordinates, annotations and calibration
constants is embedded. The publication's figure itself is not distributed.
"""
import argparse
from hashlib import sha256
from math import hypot, isclose
from pathlib import Path
from statistics import median
DOI = '10.1038/s41467-026-78187-4'
PDF_SHA256 = '4fff79489235248bd29ffa983d18c843b8416bd08a3a6abaeb5f13a4615d8487'
ARM_M = .023694
# Text labels and vertical band-boundary vector vertices, PDF points from the
# top of page 5. Data = separation, printed torque, 2-sigma half-width, x, y1, y2.
DATA = (
(.654, 11.16, 1.07, 96.691, 67.224, 72.147),
(.854, 9.80, 1.06,127.421, 77.207, 82.131),
(1.054, 7.47, 1.19,158.151, 85.221, 90.110),
(1.354, 6.16, 1.11,204.264, 94.389, 99.313),
(1.554, 4.94, 1.17,234.994, 99.109,103.998),
)
BOTTOM, TOP = 112.861, 56.358 # torque tick lines 2 and 14 aNm
def torque(y):
return 2+(BOTTOM-y)*12/(BOTTOM-TOP)
def model_values():
return [(torque((a+b)/2), (torque(a)-torque(b))/2)
for _,_,_,_,a,b in DATA]
def verify_pdf(path):
import fitz
print('PDF SHA-256:',sha256(path.read_bytes()).hexdigest())
# Several official hosts serve different PDF editions; these vector
# coordinates are for the typeset Nature PDF identified by this checksum.
assert sha256(path.read_bytes()).hexdigest() == PDF_SHA256
doc=fitz.open(path)
drawings=doc[4].get_drawings()
selected=[d for d in drawings if d['type']=='f' and d['fill']
and d['fill'][0]>.98 and .74<d['fill'][1]<.77
and 150<d['rect'].width<170 and 38<d['rect'].height<45]
assert len(selected)==1
points=[p for item in selected[0]['items'] if item[0]=='l' for p in item[1:]]
for s,_,_,x,y1,y2 in DATA:
yy=sorted(set(round(p.y,3) for p in points if abs(p.x-x)<.002))
assert yy==[y1,y2],(s,yy)
axes=[d['rect'] for d in drawings if d['type']=='s' and d['rect'].width>180
and d['rect'].x0<75 and d['rect'].height<.001]
assert all(any(abs(r.y0-y)<.002 for r in axes) for y in (TOP,BOTTOM))
print('Vector band vertices and torque-axis calibration verified.')
def verify_png(path):
from PIL import Image
image=Image.open(path).convert('RGB')
assert image.size==(950,661)
results=[]
for col,(model,_) in zip((181,309,437,629,757),model_values()):
centers=[]
for dist in range(6,13): # brackets the black marker and its error bar
shoulder=[]
for x in (col-dist,col+dist):
yy=[]
for y in range(60,251):
r,g,b=image.getpixel((x,y))
if r>235 and 140<g<230 and abs(g-b)<7:
yy.append(y)
shoulder.append((min(yy)+max(yy))/2)
centers.append(sum(shoulder)/2)
value=2+(266-median(centers))*12/(266-31)
results.append(value)
assert abs(value-model)<.02
print('Independent raster torque readout in aNm:',*[round(a,3) for a in results])
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--pdf',type=Path)
parser.add_argument('--png',type=Path)
args=parser.parse_args()
model=model_values()
tau0,err0=DATA[0][1:3]
print('mm observed torque [2sigma] modeled torque [2sigma] calibrated prediction '
'held residual force measured [2sigma] / model / prediction (aN)')
for j,((s,obs,bar,*_), (mu,band)) in enumerate(zip(DATA,model)):
ratio=mu/model[0][0]
pred=tau0*ratio
residual=obs-pred
denom=hypot(bar/2,ratio*err0/2)
print(f'{s:.3f} {obs:.2f} [{bar:.2f}] {mu:.3f} [{band:.3f}] '
f'{pred:.3f} {residual:+.3f} {obs/ARM_M:.1f} [{bar/ARM_M:.1f}] '
f'/ {mu/ARM_M:.1f} / {pred/ARM_M:.1f}')
if j:
assert abs(residual)<bar
print(f' illustrative standardized residual, independent observations and fixed shape: '
f'{residual/denom:+.3f}')
assert abs(model[0][0]-11.17)<.005 and abs(model[0][1]-.52)<.005
force,df=471e-18,23e-18
geometry,dgeom=7.06e-6,.16e-6
newton=force/geometry
relative=hypot(df/force,dgeom/geometry)
print(f'G = ({newton/1e-11:.5f} +/- {newton*relative/1e-11:.5f})e-11 SI, '
f'1-sigma relative {100*relative:.3f}%')
assert isclose(newton,6.67138810198e-11,rel_tol=1e-11)
if args.pdf: verify_pdf(args.pdf)
if args.png: verify_png(args.png)
if __name__=='__main__':
main()
pair_elastic.py
"""Static interaction of two measured pair deformation tensors through an elastic solid."""
from math import pi, sqrt
import numpy as np
# Hellmann-Feynman rest slopes for the unit inverse-length hopping law; see strain_vertex.py.
PAIR = np.diag([4.40845221,4.28496763,3.95127298])
def kelvin(axis, first, second, lame=1., shear=1.):
"""Coefficient of 1/r**3 outside the contact, from two derivatives of Kelvin's tensor."""
n = np.asarray(axis,dtype=float)
n /= np.linalg.norm(n)
a, b = n@first@n, n@second@n
product = first@second
c = n@product@n
tr1, tr2, trp = np.trace(first),np.trace(second),np.trace(product)
hessian = 3*c-trp
angular = tr1*tr2+trp-3*(tr1*b+tr2*a+3*c)+15*a*b
return ((lame+3*shear)*hessian+(lame+shear)*angular)/(8*pi*shear*(lame+2*shear))
def fourier(r, axis, first, second, sigma=1., lame=1., shear=1., order=256):
"""Independent inverse Fourier integral; each packet is an isotropic Gaussian."""
axis = np.asarray(axis,dtype=float)
axis /= np.linalg.norm(axis)
ref = np.eye(3)[np.argmin(abs(axis))]
e1 = np.cross(ref,axis)
e1 /= np.linalg.norm(e1)
e2 = np.cross(axis,e1)
t,w = np.polynomial.legendre.leggauss(order)
phi = np.arange(16)*2*pi/16
circ = np.cos(phi)[:,None]*e1+np.sin(phi)[:,None]*e2
unit = t[:,None,None]*axis+np.sqrt(1-t*t)[:,None,None]*circ
ja,jb = unit@first,unit@second
trans_long = (ja*jb).sum(axis=-1)/shear
corr = (1/(lame+2*shear)-1/shear)*(unit*ja).sum(axis=-1)*(unit*jb).sum(axis=-1)
spectral = -(trans_long+corr).mean(axis=1)
phase = r*t/(2*sigma)
radial = sqrt(pi)/(4*sigma**3)*(1-2*phase**2)*np.exp(-phase**2)
return (w@(spectral*radial))/(4*pi*pi)
def main():
eye=np.eye(3)
for n in np.eye(3):
assert abs(kelvin(n,eye,eye))<1e-14
r=2.
isotropic=-np.exp(-r*r/4)/(3*(4*pi)**1.5)
assert abs(fourier(r,[1,0,0],eye,eye)-isotropic)<1e-12
vals=[]
for label,axis in [('x',[1,0,0]),('y',[0,1,0]),('z',[0,0,1]),('xyz',[1,1,1])]:
v=kelvin(axis,PAIR,PAIR)
u1=30**3*fourier(30.,axis,PAIR,PAIR)
u2=60**3*fourier(60.,axis,PAIR,PAIR)
# Extrapolate the leading finite-profile correction, proportional to sigma^2/r^2.
assert abs((4*u2-u1)/3-v)<2e-8
vals.append(v)
print(f'{label}: point r^3 U={v:+.9f}, Gaussian r=30 {u1:+.9f}, r=60 {u2:+.9f}')
assert min(vals)<0<max(vals)
# A universal inverse-distance term is absent even if the elastic constants are rescaled.
assert abs(kelvin([1,0,0],PAIR,PAIR,2.,2.)-vals[0]/2)<1e-12
print('Isotropic point couplings reduce to a contact; anisotropic pair couplings have both signs.')
if __name__=="__main__":
main()
strain_vertex.py
"""Long-wavelength acoustic vertex of the ordered 3D pair. Requires NumPy.
Usage: python strain_vertex.py [mesh] [momentum ...]. Dimensionless energy.
"""
import argparse
from pathlib import Path
import sys
import numpy as np
if not (Path(__file__).parent / 'bound_3d.py').exists():
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'shell-clocks'))
import bound_3d as model
from form_factor import block, bound, wave
def coefficients(k, strain=0., derivative=False, axis=2):
"""Fixed-orbital hopping t_delta times old length/new length under axial stretch."""
x,y,z=k
cosine=list(map(np.cos,k))
def factor(fraction):
if derivative:
return -fraction # at strain zero
return (1+(2*strain+strain**2)*fraction)**-.5
spin=[np.sin(x)*cosine[1]*cosine[2],np.sin(y)*cosine[2],np.sin(z)]
spin=[v*factor(1/(3-i) if axis>=i else 0.) for i,v in enumerate(spin)]
mass=10*factor(0.)
for i,c in enumerate(cosine):
mass=mass+factor(float(axis==i))*(-16*c+np.cos(2*k[i]))/3
for j in range(i):
mass=mass+2*factor(.5 if axis in (i,j) else 0.)*c*cosine[j]
return (*spin,mass)
def matrix(coeffs):
arrays = np.stack(np.broadcast_arrays(*coeffs),axis=-1).reshape(-1,4)
return (arrays @ np.array(model.GAMMA[1:]).reshape(4,16)).reshape(-1,4,4)
def strained_mode(k,shape,strain):
values=coefficients(k,strain)
energy=np.sqrt(sum(v*v for v in values))
vec=np.stack([np.broadcast_to(v/energy,shape).ravel() for v in values],axis=1)
return energy.ravel(),vec
def pole_at_strain(torus,cal,k,contact,strain):
original=model.mode
try:
# Reuse the published, unmodified four-sector resolvent and its energy derivative.
model.mode=lambda momenta,shape: strained_mode(momenta,shape,strain)
return bound(torus,cal,2,k,contact)[0]
finally:
model.mode=original
def expect(torus,cal,k,contact,strain_axis=2):
energy,src=bound(torus,cal,2,k,contact)
spin=(model.BASIS@src).reshape(4,4)
total=0j
norm=0.
n=torus.size
for lo in range(0,n,3):
ks=[p*2*np.pi/n for p in (torus.grid[0][lo:lo+3],*torus.grid[1:])]
ka=[ks[0],ks[1],ks[2]+k/2]
kb=[-ks[0],-ks[1],-ks[2]+k/2]
ha,a=block(ka)
hb,b=block(kb)
psi=wave(spin,energy,ha,a,hb,b)
za=matrix(coefficients(ka,derivative=True,axis=strain_axis))
zb=matrix(coefficients(kb,derivative=True,axis=strain_axis))
total+=np.vdot(psi,za@psi+psi@zb.swapaxes(1,2))
norm+=np.vdot(psi,psi).real
assert abs(norm/n**3-1)<5e-11 and abs(total.imag/n**3)<5e-11
# psi(on coincidence) = (contact/g) src; dE/dg for the chosen contact.
lam=cal[1]
dg=lam**2*(src.conj()@contact@src).real
return energy,total.real/n**3,dg
def bond_check():
"""Check all Fourier hoppings directly under a finite stretch and a soft wave."""
n=5
grid=np.ogrid[0:n,0:n,0:n]
hs,_=block([p*(2*np.pi/n) for p in grid])
hops=np.fft.ifftn(hs.reshape(n,n,n,4,4),axes=(0,1,2))
k=np.array([.31,-.23,.19])
stretch=.017
eps=1e-4
h=np.zeros((4,4),complex)
soft=h.copy()
zero=h.copy()
for pos in np.ndindex(n,n,n):
delta=np.array([j if j<=2 else j-n for j in pos])
d2=delta@delta
bare=hops[pos]*np.exp(-1j*(k@delta))
if not d2:
h+=bare
continue
w=delta[2]**2/d2
h+=bare/np.sqrt(1+(2*stretch+stretch**2)*w)
# Displacement u_z=exp(iqz), Fourier vertex between p-q/2 and p+q/2.
soft+=bare*(-delta[2]/d2)*2j*np.sin(eps*delta[2]/2)
zero+=bare*(-delta[2]/d2)*2j*np.sin(0.)
assert abs(h-matrix(coefficients(k,stretch))[0]).max()<3e-13
assert abs(soft/(1j*eps)-matrix(coefficients(k,derivative=True))[0]).max()<3e-9
assert not np.any(zero)
def standing_strain(torus,cal,q,contact):
"""Off-forward longitudinal displacement vertex divided by iq, K_i,f=∓q/2."""
n=torus.size
energy,sf=bound(torus,cal,2,q/2,contact)
si=model.BETA_PAIR@sf
ui,uf=[(model.BASIS@s).reshape(4,4) for s in (si,sf)]
nrm=0.
total=0j
# Every active Fourier hop has |delta_z|=1, except cos(2z).
short=np.sinc(q/(2*np.pi))
long=np.sinc(q/np.pi)
for lo in range(0,n,3):
ks=[p*2*np.pi/n for p in (torus.grid[0][lo:lo+3],*torus.grid[1:])]
h0,a0=block([ks[0],ks[1],ks[2]-q/2])
h1,a1=block([ks[0],ks[1],ks[2]+q/2])
hb,b=block([-k for k in ks])
wi=wave(ui,energy,h0,a0,hb,b)
wf=wave(uf,energy,h1,a1,hb,b)
vals=[c*short for c in coefficients(ks,derivative=True)]
vals[-1]=vals[-1]-(long-short)*np.cos(2*ks[2])/3
total+=2*np.vdot(wf,matrix(vals)@wi)
nrm+=np.vdot(wi,wi).real
assert abs(total.imag/n**3)<1e-10 and abs(nrm/n**3-1)<2e-5
return total.real/n**3
def equal_energy(torus,cal,target):
"""Match the two moving preparations by excitation energy on the positive-z ray."""
rows=[]
for name,contact in (('density',model.IDENTITY),('mass',model.BETA_PAIR)):
def residual(k):
vals,vec=np.linalg.eigh(torus.green(target,2,k)-cal[1]*contact)
return vals[np.argmax(abs(vec.conj().T@cal[2]))]
old=0.
k=np.sqrt(2*torus.rest*(target-torus.rest)/1.4)
f_old,f_now=residual(old),residual(k)
for _ in range(10):
if abs(f_now)<1e-14:
break
new=k-f_now*(k-old)/(f_now-f_old)
old,k,f_old=k,new,f_now
f_now=residual(k)
if abs(f_now)>1e-13:
raise ArithmeticError('moving pole did not converge')
e,d,p=expect(torus,cal,k,contact)
assert abs(e-target)<4e-13 and abs(k)<=.2
print(f' matched E={e:.6f}: {name:7} K={k:.9f} Dzz={d:.9f} dE/dg={p:.9f}')
rows.append((d,p))
d,p=np.subtract(rows[1],rows[0])
print(f' matched-energy split {d:+.9f}, cancellation g-prime={-d/p:.6f}')
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('mesh',type=int,nargs='?',default=40)
parser.add_argument('momentum',type=float,nargs='*',default=[0.,.10,.20])
parser.add_argument('--matched',action='store_true',help='also match two moving energies')
parser.add_argument('--wave',action='store_true',help='check finite-q standing-strain matrix elements')
args=parser.parse_args()
bond_check()
torus=model.Torus(args.mesh)
cal=model.rest_calibration(torus)
print(f'mesh {args.mesh}, fixed g {1/cal[1]:.10f}')
# Uniform speed bound separates these poles from the mixed-sign continuum.
c=(7-np.sqrt(57))/4
vmax=np.sqrt(1+(1-c*c)*(28/3-4*c/3)**2)
assert .20*vmax<torus.rest
print('Bellec Table I dimensionless hopping secants:',
np.log(np.array([29.8/16.9,29.2/15.9]))/np.log(15/13))
rest_tensor=[expect(torus,cal,0.,model.IDENTITY,strain_axis=j)[1] for j in range(3)]
print('rest Dxx,Dyy,Dzz:',np.round(rest_tensor,9),flush=True)
for k in args.momentum:
for name,contact in (('density',model.IDENTITY),('mass',model.BETA_PAIR)):
if abs(k)>.20:
raise ValueError('replay certifies only |Kz| <= 0.20')
energy,dz,dg=expect(torus,cal,k,contact)
step=4e-5
fd=[]
for e in (step,step/2):
fd.append((pole_at_strain(torus,cal,k,contact,e)-
pole_at_strain(torus,cal,k,contact,-e))/(2*e))
extrapolated=(4*fd[1]-fd[0])/3
assert abs(extrapolated-dz)<5e-8
print(f' {k:.3f} {name:7} E={energy:.9f} Dzz={dz:.9f} '
f'dE/dg={dg:.9f} HF-minus-strained-pole={dz-extrapolated:.2g}',flush=True)
if args.wave:
for q in (.20,.10,.05):
dz=[standing_strain(torus,cal,q,c) for c in (model.IDENTITY,model.BETA_PAIR)]
print(f' standing strain q={q:.3f}: D_density={dz[0]:.9f}, D_mass={dz[1]:.9f}')
if args.matched:
for target in (1.904,1.912):
equal_energy(torus,cal,target)
if __name__=='__main__':
main()
optical_range.py
"""Static optical/acoustic mixing and the range allowed by a free solid's bulk stability."""
from math import exp, pi, sqrt
import numpy as np
from pair_elastic import PAIR, kelvin
def longest_range(gap, gradient):
eigenvalues, rotation = np.linalg.eigh(gap)
scale = (rotation/np.sqrt(eigenvalues))@rotation.T
return np.sqrt(np.linalg.eigvalsh(scale@gradient@scale)[-1])
def main():
bulk, shear = 5/3,1.
longitudinal = bulk+4*shear/3
coupling, gap, gradient = 1.,1.,1.
stable_bulk = bulk-coupling**2/gap
long_soft = stable_bulk+4*shear/3
length = sqrt(gradient/(gap-coupling**2/longitudinal))
cap = sqrt(longitudinal/(longitudinal-bulk))
assert abs(length*sqrt(long_soft*gap)-sqrt(gradient*longitudinal))<1e-14
assert stable_bulk>0 and length<cap
mean_charge = np.trace(PAIR)/3
# Retain only the isotropic part of the computed pair tensor in this radial example.
strength = (coupling*mean_charge/longitudinal)**2/(4*pi*gradient)
for r in (.5,1.,2.,4.,8.):
force = -strength*exp(-r/length)*(1+r/length)/r**2
print(f'r={r:g}, radial optical force={force:+.8f}, '
f'inverse-square fraction={-force*r**2/strength:.6f}')
print(f'bare optical range=1; mixed range={length:.8f}; free-solid limit={cap:.8f}')
# Compare the direct coupled response to eliminating the longitudinal displacement first.
for axis in ([1.,0.,0.],[1.,2.,3.],[0.,0.,1.]):
n=np.array(axis)/np.linalg.norm(axis)
dn=PAIR@n
d=n@dn
for q in (.002,.37,4.):
kernel = np.zeros((4,4))
kernel[:3,:3]=q*q*(shear*np.eye(3)+(longitudinal-shear)*np.outer(n,n))
kernel[:3,3] = kernel[3,:3] = coupling*q*n
kernel[3,3]=gap+gradient*q*q
source=np.r_[q*dn,0.]
direct=-source@np.linalg.solve(kernel,source)
bare=-(dn@dn-d*d)/shear-d*d/longitudinal
predicted=bare-(coupling*d/longitudinal)**2/(gap-coupling**2/longitudinal+gradient*q*q)
assert abs(direct-predicted)<8e-13
# At long distances the relaxed Lamé coefficient is lambda-b^2/gap.
vals=[kelvin(v,PAIR,PAIR,lame=0.,shear=1.) for v in np.eye(3)]
print('relaxed axial r^3 U:',*[f'{x:+.9f}' for x in vals])
assert vals[0]>0>vals[-1]
# Noncommuting optical mass and gradient matrices. Approach the free bulk limit.
mass=np.array([[1.2,.25],[.25,1.8]])
grad=np.array([[1.,-.3],[-.3,1.5]])
b=np.array([.7,-.3])
stiffness_drop=b@np.linalg.solve(mass,b)
for fraction in (.3,.9,.999):
fitted=b*sqrt(fraction*bulk/stiffness_drop)
relaxed=mass-np.outer(fitted,fitted)/longitudinal
ratio=longest_range(relaxed,grad)/longest_range(mass,grad)
assert 1 <= ratio < cap
print(f'two optical modes, relaxed fraction={fraction:g}, range ratio={ratio:.8f}')
# At nonzero shear the apparent longitudinal critical point is bulk-unstable.
assert bulk-longitudinal<0
if __name__=="__main__":
main()
crystal_recoil.py
"""Momentum exchange between two band-edge waves and a winding sine-Gordon field."""
from math import cos, sin, sqrt, pi
import numpy as np
class Crystal:
def __init__(self, k, n=192, m0=1.):
# Integrate dx/dtheta over two primitive cells; all dynamical arrays are periodic.
theta = np.linspace(0., 2*pi, 131073)
metric = k/np.sqrt(1-k*k*np.sin(theta)**2)
coordinate = np.r_[0., np.cumsum((metric[:-1]+metric[1:])*pi/(len(theta)-1))]
self.length = coordinate[-1]
self.a = self.length/2
self.dx = self.length/n
theta = np.interp(np.arange(n)*self.dx, coordinate, theta)
self.sn, self.cn = np.sin(theta), np.cos(theta)
self.k, self.m0 = k, m0
self.tilt = 4*pi/self.length
self.winding = self.tilt*np.arange(n)*self.dx
self.b = pi+2*theta-self.winding
self.mode = 2*pi*np.fft.fftfreq(n, self.dx)
self.wc = sqrt(m0*m0+1/k**2)
self.ws = sqrt(self.wc**2+1.)
def derivative(self, values, n=1):
return np.fft.ifft((1j*self.mode)**n*np.fft.fft(values)).real
def accelerations(self, b, wave):
phi = self.winding+b
return (self.derivative(b, 2)-np.sin(phi)*(1-wave**2/2),
self.derivative(wave, 2)-(self.m0**2+1+np.cos(phi))*wave)
def totals(self, b, wave, db, dw):
phi = self.winding+b
dphi = self.tilt+self.derivative(b)
grad = self.derivative(wave)
u = self.m0**2+1+np.cos(phi)
energy = (db**2+dphi**2+dw**2+grad**2+u*wave**2)/2 + 1-np.cos(phi)
# Integrals per primitive cell; the full simulation uses two cells.
return np.array([energy.sum(), -(db*dphi).sum(), -(dw*grad).sum()])*self.dx/2
def check_static(self):
phi = self.winding+self.b
dphi = self.tilt+self.derivative(self.b)
pressure = 2/self.k**2-2
energy = ((dphi*dphi/2+1-np.cos(phi)).sum())*self.dx/2
inertia = (dphi*dphi).sum()*self.dx/2
assert abs(energy+pressure*self.a-inertia)<1e-8
potential = self.m0**2+1+np.cos(phi)
for profile, frequency in ((self.cn,self.wc),(self.sn,self.ws)):
residual = self.derivative(profile,2)+(frequency**2-potential)*profile
assert np.max(abs(residual))<3e-5
coeff = (-np.sin(phi)*dphi*self.cn*self.sn).sum()*self.dx/2
assert abs(coeff-pi/2)<2e-8
print(f"k={self.k:g} a={self.a:.8f} E={energy:.8f} boost inertia={inertia:.8f} "
f"pressure={pressure:.8f} exchange coefficient={coeff:.10f}")
def release(self, amplitude, dt, stop=4.):
b = self.b.copy()
wave = amplitude*(self.cn+self.sn)
db, dw = np.zeros_like(b), np.zeros_like(wave)
base = self.totals(b,wave,db,dw)
ab, aw = self.accelerations(b,wave)
drift, error, peak = 0., 0., 0.
for j in range(1, round(stop/dt)+1):
db += dt*ab/2
dw += dt*aw/2
b += dt*db
wave += dt*dw
ab, aw = self.accelerations(b,wave)
db += dt*ab/2
dw += dt*aw/2
if j%10:continue
t = j*dt
energy, pm, pw = self.totals(b,wave,db,dw)
pred = pi*amplitude**2/2*(self.ws*sin(self.ws*t)*cos(self.wc*t)
-self.wc*sin(self.wc*t)*cos(self.ws*t))
assert abs(pm+pw)<1e-10
drift = max(drift,abs(energy-base[0]))
error = max(error,abs(pred-pm))
peak = max(peak,abs(pm))
assert drift<3e-6 and peak>amplitude**2
print(f"A={amplitude:.3f} dt={dt:.4f} Pmaterial(t=4)={pm:+.9g} "
f"Pwave={pw:+.9g} peak={peak:.9g} residual={error:.3g} energy drift={drift:.3g}")
return error,pm
def main():
for k in (.65,.8,.93):
Crystal(k).check_static()
model = Crystal(.8)
large = model.release(.08,.0025)
small = model.release(.04,.0025)
fine = model.release(.04,.00125)
assert 13 < large[0]/small[0] < 19
assert abs(small[1]-fine[1])<2e-8
if __name__=="__main__":
main()
excited_kink.py
"""Isolated spinning mode on a mobile kink: rest energy, stress and boosted momentum."""
from math import sqrt
import numpy as np
def solve_blocks(diagonal, rhs, link):
"""Thomas elimination with two-component spatial blocks and multiple right sides."""
n = len(diagonal)
upper = np.empty_like(diagonal)
value = np.empty_like(rhs)
for i in range(n):
block = diagonal[i] if i==0 else diagonal[i]-link*upper[i-1]
source = rhs[i] if i==0 else rhs[i]-link*value[i-1]
inverse = np.linalg.inv(block)
upper[i] = link*inverse
value[i] = inverse@source
for i in range(n-2,-1,-1):
value[i] -= upper[i]@value[i+1]
return value
def profile(amplitude, dx, length=16., m0=1.):
x = np.arange(round(length/dx)+1)*dx
sech = 1/np.cosh(x)
phi = 4*np.arctan(np.exp(x))-amplitude**2*sech*np.tanh(x)/4
f = amplitude*sech
phi[-1], f[-1] = 2*np.pi,0.
z = m0**2+1.
inv = 1/dx**2
for iteration in range(18):
h, a = phi[1:-1], f[1:-1]
sn,cs = np.sin(h), np.cos(h)
u = m0**2+1+cs
eq = np.stack((-inv*np.diff(phi,2)+(1-a*a/2)*sn,
-inv*np.diff(f,2)+(u-z)*a),axis=1)
end = 2*inv*(f[0]-f[1])+(m0**2-z)*amplitude
residual = max(np.max(abs(eq)),abs(end))
if residual<3e-10:break
blocks = np.empty((len(h),2,2))
blocks[:,0,0] = 2*inv+(1-a*a/2)*cs
blocks[:,0,1] = blocks[:,1,0] = -a*sn
blocks[:,1,1] = 2*inv+u-z
rhs = np.zeros_like(blocks)
rhs[:,:,0] = -eq
rhs[:,1,1] = a
delta = solve_blocks(blocks,rhs,-inv)
dz = (end-2*inv*delta[0,1,0])/(amplitude+2*inv*delta[0,1,1])
correction = delta[:,:,0]+delta[:,:,1]*dz
phi[1:-1] += correction[:,0]
f[1:-1] += correction[:,1]
z += dz
else:
raise ArithmeticError("Stationary solution did not converge")
assert np.min(f)>-1e-10 and np.max(np.diff(f))<1e-7 and z<m0**2+2
return x,phi,f,sqrt(z),residual
def measure(amplitude,dx):
x,phi,f,w,residual = profile(amplitude,dx)
integ = lambda a: 2*np.trapz(a,x)
hp = np.gradient(phi,x,edge_order=2)
fp = np.gradient(f,x,edge_order=2)
hp[0] = (phi[1]-np.pi)/dx # odd reflection for phi-pi about the center
fp[0] = 0.
u = 2+np.cos(phi)
host_v = 1-np.cos(phi)
wave_v = u*f**2/2
eh = integ(hp**2/2+host_v)
ew = integ((fp**2+(w*f)**2)/2+wave_v)
sh = integ(hp**2/2-host_v)
sw = integ((fp**2+(w*f)**2)/2-wave_v)
point_stress = (hp**2+fp**2+(w*f)**2)/2-host_v-wave_v
total=eh+ew
v=.45
gamma=1/sqrt(1-v*v)
# Differentiate the boosted fields, including the spatial rotation of their phase.
ht,hx=-gamma*v*hp,gamma*hp
ft,fx=-gamma*v*fp,gamma*fp
phase_t,phase_x=gamma*w,-gamma*w*v
eboost=integ((ht**2+hx**2+ft**2+fx**2+f**2*(phase_t**2+phase_x**2))/2+
host_v+wave_v)/gamma
pboost=integ(-ht*hx-ft*fx-f**2*phase_t*phase_x)/gamma
inertia=pboost/(gamma*v)
# Charge and the variational energy use the same second-difference discretization.
grad_energy=(np.diff(phi)**2+np.diff(f)**2).sum()/dx
evar=grad_energy+integ(host_v+wave_v+(w*f)**2/2)
charge=w*integ(f*f)
density=(hp**2+fp**2+(w*f)**2)/2+host_v+wave_v
frequency=.75
form=integ(density*np.cos(frequency*x))/total
# Differentiate the lapse-weighted rest energy of a translated profile.
# Average the left and right halves explicitly; retain the odd-in-shift term.
def shifted(shift):
lapse=(np.sin(frequency*(x+shift))+np.sin(frequency*(-x+shift)))/(2*frequency)
return integ(density*lapse)
step=.0001
assert abs((shifted(step)-shifted(-step))/(2*step*total)-form)<2e-8
assert abs(inertia-(total+sh+sw))<1e-10
assert abs(eboost/gamma-(total+v*v*(sh+sw)))<1e-10
return dict(A=amplitude,Q=charge,w=w,E=total,Evar=evar,host=sh,wave=sw,
inertia=inertia,form=form,peak=np.max(abs(point_stress)),residual=residual)
def main():
q=.75
bare_form=(np.pi*q/2)/np.sinh(np.pi*q/2)
print(f"bare isolated kink: E=8, finite-gradient response={bare_form:.9f} at q={q:g}")
for a in (.1,.6,1.):
coarse=measure(a,.02)
fine=measure(a,.01)
best=measure(a,.005)
print(f"A={a:g} Q={best['Q']:.8f} omega={best['w']:.8f} E={best['E']:.8f} "
f"internal pressure={best['wave']:+.8f} host={best['host']:+.8f} "
f"boost inertia={best['inertia']:.8f} max local stress={best['peak']:.2g} "
f"finite-gradient response={best['form']:.9f}")
errors=[abs(r['inertia']-r['E']) for r in (coarse,fine,best)]
assert errors[2]<3e-4 and errors[0]/errors[1]>3.5 and errors[1]/errors[2]>3.5
assert abs(best['E']-fine['E'])<.00015 and best['peak']<.00012
assert abs(best['form']-fine['form'])<1e-5
if a==.1:
assert abs(best['wave']/(2*a*a/3)-1)<.01
if a==.6:
lo,hi=(measure(b,.01) for b in (a-.001,a+.001))
dw=(hi['Evar']-lo['Evar'])/(hi['Q']-lo['Q'])
print(f"dE/dQ={dw:.9f} at A=.6; mode phase rate={fine['w']:.9f}")
assert abs(dw-fine['w'])<2e-6
if __name__=="__main__":
main()
mobile_host.py
"""Physical translation and differential driving of a mobile periodic host.
Python 3, standard library. The optional --paper accepts the authors' arXiv
source archive or its Impurity1DBO_FIG4A.pdf, checking printed marker positions.
"""
import argparse
from cmath import exp
from hashlib import sha256
from math import copysign, expm1, hypot, pi, sqrt
from pathlib import Path
import re
import tarfile
import zlib
M, HOST = 1., 4.
TOTAL = M+HOST
MU = M*HOST/TOTAL
G = 4 # reciprocal lattice vector; ring length 2π
V = 2. # V cos[G(x-y)]
TIME, ACCEL = .8, .35
PAPER_FIG = "abf66578dafc3539696d89b40515448c571acdf8f927e57e0ef1cdc8c4caf1c6"
GLYPH_ORIGINS = ((139.252,124.925),(154.758,102.777),(164.056,90.306),(170.574,80.940))
def bands(q, cutoff):
"""Jacobi diagonalization of the periodic relative-coordinate Hamiltonian."""
ns = list(range(-cutoff,cutoff+1))
n = len(ns)
a = [[0.]*n for _ in ns]
u = [[float(i==j) for j in range(n)] for i in range(n)]
for i,ell in enumerate(ns):
a[i][i] = (q+G*ell)**2/(2*MU)
if i:
a[i][i-1] = a[i-1][i] = V/2
for _ in range(60):
largest = 0.
for i in range(n):
for j in range(i+1,n):
off = a[i][j]
largest = max(largest,abs(off))
if abs(off) < 1e-14:
continue
tau = (a[j][j]-a[i][i])/(2*off)
t = copysign(1.,tau)/(abs(tau)+hypot(1.,tau))
c = 1/hypot(1.,t)
s = t*c
a[i][i] -= t*off
a[j][j] += t*off
a[i][j] = a[j][i] = 0.
for k in range(n):
if k != i and k != j:
x,y = a[k][i],a[k][j]
a[k][i]=a[i][k]=c*x-s*y
a[k][j]=a[j][k]=s*x+c*y
x,y=u[k][i],u[k][j]
u[k][i],u[k][j]=c*x-s*y,s*x+c*y
if largest<1e-13:
break
else:
raise ArithmeticError("relative band did not converge")
return sorted(((a[j][j],[row[j] for row in u]) for j in range(n)),key=lambda item:item[0])
def static_checks():
for q in (0.,1.,2.):
energy,u = bands(q,6)[0]
ds = .001
ep,em = (bands(q+t,6)[0][0] for t in (ds,-ds))
slope = (ep-em)/(2*ds)
curvature = (ep+em-2*energy)/ds**2
p = sum(abs(v)**2*(q+G*ell) for ell,v in zip(range(-6,7),u))
assert abs(slope-p/MU)<1e-6
if q==2:
assert abs(p)<1e-12 and curvature<0
if q==0:
assert curvature>0
print(f"q={q:g} ground E={energy:.7f} curvature={curvature:+.7f} "
f"at P=0 impurity momentum={p:+.7f} host={-p:+.7f}")
def packet(cutoff):
eigen = bands(1.,cutoff)[:2]
# Impurity + host momenta are integer pairs. These two sectors are related
# by the allowed common velocity boost one. Their internal twist is equal.
pairs = [(1+G*ell+boost,4*boost-1-G*ell) for boost in (0,1)
for ell in range(-cutoff,cutoff+1)]
def exact(t,g):
ans = []
for boost in (0,1):
p = TOTAL*boost
angle = p*p*t/(2*TOTAL)+p*g*t*t/2+TOTAL*g*g*t**3/6
common = exp(1j*(.4*boost-angle))/sqrt(2)
for i in range(2*cutoff+1):
ans.append(common*(sqrt(.7)*eigen[0][1][i]*exp(-1j*eigen[0][0]*t)
+1j*sqrt(.3)*eigen[1][1][i]*exp(-1j*eigen[1][0]*t)))
return ans
return pairs,exact
def dynamics(cutoff,steps,protocol):
pairs,exact = packet(cutoff)
lookup = {state:i for i,state in enumerate(pairs)}
neighbors = [[lookup[p] for p in ((n-G,h+G),(n+G,h-G)) if p in lookup]
for n,h in pairs]
edges = [(i,lookup[(n+G,h-G)]) for i,(n,h) in enumerate(pairs) if (n+G,h-G) in lookup]
forces = {"free":(0.,0.),"common":(M*ACCEL,HOST*ACCEL),"selective":(TOTAL*ACCEL,0.)}
fx,fy = forces[protocol]
def derivative(t,z):
result = []
for i,(n,h) in enumerate(pairs):
kinetic = (n+fx*t)**2/(2*M)+(h+fy*t)**2/(2*HOST)
result.append(-1j*(kinetic*z[i]+(V/2)*sum(z[j] for j in neighbors[i])))
return result
z = exact(0.,0.)
dt = TIME/steps
for i in range(steps):
t=i*dt
k1=derivative(t,z)
k2=derivative(t+dt/2,[v+dt*a/2 for v,a in zip(z,k1)])
k3=derivative(t+dt/2,[v+dt*a/2 for v,a in zip(z,k2)])
k4=derivative(t+dt,[v+dt*a for v,a in zip(z,k3)])
z=[v+dt*(a+2*b+2*c+d)/6 for v,a,b,c,d in zip(z,k1,k2,k3,k4)]
norm = sum(abs(v)**2 for v in z)
momentum = sum(abs(v)**2*(n+h+(fx+fy)*TIME) for v,(n,h) in zip(z,pairs))
density = sum(z[j].conjugate()*z[i] for i,j in edges)
assert abs(norm-1)<2e-8 and abs(momentum-(2.5+(fx+fy)*TIME))<1e-7
if protocol != "selective":
ref=exact(TIME,fx/M)
error=sqrt(sum(abs(v-u)**2 for v,u in zip(z,ref)))
assert error<1e-7
else:
error=None
return momentum,density,error
def figure_centers():
# Mathematica3 point glyph, centered 3.69,4.39 original graphic points
# from its graphic transform. Calibrated against the two labelled axes.
return [((x+3.69-83.596)/14.818,(165.624-y-4.39)/414.10) for x,y in GLYPH_ORIGINS]
def verify_figure(path):
if tarfile.is_tarfile(path):
with tarfile.open(path) as archive:
with archive.extractfile("Impurity1DBO_FIG4A.pdf") as handle:
pdf=handle.read()
else:
pdf=path.read_bytes()
if sha256(pdf).hexdigest()!=PAPER_FIG:
raise ValueError("the supplied file differs from the original author figure")
for marker in re.finditer(rb"stream\r?\n",pdf):
try:
stream=zlib.decompress(pdf[marker.end():])
except zlib.error:
continue
if b"83.596 165.624 m" not in stream or b"113.232 165.624 m" not in stream:
continue
glyphs=re.findall(rb"1 0 0 1 ([.0-9]+) ([.0-9]+) cm.{0,320}?/F1 9 Tf\s*\(\\346\) Tj",stream,re.S)
coordinates=[tuple(map(float,pair)) for pair in glyphs]
assert coordinates==list(GLYPH_ORIGINS)
print("Verified original figure hash, axis positions and all four point glyphs.")
return
raise ValueError("figure data stream was not found")
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("--paper",type=Path,help="check the original arXiv source archive or Fig. 4A PDF")
args=parser.parse_args()
if args.paper:
verify_figure(args.paper)
static_checks()
baseline=None
for cutoff,steps in ((4,400),(6,800)):
runs={tag:dynamics(cutoff,steps,tag) for tag in ("free","common","selective")}
for tag,(p,d,e) in runs.items():
error="" if e is None else f", state error={e:.3g}"
print(f"cutoff={cutoff} {tag:9} total physical momentum={p:.9f}, "
f"relative density wave={d.real:+.8f}{d.imag:+.8f}i{error}")
assert abs(runs["common"][1]-runs["free"][1])<1e-7
assert abs(runs["common"][1]-runs["selective"][1])>.05
if baseline:
assert max(abs(runs[k][1]-baseline[k][1]) for k in runs)<2e-6
baseline=runs
for ql in (.2,.4):
impurity=-expm1(-ql*ql/4)
common=impurity**2/2
# Independently sum the squared harmonic-oscillator transition amplitudes.
u2=ql*ql/4
weight=1-impurity
odd_even=even=0.
for n in range(1,17):
weight*=u2/n
odd_even+=weight
if n%2==0:
even+=weight
assert abs(odd_even-impurity)<2e-15 and abs(even-common)<2e-15
print(f"q*ell={ql:g} inelastic impurity={impurity:.8f} common mass={common:.8f}")
for force,frequency in figure_centers():
pred=force/pi**3
print(f"Cs dimensionless force={force:.3f}: measured f*tF={frequency:.4f}, "
f"2k_F prediction={pred:.4f}, residual={frequency-pred:+.4f}")
if __name__=="__main__":
main()
self_gravity.py
"""Nodeless spherical Einstein--Klein--Gordon equilibrium, standard library only."""
import argparse
from dataclasses import dataclass
from math import exp, sqrt
def rhs(x,y,w):
m,lapse_log,s,v=y
f=1-2*m/x
if f<.01 or abs(s)>2 or abs(lapse_log)>20:
raise ArithmeticError('strong-field trial left the shooting domain')
local=w*exp(-lapse_log)
t=(local*s)**2
grad=f*v*v
density=t+s*s+grad
radial=t-s*s+grad
mp=x*x*density
lp=(m/x**2+x*radial)/f
fp=2*(m/x**2-mp/x)
vp=(1-local**2)*s/f-(2/x+lp+fp/(2*f))*v
return mp,lp,v,vp
def rk4(x,y,h,w):
k1=rhs(x,y,w)
k2=rhs(x+h/2,tuple(a+h*b/2 for a,b in zip(y,k1)),w)
k3=rhs(x+h/2,tuple(a+h*b/2 for a,b in zip(y,k2)),w)
k4=rhs(x+h,tuple(a+h*b for a,b in zip(y,k3)),w)
return tuple(a+h*(b+2*c+2*d+e)/6 for a,b,c,d,e in zip(y,k1,k2,k3,k4))
def origin(x,c,w):
s2=(1-w*w)*c/6
m3=(w*w+1)*c*c/3
l2=(m3+(w*w-1)*c*c)/2
t2=2*w*w*(c*s2-l2*c*c)
grad2=4*s2*s2
m5=(t2+2*c*s2+grad2)/5
p2=t2-2*c*s2+grad2
l4=(m5+p2+4*m3*l2)/4
s4=((1-w*w)*(s2+2*m3*c)+2*w*w*l2*c-4*(l2-m3)*s2)/20
return (x**3*(m3+m5*x*x),x*x*(l2+l4*x*x),
c+x*x*(s2+s4*x*x),x*(2*s2+4*s4*x*x))
def integrate(c,w,r,n,keep=False):
"""Sign of outer growing tail. A zero or positive derivative brackets from inside."""
h=r/n
# Start on-grid with the regular central series to avoid the singular 2/x drift.
y=origin(h,c,w)
rows=[(0.,(0.,0.,c,0.)),(h,y)] if keep else None
try:
for i in range(1,n):
x=i*h
y=rk4(x,y,h,w)
if not keep:
if y[2]<=0:
return -1
if y[3]>=0:
return 1
if keep:
rows.append(((i+1)*h,y))
except (ArithmeticError,OverflowError):
if keep:
raise
return 1
if keep:
return rows
m,l,s,v=y
flat=exp(l)/sqrt(1-2*m/r)
freq=w/flat
if freq>=1:
return -1
decay=sqrt(1-freq*freq)
tail_power=m*(2*freq*freq-1)/decay-1
return 1 if v+(decay-tail_power/r)*s>0 else -1
@dataclass
class Star:
mass:float
charge:float
frequency:float
lapse0:float
komar:float
density_only:float
field_edge:float
def solve(c,r,n):
if n%2:
raise ValueError('Simpson integration requires an even interval count')
lo,hi=1.,1.6
assert integrate(c,lo,r,n)>0 and integrate(c,hi,r,n)<0
for _ in range(52):
mid=(lo+hi)/2
if mid in (lo,hi):
break
if integrate(c,mid,r,n)>0:
lo=mid
else:
hi=mid
w=(lo+hi)/2
rows=integrate(c,w,r,n,True)
m,l,tail,_=rows[-1][1]
a_inf=exp(l)/sqrt(1-2*m/r)
omega=w/a_inf
totals=[0.]*3
for i,(x,(mass,l,s,v)) in enumerate(rows):
if i==0:
continue
if s<=0 or v>0:
raise ArithmeticError('final profile is not positive and monotonically decreasing')
f=1-2*mass/x
alpha=exp(l)/a_inf
local=omega/alpha
t=(local*s)**2
grad=f*v*v
rho=t+s*s+grad
pr=t-s*s+grad
pt=t-s*s-grad
volume=x*x/sqrt(f)
terms=(volume*2*local*s*s,volume*alpha*(rho+pr+2*pt),volume*alpha*rho)
weight=1 if i==n else (4 if i%2 else 2)
for j,value in enumerate(terms):
totals[j]+=weight*value
q,k,d=(a*r/(3*n) for a in totals)
return Star(m,q,omega,1/a_inf,k,d,tail)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fine',action='store_true',help='halve radial step; extend outer boundary')
args=parser.parse_args()
masses=[]
for c,r in ((.08,37.),(.18,29.),(.192,29.),(.20,29.)):
if args.fine:
r+=3
n=round(r/(.025 if args.fine else .05))
n+=n%2
s=solve(c,r,n)
masses.append(s.mass)
if c==.192:
assert abs(s.mass-.633)<.0005 and abs(s.frequency-.853)<.0005
print(f'sigma0 {c:.3f}, Rcut={r:g}, N={n}: ADM={s.mass:.9f} Q={s.charge:.9f} '
f'binding={s.mass-s.charge:.9f} omega={s.frequency:.9f} alpha0={s.lapse0:.9f}')
print(f' redshift={1/s.lapse0-1:.9f} Komar={s.komar:.9f} '
f'lapse-weighted density alone={s.density_only:.9f} '
f'Komar-ADM={s.komar-s.mass:+.3g} edge-field={s.field_edge:.2g}',flush=True)
assert s.mass<s.charge and 0<s.lapse0<s.frequency<1
assert abs(s.komar-s.mass)<2e-6 and s.field_edge<1e-6
if c==.08:
derivatives=[]
for delta in (.001,.0005):
left,right=[solve(c+i*delta,r,n) for i in (-1,1)]
dq=(right.mass-left.mass)/(right.charge-left.charge)
derivatives.append(dq)
print(f' centered dM/dQ={dq:.9f}, offset from omega={dq-s.frequency:+.3g}',flush=True)
extrapolated=(4*derivatives[-1]-derivatives[0])/3
print(f' extrapolated dM/dQ={extrapolated:.9f}, frequency error={extrapolated-s.frequency:+.3g}')
assert abs(extrapolated-s.frequency)<2e-7
assert masses[1]<masses[2] and masses[3]<masses[2]
if __name__=='__main__':
main()
membrane.py
"""Replay the ringdown test in Camerer et al., PRL 107, 223001 (2011)."""
import argparse
from hashlib import sha256
from math import hypot, isclose, pi, sqrt
from pathlib import Path
# Figure 4 in arXiv:1107.3650v1. Each row gives atom number in millions,
# excess membrane energy-decay rate and plotted bar half-width, both in 10^-3 /s.
FIGURE = (
(0.000, -0.064, 0.899), (0.412, 2.164, 1.018),
(0.414, 2.329, 1.000), (0.681, 5.276, 0.936),
(0.881, 8.102, 1.024), (0.969, 7.263, 0.917),
(1.115, 9.214, 0.991), (1.240, 9.991, 1.000),
(1.355, 11.397, 0.954), (1.439, 10.235, 1.006),
(1.465, 11.839, 1.024), (1.507, 10.915, 0.991),
(1.624, 11.918, 0.939), (2.316, 17.901, 0.899),
)
PDF_SHA256 = "cdab3db449b124c554a4ebfe58c8b477b4e7dfad889a59ff10594ace6e6cc797"
def excess_rate(atom_number, atom_hz, membrane_hz, linewidth_hz, r=0.28, t=0.82):
rb87_kg = 86.9091805310 * 1.66053906660e-27
membrane_kg = 1e-11
omega_a = 2 * pi * atom_hz
omega_m = 2 * pi * membrane_hz
gamma = 2 * pi * linewidth_hz
coupling_squared = omega_a**2 / 4 * (atom_number * rb87_kg / membrane_kg) * omega_a / omega_m
return gamma * coupling_squared * r * t / ((omega_a - omega_m)**2 + (gamma / 2)**2)
def predict_last(points):
training = points[:-1]
information = sum((n / bar)**2 for n, _, bar in training)
slope = sum(n * rate / bar**2 for n, rate, bar in training) / information
slope_error = 1 / sqrt(information)
n, measured, bar = points[-1]
predicted = slope * n
residual = (measured - predicted) / hypot(bar, slope_error * n)
return slope, slope_error, predicted, slope_error * n, measured, bar, residual
def verify_vectors(path):
# Optional audit only. Ordinary replay uses the table above and the standard library.
import pymupdf
if sha256(path.read_bytes()).hexdigest() != PDF_SHA256:
raise ValueError("Expected the arXiv:1107.3650v1 PDF")
with pymupdf.open(path) as document:
vertical_bars = []
for drawing in document[2].get_drawings():
color = drawing.get("color")
if not color or color[0] < 0.9 or color[1] > 0.15 or color[2] > 0.16:
continue
for item in drawing["items"]:
if item[0] != "l":
continue
a, b = item[1:]
if 360 < a.x < 533 and 330 < a.y < 435 and a.x == b.x and 8 < b.y - a.y < 12:
vertical_bars.append((a.x, a.y, b.y))
rows = []
for x, top, bottom in sorted(vertical_bars):
n = (x - 361.210) / 73.331
rate = (433.348 - (top + bottom) / 2) / 5.32736
bar = (bottom - top) / (2 * 5.32736)
rows.append((n, rate, bar))
assert len(rows) == len(FIGURE)
assert all(abs(a - b) <= 0.00051 for x, y in zip(rows, FIGURE) for a, b in zip(x, y))
print("All 14 vector centers and bar half-widths match the table.")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check-pdf", type=Path, help="optionally audit Figure 4 with PyMuPDF installed")
args = parser.parse_args()
if args.check_pdf:
verify_vectors(args.check_pdf)
absolute = excess_rate(2.3e6, 305e3, 244e3, 130e3)
assert isclose(absolute, 0.02277397463, rel_tol=1e-8)
assert isclose(excess_rate(2.3e6, 305e3, 244e3, 130e3, r=0), 0)
assert isclose(excess_rate(4.6e6, 305e3, 244e3, 130e3), 2 * absolute)
slope, error, predicted, pred_error, measured, bar, residual = predict_last(FIGURE)
assert 7.70 < slope < 7.73 and abs(residual) < 0.04
print(f"Absolute prediction {absolute:.6f} /s; paper measured 0.018 +/- 0.001 /s.")
print(f"Returning force fraction r*t = {0.28 * 0.82:.4f}.")
print(f"13-point slope {slope:.3f} +/- {error:.3f} in 0.001 /s per million atoms.")
print(f"Held out {FIGURE[-1][0]:.3f} million: {predicted:.3f} +/- {pred_error:.3f} predicted; "
f"{measured:.3f} +/- {bar:.3f} plotted (0.001 /s).")
if __name__ == "__main__":
main()
radar_geometry.py
"""Infer spherical geometry from ideal clock ratios and radial echoes, standard library only."""
import argparse
from dataclasses import dataclass
from math import exp, log, pi, sqrt
from self_gravity import integrate, solve
@dataclass(frozen=True)
class Reading:
radius:float
clock:float # local clock divided by central observer clock
echo:float # central observer's round-trip proper time
def simulate(fine):
c=.18
outer=32.
n=2560 if fine else 1280
star=solve(c,outer,n)
# The frozen solver uses unit central lapse before its final time normalization.
rows=integrate(c,star.frequency/star.lapse0,outer,n,True)
h=outer/n
truth={}
data=({}, {})
F=[[],[]]
T=[0.,0.]
for i,(r,(m,l,s,v)) in enumerate(rows):
if r>18.:
break
f=1-2*m/r if r else 1.
clock=exp(l)
F[0].append(2/(clock*sqrt(f)))
F[1].append(2/clock)
if i%2:
continue
if i:
for j in (0,1):
T[j]+=h*(F[j][-3]+4*F[j][-2]+F[j][-1])/3
# Dictionary keys identify rational areal-radius markers on a common scale.
key=round(r,8)
for j in (0,1):
data[j][key]=Reading(r,clock,T[j])
pr=((star.frequency/(clock*star.lapse0))**2-1)*s*s+f*v*v
truth[key]=(m,pr)
return data,truth
@dataclass(frozen=True)
class Reconstruction:
mass:float
pressure:float
orbit2:float
lower:float
upper:float
condition:float
def infer(r,h,readings,clock_relative=1e-5,echo_absolute=1e-5):
"""Use only the marker labels, clock ratios and measured echoes in this function."""
left,center,right=[readings[round(x,8)] for x in (r-h,r,r+h)]
slope=(right.echo-left.echo)/(2*h)
a=center.clock*slope/2
f=1/a**2
m=r*(1-f)/2
log_derivative=log(right.clock/left.clock)/(2*h)
p=(r*r*f*log_derivative-m)/r**3
# Coordinate angular frequency referred to the *central* proper-time standard.
omega2=center.clock**2*log_derivative/r
# Independent allowed error budgets; no Gaussian assumption or calibration correlation.
slope_error=echo_absolute/h
a_lo=(1-clock_relative)*center.clock*(slope-slope_error)/2
a_hi=(1+clock_relative)*center.clock*(slope+slope_error)/2
if a_lo<=0:
raise ValueError('echo difference not resolved')
low,high=[r*(1-1/b**2)/2 for b in (a_lo,a_hi)]
cond=r*f/abs(m) if m else float('inf')
return Reconstruction(m,p,omega2,low,high,cond)
def extrapolated(r,h,observed):
raw=infer(r,h,observed)
smaller=infer(r,h/2,observed)
return tuple((4*getattr(smaller,k)-getattr(raw,k))/3 for k in ('mass','pressure'))
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fine',action='store_true',help='halve forward-model radial step')
args=parser.parse_args()
# Fomalont et al. Table 5, corona-corrected solution only.
gamma_minus_one,gamma_sigma=-2.4e-4,3.2e-4
bend,bend_sigma=1+gamma_minus_one/2,gamma_sigma/2
assert abs(bend-.99988)<1e-14 and abs(bend_sigma-.00016)<1e-14
print(f'Solar differential bending / Einstein: {bend:.5f} +/- {bend_sigma:.5f}; '
'equal Newtonian lapse, flat space, zero shift: 0.5')
# Kramer et al. Tables 1/2. GR periastron advance gives GM_total/c^3.
period=.10225156248*86400
ecc,ratio=.0877775,1.0714
advance=16.89947*pi/(180*365.25*86400)
total=(advance*(1-ecc**2)/3)**1.5*(period/(2*pi))**2.5
shapiro=1e6*total/(1+ratio)
assert abs(shapiro-6.15169)<.00001
print(f'Double-pulsar Shapiro range: {shapiro:.5f} microseconds; measured 6.21 +/- 0.33')
(curved,flat),truth=simulate(args.fine)
print('central observer: echo proper times, curved and flat spatial metrics')
for r in (2.,6.,12.,16.):
print(f' r={r:g}: clock ratio {curved[r].clock:.9f}; '
f'T={curved[r].echo:.9f}, {flat[r].echo:.9f}')
print('r, true m, inferred m (h=.4,.2,.1), extrapolated m, pressure true/inferred')
for r in (1.,2.,4.,8.,12.,16.):
mass,p=truth[r]
# Only send three pairs of neighboring echoes and the clock ratios.
# The target's own echo and its source mass/pressure are held out.
def observations(source):
obs={round(r+j*h,8):source[round(r+j*h,8)]
for j in (-1,1) for h in (.4,.2,.1)}
obs[r]=Reading(r,source[r].clock,float('nan'))
return obs
curved_obs,flat_obs=observations(curved),observations(flat)
ms=[infer(r,h,curved_obs).mass for h in (.4,.2,.1)]
m_ext,p_ext=extrapolated(r,.2,curved_obs)
flat_m,_=extrapolated(r,.2,flat_obs)
curved_readout=infer(r,.1,curved_obs)
flat_readout=infer(r,.1,flat_obs)
assert abs(curved_readout.orbit2-flat_readout.orbit2)<1e-14
assert abs(m_ext-mass)<3e-7 and abs(flat_m)<3e-7
assert abs(p_ext-p)<8e-7
print(f' {r:4.1f} {mass:.9f} '+ ' '.join(f'{v:.9f}' for v in ms)+
f' {m_ext:.9f} {p:.7g} {p_ext:.7g}; flat m={flat_m:.3g}')
print(f' h=.1 noise-only mass interval [{curved_readout.lower:.8f}, '
f'{curved_readout.upper:.8f}], condition={curved_readout.condition:.3f}, '
f'central-time circular Omega^2={curved_readout.orbit2:.7g}')
assert curved_readout.lower<curved_readout.mass<curved_readout.upper
# Two exactly opposite signed endpoint errors and a clock-ratio error
# realize both extremes of the bounded noise interval at a selected stencil.
r,h=8.,.1
base=infer(r,h,curved)
for sign,target in ((-1,base.lower),(1,base.upper)):
sample=dict(curved)
for x,e,c in ((r-h,-sign*1e-5,0.),(r,0.,sign*1e-5),(r+h,sign*1e-5,0.)):
key=round(x,8)
row=sample[key]
sample[key]=Reading(row.radius,row.clock*(1+c),row.echo+e)
assert abs(infer(r,h,sample).mass-target)<2e-12
if __name__=='__main__':
main()
bound_3d.py
"""Three-dimensional bound-pair curvature on the full Brillouin torus.
Optional dependency: NumPy. Run python bound_3d.py for converged quadrature.
Use python bound_3d.py 16 for a quick check. No fitting libraries are used.
"""
import sys
import numpy as np
REST = 1.90
I2 = np.eye(2)
X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
Z = np.diag([1., -1.])
GAMMA = [np.eye(4)] + [np.kron(X, a) for a in (X, Y, Z)] + [np.kron(Z, I2)]
PAIRS = [(i, j) for i in range(4) for j in range(i+1, 4)]
BASIS = np.zeros((16, len(PAIRS)))
for col, (a, b) in enumerate(PAIRS):
BASIS[4*a+b, col] = 1/np.sqrt(2)
BASIS[4*b+a, col] = -1/np.sqrt(2)
FULL_TENSORS = np.array([np.kron(a, b) for a in GAMMA for b in GAMMA])
TENSORS = np.array([BASIS.T @ t @ BASIS for t in FULL_TENSORS])
BETA_PAIR = TENSORS[-1].real
IDENTITY = np.eye(6)
def mode(k, shape):
x, y, z = k
t = [2*np.sin(a/2)**2 for a in k]
b = [np.sin(x)*np.cos(y)*np.cos(z), np.sin(y)*np.cos(z), np.sin(z)]
m = 1+2*sum(a*a for a in t)/3+2*(t[0]*t[1]+t[0]*t[2]+t[1]*t[2])
e = np.sqrt(sum(a*a for a in b)+m*m)
basis = np.stack([np.broadcast_to(a/e, shape).ravel() for a in (*b, m)], axis=1)
return e.ravel(), basis
class Torus:
def __init__(self, size, rest=REST):
self.rest = rest
self.size = size
self.grid = tuple(np.asarray(axis) for axis in
np.ogrid[0:size:1, 0:size:1, 0:size:1])
def green(self, energy, axis=0, momentum=0., derivative=False, full=False):
# The four signed spectral projectors span all sixteen physical spin states.
# Integrate them first, then restrict the coincident source to exchange-odd.
moments = np.zeros((5, 5))
n = self.size
for lo in range(0, n, 8):
k = [self.grid[0][lo:lo+8], self.grid[1], self.grid[2]]
k = [p*(2*np.pi/n) for p in k]
shape = np.broadcast_shapes(*(p.shape for p in k))
shift = [momentum/2 if i == axis else 0. for i in range(3)]
ea, a = mode([p+s for p, s in zip(k, shift)], shape)
eb, b = mode([-p+s for p, s in zip(k, shift)], shape)
w = []
for s, t in ((1,1), (1,-1), (-1,1), (-1,-1)):
den = energy-s*ea-t*eb
w.append(-.25/den**2 if derivative else .25/den)
pp, pm, mp, mm = w
const = pp+pm+mp+mm
first = pp+pm-mp-mm
second = pp-pm+mp-mm
cross = pp-pm-mp+mm
moments[0,0] += np.sum(const)
moments[1:,0] += np.sum(first[:,None]*a, axis=0)
moments[0,1:] += np.sum(second[:,None]*b, axis=0)
moments[1:,1:] += a.T @ (cross[:,None]*b)
g = np.tensordot(moments.ravel()/n**3, FULL_TENSORS if full else TENSORS, axes=1)
assert np.max(abs(g-g.conj().T)) < 1e-12
return g
def rest_calibration(torus):
green = torus.green(torus.rest)
germ = green[np.ix_((0,5),(0,5))]
ev, vec = np.linalg.eigh(germ)
# Choose the negative pole with largest positive-mass-orbital coincidence amplitude.
root = np.argmax(abs(vec[0])**2)
lam = ev[root]
state = np.zeros(6,dtype=complex)
state[[0,5]] = vec[:,root]
assert lam < 0 and abs(state[0])**2 > .97
assert np.linalg.norm(green@state-lam*state) < 1e-12
d_energy = (state.conj() @ torus.green(torus.rest, derivative=True) @ state).real
assert d_energy < 0
return green, lam, state, d_energy
def row(torus, spacing, axis, calibrated):
plus = torus.green(torus.rest, axis, spacing)
return extract_curvature(torus.rest, spacing, plus, calibrated)
def extract_curvature(rest, spacing, plus, calibrated):
green0, lam, state, d_energy = calibrated
minus = BETA_PAIR @ plus @ BETA_PAIR # exact inversion on a symmetric torus
slope = (plus-minus)/(2*spacing)
curve = (plus+minus-2*green0)/spacing**2
results = []
for contact in (IDENTITY, BETA_PAIR):
pole_matrix = green0-lam*contact
eigenvalues, vectors = np.linalg.eigh(pole_matrix)
kept = abs(eigenvalues)>1e-9
assert np.sum(~kept) == 1
gaps = eigenvalues[kept]
overlaps = vectors[:,kept].conj().T @ slope @ state
pole_curve = (state.conj() @ curve @ state).real - 2*np.sum(abs(overlaps)**2/gaps)
results.append(-rest*pole_curve/d_energy)
return np.array(results)
def moving_root(torus, axis, momentum, contact, calibrated):
_, lam, state, _ = calibrated
energy = torus.rest
for _ in range(3):
vals, vecs = np.linalg.eigh(torus.green(energy, axis, momentum)-lam*contact)
j = np.argmax(abs(vecs.conj().T @ state)**2)
slope = (vecs[:,j].conj() @ torus.green(energy, axis, momentum, derivative=True)
@ vecs[:,j]).real
energy -= vals[j]/slope
residual = min(abs(np.linalg.eigvalsh(torus.green(energy, axis, momentum)-lam*contact)))
assert residual < 1e-12
return energy
def rotations():
# The 24 proper cubic rotations, generated by quarter-turns about x and z.
turns = [(np.array([[1,0,0],[0,0,-1],[0,1,0]]), (I2-1j*X)/np.sqrt(2)),
(np.array([[0,-1,0],[1,0,0],[0,0,1]]), (I2-1j*Z)/np.sqrt(2))]
queue = [(np.eye(3,dtype=int), I2)]
seen = set()
for r, u in queue:
key = tuple(r.ravel())
if key in seen:
continue
seen.add(key)
for t, v in turns:
queue.append((t@r, v@u))
u4 = np.kron(I2,u)
yield r, BASIS.T@np.kron(u4,u4)@BASIS
assert len(seen) == 24
ROTATIONS = list(rotations())
def average_channels(positive, axis=2):
# For K along lab axis i select U_R G(R^-1 K) U_R†.
total = np.zeros((6,6), dtype=complex)
for r, u in ROTATIONS:
direction = r[axis,:]
j = np.argmax(abs(direction))
g = positive[j]
if direction[j] < 0:
g = BETA_PAIR@g@BETA_PAIR
total += u@g@u.conj().T
return total/len(ROTATIONS)
def calculate(n, rest=REST, detailed=False):
torus = Torus(n,rest)
cal = rest_calibration(torus)
green, lam, state, d_energy = cal
weight = lam**2/(-d_energy)
full = torus.green(rest,full=True)
full_gaps = [np.sort(abs(np.linalg.eigvalsh(full-lam*contact)))[1]
for contact in (np.eye(16),FULL_TENSORS[-1])]
assert min(full_gaps) > 1e-5
print(f'E0={rest:.3f}, mesh={n}, g={1/lam:.10f}, E0*contact={rest*weight:.9f}, '
f'next full inverse-kernel gap={min(full_gaps):.7f}')
results = []
orient_rest = average_channels([green]*3)
assert np.linalg.norm(orient_rest@state-lam*state) < 1e-12
oriented_cal = (orient_rest,lam,state,d_energy)
# Richardson elimination of the leading step-squared error.
for step in (.01,.005,.0025):
plus = [torus.green(rest,j,step) for j in range(3)]
row_ = [extract_curvature(rest,step,g,cal) for g in plus]
avg = average_channels(plus)
for j in (0,1):
values = extract_curvature(rest,step,average_channels(plus,j),oriented_cal)
assert np.max(abs(values-extract_curvature(rest,step,avg,oriented_cal))) < 5e-8
row_.append(extract_curvature(rest,step,avg,oriented_cal))
results.append(np.array(row_))
coarse = (4*results[1]-results[0])/3
fine = (4*results[2]-results[1])/3
print(' refinement of extrapolated curvatures:',f'{np.max(abs(fine-coarse)):.2g}')
for name,pair in zip(('x','y','z','cubic'),fine):
print(f' {name}: R_density={pair[0]:.9f}, R_mass={pair[1]:.9f}')
if detailed:
# Locate actual moving poles independently of the curvature formula.
steps = (.012,.006)
for j,axis in enumerate('xyz'):
for i,contact in enumerate((IDENTITY,BETA_PAIR)):
energies = [moving_root(torus,j,k,contact,cal) for k in steps]
raw = [2*rest*(e-rest)/k**2 for e,k in zip(energies,steps)]
cross = (4*raw[1]-raw[0])/3
assert abs(cross-fine[j,i]) < 3e-6
print(f' {axis} contact {i}, E(.012)={energies[0]:.10f}, '
f'E(.006)={energies[1]:.10f}, independent R={cross:.8f}')
return fine,rest*weight
def independent_green():
# Invert the unrestricted 16 by 16 Hamiltonian directly on a small grid.
n = 5
torus = Torus(n)
ktotal = .117
full = np.zeros((16,16),complex)
for index in np.ndindex(n,n,n):
p = 2*np.pi*np.array(index)/n
halves = np.array((0,ktotal/2,0))
pair = []
for k in (p+halves,-p+halves):
en, basis = mode(k,())
pair.append(en[0]*sum(a*b for a,b in zip(basis[0],GAMMA[1:])))
h = np.kron(pair[0],GAMMA[0])+np.kron(GAMMA[0],pair[1])
full += np.linalg.inv(REST*np.eye(16)-h)
err = np.max(abs(full/n**3-torus.green(REST,1,ktotal,full=True)))
assert err < 1e-14
print(f'independent full Green matrix direct-inversion residual {err:.2g}')
if __name__ == '__main__':
independent_green()
sizes = [int(x) for x in sys.argv[1:]] or [16,32,48,64,80]
results = [calculate(n,detailed=(n == sizes[0])) for n in sizes]
if len(sys.argv) == 1:
assert np.max(abs(results[-1][0]-results[-2][0])) < 2e-6
held = [calculate(n,1.975) for n in (64,96,112)]
print('held-out mesh difference in R:', np.max(abs(held[-1][0]-held[-2][0])))
train, weight_train = results[-1]
test, weight_test = held[-1]
c = (1-train[-1])/weight_train
print('onsite pair-hop calibration c (density, mass):', c)
print('held-out ratios after this correction:', test[-1]+weight_test*c)
replay.py
"""Replay the pair-inertia study with the published Tally runtime."""
import argparse
import hashlib
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parent
RUNTIME_SHA = "6f3e168661968c1ff3e32d0390de7ba79fd72ef452b6fd44efce7012df2263ee"
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"
def checked(path, expected):
data = path.read_bytes()
if hashlib.sha256(data).hexdigest() != expected:
raise ValueError(f"Unexpected SHA-256 for {path.name}")
return data
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("runtime", type=Path, help="published Tally release 184 ZIP")
parser.add_argument("--full", action="store_true", help="include the full 3D calculations (NumPy)")
args = parser.parse_args()
checked(args.runtime, RUNTIME_SHA)
atom = ROOT/"lib/atom.tly"
if not atom.is_file():
atom = ROOT.parent/"walk-clock-recoil/tally/lib/atom.tly"
library = checked(atom, ATOM_SHA)
python = [sys.executable,"-B"]
standard = ("alignment","dimer","mass_data","scattering","covering_source","binding_charge","dipole","support","measured_source",
"mobile_host","membrane","self_gravity","radar_geometry")
multiband = ("current","molecule","binding","fall","pair_fall","source","form_factor","tensor_source","mediating_field",
"pair_elastic","strain_vertex","optical_range","crystal_recoil","excited_kink")
full_options = {"scattering": ["--full", "--order", "20"], "covering_source": ["--finite"],
"self_gravity": ["--fine"], "radar_geometry": ["--fine"]}
for script in standard:
extra = full_options.get(script, []) if args.full else []
subprocess.run([*python, str(ROOT/(script+".py")), *extra], check=True)
if args.full:
arguments = {"binding": ["--refine"], "tensor_source": ["--size", "48", "--refine", "64"],
"form_factor": ["80", "z"], "strain_vertex": ["80", "--matched", "--wave"]}
for script in multiband:
extra = arguments.get(script, [])
subprocess.run([*python,str(ROOT/(script+".py")), *extra],check=True,
env=dict(os.environ,OPENBLAS_NUM_THREADS="1"))
with tempfile.TemporaryDirectory() as path:
work = Path(path)
with ZipFile(args.runtime) as release:
release.extractall(work)
tally = work/"Tally-0.3.0"
(tally/"lib/atom.tly").write_bytes(library)
shutil.copyfile(ROOT/"pair.tly",work/"pair.tly")
output = subprocess.run([*python,str(tally/"tally.py"),"pair.tly"],cwd=work,
check=True,stdout=subprocess.PIPE).stdout.decode("utf-8").splitlines()
if output != (ROOT/"pair.out").read_text(encoding="utf-8").splitlines() or sum(row.startswith("✓") for row in output) != 60:
raise ValueError("Native transcript differs from the published 60 checks")
count = len(standard) + (len(multiband) if args.full else 0)
print(f"Passed {count} calculation programs and all 60 native Tally checks.")
if __name__ == "__main__":
main()